From 668d3393b9da1a7b971d0ab434eebd7e51a7a193 Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Tue, 6 May 2025 13:57:38 +0800 Subject: [PATCH 1/4] =?UTF-8?q?=E5=90=8C=E6=AD=A5=E9=BB=84=E5=8C=BA?= =?UTF-8?q?=E4=B8=BB=E5=B9=B2=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- .../include/authentication/dm_auth_manager.h | 14 +- .../authentication/dm_auth_manager.h.bak | 660 ++++ .../include/authentication_v2/auth_manager.h | 4 +- .../authentication_v2/auth_manager.h.bak | 210 + .../authentication_v2/dm_auth_context.h | 7 - .../authentication_v2/dm_auth_context.h.bak | 257 ++ .../authentication_v2/dm_auth_manager_base.h | 17 +- .../dm_auth_manager_base.h.bak | 258 ++ .../include/authentication_v2/dm_auth_state.h | 1 - .../authentication_v2/dm_auth_state.h.bak | 509 +++ .../include/device_manager_service_impl.h | 14 + .../include/device_manager_service_impl.h.bak | 284 ++ .../src/authentication/dm_auth_manager.cpp | 168 +- .../authentication/dm_auth_manager.cpp.bak | 3404 +++++++++++++++++ .../src/authentication_v2/auth_manager.cpp | 73 +- .../authentication_v2/auth_manager.cpp.bak | 1051 +++++ .../auth_stages/auth_negotiate.cpp | 2 +- .../auth_stages/auth_negotiate.cpp.bak | 534 +++ .../dm_auth_manager_base.cpp | 38 + .../dm_auth_manager_base.cpp.bak | 514 +++ .../src/authentication_v2/dm_auth_state.cpp | 40 - .../authentication_v2/dm_auth_state.cpp.bak | 461 +++ .../src/device_manager_service_impl.cpp | 120 +- .../src/device_manager_service_impl.cpp.bak | 2438 ++++++++++++ 24 files changed, 10821 insertions(+), 257 deletions(-) create mode 100644 services/implementation/include/authentication/dm_auth_manager.h.bak create mode 100644 services/implementation/include/authentication_v2/auth_manager.h.bak create mode 100644 services/implementation/include/authentication_v2/dm_auth_context.h.bak create mode 100644 services/implementation/include/authentication_v2/dm_auth_manager_base.h.bak create mode 100644 services/implementation/include/authentication_v2/dm_auth_state.h.bak create mode 100644 services/implementation/include/device_manager_service_impl.h.bak create mode 100644 services/implementation/src/authentication/dm_auth_manager.cpp.bak create mode 100644 services/implementation/src/authentication_v2/auth_manager.cpp.bak create mode 100644 services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp.bak create mode 100644 services/implementation/src/authentication_v2/dm_auth_manager_base.cpp.bak create mode 100644 services/implementation/src/authentication_v2/dm_auth_state.cpp.bak create mode 100644 services/implementation/src/device_manager_service_impl.cpp.bak diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index a9631252f..5a9e031b8 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -494,9 +494,6 @@ public: static bool IsPinCodeValid(int32_t numpin); bool IsImportedAuthCodeValid(); bool IsSrc(); - void GetCallerInfo(DmBindCallerInfo &callerInfo); - void SetCallerInfo(const DmBindCallerInfo &callerInfo); - void ClearCallerInfo(); private: bool IsHmlSessionType(); @@ -513,7 +510,6 @@ private: const std::string &extra); int32_t CheckAuthParamVaildExtra(const std::string &extra, const std::string &deviceId); bool CheckHmlParamValid(JsonObject &jsonObject); - bool CheckProcessNameInWhiteList(const std::string &processName); void ProcessSourceMsg(); void ProcessSinkMsg(); std::string GetAccountGroupIdHash(); @@ -539,7 +535,6 @@ private: void MemberJoinAuthRequest(int64_t requestId, int32_t status); void PutSrcAccessControlList(DmAccesser &accesser, DmAccessee &accessee, const std::string &localUdid); void PutSinkAccessControlList(DmAccesser &accesser, DmAccessee &accessee, const std::string &localUdid); - void GetCallerInfo(const std::string &pkgName, JsonObject &jsonObject); public: void RequestCredential(); @@ -582,7 +577,6 @@ private: void PutAccessControlList(); void SinkAuthenticateFinish(); void SrcAuthenticateFinish(); - std::string GetBundleLable(const std::string &bundleName); bool IsScreenLocked(); void CheckAndEndTvDream(); std::string ConvertSinkVersion(const std::string &version); @@ -592,8 +586,6 @@ private: void GetPeerUdidHash(int32_t sessionId, std::string &peerUdidHash); void DeleteOffLineTimer(int32_t sessionId); bool IsAllowDeviceBind(); - int32_t GetBindLevel(int32_t bindLevel); - std::string GetBundleName(JsonObject &jsonObject); int32_t GetBinderInfo(); void SetProcessInfo(); int32_t GetCloseSessionDelaySeconds(std::string &delaySecondsStr); @@ -604,6 +596,7 @@ private: int32_t GetTokenIdByBundleName(int32_t userId, std::string &bundleName, int64_t &tokenId); bool CheckBindLevel(const JsonItemObject &jsonObj, const std::string &key, int32_t &bindLevel); void RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback); + void GetBindCallerInfo(); private: std::shared_ptr softbusConnector_; @@ -651,9 +644,8 @@ private: std::map> sessionKeyIdAsyncResult_; bool isWaitingJoinLnnCallback_ = false; CleanNotifyCallback cleanNotifyCallback_{nullptr}; - std::mutex callerInfoMutex_; - DmBindCallerInfo callerInfo_; - bool callerInfoReady_ = false; + std::mutex bindParamMutex_; + std::map bindParam_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/authentication/dm_auth_manager.h.bak b/services/implementation/include/authentication/dm_auth_manager.h.bak new file mode 100644 index 000000000..a9631252f --- /dev/null +++ b/services/implementation/include/authentication/dm_auth_manager.h.bak @@ -0,0 +1,660 @@ +/* + * 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 + * + * 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_AUTH_MANAGER_H +#define OHOS_DM_AUTH_MANAGER_H +#define TYPE_TV_ID 0x9C + +#include +#include +#include + +#include "auth_request_state.h" +#include "auth_response_state.h" +#include "auth_ui_state_manager.h" +#include "authentication.h" +#include "idevice_manager_service_listener.h" +#include "deviceprofile_connector.h" +#include "dm_ability_manager.h" +#include "dm_adapter_manager.h" +#include "dm_auth_manager_base.h" +#include "dm_constants.h" +#include "dm_device_info.h" +#include "dm_timer.h" +#include "hichain_auth_connector.h" +#include "hichain_connector.h" +#include "service_info_unique_key.h" +#include "softbus_connector.h" +#include "softbus_session.h" + +namespace OHOS { +namespace DistributedHardware { +typedef enum AuthState { + AUTH_REQUEST_INIT = 1, + AUTH_REQUEST_NEGOTIATE, + AUTH_REQUEST_NEGOTIATE_DONE, + AUTH_REQUEST_REPLY, + AUTH_REQUEST_JOIN, + AUTH_REQUEST_NETWORK, + AUTH_REQUEST_FINISH, + AUTH_REQUEST_CREDENTIAL, + AUTH_REQUEST_CREDENTIAL_DONE, + AUTH_REQUEST_AUTH_FINISH, + AUTH_REQUEST_RECHECK_MSG, + AUTH_REQUEST_RECHECK_MSG_DONE, + + AUTH_RESPONSE_INIT = 20, + AUTH_RESPONSE_NEGOTIATE, + AUTH_RESPONSE_CONFIRM, + AUTH_RESPONSE_GROUP, + AUTH_RESPONSE_SHOW, + AUTH_RESPONSE_FINISH, + AUTH_RESPONSE_CREDENTIAL, + AUTH_RESPONSE_AUTH_FINISH, + AUTH_RESPONSE_RECHECK_MSG, +} AuthState; + +enum DmMsgType : int32_t { + MSG_TYPE_UNKNOWN = 0, + MSG_TYPE_NEGOTIATE = 80, + MSG_TYPE_RESP_NEGOTIATE = 90, + MSG_TYPE_REQ_AUTH = 100, + MSG_TYPE_INVITE_AUTH_INFO = 102, + MSG_TYPE_REQ_AUTH_TERMINATE = 104, + MSG_TYPE_RESP_AUTH = 200, + MSG_TYPE_JOIN_AUTH_INFO = 201, + MSG_TYPE_RESP_AUTH_TERMINATE = 205, + MSG_TYPE_CHANNEL_CLOSED = 300, + MSG_TYPE_SYNC_GROUP = 400, + MSG_TYPE_AUTH_BY_PIN = 500, + + MSG_TYPE_RESP_AUTH_EXT, + MSG_TYPE_REQ_PUBLICKEY, + MSG_TYPE_RESP_PUBLICKEY, + MSG_TYPE_REQ_RECHECK_MSG, + MSG_TYPE_RESP_RECHECK_MSG, + MSG_TYPE_REQ_AUTH_DEVICE_NEGOTIATE = 600, + MSG_TYPE_RESP_AUTH_DEVICE_NEGOTIATE = 700, +}; + +enum DmAuthType : int32_t { + AUTH_TYPE_CRE = 0, + AUTH_TYPE_PIN, + AUTH_TYPE_QR_CODE, + AUTH_TYPE_NFC, + AUTH_TYPE_NO_INTER_ACTION, + AUTH_TYPE_IMPORT_AUTH_CODE, + AUTH_TYPE_UNKNOW, +}; + +typedef struct DmAuthRequestContext { + int32_t authType; + std::string localDeviceId; + std::string localDeviceName; + int32_t localDeviceTypeId; + std::string deviceId; + std::string deviceName; + std::string deviceTypeId; + int32_t sessionId; + int32_t groupVisibility; + bool cryptoSupport; + std::string cryptoName; + std::string cryptoVer; + std::string hostPkgName; + std::string targetPkgName; + std::string bundleName; + std::string peerBundleName; + std::string appOperation; + std::string appDesc; + std::string appName; + std::string customDesc; + std::string appThumbnail; + std::string token; + int32_t reason; + std::vector syncGroupList; + std::string dmVersion; + int32_t localUserId; + std::string localAccountId; + std::vector bindType; + bool isOnline; + bool authed; + int32_t bindLevel; + int64_t tokenId; + std::string remoteAccountId; + int32_t remoteUserId; + std::string addr; + std::string hostPkgLabel; + int32_t closeSessionDelaySeconds = 0; + std::string remoteDeviceName; + std::string connSessionType; + int32_t hmlActionId = 0; + bool hmlEnable160M = false; +} DmAuthRequestContext; + +typedef struct DmAuthResponseContext { + int32_t authType; + std::string deviceId; + std::string localDeviceId; + std::string deviceName; + int32_t deviceTypeId; + int32_t msgType; + int32_t sessionId; + bool cryptoSupport; + bool isIdenticalAccount; + bool isAuthCodeReady; + bool isShowDialog; + std::string cryptoName; + std::string cryptoVer; + int32_t reply; + std::string networkId; + std::string groupId; + std::string groupName; + std::string hostPkgName; + std::string targetPkgName; + std::string bundleName; + std::string peerBundleName; + std::string appOperation; + std::string appDesc; + std::string customDesc; + std::string appIcon; + std::string appThumbnail; + std::string token; + std::string authToken; + int32_t pageId; + int64_t requestId; + std::string code = ""; + int32_t state; + std::vector syncGroupList; + std::string accountGroupIdHash; + std::string publicKey; + bool isOnline; + int32_t bindLevel; + bool haveCredential; + int32_t confirmOperation; + std::string localAccountId; + int32_t localUserId; + int64_t tokenId; + int64_t remoteTokenId; + bool authed; + std::string dmVersion; + std::vector bindType; + std::string remoteAccountId; + int32_t remoteUserId; + std::string targetDeviceName; + std::string importAuthCode; + std::string hostPkgLabel; + bool isFinish = false; + std::string edition; + int32_t localBindLevel; + std::string remoteDeviceName; + int32_t localSessionKeyId = 0; + int32_t remoteSessionKeyId = 0; +} DmAuthResponseContext; + +class AuthMessageProcessor; + +class DmAuthManager final : public AuthManagerBase, + public std::enable_shared_from_this { +public: + DmAuthManager(std::shared_ptr softbusConnector, + std::shared_ptr hiChainConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector); + ~DmAuthManager(); + + /** + * @tc.name: DmAuthManager::AuthenticateDevice + * @tc.desc: Authenticate Device of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, + const std::string &extra); + + /** + * @tc.name: DmAuthManager::UnAuthenticateDevice + * @tc.desc: UnAuthenticate Device of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel); + + /** + * @brief UnBind device. + * @param pkgName package name. + * @param deviceId device id. + * @return Return 0 if success. + */ + int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel, const std::string &extra); + + /** + * @tc.name: DmAuthManager::OnSessionOpened + * @tc.desc: Opened Session of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + void OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result); + + /** + * @tc.name: DmAuthManager::OnSessionClosed + * @tc.desc: Closed Session of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + void OnSessionClosed(const int32_t sessionId); + + /** + * @tc.name: DmAuthManager::OnDataReceived + * @tc.desc: Received Data of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + void OnDataReceived(const int32_t sessionId, const std::string message); + + /** + * @tc.name: DmAuthManager::OnSoftbusJoinLNNResult + * @tc.desc: OnSoftbus JoinLNN Result of the SoftbusConnector + * @tc.type: FUNC + */ + void OnSoftbusJoinLNNResult(const int32_t sessionId, const char *networkId, int32_t result); + + /** + * @tc.name: DmAuthManager::OnGroupCreated + * @tc.desc: Created Group of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + void OnGroupCreated(int64_t requestId, const std::string &groupId); + + /** + * @tc.name: DmAuthManager::OnMemberJoin + * @tc.desc: Join Member of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + void OnMemberJoin(int64_t requestId, int32_t status); + + /** + * @tc.name: DmAuthManager::EstablishAuthChannel + * @tc.desc: Establish Auth Channel of the DeviceManager Authenticate Manager, auth state machine + * @tc.type: FUNC + */ + int32_t EstablishAuthChannel(const std::string &deviceId); + + /** + * @tc.name: DmAuthManager::StartNegotiate + * @tc.desc: Start Negotiate of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + void StartNegotiate(const int32_t &sessionId); + + /** + * @tc.name: DmAuthManager::RespNegotiate + * @tc.desc: Resp Negotiate of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + void RespNegotiate(const int32_t &sessionId); + + /** + * @tc.name: DmAuthManager::SendAuthRequest + * @tc.desc: Send Auth Request of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + void SendAuthRequest(const int32_t &sessionId); + + /** + * @tc.name: DmAuthManager::StartAuthProcess + * @tc.desc: Start Auth Process of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + int32_t StartAuthProcess(const int32_t &action); + + /** + * @tc.name: DmAuthManager::StartRespAuthProcess + * @tc.desc: Start Resp Auth Process of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + void StartRespAuthProcess(); + + /** + * @tc.name: DmAuthManager::CreateGroup + * @tc.desc: Create Group of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + int32_t CreateGroup(); + + /** + * @tc.name: DmAuthManager::ProcessPincode + * @tc.desc: Process pin code of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + int32_t ProcessPincode(const std::string &pinCode); + + /** + * @tc.name: DmAuthManager::GetConnectAddr + * @tc.desc: Get Connect Addr of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + std::string GetConnectAddr(std::string deviceId); + + /** + * @tc.name: DmAuthManager::JoinNetwork + * @tc.desc: Join Net work of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + int32_t JoinNetwork(); + + /** + * @tc.name: DmAuthManager::AuthenticateFinish + * @tc.desc: Finish Authenticate of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + void AuthenticateFinish(); + + /** + * @tc.name: DmAuthManager::GetIsCryptoSupport + * @tc.desc: Get Cryp to Support of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + bool GetIsCryptoSupport(); + + /** + * @tc.name: DmAuthManager::SetAuthRequestState + * @tc.desc: Set Auth Request State of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + int32_t SetAuthRequestState(std::shared_ptr authRequestState); + + /** + * @tc.name: DmAuthManager::SetAuthResponseState + * @tc.desc: Set Auth Response State of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + int32_t SetAuthResponseState(std::shared_ptr authResponseState); + + /** + * @tc.name: DmAuthManager::GetPinCode + * @tc.desc: Get Pin Code of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + int32_t GetPinCode(std::string &code); + + /** + * @tc.name: DmAuthManager::GenerateGroupName + * @tc.desc: Generate Group Name of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + std::string GenerateGroupName(); + + /** + * @tc.name: DmAuthManager::HandleAuthenticateTimeout + * @tc.desc: Handle Authenticate Timeout of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + void HandleAuthenticateTimeout(std::string name); + + /** + * @tc.name: DmAuthManager::GeneratePincode + * @tc.desc: Generate Pincode of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + std::string GeneratePincode(); + + /** + * @tc.name: DmAuthManager::ShowConfigDialog + * @tc.desc: Show Config Dialog of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + void ShowConfigDialog(); + + /** + * @tc.name: DmAuthManager::ShowAuthInfoDialog + * @tc.desc: Show AuthInfo Dialog of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + void ShowAuthInfoDialog(bool authDeviceError = false); + + /** + * @tc.name: DmAuthManager::ShowStartAuthDialog + * @tc.desc: Show Start Auth Dialog of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + void ShowStartAuthDialog(); + + /** + * @tc.name: DmAuthManager::OnUserOperation + * @tc.desc: User Operation of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + int32_t OnUserOperation(int32_t action, const std::string ¶ms); + + /** + * @tc.name: DmAuthManager::SetPageId + * @tc.desc: Set PageId of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + int32_t SetPageId(int32_t pageId); + + /** + * @tc.name: DmAuthManager::SetReasonAndFinish + * @tc.desc: Set Reason of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + int32_t SetReasonAndFinish(int32_t reason, int32_t state); + + /** + * @tc.name: DmAuthManager::IsIdenticalAccount + * @tc.desc: judge IdenticalAccount or not + * @tc.type: FUNC + */ + bool IsIdenticalAccount(); + + /** + * @tc.name: DmAuthManager::RegisterUiStateCallback + * @tc.desc: Register ui state callback + * @tc.type: FUNC + */ + int32_t RegisterUiStateCallback(const std::string pkgName); + + /** + * @tc.name: DmAuthManager::UnRegisterUiStateCallback + * @tc.desc: Unregister ui state callback + * @tc.type: FUNC + */ + int32_t UnRegisterUiStateCallback(const std::string pkgName); + + /** + * @tc.name: DmAuthManager::ImportAuthCode + * @tc.desc: Import auth code + * @tc.type: FUNC + */ + int32_t ImportAuthCode(const std::string &pkgName, const std::string &authCode); + + /** + * @tc.name: DmAuthManager::BindTarget + * @tc.desc: Bind Target + * @tc.type: FUNC + */ + int32_t BindTarget(const std::string &pkgName, const PeerTargetId &targetId, + const std::map &bindParam, int sessionId, uint64_t logicalSessionId); + + void ClearSoftbusSessionCallback(); + void PrepareSoftbusSessionCallback(); + + void HandleSessionHeartbeat(std::string name); + + int32_t RegisterAuthenticationType(int32_t authenticationType); + static bool IsPinCodeValid(const std::string strpin); + static bool IsPinCodeValid(int32_t numpin); + bool IsImportedAuthCodeValid(); + bool IsSrc(); + void GetCallerInfo(DmBindCallerInfo &callerInfo); + void SetCallerInfo(const DmBindCallerInfo &callerInfo); + void ClearCallerInfo(); + +private: + bool IsHmlSessionType(); + bool CanUsePincodeFromDp(); + bool IsServiceInfoAuthTypeValid(int32_t authType); + bool IsServiceInfoAuthBoxTypeValid(int32_t authBoxType); + bool IsServiceInfoPinExchangeTypeValid(int32_t pinExchangeType); + bool IsLocalServiceInfoValid(const DistributedDeviceProfile::LocalServiceInfo &localServiceInfo); + void GetLocalServiceInfoInDp(); + bool CheckNeedShowAuthInfoDialog(int32_t errorCode); + void UpdateInputPincodeDialog(int32_t errorCode); + void JoinLnn(const std::string &deviceId, bool isForceJoin = false); + int32_t CheckAuthParamVaild(const std::string &pkgName, int32_t authType, const std::string &deviceId, + const std::string &extra); + int32_t CheckAuthParamVaildExtra(const std::string &extra, const std::string &deviceId); + bool CheckHmlParamValid(JsonObject &jsonObject); + bool CheckProcessNameInWhiteList(const std::string &processName); + void ProcessSourceMsg(); + void ProcessSinkMsg(); + std::string GetAccountGroupIdHash(); + void AbilityNegotiate(); + void HandleMemberJoinImportAuthCode(const int64_t requestId, const int32_t status); + int32_t DeleteAuthCode(); + int32_t GetAuthCode(const std::string &pkgName, std::string &pinCode); + bool IsAuthTypeSupported(const int32_t &authType); + bool IsAuthCodeReady(const std::string &pkgName); + int32_t ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, std::string &addrType); + std::string ParseExtraFromMap(const std::map &bindParam); + std::string GenerateBindResultContent(); + void InitAuthState(const std::string &pkgName, int32_t authType, const std::string &deviceId, + const std::string &extra); + void CompatiblePutAcl(); + void ProcRespNegotiateExt(const int32_t &sessionId); + void ProcRespNegotiate(const int32_t &sessionId); + void GetAuthRequestContext(); + void SinkAuthDeviceFinish(); + void SrcAuthDeviceFinish(); + int32_t CheckTrustState(); + void ProcIncompatible(const int32_t &sessionId); + void MemberJoinAuthRequest(int64_t requestId, int32_t status); + void PutSrcAccessControlList(DmAccesser &accesser, DmAccessee &accessee, const std::string &localUdid); + void PutSinkAccessControlList(DmAccesser &accesser, DmAccessee &accessee, const std::string &localUdid); + void GetCallerInfo(const std::string &pkgName, JsonObject &jsonObject); + +public: + void RequestCredential(); + void GenerateCredential(std::string &publicKey); + void RequestCredentialDone(); + void ResponseCredential(); + bool AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen); + void AuthDeviceFinish(int64_t requestId); + void AuthDeviceError(int64_t requestId, int32_t errorCode); + void GetRemoteDeviceId(std::string &deviceId); + void AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen); + char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams); + int32_t GetSessionKeyIdSync(int64_t requestId); + void OnAuthDeviceDataReceived(const int32_t sessionId, const std::string message); + void OnScreenLocked(); + void HandleDeviceNotTrust(const std::string &udid); + int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); + int32_t DeleteGroup(const std::string &pkgName, int32_t userId, const std::string &deviceId); + int32_t StopAuthenticateDevice(const std::string &pkgName); + void RequestReCheckMsg(); + void ResponseReCheckMsg(); + void RequestReCheckMsgDone(); + void CloseAuthSession(const int32_t sessionId); +private: + int32_t ImportCredential(std::string &deviceId, std::string &publicKey); + void GetAuthParam(const std::string &pkgName, int32_t authType, const std::string &deviceId, + const std::string &extra); + void ParseJsonObject(JsonObject &jsonObject); + void ParseHmlInfoInJsonObject(JsonObject &jsonObject); + void PutSessionKeyAsync(int64_t requestId, std::vector hash); + int32_t DeleteAcl(const std::string &pkgName, const std::string &localUdid, const std::string &remoteUdid, + int32_t bindLevel, const std::string &extra); + void ProcessAuthRequestExt(const int32_t &sessionId); + bool IsAuthFinish(); + void ProcessAuthRequest(const int32_t &sessionId); + int32_t ConfirmProcess(const int32_t &action); + int32_t ConfirmProcessExt(const int32_t &action); + int32_t AddMember(const std::string &pinCode); + int32_t AuthDevice(const std::string &pinCode); + void PutAccessControlList(); + void SinkAuthenticateFinish(); + void SrcAuthenticateFinish(); + std::string GetBundleLable(const std::string &bundleName); + bool IsScreenLocked(); + void CheckAndEndTvDream(); + std::string ConvertSinkVersion(const std::string &version); + void NegotiateRespMsg(const std::string &version); + void SetAuthType(int32_t authType); + int32_t GetTaskTimeout(const char* taskName, int32_t taskTimeOut); + void GetPeerUdidHash(int32_t sessionId, std::string &peerUdidHash); + void DeleteOffLineTimer(int32_t sessionId); + bool IsAllowDeviceBind(); + int32_t GetBindLevel(int32_t bindLevel); + std::string GetBundleName(JsonObject &jsonObject); + int32_t GetBinderInfo(); + void SetProcessInfo(); + int32_t GetCloseSessionDelaySeconds(std::string &delaySecondsStr); + void ConverToFinish(); + bool IsSinkMsgValid(); + bool IsSourceMsgValid(); + void ProcessReqPublicKey(); + int32_t GetTokenIdByBundleName(int32_t userId, std::string &bundleName, int64_t &tokenId); + bool CheckBindLevel(const JsonItemObject &jsonObj, const std::string &key, int32_t &bindLevel); + void RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback); + +private: + std::shared_ptr softbusConnector_; + std::shared_ptr hiChainConnector_; + std::shared_ptr authUiStateMgr_; + std::shared_ptr listener_; + std::shared_ptr adapterMgr_; + std::map> authenticationMap_; + std::shared_ptr authRequestState_ = nullptr; + std::shared_ptr authRequestStateTemp_ = nullptr; + std::shared_ptr authResponseState_ = nullptr; + std::shared_ptr authRequestContext_; + std::shared_ptr authResponseContext_; + std::shared_ptr authMessageProcessor_; + std::shared_ptr timer_; + std::shared_ptr dmAbilityMgr_; + std::shared_ptr hiChainAuthConnector_; + bool isCryptoSupport_ = false; + bool isFinishOfLocal_ = true; + int32_t authTimes_ = 0; + int32_t action_ = USER_OPERATION_TYPE_CANCEL_AUTH; + std::shared_ptr authPtr_; + bool isAddingMember_ = false; + std::string importPkgName_ = ""; + std::string importAuthCode_ = ""; + PeerTargetId peerTargetId_; + std::string remoteDeviceId_ = ""; + std::string dmVersion_ = ""; + bool isAuthDevice_ = false; + bool isAuthenticateDevice_ = false; + int32_t authForm_ = DmAuthForm::ACROSS_ACCOUNT; + std::string remoteVersion_ = ""; + std::atomic authType_ = AUTH_TYPE_UNKNOW; + std::string remoteUdidHash_ = ""; + ProcessInfo processInfo_; + std::mutex srcReqMsgLock_; + bool isNeedProcCachedSrcReqMsg_ = false; + std::string srcReqMsg_ = ""; + int32_t authenticationType_ = USER_OPERATION_TYPE_ALLOW_AUTH; + DistributedDeviceProfile::LocalServiceInfo serviceInfoProfile_; + bool pincodeDialogEverShown_ = false; + std::string bundleName_ = ""; + std::mutex sessionKeyIdMutex_; + std::condition_variable sessionKeyIdCondition_; + std::map> sessionKeyIdAsyncResult_; + bool isWaitingJoinLnnCallback_ = false; + CleanNotifyCallback cleanNotifyCallback_{nullptr}; + std::mutex callerInfoMutex_; + DmBindCallerInfo callerInfo_; + bool callerInfoReady_ = false; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_MANAGER_H diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index f0cb9b39d..e9928b6c2 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -120,11 +120,10 @@ public: void RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback); void ClearSoftbusSessionCallback(); void PrepareSoftbusSessionCallback(); - void GetCallerInfo(DmBindCallerInfo &callerInfo); - void SetCallerInfo(const DmBindCallerInfo &callerInfo); protected: std::shared_ptr context_; + std::mutex bindParamMutex_; std::map bindParam_; PeerTargetId targetId_; @@ -146,6 +145,7 @@ private: int32_t AuthenticateDevice(const std::string &sessionName, int32_t authType, const std::string &deviceId, const std::string &extra); void ParseUltrasonicSide(const JsonObject &jsonObject); + void GetBindCallerInfo(); }; class AuthSrcManager : public AuthManager { diff --git a/services/implementation/include/authentication_v2/auth_manager.h.bak b/services/implementation/include/authentication_v2/auth_manager.h.bak new file mode 100644 index 000000000..f0cb9b39d --- /dev/null +++ b/services/implementation/include/authentication_v2/auth_manager.h.bak @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2025 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_AUTH_MANAGER_V2_H +#define OHOS_DM_AUTH_MANAGER_V2_H + +#include + +#include "auth_ui_state_manager.h" +#include "dm_auth_manager_base.h" +#include "hichain_auth_connector.h" +#include "hichain_connector.h" +#include "json_object.h" +#include "softbus_connector.h" +#include "softbus_session.h" + +namespace OHOS { +namespace DistributedHardware { +struct DmAuthContext; + +class AuthManager : public AuthManagerBase, + public std::enable_shared_from_this { +public: + AuthManager(std::shared_ptr softbusConnector, + std::shared_ptr hiChainConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector); + virtual ~AuthManager(); + + // External API begin + /** + * @tc.name: DmAuthManager::OnUserOperation + * @tc.desc: User Operation of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + virtual int32_t OnUserOperation(int32_t action, const std::string ¶ms) = 0; + + /** + * @tc.name: AuthManager::GeneratePincode + * @tc.desc: Generate Pincode of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + int32_t BindTarget(const std::string &sessionName, const PeerTargetId &targetId, + const std::map &bindParam, int sessionId, uint64_t logicalSessionId); + + /** + * @tc.name: AuthManager::OnUserOperation + * @tc.desc: User Operation of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + std::string GeneratePincode(); + + /** + * @tc.name: AuthManager::ImportAuthCode + * @tc.desc: Import auth code + * @tc.type: FUNC + */ + int32_t ImportAuthCode(const std::string &sessionName, const std::string &authCode); + + /** + * @tc.name: AuthManager::RegisterUiStateCallback + * @tc.desc: Register ui state callback + * @tc.type: FUNC + */ + int32_t RegisterUiStateCallback(const std::string sessionName); + + /** + * @tc.name: AuthManager::UnRegisterUiStateCallback + * @tc.desc: Unregister ui state callback + * @tc.type: FUNC + */ + int32_t UnRegisterUiStateCallback(const std::string sessionName); + + /** + * @tc.name: AuthManager::UnAuthenticateDevice + * @tc.desc: UnAuthenticate Device of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + int32_t UnAuthenticateDevice(const std::string &sessionName, const std::string &udid, int32_t bindLevel); + + /** + * @brief UnBind device. + * @param sessionName package name. + * @param deviceId device id. + * @return Return 0 if success. + */ + int32_t UnBindDevice(const std::string &sessionName, const std::string &udid, + int32_t bindLevel, const std::string &extra); + + void HandleDeviceNotTrust(const std::string &udid); + + int32_t RegisterAuthenticationType(int32_t authenticationType); + void OnScreenLocked(); + int32_t StopAuthenticateDevice(const std::string &sessionName); + // External API begin end + + // Internal API begin + void SetAuthContext(std::shared_ptr context); + std::shared_ptr GetAuthContext(); + static bool IsHmlSessionType(const std::string &sessionType); + int32_t GetTokenIdByBundleName(int32_t userId, std::string &bundleName, int64_t &tokenId); + void GetBindTargetParams(std::string &pkgName, PeerTargetId &targetId, + std::map &bindParam); + void SetBindTargetParams(const PeerTargetId &targetId); + int32_t GetReason(); + + // Internal API end + void RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback); + void ClearSoftbusSessionCallback(); + void PrepareSoftbusSessionCallback(); + void GetCallerInfo(DmBindCallerInfo &callerInfo); + void SetCallerInfo(const DmBindCallerInfo &callerInfo); + +protected: + std::shared_ptr context_; + std::map bindParam_; + PeerTargetId targetId_; + + int32_t GetPinCode(std::string &code); + void GetRemoteDeviceId(std::string &deviceId); +private: + void ParseHmlInfoInJsonObject(const JsonObject &jsonObject); + void ParseJsonObject(const JsonObject &jsonObject); + void GetAuthParam(const std::string &sessionName, int32_t authType, + const std::string &deviceId, const std::string &extra); + std::string GetBundleName(const JsonObject &jsonObject); + void SetAuthType(int32_t authType); + bool IsAuthTypeSupported(const int32_t &authType); + bool IsAuthCodeReady(const std::string &sessionName); + int32_t CheckAuthParamVaild(const std::string &sessionName, int32_t authType, + const std::string &deviceId, const std::string &extra); + void InitAuthState(const std::string &sessionName, int32_t authType, + const std::string &deviceId, const std::string &extra); + int32_t AuthenticateDevice(const std::string &sessionName, int32_t authType, + const std::string &deviceId, const std::string &extra); + void ParseUltrasonicSide(const JsonObject &jsonObject); +}; + +class AuthSrcManager : public AuthManager { +public: + AuthSrcManager(std::shared_ptr softbusConnector, + std::shared_ptr hiChainConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector); + virtual ~AuthSrcManager() override = default; + + // External API begin + int32_t OnUserOperation(int32_t action, const std::string ¶ms) override; + // External API end + + // IDmDeviceAuthCallback implement begin + bool AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) override; + void AuthDeviceError(int64_t requestId, int32_t errorCode) override; + void AuthDeviceFinish(int64_t requestId) override; + void AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) override; + char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) override; + // IDmDeviceAuthCallback implement end + + // ISoftbusSessionCallback implement begin + void OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) override; + void OnSessionClosed(int32_t sessionId) override; + void OnSessionDisable() override; + void OnDataReceived(int32_t sessionId, std::string message) override; + + bool GetIsCryptoSupport() override; + // ISoftbusSessionCallback implement end +}; + +class AuthSinkManager : public AuthManager { +public: + AuthSinkManager(std::shared_ptr softbusConnector, + std::shared_ptr hiChainConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector); + virtual ~AuthSinkManager() override = default; + + // External API begin + int32_t OnUserOperation(int32_t action, const std::string ¶ms) override; + // External API end + + // IDmDeviceAuthCallback implement begin + bool AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) override; + void AuthDeviceError(int64_t requestId, int32_t errorCode) override; + void AuthDeviceFinish(int64_t requestId) override; + void AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) override; + char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) override; + // IDmDeviceAuthCallback implement end + + // ISoftbusSessionCallback implement begin + void OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) override; + void OnSessionClosed(int32_t sessionId) override; + void OnDataReceived(int32_t sessionId, std::string message) override; + bool GetIsCryptoSupport() override; + // ISoftbusSessionCallback implement end +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_MANAGER_V2_H \ No newline at end of file diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index e54240926..c3336ecf2 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -76,13 +76,6 @@ enum DmAuthScope { DM_AUTH_SCOPE_APP, }; -enum DmRole { - DM_ROLE_UNKNOWN = 0, - DM_ROLE_USER = 1, - DM_ROLE_SA, - DM_ROLE_FA, -}; - enum { DM_UNKNOWN_TYPE = 0, DM_SAME_ACCOUNT_TYPE = 1, diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h.bak b/services/implementation/include/authentication_v2/dm_auth_context.h.bak new file mode 100644 index 000000000..e54240926 --- /dev/null +++ b/services/implementation/include/authentication_v2/dm_auth_context.h.bak @@ -0,0 +1,257 @@ +/* + * Copyright (c) 2025 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_AUTH_CONTEXT_V2_H +#define OHOS_DM_AUTH_CONTEXT_V2_H +#include +#include + +#include "access_control_profile.h" +#include "authentication.h" +#include "auth_ui_state_manager.h" +#include "dm_ability_manager.h" +#include "dm_anonymous.h" +#include "dm_auth_message_processor.h" +#include "dm_constants.h" +#include "dm_device_info.h" +#include "dm_log.h" +#include "dm_timer.h" +#include "hichain_auth_connector.h" +#include "hichain_connector.h" +#include "softbus_connector.h" +#include "softbus_session.h" + +namespace OHOS { +namespace DistributedHardware { + +class DmAuthStateMachine; +class DmAuthMessageProcessor; + +using CleanNotifyCallback = std::function; + +// PIN Code Authentication Type +enum DmAuthType : int32_t { + AUTH_TYPE_CRE = 0, + AUTH_TYPE_PIN, // Input PIN code + AUTH_TYPE_QR_CODE, // Not used in the new protocol + AUTH_TYPE_NFC, + AUTH_TYPE_NO_INTER_ACTION, // Not used in the new protocol + AUTH_TYPE_IMPORT_AUTH_CODE, // Import PIN code + AUTH_TYPE_PIN_ULTRASONIC, // Ultrasonic PIN code + AUTH_TYPE_UNKNOW, // Not used in the new protocol +}; + +enum DmAuthDirection { + DM_AUTH_SOURCE = 0, + DM_AUTH_SINK, +}; + +enum DmBindType { + DM_AUTH_USERID = 1, + DM_AUTH_SYSTEM_SERVICE, + DM_AUTH_APP_SERVICE, + DM_AUTH_DEVICEID, +}; + +enum DmAuthSide { + DM_AUTH_LOCAL_SIDE = 0, + DM_AUTH_REMOTE_SIDE, +}; + +enum DmAuthScope { + DM_AUTH_SCOPE_DEVICE = 1, + DM_AUTH_SCOPE_USER, + DM_AUTH_SCOPE_APP, +}; + +enum DmRole { + DM_ROLE_UNKNOWN = 0, + DM_ROLE_USER = 1, + DM_ROLE_SA, + DM_ROLE_FA, +}; + +enum { + DM_UNKNOWN_TYPE = 0, + DM_SAME_ACCOUNT_TYPE = 1, + DM_SHARE_TYPE = 2, + DM_POINT_TO_POINT_TYPE = 256, + DM_SAME_GROUP_TYPE = 3, +}; + +enum DmUltrasonicInfo { + // Forward means the pincode is generated at sink side, then send by ultrasonic from sink to source side. + DM_Ultrasonic_Forward = 0, + // Reverse means the pincode is generated at source side, then send by ultrasonic from source to sink side. + DM_Ultrasonic_Reverse = 1, + DM_Ultrasonic_Invalid = 2, +}; + +// Used for one-touch pairing +struct DmPeerTargetAddress { + // directly establish a Bluetooth connection + std::string peerBrMacAddress; + std::string peerBleMacAddress; + std::string peerWifiMacAddress; + std::string peerActionMacAddress; + + std::string peerWifiChannel; + std::string peerWifiIp; + uint16_t peerWifiPort; +}; + +struct DmPeerTarget { + DmBindType peerType; + std::string peerDeviceId; + int64_t peerServiceId; + int64_t peerSaTokenId; + std::string peerBundleName; + DmPeerTargetAddress peerTargetAddress; +}; + +struct DmAccess { + std::string deviceName; + int32_t deviceType; // Device types such as PC, mobile, watch, large screen, etc. + std::string deviceId; + std::string deviceIdHash; + std::string addr; + int32_t userId{-1}; + int32_t displayId{-1}; // Logical screen ID, used for query userId + std::string accountId; + std::string accountIdHash; + int64_t tokenId; + std::string tokenIdHash; + std::string networkId; + std::string bundleName; // Stores the bundleName, HAP -> bundleName in BMS, SA -> process name + std::string pkgName; // store pkgName set by client + std::string language; + int64_t serviceId; // Reserved field, to be used in HM 6.0 + std::string accesserHapSignature; + int32_t bindLevel; + int32_t lnnBindType; + int32_t transmitBindType; + std::string lnnCredentialId; // User-level credential ID + std::string transmitCredentialId; // Application-level credential ID + std::string lnnPublicKey; // User-level public key + std::string transmitPublicKey; // Application-level public key + std::vector bindType; // such as DM_AUTH_CREDENTIAL_ACCOUNT_RELATED + std::string publicKey; + int32_t status; // Indicates whether the service is in the foreground or background + int32_t sessionKeyId; // Used as key delivery material, retrieves the SK from the bus + int32_t transmitSessionKeyId; // Permanent application SKID on this end, returned by DP for ACL updates and aging + int32_t lnnSessionKeyId{0}; // Permanent user SKID on this end, returned by DP for ACL updates and aging + int64_t transmitSkTimeStamp; // Used for aging, time is 2 days, application-level credential timestamp + int64_t lnnSkTimeStamp{0}; // Used for aging, time is 2 days, user-level credential timestamp + int64_t skTimeStamp; // Used for aging, time is 2 days + bool isAuthed; + bool isOnline; + bool isGenerateLnnCredential{true}; + bool isPutLnnAcl{true}; + std::string dmVersion; + std::string edition; // Used for compatibility before version 5.1.0, assists in version negotiation + std::string aclTypeList; // Trust relationship list, used for data aging, KV format + std::string credTypeList; + std::string aclStrList; + std::map credentialInfos; // map: , cred is string tranformed by json + std::map aclProfiles; + // construct for old version compatible start + // In the scenario of compatibility between the new and old protocols, it is necessary to + // send both the new and old protocol messages simultaneously in the 80 message when + // authType == import. Therefore, it is required to define these fields for compatibility processing. + std::string accountGroupIdHash; + int32_t oldBindLevel; + std::string oldBundleName; + // construct for old version compatible end + std::string extraInfo; // Expandable field, JSON format, KV structure +}; + +struct DmAuthContext { + bool isOnline; + uint64_t logicalSessionId; + DmMessageType msgType; + int32_t sessionId; + int64_t requestId; // HiChain authentication ID + DMLocalServiceInfoAuthBoxType authBoxType{DMLocalServiceInfoAuthBoxType::STATE3}; // Authentication box type + UiAction pinInputResult; + // Authorization result (using 0, 1, 6, representing single use, cancel, and always trust, enum UiAction) + UiAction confirmOperation{UiAction::USER_OPERATION_TYPE_ALLOW_AUTH}; + DmAuthType authType{DmAuthType::AUTH_TYPE_PIN}; // PIN code, ultrasonic PIN code, imported PIN code + std::vector authTypeList; + uint32_t currentAuthTypeIdx{0}; + int32_t inputPinAuthFailTimes{0}; // Number of failed PIN authentication attempts, exceeding 3 results in failure + std::string pinCode{""}; + bool serviceInfoFound{false}; + // Link delay release time, does not automatically disconnect after + // authorization (used for specific business needs), reserved field + int32_t connDelayCloseTime; + int32_t reason{DM_OK}; + int32_t reply; + int32_t state; + int32_t hmlActionId = 0; + bool authenticating; // Indicator whether authentication is in progress + bool successFinished{false}; + bool isAppCredentialVerified{false}; // Whether the application credential has been verified + bool hmlEnable160M{false}; + std::string pkgName; // Business-provided identifier, custom-defined by business, carries risk of spoofing + std::string pkgLabel; + std::string importCodeBundleName; // Bundle name for imported PIN code + std::string appThumbnail; // Application thumbnail + // Description of the operation this binding is used for, displayed in authorization dialog + std::string appOperation; + // Custom business field, provides detailed information to the user about this binding operation + std::string customData; + std::string connSessionType; + std::string extraInfo; // Expandable field, key-value structure + DmAuthDirection direction; // Indicator of authentication direction + ProcessInfo processInfo; + DmPeerTarget peerTarget; + DmUltrasonicInfo ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Forward; // Ultrasonic information + DmAccess accesser; + DmAccess accessee; + std::multimap proxy; // Multimap where the key is the accessor and the value is the accesssee + + std::shared_ptr authStateMachine; + std::shared_ptr authUiStateMgr; + std::shared_ptr hiChainConnector; + std::shared_ptr hiChainAuthConnector; + std::shared_ptr authMessageProcessor; + std::shared_ptr softbusConnector; + std::shared_ptr listener; + std::shared_ptr authPtr; // Pointer to authentication interface + std::shared_ptr timer; + std::string transmitData; // Data returned from onTransmit function + std::string importPkgName = ""; + std::string importAuthCode = ""; + std::map> authenticationMap; + PeerTargetId peerTargetId; + bool pinNegotiateStarted{false}; + bool isAuthenticateDevice{false}; // Whether device authentication is in progress + bool needBind{true}; + bool needAgreeCredential{true}; + bool needAuth{true}; + + CleanNotifyCallback cleanNotifyCallback{nullptr}; + + std::string GetDeviceId(DmAuthSide side); + int32_t GetUserId(DmAuthSide side); + std::string GetCredentialId(DmAuthSide side, DmAuthScope authorizedScope); + std::string GetPublicKey(DmAuthSide side, DmAuthScope authorizedScope); + void SetCredentialId(DmAuthSide side, DmAuthScope authorizedScope, const std::string &credentialId); + void SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope, const std::string &publicKey); + std::string GetAccountId(DmAuthSide side); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_CONTEXT_V2_H diff --git a/services/implementation/include/authentication_v2/dm_auth_manager_base.h b/services/implementation/include/authentication_v2/dm_auth_manager_base.h index 2ceff22d2..708aad02e 100644 --- a/services/implementation/include/authentication_v2/dm_auth_manager_base.h +++ b/services/implementation/include/authentication_v2/dm_auth_manager_base.h @@ -102,15 +102,15 @@ extern const int32_t DM_AUTH_TYPE_MIN; extern const int32_t MIN_PIN_TOKEN; extern const int32_t MAX_PIN_TOKEN; -typedef struct DmBindCallerInfo { - int32_t userId = -1; - int32_t tokenId = -1; - std::string bundleName = ""; - std::string hostPkgLabel = ""; -} DmBindCallerInfo; - using CleanNotifyCallback = std::function; +enum DmRole { + DM_ROLE_UNKNOWN = 0, + DM_ROLE_USER = 1, + DM_ROLE_SA, + DM_ROLE_FA, +}; + class AuthManagerBase : public ISoftbusSessionCallback, public ISoftbusConnectorCallback, public IHiChainConnectorCallback, @@ -242,8 +242,7 @@ public: void EnableInsensibleSwitching(); void DisableInsensibleSwitching(); int32_t ParseAuthType(const std::map &bindParam, int32_t &authType); - virtual void GetCallerInfo(DmBindCallerInfo &callerInfo) = 0; - virtual void SetCallerInfo(const DmBindCallerInfo &callerInfo) = 0; + static bool CheckProcessNameInWhiteList(const std::string &processName); protected: bool NeedInsensibleSwitching(); bool isTransferReady_{true}; diff --git a/services/implementation/include/authentication_v2/dm_auth_manager_base.h.bak b/services/implementation/include/authentication_v2/dm_auth_manager_base.h.bak new file mode 100644 index 000000000..2ceff22d2 --- /dev/null +++ b/services/implementation/include/authentication_v2/dm_auth_manager_base.h.bak @@ -0,0 +1,258 @@ +/* + * Copyright (c) 2025 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_AUTH_ADAPTER_V2_H +#define OHOS_DM_AUTH_ADAPTER_V2_H + +#include +#include +#include +#include + +#include "softbus_session_callback.h" +#include "softbus_connector_callback.h" +#include "hichain_connector_callback.h" +#include "auth_request_state.h" +#include "auth_response_state.h" +#include "dm_device_info.h" + +namespace OHOS { +namespace DistributedHardware { +extern const char* TAG_DMVERSION; +extern const char* TAG_DM_VERSION_V2; // compatible for new and old protocol +extern const char* TAG_EDITION; +extern const char* TAG_DATA; +extern const char* TAG_DATA_LEN; +extern const char* TAG_BUNDLE_NAME; +extern const char* TAG_BUNDLE_NAME_V2; +extern const char* TAG_PEER_BUNDLE_NAME; +extern const char* TAG_PEER_BUNDLE_NAME_V2; +extern const char* TAG_PEER_PKG_NAME; +extern const char* TAG_BIND_LEVEL; +extern const char* TAG_REPLY; +extern const char* TAG_APP_THUMBNAIL2; // Naming Add 2 to resolve conflicts with TAG_APP_THUMBNAIL +extern const char* TAG_AUTH_FINISH; +extern const char* TAG_LOCAL_USERID; +extern const char* TAG_LOCAL_DEVICE_ID; +extern const char* TAG_IDENTICAL_ACCOUNT; +extern const char* TAG_ACCOUNT_GROUPID; +extern const char* TAG_HAVE_CREDENTIAL; +extern const char* TAG_ISONLINE; +extern const char* TAG_AUTHED; +extern const char* TAG_LOCAL_ACCOUNTID; +extern const char* TAG_TOKENID; +extern const char* TAG_HOST_PKGLABEL; +extern const char* TAG_REMOTE_DEVICE_NAME; +extern const char* TAG_HOST; + +extern const char* APP_OPERATION_KEY; +extern const char* TARGET_PKG_NAME_KEY; +extern const char* CUSTOM_DESCRIPTION_KEY; +extern const char* CANCEL_DISPLAY_KEY; +extern const char* BUNDLE_NAME_KEY; + +extern const char* AUTHENTICATE_TIMEOUT_TASK; +extern const char* NEGOTIATE_TIMEOUT_TASK; +extern const char* CONFIRM_TIMEOUT_TASK; +extern const char* INPUT_TIMEOUT_TASK; +extern const char* SESSION_HEARTBEAT_TIMEOUT_TASK; +extern const char* WAIT_REQUEST_TIMEOUT_TASK; +extern const char* AUTH_DEVICE_TIMEOUT_TASK; +extern const char* WAIT_PIN_AUTH_TIMEOUT_TASK; +extern const char* WAIT_NEGOTIATE_TIMEOUT_TASK; +extern const char* ADD_TIMEOUT_TASK; +extern const char* WAIT_SESSION_CLOSE_TIMEOUT_TASK; +extern const char* CLOSE_SESSION_TASK_SEPARATOR; + +extern const int32_t AUTHENTICATE_TIMEOUT; +extern const int32_t CONFIRM_TIMEOUT; +extern const int32_t NEGOTIATE_TIMEOUT; +extern const int32_t INPUT_TIMEOUT; +extern const int32_t ADD_TIMEOUT; +extern const int32_t WAIT_NEGOTIATE_TIMEOUT; +extern const int32_t WAIT_REQUEST_TIMEOUT; +extern const int32_t CLONE_AUTHENTICATE_TIMEOUT; +extern const int32_t CLONE_CONFIRM_TIMEOUT; +extern const int32_t CLONE_NEGOTIATE_TIMEOUT; +extern const int32_t CLONE_ADD_TIMEOUT; +extern const char* GET_ULTRASONIC_PIN_TIMEOUT_TASK; +extern const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT; +extern const int32_t CLONE_WAIT_REQUEST_TIMEOUT; +extern const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT; +extern const int32_t CLONE_PIN_AUTH_TIMEOUT; +extern const int32_t HML_SESSION_TIMEOUT; +extern const int32_t SESSION_HEARTBEAT_TIMEOUT; +extern const int32_t PIN_AUTH_TIMEOUT; +extern const int32_t EVENT_TIMEOUT; + +extern const int32_t DM_AUTH_TYPE_MAX; +extern const int32_t DM_AUTH_TYPE_MIN; +extern const int32_t MIN_PIN_TOKEN; +extern const int32_t MAX_PIN_TOKEN; + +typedef struct DmBindCallerInfo { + int32_t userId = -1; + int32_t tokenId = -1; + std::string bundleName = ""; + std::string hostPkgLabel = ""; +} DmBindCallerInfo; + +using CleanNotifyCallback = std::function; + +class AuthManagerBase : public ISoftbusSessionCallback, + public ISoftbusConnectorCallback, + public IHiChainConnectorCallback, + public IDmDeviceAuthCallback { +public: + virtual int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, + const std::string &extra); + + virtual int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel); + + virtual int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel, const std::string &extra); + + virtual void OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result); + + virtual void OnSessionClosed(const int32_t sessionId); + + virtual void OnSessionDisable(); + + virtual void OnDataReceived(const int32_t sessionId, const std::string message); + + virtual void OnAuthDeviceDataReceived(int32_t sessionId, std::string message); + + virtual void OnSoftbusJoinLNNResult(const int32_t sessionId, const char *networkId, int32_t result); + + virtual void OnGroupCreated(int64_t requestId, const std::string &groupId); + + virtual void OnMemberJoin(int64_t requestId, int32_t status); + + virtual int32_t EstablishAuthChannel(const std::string &deviceId); + + virtual void StartNegotiate(const int32_t &sessionId); + + virtual void RespNegotiate(const int32_t &sessionId); + + virtual void SendAuthRequest(const int32_t &sessionId); + + virtual int32_t StartAuthProcess(const int32_t &action); + + virtual void StartRespAuthProcess(); + + virtual int32_t CreateGroup(); + + virtual int32_t ProcessPincode(const std::string &pinCode); + + virtual std::string GetConnectAddr(std::string deviceId); + + virtual int32_t JoinNetwork(); + + virtual void AuthenticateFinish(); + + virtual bool GetIsCryptoSupport(); + + virtual int32_t SetAuthRequestState(std::shared_ptr authRequestState); + + virtual int32_t SetAuthResponseState(std::shared_ptr authResponseState); + + virtual int32_t GetPinCode(std::string &code); + + virtual std::string GenerateGroupName(); + + virtual void HandleAuthenticateTimeout(std::string name); + + virtual std::string GeneratePincode(); + + virtual void ShowConfigDialog(); + + virtual void ShowAuthInfoDialog(bool authDeviceError = false); + + virtual void ShowStartAuthDialog(); + + virtual int32_t OnUserOperation(int32_t action, const std::string ¶ms); + + virtual int32_t SetPageId(int32_t pageId); + + virtual int32_t SetReasonAndFinish(int32_t reason, int32_t state); + + virtual bool IsIdenticalAccount(); + + virtual int32_t RegisterUiStateCallback(const std::string pkgName); + + virtual int32_t UnRegisterUiStateCallback(const std::string pkgName); + + virtual int32_t ImportAuthCode(const std::string &pkgName, const std::string &authCode); + + virtual int32_t BindTarget(const std::string &pkgName, const PeerTargetId &targetId, + const std::map &bindParam, int sessionId, uint64_t logicalSessionId); + + virtual int32_t RegisterAuthenticationType(int32_t authenticationType); + + virtual int32_t StopAuthenticateDevice(const std::string &pkgName); + + virtual void OnScreenLocked() = 0; + + virtual void HandleDeviceNotTrust(const std::string &udid) = 0; + + virtual int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); + + // New interface added in version 5.1.0 + virtual int32_t GetReason(); + // When switching from the new protocol to the old protocol, the previous parameters + // need to be obtained for use by the old protocol + virtual void GetBindTargetParams(std::string &pkgName, PeerTargetId &targetId, + std::map &bindParam); + + virtual void SetBindTargetParams(const PeerTargetId &targetId); + // Register the notification function when the auth_mgr event is complete. + virtual void RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback); + + /** + * @brief Classical authMgr is global, single-frame collabration with double-frame device + * need it. If we start bind with single-frame device, we need clear dsoftbus callback + * to avoid the classical authMgr affect the single to single logical. + * For new protocal, the source and sink authMgr lifecycle obey the bind session, no need + * to process it. + */ + virtual void ClearSoftbusSessionCallback(); + /** + * @brief Classical authMgr is global, if we use classical logic, we need prepare the callback. + */ + virtual void PrepareSoftbusSessionCallback(); + + // Public functions + static std::string ConvertSrcVersion(const std::string &version, const std::string &edition); + static int32_t DmGetUserId(int32_t displayId); + static int32_t EndDream(); + bool IsTransferReady(); + void SetTransferReady(bool version); + void EnableInsensibleSwitching(); + void DisableInsensibleSwitching(); + int32_t ParseAuthType(const std::map &bindParam, int32_t &authType); + virtual void GetCallerInfo(DmBindCallerInfo &callerInfo) = 0; + virtual void SetCallerInfo(const DmBindCallerInfo &callerInfo) = 0; +protected: + bool NeedInsensibleSwitching(); + bool isTransferReady_{true}; + /** + For old protocol, when insensible switching is true, no new session needs to be created, + and the actual method 80 message is not sent. + */ + bool insensibleSwitching{false}; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_ADAPTER_V2_H diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 51ed72ec0..b01040a61 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -154,7 +154,6 @@ public: void SetAclExtraInfo(std::shared_ptr context); void SetAclInfo(std::shared_ptr context); int32_t GetAclBindType(std::shared_ptr context, std::string credId); - static bool CheckProcessNameInWhiteList(const std::string &processName); int32_t GetOutputState(const std::string &processName, int32_t state); int32_t GetOutputReplay(const std::string &processName, int32_t replay); static uint64_t GetSysTimeMs(); diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h.bak b/services/implementation/include/authentication_v2/dm_auth_state.h.bak new file mode 100644 index 000000000..51ed72ec0 --- /dev/null +++ b/services/implementation/include/authentication_v2/dm_auth_state.h.bak @@ -0,0 +1,509 @@ +/* + * Copyright (c) 2025 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_AUTH_STATE_V2_H +#define OHOS_DM_AUTH_STATE_V2_H +#define TYPE_TV_ID 0x9C + +#include + +#include "access_control_profile.h" +#include "dm_auth_context.h" + +namespace OHOS { +namespace DistributedHardware { +const char* const FILED_CRED_OWNER = "credOwner"; +const char* const FILED_DEVICE_ID = "deviceId"; +const char* const FILED_USER_ID = "userId"; +const char* const FILED_DEVICE_ID_HASH = "deviceIdHash"; +const char* const FILED_PEER_USER_SPACE_ID = "peerUserSpaceId"; +const char* const FILED_CRED_ID = "credId"; +const char* const FILED_CRED_TYPE = "credType"; +const char* const FILED_AUTHORIZED_SCOPE = "authorizedScope"; +const char* const FILED_AUTHORIZED_APP_LIST = "authorizedAppList"; +const char* const FILED_SUBJECT = "subject"; + +// State Types +enum class DmAuthStateType { + AUTH_IDLE_STATE = 0, // When the device is initialized + // source end state + AUTH_SRC_START_STATE = 1, // User triggers BindTarget + AUTH_SRC_NEGOTIATE_STATE = 2, // Receive softbus callback OnSessionOpened, send 80 message + AUTH_SRC_CONFIRM_STATE = 3, // Receive 90 authorization result message, send 100 message + AUTH_SRC_PIN_NEGOTIATE_START_STATE = 4, // Start negotiating PIN code, receive 110 authorization message + // or rollback or 90 jump + AUTH_SRC_PIN_INPUT_STATE = 5, // Enter PIN + AUTH_SRC_REVERSE_ULTRASONIC_START_STATE = 6, + AUTH_SRC_REVERSE_ULTRASONIC_DONE_STATE = 7, + AUTH_SRC_FORWARD_ULTRASONIC_START_STATE = 8, + AUTH_SRC_FORWARD_ULTRASONIC_DONE_STATE = 9, + AUTH_SRC_PIN_AUTH_START_STATE = 10, // Start authentication and send 120 message. + AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE = 11, // Receive 130 authentication PIN result message, send 121 message + AUTH_SRC_PIN_AUTH_DONE_STATE = 12, // Receive 131 authentication PIN result message, call processData + AUTH_SRC_CREDENTIAL_EXCHANGE_STATE = 13, // Trigger the Onfinish callback event and send a 140 message + AUTH_SRC_CREDENTIAL_AUTH_START_STATE = 14, // Received 150 encrypted messages, sent 160 messages + AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE = 15, // 收到170凭据认证报文,发送161报文 + AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE = 16, // Received 170 credential authentication message, sent 161 message + AUTH_SRC_DATA_SYNC_STATE = 17, // Received 190 message, sent 200 message + AUTH_SRC_FINISH_STATE = 18, // Received 201 message + + // sink end state + AUTH_SINK_START_STATE = 50, // Bus trigger OnSessionOpened + AUTH_SINK_NEGOTIATE_STATE = 51, // Received 80 trusted relationship negotiation message, send 90 message + AUTH_SINK_CONFIRM_STATE = 52, // Received 100 user authorization messages, sent 110 messages + AUTH_SINK_PIN_NEGOTIATE_START_STATE = 53, // Start negotiating PIN code, active migration or error rollback + AUTH_SINK_PIN_DISPLAY_STATE = 54, // Generate and display PIN + AUTH_SINK_REVERSE_ULTRASONIC_START_STATE = 55, + AUTH_SINK_REVERSE_ULTRASONIC_DONE_STATE = 56, + AUTH_SINK_FORWARD_ULTRASONIC_START_STATE = 57, + AUTH_SINK_FORWARD_ULTRASONIC_DONE_STATE = 58, + AUTH_SINK_PIN_AUTH_START_STATE = 59, // Receive 120 authentication PIN message, send 130 message + AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE = 60, // Received 121 authentication PIN message, send 131 message + AUTH_SINK_PIN_AUTH_DONE_STATE = 61, // Trigger the Onfinish callback event + AUTH_SINK_CREDENTIAL_EXCHANGE_STATE = 62, // Received 140 encrypted messages, sent 150 messages + AUTH_SINK_CREDENTIAL_AUTH_START_STATE = 63, // Receive 160 authentication message, send 170 message + AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE = 64, // Received 161 credential negotiation message, + AUTH_SINK_DATA_SYNC_STATE = 65, // Received 180 synchronization message, send 190 message + AUTH_SINK_FINISH_STATE = 66, // Received 200 end message, send 201 message +}; + +// Credential Addition Method +enum DmAuthCredentialAddMethod : uint8_t { + DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE = 1, // Generate + DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT, // Import +}; + +// Credential Subject +enum DmAuthCredentialSubject : uint8_t { + DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY = 1, // Main Control + DM_AUTH_CREDENTIAL_SUBJECT_SUPPLEMENT, // Accessories +}; + +// Credentials and account association +enum DmAuthCredentialAccountRelation : uint8_t { + DM_AUTH_CREDENTIAL_INVALID = 0, // Invalid + DM_AUTH_CREDENTIAL_ACCOUNT_RELATED = 1, // Account related + DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED = 2, // Account independent + DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS = 3, // Share +}; + +// Key Type +enum DmAuthKeyFormat : uint8_t { + DM_AUTH_KEY_FORMAT_SYMM_IMPORT = 1, // Symmetric key (supported only for import) + DM_AUTH_KEY_FORMAT_ASYMM_IMPORT, // Asymmetric key public key (supported only for import) + DM_AUTH_KEY_FORMAT_ASYMM_GENERATE, // Asymmetric key (supported only for generation) + DM_AUTH_KEY_FORMAT_X509, // X509 certificate +}; + +// Algorithm type +enum DmAuthAlgorithmType : uint8_t { + DM_AUTH_ALG_TYPE_AES256 = 1, // AES256 + DM_AUTH_ALG_TYPE_AES128, // AES128 + DM_AUTH_ALG_TYPE_P256, // P256 + DM_AUTH_ALG_TYPE_ED25519 // ED25519 +}; + +// Credential proof type +enum DmAuthCredentialProofType : uint8_t { + DM_AUTH_CREDENTIAL_PROOF_PSK = 1, // PSK + DM_AUTH_CREDENTIAL_PROOF_PKI, // PKI +}; + +enum DmCredType : uint8_t { + ACCOUNT_RELATED = 1, + ACCOUNT_UNRELATED, + ACCOUNT_ACROSS +}; + +enum DmAuthorizedScope : uint8_t { + SCOPE_DEVICE = 1, + SCOPE_USER, + SCOPE_APP, +}; + +enum DM_SUBJECT : uint8_t { + SUBJECT_PRIMARY = 1, + SUBJECT_SECONDARY, +}; + +class DmAuthState { +public: + virtual ~DmAuthState() {}; + virtual DmAuthStateType GetStateType() = 0; + virtual int32_t Action(std::shared_ptr context) = 0; + void SourceFinish(std::shared_ptr context); + void SinkFinish(std::shared_ptr context); + std::string GenerateBindResultContent(std::shared_ptr context); + static bool IsScreenLocked(); + static int32_t GetTaskTimeout(std::shared_ptr context, const char* taskName, int32_t taskTimeOut); + static void HandleAuthenticateTimeout(std::shared_ptr context, std::string name); + static bool IsImportAuthCodeCompatibility(DmAuthType authType); + + void SetAclExtraInfo(std::shared_ptr context); + void SetAclInfo(std::shared_ptr context); + int32_t GetAclBindType(std::shared_ptr context, std::string credId); + static bool CheckProcessNameInWhiteList(const std::string &processName); + int32_t GetOutputState(const std::string &processName, int32_t state); + int32_t GetOutputReplay(const std::string &processName, int32_t replay); + static uint64_t GetSysTimeMs(); + static void DeleteAcl(std::shared_ptr context, + const DistributedDeviceProfile::AccessControlProfile &profile); +protected: + bool NeedReqUserConfirm(std::shared_ptr context); + bool NeedAgreeCredential(std::shared_ptr context); + bool NeedAgreeAcl(std::shared_ptr context); + uint32_t GetCredType(std::shared_ptr context, const JsonItemObject &credInfo); + uint32_t GetCredentialType(std::shared_ptr context, const JsonItemObject &credInfo); + bool HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList); + void SetProcessInfo(std::shared_ptr context); +}; + +class AuthSrcConfirmState : public DmAuthState { +public: + virtual ~AuthSrcConfirmState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +private: + void NegotiateCredential(std::shared_ptr context, JsonObject &credTypeNegoRsult); + void NegotiateAcl(std::shared_ptr context, JsonObject &aclNegoRsult); + void GetSrcCredentialInfo(std::shared_ptr context, JsonObject &credInfo); + void GetIdenticalCredentialInfo(std::shared_ptr context, JsonObject &credInfo); + void GetShareCredentialInfo(std::shared_ptr context, JsonObject &credInfo); + void GetP2PCredentialInfo(std::shared_ptr context, JsonObject &credInfo); + void GetSrcAclInfo(std::shared_ptr context, JsonObject &credInfo, JsonObject &aclInfo); + void GetSrcAclInfoForP2P(std::shared_ptr context, + const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, JsonObject &aclInfo); + bool IdenticalAccountAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool ShareAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool Point2PointAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool LnnAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool CheckCredIdInAcl(std::shared_ptr context, + const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, uint32_t bindType); + void CheckCredIdInAclForP2P(std::shared_ptr context, std::string &credId, + const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, uint32_t bindType, + bool &checkResult); + void GetSrcCredType(std::shared_ptr context, JsonObject &credInfo, JsonObject &aclInfo, + JsonObject &credTypeJson); + void GetSrcCredTypeForP2P(std::shared_ptr context, const JsonItemObject &credObj, + JsonObject &aclInfo, JsonObject &credTypeJson, int32_t credType, std::vector &deleteCredInfo); +}; + +class AuthSinkStatePinAuthComm { +public: + static bool IsPinCodeValid(int32_t numpin); + static bool IsPinCodeValid(const std::string& strpin); + static bool IsAuthCodeReady(std::shared_ptr context); + static void GeneratePincode(std::shared_ptr context); + static int32_t ShowAuthInfoDialog(std::shared_ptr context); +private: + static void HandleSessionHeartbeat(std::shared_ptr context, std::string name); +}; + +class AuthSinkConfirmState : public DmAuthState { +public: + virtual ~AuthSinkConfirmState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +private: + void NegotiateCredential(std::shared_ptr context, JsonObject &credTypeNegoRsult); + void NegotiateAcl(std::shared_ptr context, JsonObject &aclNegoRsult); + int32_t ShowConfigDialog(std::shared_ptr context); + void ReadServiceInfo(std::shared_ptr context); + void MatchFallBackCandidateList(std::shared_ptr context, DmAuthType authType); + int32_t ProcessBindAuthorize(std::shared_ptr context); + int32_t ProcessNoBindAuthorize(std::shared_ptr context); + std::string GetCredIdByCredType(std::shared_ptr context, int32_t credType); +}; + +class AuthSrcPinNegotiateStartState : public DmAuthState { +public: + virtual ~AuthSrcPinNegotiateStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +private: + int32_t NegotiatePinAuth(std::shared_ptr context, bool firstTime); + int32_t ProcessCredAuth(std::shared_ptr context); + int32_t ProcessPinBind(std::shared_ptr context); + std::string GetCredIdByCredType(std::shared_ptr context, int32_t credType); +}; + +class AuthSrcPinInputState : public DmAuthState { +public: + virtual ~AuthSrcPinInputState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +private: + int32_t ShowStartAuthDialog(std::shared_ptr context); +}; + +class AuthSinkPinNegotiateStartState : public DmAuthState { +public: + virtual ~AuthSinkPinNegotiateStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkPinDisplayState : public DmAuthState { +public: + virtual ~AuthSinkPinDisplayState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcReverseUltrasonicStartState : public DmAuthState { +public: + virtual ~AuthSrcReverseUltrasonicStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcReverseUltrasonicDoneState : public DmAuthState { +public: + virtual ~AuthSrcReverseUltrasonicDoneState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcForwardUltrasonicStartState : public DmAuthState { +public: + virtual ~AuthSrcForwardUltrasonicStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcForwardUltrasonicDoneState : public DmAuthState { +public: + virtual ~AuthSrcForwardUltrasonicDoneState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkReverseUltrasonicStartState : public DmAuthState { +public: + virtual ~AuthSinkReverseUltrasonicStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkReverseUltrasonicDoneState : public DmAuthState { +public: + virtual ~AuthSinkReverseUltrasonicDoneState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkForwardUltrasonicStartState : public DmAuthState { +public: + virtual ~AuthSinkForwardUltrasonicStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkForwardUltrasonicDoneState : public DmAuthState { +public: + virtual ~AuthSinkForwardUltrasonicDoneState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcPinAuthStartState : public DmAuthState { +public: + virtual ~AuthSrcPinAuthStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +private: + int32_t ShowStartAuthDialog(std::shared_ptr context); // Display PIN input box to user +}; + +class AuthSinkPinAuthStartState : public DmAuthState { +public: + virtual ~AuthSinkPinAuthStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcPinAuthMsgNegotiateState : public DmAuthState { +public: + virtual ~AuthSrcPinAuthMsgNegotiateState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkPinAuthMsgNegotiateState : public DmAuthState { +public: + virtual ~AuthSinkPinAuthMsgNegotiateState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkPinAuthDoneState : public DmAuthState { +public: + virtual ~AuthSinkPinAuthDoneState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcPinAuthDoneState : public DmAuthState { +public: + virtual ~AuthSrcPinAuthDoneState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcStartState : public DmAuthState { +public: + virtual ~AuthSrcStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcNegotiateStateMachine : public DmAuthState { +public: + virtual ~AuthSrcNegotiateStateMachine() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +private: + std::string GetAccountGroupIdHash(std::shared_ptr context); +}; + +// Middle class encapsulates public interfaces related to business. +class AuthCredentialAgreeState : public DmAuthState { +public: + virtual ~AuthCredentialAgreeState() {}; +protected: + std::string CreateAuthParamsString(DmAuthScope authorizedScope, DmAuthCredentialAddMethod method, + const std::shared_ptr &authContext); + int32_t GenerateCredIdAndPublicKey(DmAuthScope authorizedScope, std::shared_ptr &authContext); + int32_t AgreeCredential(DmAuthScope authorizedScope, std::shared_ptr &authContext); +}; + +class AuthSrcCredentialExchangeState : public AuthCredentialAgreeState { +public: + virtual ~AuthSrcCredentialExchangeState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkCredentialExchangeState : public AuthCredentialAgreeState { +public: + virtual ~AuthSinkCredentialExchangeState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcCredentialAuthStartState : public AuthCredentialAgreeState { +public: + virtual ~AuthSrcCredentialAuthStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcCredentialAuthNegotiateState : public DmAuthState { +public: + virtual ~AuthSrcCredentialAuthNegotiateState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcCredentialAuthDoneState : public DmAuthState { +public: + virtual ~AuthSrcCredentialAuthDoneState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkCredentialAuthStartState : public DmAuthState { +public: + virtual ~AuthSinkCredentialAuthStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkCredentialAuthNegotiateState : public DmAuthState { +public: + virtual ~AuthSinkCredentialAuthNegotiateState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkNegotiateStateMachine : public DmAuthState { +public: + virtual ~AuthSinkNegotiateStateMachine() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; + +private: + int32_t RespQueryAcceseeIds(std::shared_ptr context); + int32_t ProcRespNegotiate5_1_0(std::shared_ptr context); + void GetSinkCredentialInfo(std::shared_ptr context, JsonObject &credInfo); + void GetIdenticalCredentialInfo(std::shared_ptr context, JsonObject &credInfo); + void GetShareCredentialInfo(std::shared_ptr context, JsonObject &credInfo); + void GetP2PCredentialInfo(std::shared_ptr context, JsonObject &credInfo); + void GetSinkAclInfo(std::shared_ptr context, JsonObject &credInfo, JsonObject &aclInfo); + void GetSinkAclInfoForP2P(std::shared_ptr context, + const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, JsonObject &aclInfo); + bool IdenticalAccountAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool ShareAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool Point2PointAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool LnnAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool CheckCredIdInAcl(std::shared_ptr context, + const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, uint32_t bindType); + void CheckCredIdInAclForP2P(std::shared_ptr context, std::string &credId, + const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, uint32_t bindType, + bool &checkResult); + void GetSinkCredType(std::shared_ptr context, JsonObject &credInfo, JsonObject &aclInfo, + JsonObject &credTypeJson); + void GetSinkCredTypeForP2P(std::shared_ptr context, const JsonItemObject &credObj, + JsonObject &aclInfo, JsonObject &credTypeJson, int32_t credType, std::vector &deleteCredInfo); +}; + +class AuthSinkDataSyncState : public DmAuthState { +public: + virtual ~AuthSinkDataSyncState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcDataSyncState : public DmAuthState { +public: + virtual ~AuthSrcDataSyncState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkFinishState : public DmAuthState { +public: + virtual ~AuthSinkFinishState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcFinishState : public DmAuthState { +public: + virtual ~AuthSrcFinishState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_STATE_V2_H \ No newline at end of file diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index ada8d9966..8371ea709 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -60,6 +60,14 @@ struct Config { int32_t authenticationType{0}; }; +typedef struct DmBindCallerInfo { + int32_t userId = -1; + int32_t tokenId = -1; + int32_t bindLevel = -1; + std::string bundleName = ""; + std::string hostPkgLabel = ""; +} DmBindCallerInfo; + class DeviceManagerServiceImpl : public IDeviceManagerServiceImpl { public: DeviceManagerServiceImpl(); @@ -243,6 +251,12 @@ private: void CheckIsLastLnnAcl(DistributedDeviceProfile::AccessControlProfile profile, DistributedDeviceProfile::AccessControlProfile delProfile, DmOfflineParam &lnnAclParam, bool &isLastLnnAcl, const std::string &localUdid); + void BindTargetImpl(uint64_t tokenId, const std::string &pkgName, const PeerTargetId &targetId, + const std::map &bindParam); + void GetBindCallerInfo(DmBindCallerInfo &bindCallerInfo); + void SetBindCallerInfoToBindParam(const std::map &bindParam, + std::map &bindParamTmp, const DmBindCallerInfo &bindCallerInfo); + std::string GetBundleLable(const std::string &bundleName); private: std::shared_ptr authMgr_; // Old protocol only std::mutex authMgrMtx_; diff --git a/services/implementation/include/device_manager_service_impl.h.bak b/services/implementation/include/device_manager_service_impl.h.bak new file mode 100644 index 000000000..ada8d9966 --- /dev/null +++ b/services/implementation/include/device_manager_service_impl.h.bak @@ -0,0 +1,284 @@ +/* + * Copyright (c) 2022-2025 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_SERVICE_IMPL_H +#define OHOS_DM_SERVICE_IMPL_H + +#include +#include +#include +#include +#include +#include + +#include "access_control_profile.h" +#include "auth_manager.h" +#include "dm_ability_manager.h" +#include "dm_auth_manager.h" +#include "dm_auth_manager_base.h" +#include "dm_common_event_manager.h" +#include "dm_credential_manager.h" +#include "dm_device_info.h" +#include "dm_device_state_manager.h" +#include "dm_single_instance.h" +#include "dp_inited_callback.h" +#include "idevice_manager_service_impl.h" +#include "ipc_skeleton.h" +#include "mine_hichain_connector.h" +#include "softbus_connector.h" +#include "deviceprofile_connector.h" + +namespace OHOS { +namespace DistributedHardware { + +class Session { +public: + Session(int sessionId, std::string deviceId); + int sessionId_; + std::string deviceId_; + std::string version_{""}; + std::atomic flag_{false}; // Only one session is allowed + std::set logicalSessionSet_; // Logical Session Set + std::atomic logicalSessionCnt_{0}; +}; + +struct Config { + std::string pkgName; + std::string authCode; + int32_t authenticationType{0}; +}; + +class DeviceManagerServiceImpl : public IDeviceManagerServiceImpl { +public: + DeviceManagerServiceImpl(); + virtual ~DeviceManagerServiceImpl(); + + int32_t Initialize(const std::shared_ptr &listener); + + void Release(); + + int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel); + + int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel); + + int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel, const std::string &extra); + + int32_t SetUserOperation(std::string &pkgName, int32_t action, const std::string ¶ms); + + void HandleDeviceStatusChange(DmDeviceState devState, DmDeviceInfo &devInfo); + + int OnSessionOpened(int sessionId, int result); + + void OnSessionClosed(int sessionId); + + void OnBytesReceived(int sessionId, const void *data, unsigned int dataLen); + + int OnPinHolderSessionOpened(int sessionId, int result); + + void OnPinHolderSessionClosed(int sessionId); + + void OnPinHolderBytesReceived(int sessionId, const void *data, unsigned int dataLen); + + int32_t RequestCredential(const std::string &reqJsonStr, std::string &returnJsonStr); + + int32_t ImportCredential(const std::string &pkgName, const std::string &credentialInfo); + + int32_t DeleteCredential(const std::string &pkgName, const std::string &deleteInfo); + + int32_t MineRequestCredential(const std::string &pkgName, std::string &returnJsonStr); + + int32_t CheckCredential(const std::string &pkgName, const std::string &reqJsonStr, + std::string &returnJsonStr); + + int32_t ImportCredential(const std::string &pkgName, const std::string &reqJsonStr, + std::string &returnJsonStr); + + int32_t DeleteCredential(const std::string &pkgName, const std::string &reqJsonStr, + std::string &returnJsonStr); + + int32_t RegisterCredentialCallback(const std::string &pkgName); + + int32_t UnRegisterCredentialCallback(const std::string &pkgName); + + int32_t NotifyEvent(const std::string &pkgName, const int32_t eventId, const std::string &event); + + int32_t GetGroupType(std::vector &deviceList); + + int32_t GetUdidHashByNetWorkId(const char *networkId, std::string &deviceId); + + void LoadHardwareFwkService(); + + int32_t RegisterUiStateCallback(const std::string &pkgName); + + int32_t UnRegisterUiStateCallback(const std::string &pkgName); + + int32_t ImportAuthCode(const std::string &pkgName, const std::string &authCode); + + int32_t ExportAuthCode(std::string &authCode); + + int32_t BindTarget(const std::string &pkgName, const PeerTargetId &targetId, + const std::map &bindParam); + + std::unordered_map GetAppTrustDeviceIdList(std::string pkgname); + + int32_t DpAclAdd(const std::string &udid); + int32_t IsSameAccount(const std::string &udid); + uint64_t GetTokenIdByNameAndDeviceId(std::string pkgName, std::string requestDeviceId); + void ScreenCommonEventCallback(std::string commonEventType); + int32_t CheckIsSameAccount(const DmAccessCaller &caller, const std::string &srcUdid, + const DmAccessCallee &callee, const std::string &sinkUdid); + int32_t CheckAccessControl(const DmAccessCaller &caller, const std::string &srcUdid, + const DmAccessCallee &callee, const std::string &sinkUdid); + void HandleDeviceNotTrust(const std::string &udid); + int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, + const std::string &udid, uint64_t &tokenId); + void HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, + int32_t peerUserId); + void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); + int32_t StopAuthenticateDevice(const std::string &pkgName); + void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); + int32_t SyncLocalAclListProcess(const DevUserInfo &localDevUserInfo, + const DevUserInfo &remoteDevUserInfo, std::string remoteAclList); + int32_t GetAclListHash(const DevUserInfo &localDevUserInfo, + const DevUserInfo &remoteDevUserInfo, std::string &aclList); + int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId); + void HandleSyncUserIdEvent(const std::vector &foregroundUserIds, + const std::vector &backgroundUserIds, const std::string &remoteUdid, bool isCheckUserStatus); + void HandleUserSwitched(const std::vector &deviceVec, int32_t currentUserId, + int32_t beforeUserId); + std::multimap GetDeviceIdAndUserId(int32_t localUserId); + int32_t SaveOnlineDeviceInfo(const std::vector &deviceList); + void HandleDeviceUnBind(int32_t bindType, const std::string &peerUdid, + const std::string &localUdid, int32_t localUserId, const std::string &localAccountId); + int32_t RegisterAuthenticationType(int32_t authenticationType); + void DeleteAlwaysAllowTimeOut(); + void CheckDeleteCredential(const std::string &remoteUdid, int32_t remoteUserId); + int32_t CheckDeviceInfoPermission(const std::string &localUdid, const std::string &peerDeviceId); + int32_t DeleteAcl(const std::string &sessionName, const std::string &localUdid, const std::string &remoteUdid, + int32_t bindLevel, const std::string &extra); + int32_t DeleteAclV2(const std::string &sessionName, const std::string &localUdid, const std::string &remoteUdid, + int32_t bindLevel, const std::string &extra); + static void NotifyCleanEvent(uint64_t logicalSessionId); + void HandleServiceUnBindEvent(int32_t userId, const std::string &remoteUdid, + int32_t remoteTokenId); + int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); + int32_t InitAndRegisterAuthMgr(bool isSrcSide, uint64_t tokenId, std::shared_ptr session, + uint64_t logicalSessionId); + void HandleCommonEventBroadCast(const std::vector &foregroundUserIds, + const std::vector &backgroundUserIds, const std::string &remoteUdid); +private: + int32_t PraseNotifyEventJson(const std::string &event, JsonObject &jsonObject); + std::string GetUdidHashByNetworkId(const std::string &networkId); + void HandleOffline(DmDeviceState devState, DmDeviceInfo &devInfo); + void HandleOnline(DmDeviceState devState, DmDeviceInfo &devInfo); + std::map GetDeviceIdAndBindLevel(int32_t userId); + std::multimap GetDeviceIdAndUserId(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 HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + int32_t tokenId, int32_t peerTokenId); + void HandleUserRemoved(std::vector peerUdids, int32_t preUserId); + void HandleRemoteUserRemoved(int32_t preUserId, const std::string &remoteUdid); + DmAuthForm ConvertBindTypeToAuthForm(int32_t bindType); + std::shared_ptr GetAuthMgr(); + std::shared_ptr GetAuthMgrByTokenId(uint64_t tokenId); + std::shared_ptr GetCurrentAuthMgr(); + void CreateGlobalClassicalAuthMgr(); + std::shared_ptr GetCurSession(int sessionId); + std::shared_ptr GetOrCreateSession(const std::string& deviceId, + const std::map &bindParam); + int32_t ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, + const std::map &bindParam); + std::shared_ptr GetConfigByTokenId(); + int OpenAuthSession(const std::string& deviceId, const std::map &bindParam); + int32_t ChangeUltrasonicTypeToPin(std::map &bindParam); + int32_t TransferByAuthType(int32_t authType, + std::shared_ptr curSession, std::shared_ptr authMgr, + std::map &bindParam, uint64_t logicalSessionId); + + std::shared_ptr GetAuthMgrByMessage(int32_t msgType, uint64_t logicalSessionId, + const JsonObject &jsonObject, std::shared_ptr curSession); + int32_t TransferOldAuthMgr(int32_t msgType, const JsonObject &jsonObject, + std::shared_ptr curSession); + int32_t TransferSrcOldAuthMgr(std::shared_ptr curSession); + int32_t TransferSinkOldAuthMgr(const JsonObject &jsonObject, std::shared_ptr curSession); + int32_t GetDeviceInfo(const PeerTargetId &targetId, std::string &addrType, std::string &deviceId, + std::shared_ptr deviceInfo, int32_t &index); + bool IsAuthNewVersion(int32_t bindLevel, std::string localUdid, std::string remoteUdid, + int32_t tokenId, int32_t userId); + void ImportConfig(std::shared_ptr authMgr, uint64_t tokenId); + + // Resource cleanup thread + void CleanWorker(); + // Stop the thread + void Stop(); + uint64_t FetchCleanEvent(); + void CleanAuthMgrByLogicalSessionId(uint64_t logicalSessionId); + void CleanSessionMap(int sessionId, std::shared_ptr session); + void CleanSessionMapByLogicalSessionId(uint64_t logicalSessionId); + int32_t DeleteAclForProcV2(const std::string &localUdid, uint32_t localTokenId, const std::string &remoteUdid, + int32_t bindLevel, const std::string &extra, int32_t userId); + int32_t DeleteSkCredAndAcl(const std::vector &acls); + void DeleteAclByTokenId(const int32_t accessTokenId, + std::vector &profiles, + std::map &delProfileMap, + std::vector> &delACLInfoVec, std::vector &userIdVec); + bool CheckLnnAcl(DistributedDeviceProfile::AccessControlProfile delProfile, + DistributedDeviceProfile::AccessControlProfile lastprofile); + void CheckIsLastLnnAcl(DistributedDeviceProfile::AccessControlProfile profile, + DistributedDeviceProfile::AccessControlProfile delProfile, DmOfflineParam &lnnAclParam, + bool &isLastLnnAcl, const std::string &localUdid); +private: + std::shared_ptr authMgr_; // Old protocol only + std::mutex authMgrMtx_; + std::map> authMgrMap_; // New protocol sharing + std::shared_ptr hiChainConnector_; + std::shared_ptr hiChainAuthConnector_; + std::shared_ptr deviceStateMgr_; + std::shared_ptr softbusConnector_; + std::shared_ptr abilityMgr_; + std::shared_ptr mineHiChainConnector_; + std::shared_ptr credentialMgr_; + std::shared_ptr commonEventManager_; + std::shared_ptr listener_; + std::atomic isCredentialType_ = false; + sptr dpInitedCallback_ = nullptr; + + // The session ID corresponding to the device ID, used only on the src side + std::map deviceId2SessionIdMap_; + std::map> sessionsMap_; // sessionId corresponds to the session object + std::map deviceIdMutexMap_; // Lock corresponding to the device ID + std::mutex mapMutex_; // sessionsMap_ lock + std::map sessionEnableCvMap_; // Condition variable corresponding to the session + std::map sessionEnableMutexMap_; // Lock corresponding to the session + std::map sessionEnableCvReadyMap_; // Condition variable ready flag + std::map logicalSessionId2TokenIdMap_; // The relationship between logicalSessionId and tokenId + std::map logicalSessionId2SessionIdMap_; // The relationship logicalSessionId and physical sessionId + std::map> configsMap_; // Import when authMgr is not initialized + + std::thread thread_; + std::atomic running_; + static std::condition_variable cleanEventCv_; + static std::mutex cleanEventMutex_; + static std::queue cleanEventQueue_; +}; + +using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_SERVICE_IMPL_H diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 450817663..78592272e 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -20,13 +20,10 @@ #include #include -#include "bundle_mgr_interface.h" -#include "bundle_mgr_proxy.h" #include "iservice_registry.h" #if defined(SUPPORT_SCREENLOCK) #include "screenlock_manager.h" #endif -#include "system_ability_definition.h" #include "app_manager.h" #include "auth_message_processor.h" @@ -231,25 +228,6 @@ bool DmAuthManager::CheckHmlParamValid(JsonObject &jsonObject) return true; } -bool DmAuthManager::CheckProcessNameInWhiteList(const std::string &processName) -{ - LOGI("DmAuthManager::CheckProcessNameInWhiteList start"); - if (processName.empty()) { - LOGE("processName is empty"); - return false; - } - uint16_t index = 0; - for (; index < PROCESS_NAME_WHITE_LIST_NUM; ++index) { - std::string whitePkgName(PROCESS_NAME_WHITE_LIST[index]); - if (processName == whitePkgName) { - LOGI("processName = %{public}s in whiteList.", processName.c_str()); - return true; - } - } - LOGI("CheckProcessNameInWhiteList: %{public}s invalid.", processName.c_str()); - return false; -} - void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra) { @@ -265,7 +243,8 @@ void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, authRequestContext_->deviceId = deviceId; authRequestContext_->addr = deviceId; authRequestContext_->dmVersion = DM_VERSION_5_0_5; - authRequestContext_->localAccountId = + authRequestContext_->localUserId = MultipleUserConnector::GetFirstForegroundUserId(); + authRequestContext_->localAccountId = MultipleUserConnector::GetFirstForegroundUserId(); MultipleUserConnector::GetOhosAccountIdByUserId(authRequestContext_->localUserId); authRequestContext_->isOnline = false; authRequestContext_->authed = !authRequestContext_->bindType.empty(); @@ -277,7 +256,6 @@ void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, } ParseJsonObject(jsonObject); authRequestContext_->token = std::to_string(GenRandInt(MIN_PIN_TOKEN, MAX_PIN_TOKEN)); - authRequestContext_->bindLevel = GetBindLevel(authRequestContext_->bindLevel); } void DmAuthManager::ParseJsonObject(JsonObject &jsonObject) @@ -375,7 +353,7 @@ void DmAuthManager::InitAuthState(const std::string &pkgName, int32_t authType, LOGE("extra string not a json type."); return; } - GetCallerInfo(pkgName, jsonObject); + GetAuthParam(pkgName, authType, deviceId, extra); authMessageProcessor_->SetRequestContext(authRequestContext_); authRequestState_ = std::make_shared(); @@ -403,12 +381,10 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au LOGE("CheckAuthParamVaildExtra failed, param is invaild."); return ret; } + processInfo_.pkgName = pkgName; InitAuthState(pkgName, authType, deviceId, extra); + GetBindCallerInfo(); isAuthenticateDevice_ = true; - int32_t userId = -1; - MultipleUserConnector::GetCallerUserId(userId); - processInfo_.pkgName = pkgName; - processInfo_.userId = userId; if (authType == AUTH_TYPE_CRE) { LOGI("DmAuthManager::AuthenticateDevice for credential type, joinLNN directly."); softbusConnector_->JoinLnn(deviceId, true); @@ -1511,7 +1487,6 @@ void DmAuthManager::AuthenticateFinish() isAddingMember_ = false; isAuthenticateDevice_ = false; isAuthDevice_ = false; - ClearCallerInfo(); if (DeviceProfileConnector::GetInstance().GetTrustNumber(remoteDeviceId_) >= 1 && CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && softbusConnector_->CheckIsOnline(remoteDeviceId_) && authResponseContext_->isFinish) { @@ -2072,6 +2047,10 @@ int32_t DmAuthManager::BindTarget(const std::string &pkgName, const PeerTargetId if (bindParam.count(PARAM_KEY_CONN_ADDR_TYPE) != 0) { addrType = bindParam.at(PARAM_KEY_CONN_ADDR_TYPE); } + { + std::lock_guard lock(bindParamMutex_); + bindParam_ = bindParam; + } if (ParseConnectAddr(targetId, deviceId, addrType) == DM_OK) { return AuthenticateDevice(pkgName, authType, deviceId, ParseExtraFromMap(bindParam)); } else if (!targetId.deviceId.empty()) { @@ -2933,42 +2912,6 @@ int32_t DmAuthManager::CheckTrustState() return DM_OK; } -std::string DmAuthManager::GetBundleLable(const std::string &bundleName) -{ - auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (samgr == nullptr) { - LOGE("Get ability manager failed"); - return bundleName; - } - - sptr object = samgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); - if (object == nullptr) { - LOGE("object is NULL."); - return bundleName; - } - - sptr bms = iface_cast(object); - if (bms == nullptr) { - LOGE("bundle manager service is NULL."); - return bundleName; - } - - auto bundleResourceProxy = bms->GetBundleResourceProxy(); - if (bundleResourceProxy == nullptr) { - LOGE("GetBundleResourceProxy fail"); - return bundleName; - } - AppExecFwk::BundleResourceInfo resourceInfo; - auto result = bundleResourceProxy->GetBundleResourceInfo(bundleName, - static_cast(OHOS::AppExecFwk::ResourceFlag::GET_RESOURCE_INFO_ALL), resourceInfo); - if (result != ERR_OK) { - LOGE("GetBundleResourceInfo failed"); - return bundleName; - } - LOGI("bundle resource label is %{public}s ", (resourceInfo.label).c_str()); - return resourceInfo.label; -} - bool DmAuthManager::IsScreenLocked() { bool isLocked = false; @@ -3058,42 +3001,6 @@ bool DmAuthManager::IsAllowDeviceBind() return false; } -int32_t DmAuthManager::GetBindLevel(int32_t bindLevel) -{ -#ifdef DEVICE_MANAGER_COMMON_FLAG - LOGI("device_manager_common is true!"); - std::string processName = ""; - int32_t ret = AppManager::GetInstance().GetCallerProcessName(processName); - LOGI("GetBindLevel processName = %{public}s", GetAnonyString(processName).c_str()); - if (ret == DM_OK && CheckProcessNameInWhiteList(processName)) { - return USER; - } -#endif - if (IsAllowDeviceBind()) { - if (static_cast(bindLevel) == INVALIED_TYPE || static_cast(bindLevel) > APP || - static_cast(bindLevel) < USER) { - return USER; - } - return bindLevel; - } - if (static_cast(bindLevel) == INVALIED_TYPE || (static_cast(bindLevel) != APP && - static_cast(bindLevel) != SERVICE)) { - return APP; - } - return bindLevel; -} - -std::string DmAuthManager::GetBundleName(JsonObject &jsonObject) -{ - if (!jsonObject.IsDiscarded() && 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); @@ -3379,47 +3286,28 @@ void DmAuthManager::RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyC return; } -void DmAuthManager::GetCallerInfo(DmBindCallerInfo &callerInfo) -{ - (void)callerInfo; -} - -void DmAuthManager::SetCallerInfo(const DmBindCallerInfo &callerInfo) -{ - std::lock_guard lock(callerInfoMutex_); - callerInfo_.userId = callerInfo.userId; - callerInfo_.tokenId = callerInfo.tokenId; - callerInfo_.bundleName = callerInfo.bundleName; - callerInfo_.hostPkgLabel = callerInfo.hostPkgLabel; - callerInfoReady_ = true; -} - -void DmAuthManager::GetCallerInfo(const std::string &pkgName, JsonObject &jsonObject) +void DmAuthManager::GetBindCallerInfo() { + LOGI("start."); CHECK_NULL_VOID(authRequestContext_); - std::lock_guard lock(callerInfoMutex_); - if (callerInfoReady_) { - authRequestContext_->localUserId = callerInfo_.userId; - authRequestContext_->tokenId = static_cast(callerInfo_.tokenId); - authRequestContext_->bundleName = callerInfo_.bundleName; - authRequestContext_->hostPkgLabel = callerInfo_.hostPkgLabel; - } else { - authRequestContext_->hostPkgLabel = GetBundleLable(pkgName); - uint32_t tokenId = 0 ; - MultipleUserConnector::GetTokenIdAndForegroundUserId(tokenId, authRequestContext_->localUserId); - authRequestContext_->tokenId = static_cast(tokenId); - authRequestContext_->bundleName = GetBundleName(jsonObject); + { + std::lock_guard lock(bindParamMutex_); + if (bindParam_.find("bindCallerUserId") != bindParam_.end()) { + processInfo_.userId = std::atoi(bindParam_["bindCallerUserId"].c_str()); + } + if (bindParam_.find("bindCallerTokenId") != bindParam_.end()) { + authRequestContext_->tokenId = std::atoi(bindParam_["bindCallerTokenId"].c_str()); + } + if (bindParam_.find("bindCallerOldBindLevel") != bindParam_.end()) { + authRequestContext_->bindLevel = std::atoi(bindParam_["bindCallerOldBindLevel"].c_str()); + } + if (bindParam_.find("bindCallerBundleName") != bindParam_.end()) { + authRequestContext_->bundleName = bindParam_["bindCallerBundleName"]; + } + if (bindParam_.find("bindCallerHostPkgLabel") != bindParam_.end()) { + authRequestContext_->hostPkgLabel = bindParam_["bindCallerHostPkgLabel"]; + } } } - -void DmAuthManager::ClearCallerInfo() -{ - std::lock_guard lock(callerInfoMutex_); - callerInfo_.userId = -1; - callerInfo_.tokenId = -1; - callerInfo_.bundleName = ""; - callerInfo_.hostPkgLabel = ""; - callerInfoReady_ = false; -} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp.bak b/services/implementation/src/authentication/dm_auth_manager.cpp.bak new file mode 100644 index 000000000..0ef4020de --- /dev/null +++ b/services/implementation/src/authentication/dm_auth_manager.cpp.bak @@ -0,0 +1,3404 @@ +/* + * 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 + * + * 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_auth_manager.h" + +#include +#include +#include +#include + +#include "iservice_registry.h" +#if defined(SUPPORT_SCREENLOCK) +#include "screenlock_manager.h" +#endif + +#include "app_manager.h" +#include "auth_message_processor.h" +#include "common_event_support.h" +#include "dm_ability_manager.h" +#include "dm_anonymous.h" +#include "dm_config_manager.h" +#include "dm_constants.h" +#include "dm_crypto.h" +#include "dm_dialog_manager.h" +#include "dm_language_manager.h" +#include "dm_log.h" +#include "dm_radar_helper.h" +#include "dm_random.h" +#include "multiple_user_connector.h" +#include "json_object.h" +#include "openssl/sha.h" +#include "parameter.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "multiple_user_connector.h" +#endif + +namespace OHOS { +namespace DistributedHardware { +const int32_t CANCEL_PIN_CODE_DISPLAY = 1; +const int32_t DEVICE_ID_HALF = 2; +const int32_t MAX_AUTH_TIMES = 3; +const int32_t MIN_PIN_TOKEN = 10000000; +const int32_t MAX_PIN_TOKEN = 90000000; +const int32_t MIN_PIN_CODE = 100000; +const int32_t MAX_PIN_CODE = 999999; +const int32_t DM_AUTH_TYPE_MAX = 6; +const int32_t DM_AUTH_TYPE_MIN = 0; +const int32_t AUTH_SESSION_SIDE_SERVER = 0; +const int32_t USLEEP_TIME_US_500000 = 500000; // 500ms +const int32_t AUTH_DEVICE_TIMEOUT = 10; +const int32_t ALREADY_BIND = 1; +const int32_t STRTOLL_BASE_10 = 10; +const int32_t MAX_PUT_SESSIONKEY_TIMEOUT = 100; //ms +const int32_t SESSION_CLOSE_TIMEOUT = 2; + +// clone task timeout map +const std::map TASK_TIME_OUT_MAP = { + { std::string(AUTHENTICATE_TIMEOUT_TASK), CLONE_AUTHENTICATE_TIMEOUT }, + { std::string(NEGOTIATE_TIMEOUT_TASK), CLONE_NEGOTIATE_TIMEOUT }, + { std::string(CONFIRM_TIMEOUT_TASK), CLONE_CONFIRM_TIMEOUT }, + { std::string(ADD_TIMEOUT_TASK), CLONE_ADD_TIMEOUT }, + { std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), CLONE_WAIT_NEGOTIATE_TIMEOUT }, + { std::string(WAIT_REQUEST_TIMEOUT_TASK), CLONE_WAIT_REQUEST_TIMEOUT }, + { std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), CLONE_SESSION_HEARTBEAT_TIMEOUT } +}; +constexpr int32_t PROCESS_NAME_WHITE_LIST_NUM = 1; +constexpr const static char* PROCESS_NAME_WHITE_LIST[PROCESS_NAME_WHITE_LIST_NUM] = { + "com.example.myapplication" +}; + +constexpr const char* DM_VERSION_4_1_5_1 = "4.1.5.1"; +std::mutex g_authFinishLock; + +DmAuthManager::DmAuthManager(std::shared_ptr softbusConnector, + std::shared_ptr hiChainConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector) + : softbusConnector_(softbusConnector), hiChainConnector_(hiChainConnector), listener_(listener), + hiChainAuthConnector_(hiChainAuthConnector) +{ + LOGI("DmAuthManager constructor"); + DmConfigManager &dmConfigManager = DmConfigManager::GetInstance(); + dmConfigManager.GetAuthAdapter(authenticationMap_); + authUiStateMgr_ = std::make_shared(listener_); + authenticationMap_[AUTH_TYPE_IMPORT_AUTH_CODE] = nullptr; + authenticationMap_[AUTH_TYPE_CRE] = nullptr; + authenticationMap_[AUTH_TYPE_NFC] = nullptr; + dmVersion_ = DM_VERSION_5_0_5; +} + +DmAuthManager::~DmAuthManager() +{ + LOGI("DmAuthManager destructor"); +} + +bool DmAuthManager::IsHmlSessionType() +{ + CHECK_NULL_RETURN(authRequestContext_, false); + return authRequestContext_->connSessionType == CONN_SESSION_TYPE_HML; +} + +int32_t DmAuthManager::CheckAuthParamVaild(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + LOGI("DmAuthManager::CheckAuthParamVaild start."); + if (authType < DM_AUTH_TYPE_MIN || authType > DM_AUTH_TYPE_MAX) { + LOGE("CheckAuthParamVaild failed, authType is illegal."); + return ERR_DM_AUTH_FAILED; + } + if (pkgName.empty() || deviceId.empty()) { + LOGE("DmAuthManager::CheckAuthParamVaild failed, pkgName is %{public}s, deviceId is %{public}s, extra is" + "%{public}s.", pkgName.c_str(), GetAnonyString(deviceId).c_str(), extra.c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + if (listener_ == nullptr || authUiStateMgr_ == nullptr) { + LOGE("DmAuthManager::CheckAuthParamVaild listener or authUiStateMgr is nullptr."); + return ERR_DM_INPUT_PARA_INVALID; + } + + if (!IsAuthTypeSupported(authType)) { + LOGE("DmAuthManager::CheckAuthParamVaild authType %{public}d not support.", authType); + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, + ERR_DM_UNSUPPORTED_AUTH_TYPE); + listener_->OnBindResult(processInfo_, peerTargetId_, ERR_DM_UNSUPPORTED_AUTH_TYPE, STATUS_DM_AUTH_DEFAULT, ""); + return ERR_DM_UNSUPPORTED_AUTH_TYPE; + } + + if (authRequestState_ != nullptr || authResponseState_ != nullptr) { + LOGE("DmAuthManager::CheckAuthParamVaild %{public}s is request authentication.", pkgName.c_str()); + return ERR_DM_AUTH_BUSINESS_BUSY; + } + + if ((authType == AUTH_TYPE_IMPORT_AUTH_CODE || authType == AUTH_TYPE_NFC) && (!IsAuthCodeReady(pkgName))) { + LOGE("Auth code not exist."); + 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; +} + +int32_t DmAuthManager::CheckAuthParamVaildExtra(const std::string &extra, const std::string &deviceId) +{ + JsonObject jsonObject(extra); + if ((jsonObject.IsDiscarded() || !IsString(jsonObject, PARAM_KEY_CONN_SESSIONTYPE) || + jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get() != CONN_SESSION_TYPE_HML) && + !softbusConnector_->HaveDeviceInMap(deviceId)) { + LOGE("CheckAuthParamVaild failed, the discoveryDeviceInfoMap_ not have this device."); + 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 (jsonObject.IsDiscarded()) { + return DM_OK; + } + std::string connSessionType; + if (IsString(jsonObject, PARAM_KEY_CONN_SESSIONTYPE)) { + connSessionType = jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get(); + } + if (connSessionType == CONN_SESSION_TYPE_HML && !CheckHmlParamValid(jsonObject)) { + LOGE("CONN_SESSION_TYPE_HML, CheckHmlParamValid failed"); + return ERR_DM_INPUT_PARA_INVALID; + } + + if (jsonObject.IsDiscarded() || !jsonObject.Contains(TAG_BIND_LEVEL)) { + return DM_OK; + } + int32_t bindLevel = INVALID_TYPE; + if (!CheckBindLevel(jsonObject, TAG_BIND_LEVEL, bindLevel)) { + LOGE("TAG_BIND_LEVEL is not integer string or int32."); + return ERR_DM_INPUT_PARA_INVALID; + } + if (static_cast(bindLevel) > APP || bindLevel < INVALID_TYPE) { + LOGE("bindlevel error %{public}d.", bindLevel); + return ERR_DM_INPUT_PARA_INVALID; + } + + if (static_cast(bindLevel) == USER && !IsAllowDeviceBind()) { + LOGE("not allowd user level bind bindlevel: %{public}d.", bindLevel); + return ERR_DM_INPUT_PARA_INVALID; + } + return DM_OK; +} + +bool DmAuthManager::CheckBindLevel(const JsonItemObject &jsonObj, const std::string &key, int32_t &bindLevel) +{ + if (IsJsonValIntegerString(jsonObj, TAG_BIND_LEVEL)) { + bindLevel = std::atoi(jsonObj[TAG_BIND_LEVEL].Get().c_str()); + return true; + } + if (IsInt32(jsonObj, TAG_BIND_LEVEL)) { + bindLevel = jsonObj[TAG_BIND_LEVEL].Get(); + return true; + } + return false; +} + +bool DmAuthManager::CheckHmlParamValid(JsonObject &jsonObject) +{ + if (!IsString(jsonObject, PARAM_KEY_HML_ACTIONID)) { + LOGE("PARAM_KEY_HML_ACTIONID is not string"); + return false; + } + std::string actionIdStr = jsonObject[PARAM_KEY_HML_ACTIONID].Get(); + if (!IsNumberString(actionIdStr)) { + LOGE("PARAM_KEY_HML_ACTIONID is not number"); + return false; + } + int32_t actionId = std::atoi(actionIdStr.c_str()); + if (actionId <= 0) { + LOGE("PARAM_KEY_HML_ACTIONID is <= 0"); + return false; + } + return true; +} + +void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + LOGI("Get auth param."); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string localUdid = static_cast(localDeviceId); + authRequestContext_->hostPkgName = pkgName; + authRequestContext_->authType = authType; + authRequestContext_->localDeviceName = softbusConnector_->GetLocalDeviceName(); + authRequestContext_->localDeviceTypeId = softbusConnector_->GetLocalDeviceTypeId(); + authRequestContext_->localDeviceId = localUdid; + authRequestContext_->deviceId = deviceId; + authRequestContext_->addr = deviceId; + authRequestContext_->dmVersion = DM_VERSION_5_0_5; + authRequestContext_->localUserId = MultipleUserConnector::GetFirstForegroundUserId(); + authRequestContext_->localAccountId = MultipleUserConnector::GetFirstForegroundUserId(); + MultipleUserConnector::GetOhosAccountIdByUserId(authRequestContext_->localUserId); + authRequestContext_->isOnline = false; + authRequestContext_->authed = !authRequestContext_->bindType.empty(); + authRequestContext_->bindLevel = INVALIED_TYPE; + JsonObject jsonObject(extra); + if (jsonObject.IsDiscarded()) { + LOGE("extra string not a json type."); + return; + } + ParseJsonObject(jsonObject); + authRequestContext_->token = std::to_string(GenRandInt(MIN_PIN_TOKEN, MAX_PIN_TOKEN)); + authRequestContext_->bindLevel = GetBindLevel(authRequestContext_->bindLevel); +} + +void DmAuthManager::ParseJsonObject(JsonObject &jsonObject) +{ + if (!jsonObject.IsDiscarded()) { + if (IsString(jsonObject, TARGET_PKG_NAME_KEY)) { + authRequestContext_->targetPkgName = jsonObject[TARGET_PKG_NAME_KEY].Get(); + } + if (IsString(jsonObject, APP_OPERATION_KEY)) { + authRequestContext_->appOperation = jsonObject[APP_OPERATION_KEY].Get(); + } + if (IsString(jsonObject, CUSTOM_DESCRIPTION_KEY)) { + authRequestContext_->customDesc = DmLanguageManager::GetInstance(). + GetTextBySystemLanguage(jsonObject[CUSTOM_DESCRIPTION_KEY].Get()); + } + if (IsString(jsonObject, TAG_APP_THUMBNAIL2)) { + authRequestContext_->appThumbnail = jsonObject[TAG_APP_THUMBNAIL2].Get(); + } + CheckBindLevel(jsonObject, TAG_BIND_LEVEL, authRequestContext_->bindLevel); + authRequestContext_->closeSessionDelaySeconds = 0; + if (IsString(jsonObject, PARAM_CLOSE_SESSION_DELAY_SECONDS)) { + std::string delaySecondsStr = jsonObject[PARAM_CLOSE_SESSION_DELAY_SECONDS].Get(); + authRequestContext_->closeSessionDelaySeconds = GetCloseSessionDelaySeconds(delaySecondsStr); + } + if (IsString(jsonObject, TAG_PEER_BUNDLE_NAME)) { + authRequestContext_->peerBundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get(); + if (authRequestContext_->peerBundleName == "") { + authRequestContext_->peerBundleName = authRequestContext_->hostPkgName; + } + LOGI("ParseJsonObject peerBundleName = %{public}s", authRequestContext_->peerBundleName.c_str()); + } else { + authRequestContext_->peerBundleName = authRequestContext_->hostPkgName; + } + ParseHmlInfoInJsonObject(jsonObject); + } +} + +void DmAuthManager::ParseHmlInfoInJsonObject(JsonObject &jsonObject) +{ + CHECK_NULL_VOID(authRequestContext_); + if (IsString(jsonObject, PARAM_KEY_CONN_SESSIONTYPE)) { + authRequestContext_->connSessionType = jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get(); + LOGI("connSessionType %{public}s", authRequestContext_->connSessionType.c_str()); + } + if (!IsHmlSessionType()) { + return; + } + if (IsString(jsonObject, PARAM_KEY_HML_ACTIONID)) { + std::string actionIdStr = jsonObject[PARAM_KEY_HML_ACTIONID].Get(); + if (IsNumberString(actionIdStr)) { + authRequestContext_->hmlActionId = std::atoi(actionIdStr.c_str()); + } + if (authRequestContext_->hmlActionId <= 0) { + authRequestContext_->hmlActionId = 0; + } + LOGI("hmlActionId %{public}d", authRequestContext_->hmlActionId); + } +} + +int32_t DmAuthManager::GetCloseSessionDelaySeconds(std::string &delaySecondsStr) +{ + if (!IsNumberString(delaySecondsStr)) { + LOGE("Invalid parameter, param is not number."); + return 0; + } + const int32_t CLOSE_SESSION_DELAY_SECONDS_MAX = 10; + int32_t delaySeconds = std::atoi(delaySecondsStr.c_str()); + if (delaySeconds < 0 || delaySeconds > CLOSE_SESSION_DELAY_SECONDS_MAX) { + LOGE("Invalid parameter, param out of range."); + return 0; + } + return delaySeconds; +} + +void DmAuthManager::InitAuthState(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + auto iter = authenticationMap_.find(authType); + if (iter != authenticationMap_.end()) { + authPtr_ = iter->second; + } + + if (timer_ == nullptr) { + timer_ = std::make_shared(); + } + timer_->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), + GetTaskTimeout(AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + authMessageProcessor_ = std::make_shared(shared_from_this()); + authResponseContext_ = std::make_shared(); + authRequestContext_ = std::make_shared(); + JsonObject jsonObject(extra); + if (jsonObject.IsDiscarded()) { + LOGE("extra string not a json type."); + return; + } + GetCallerInfo(pkgName, jsonObject); + GetAuthParam(pkgName, authType, deviceId, extra); + authMessageProcessor_->SetRequestContext(authRequestContext_); + authRequestState_ = std::make_shared(); + authRequestState_->SetAuthManager(shared_from_this()); + authRequestState_->SetAuthContext(authRequestContext_); + if (!DmRadarHelper::GetInstance().ReportAuthStart(peerTargetId_.deviceId, pkgName)) { + LOGE("ReportAuthStart failed"); + } + authRequestState_->Enter(); + LOGI("DmAuthManager::AuthenticateDevice complete"); +} + +int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + LOGI("DmAuthManager::AuthenticateDevice start auth type %{public}d.", authType); + SetAuthType(authType); + int32_t ret = CheckAuthParamVaild(pkgName, authType, deviceId, extra); + if (ret != DM_OK) { + LOGE("DmAuthManager::AuthenticateDevice failed, param is invaild."); + return ret; + } + ret = CheckAuthParamVaildExtra(extra, deviceId); + if (ret != DM_OK) { + LOGE("CheckAuthParamVaildExtra failed, param is invaild."); + return ret; + } + InitAuthState(pkgName, authType, deviceId, extra); + isAuthenticateDevice_ = true; + int32_t userId = -1; + MultipleUserConnector::GetCallerUserId(userId); + processInfo_.pkgName = pkgName; + processInfo_.userId = userId; + if (authType == AUTH_TYPE_CRE) { + LOGI("DmAuthManager::AuthenticateDevice for credential type, joinLNN directly."); + softbusConnector_->JoinLnn(deviceId, true); + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, DM_OK); + listener_->OnBindResult(processInfo_, peerTargetId_, DM_OK, STATUS_DM_AUTH_DEFAULT, ""); + } + return DM_OK; +} + +int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) +{ + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return ERR_DM_FAILED; + } + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + struct RadarInfo info = { + .funcName = "UnAuthenticateDevice", + .toCallPkg = HICHAINNAME, + .hostName = pkgName, + .peerUdid = udid, + }; + if (!DmRadarHelper::GetInstance().ReportDeleteTrustRelation(info)) { + LOGE("ReportDeleteTrustRelation failed"); + } + remoteDeviceId_ = udid; + if (static_cast(bindLevel) == USER) { + DeleteGroup(pkgName, udid); + } + std::string extra = ""; + return DeleteAcl(pkgName, std::string(localDeviceId), udid, bindLevel, extra); +} + +int32_t DmAuthManager::StopAuthenticateDevice(const std::string &pkgName) +{ + if (pkgName.empty() || authRequestContext_ == nullptr || authResponseContext_ == nullptr) { + LOGE("Invalid parameter, pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + if (((authRequestState_!= nullptr && authRequestContext_->hostPkgName == pkgName) || + (authResponseContext_ != nullptr && authResponseContext_->hostPkgName == pkgName)) && + isAuthenticateDevice_) { + LOGI("Stop previous AuthenticateDevice."); + authRequestContext_->reason = STOP_BIND; + authResponseContext_->state = authRequestState_->GetStateType(); + authResponseContext_->reply = STOP_BIND; + authRequestState_->TransitionTo(std::make_shared()); + } + return DM_OK; +} + +int32_t DmAuthManager::DeleteAcl(const std::string &pkgName, const std::string &localUdid, + const std::string &remoteUdid, int32_t bindLevel, const std::string &extra) +{ + LOGI("DeleteAcl pkgName %{public}s, localUdid %{public}s, remoteUdid %{public}s, bindLevel %{public}d.", + pkgName.c_str(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str(), bindLevel); + DmOfflineParam offlineParam = + DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localUdid, remoteUdid, bindLevel, extra); + if (offlineParam.bindType == INVALIED_TYPE) { + LOGE("Acl not contain the pkgname bind data."); + return ERR_DM_FAILED; + } + if (static_cast(bindLevel) == APP) { + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); + 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(), + offlineParam.peerUserId); + return DM_OK; + } + } + if (static_cast(bindLevel) == USER && offlineParam.leftAclNumber != 0) { + LOGI("Unbind deivce-level, retain identical account bind type."); + return DM_OK; + } + if (static_cast(bindLevel) == USER && offlineParam.leftAclNumber == 0) { + LOGI("Unbind deivce-level, retain null."); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(), + offlineParam.peerUserId); + return DM_OK; + } + return ERR_DM_FAILED; +} + +int32_t DmAuthManager::UnBindDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel, const std::string &extra) +{ + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return ERR_DM_FAILED; + } + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + if (static_cast(bindLevel) == USER) { + DeleteGroup(pkgName, udid); + } + return DeleteAcl(pkgName, std::string(localDeviceId), udid, bindLevel, extra); +} + +void DmAuthManager::GetPeerUdidHash(int32_t sessionId, std::string &peerUdidHash) +{ + std::string peerUdid = ""; + int32_t ret = softbusConnector_->GetSoftbusSession()->GetPeerDeviceId(sessionId, peerUdid); + if (ret != DM_OK) { + LOGE("DmAuthManager::GetPeerUdidHash failed."); + peerUdidHash = ""; + return; + } + char udidHashTmp[DM_MAX_DEVICE_ID_LEN] = {0}; + if (Crypto::GetUdidHash(peerUdid, reinterpret_cast(udidHashTmp)) != DM_OK) { + LOGE("get udidhash by udid: %{public}s failed.", GetAnonyString(peerUdid).c_str()); + peerUdidHash = ""; + return; + } + peerUdidHash = std::string(udidHashTmp); +} + +void DmAuthManager::DeleteOffLineTimer(int32_t sessionId) +{ + GetPeerUdidHash(sessionId, remoteUdidHash_); + if (remoteUdidHash_.empty()) { + LOGE("DeleteOffLineTimer remoteUdidHash is empty."); + return; + } + if (softbusConnector_ != nullptr) { + softbusConnector_->DeleteOffLineTimer(remoteUdidHash_); + } +} + +void DmAuthManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) +{ + LOGI("sessionId = %{public}d and sessionSide = %{public}d result = %{public}d", sessionId, sessionSide, result); + DeleteOffLineTimer(sessionId); + if (sessionSide == AUTH_SESSION_SIDE_SERVER) { + if (authResponseState_ == nullptr && authRequestState_ == nullptr) { + authMessageProcessor_ = std::make_shared(shared_from_this()); + authResponseState_ = std::make_shared(); + authResponseState_->SetAuthManager(shared_from_this()); + authResponseState_->Enter(); + authResponseContext_ = std::make_shared(); + authResponseContext_->sessionId = sessionId; + if (timer_ == nullptr) { + timer_ = std::make_shared(); + } + timer_->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), + GetTaskTimeout(AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + timer_->StartTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), + GetTaskTimeout(WAIT_NEGOTIATE_TIMEOUT_TASK, WAIT_NEGOTIATE_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + } else { + std::shared_ptr authMessageProcessor = + std::make_shared(shared_from_this()); + std::shared_ptr authResponseContext = std::make_shared(); + authResponseContext->reply = ERR_DM_AUTH_BUSINESS_BUSY; + authMessageProcessor->SetResponseContext(authResponseContext); + std::string message = authMessageProcessor->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE); + softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); + softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId); + } + } else { + if (authResponseState_ == nullptr && authRequestState_ != nullptr && + authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT) { + authRequestContext_->sessionId = sessionId; + authResponseContext_->sessionId = sessionId; + authMessageProcessor_->SetRequestContext(authRequestContext_); + authRequestState_->SetAuthContext(authRequestContext_); + authRequestState_->TransitionTo(std::make_shared()); + struct RadarInfo info = { .funcName = "OnSessionOpened" }; + info.channelId = sessionId; + DmRadarHelper::GetInstance().ReportAuthSendRequest(info); + } else { + softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId); + LOGE("DmAuthManager::OnSessionOpened but request state is wrong"); + } + } +} + +void DmAuthManager::OnSessionClosed(const int32_t sessionId) +{ + LOGI("DmAuthManager::OnSessionClosed sessionId = %{public}d", sessionId); + if (authResponseState_ != nullptr && authResponseContext_ != nullptr) { + isFinishOfLocal_ = false; + authResponseContext_->state = authResponseState_->GetStateType(); + authResponseState_->TransitionTo(std::make_shared()); + } +} + +void DmAuthManager::ClearSoftbusSessionCallback() +{ + LOGI("DmAuthManager ClearSoftbusSessionCallback"); + if (softbusConnector_ != nullptr && softbusConnector_->GetSoftbusSession() != nullptr) { + softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback(); + } +} + +void DmAuthManager::PrepareSoftbusSessionCallback() +{ + LOGI("DmAuthManager PrepareSoftbusSessionCallback"); + if (softbusConnector_ != nullptr && softbusConnector_->GetSoftbusSession() != nullptr) { + softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(shared_from_this()); + } +} + +void DmAuthManager::ProcessSourceMsg() +{ + authRequestContext_ = authMessageProcessor_->GetRequestContext(); + authRequestState_->SetAuthContext(authRequestContext_); + LOGI("OnDataReceived for source device, authResponseContext msgType = %{public}d, authRequestState stateType =" + "%{public}d", authResponseContext_->msgType, authRequestState_->GetStateType()); + + switch (authResponseContext_->msgType) { + case MSG_TYPE_RESP_AUTH: + case MSG_TYPE_RESP_AUTH_EXT: + if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) { + authRequestState_->TransitionTo(std::make_shared()); + } + break; + case MSG_TYPE_RESP_NEGOTIATE: + if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE) { + authRequestState_->TransitionTo(std::make_shared()); + } + break; + case MSG_TYPE_REQ_AUTH_TERMINATE: + if (authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) { + isFinishOfLocal_ = false; + authResponseContext_->state = authRequestState_->GetStateType(); + authRequestState_->TransitionTo(std::make_shared()); + } + break; + case MSG_TYPE_RESP_PUBLICKEY: + if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_CREDENTIAL) { + authRequestState_->TransitionTo(std::make_shared()); + } + break; + case MSG_TYPE_RESP_RECHECK_MSG: + if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_RECHECK_MSG) { + authRequestState_->TransitionTo(std::make_shared()); + } + break; + default: + break; + } +} + +void DmAuthManager::ProcessSinkMsg() +{ + authResponseState_->SetAuthContext(authResponseContext_); + LOGI("OnDataReceived for sink device, authResponseContext msgType = %{public}d, authResponseState stateType =" + "%{public}d", authResponseContext_->msgType, authResponseState_->GetStateType()); + + switch (authResponseContext_->msgType) { + case MSG_TYPE_NEGOTIATE: + if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_INIT) { + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK)); + } + authResponseState_->TransitionTo(std::make_shared()); + } + break; + case MSG_TYPE_REQ_AUTH: + if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_NEGOTIATE) { + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); + } + authResponseState_->TransitionTo(std::make_shared()); + } + break; + case MSG_TYPE_REQ_AUTH_TERMINATE: + if (authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) { + isFinishOfLocal_ = false; + authResponseContext_->state = authResponseState_->GetStateType(); + if (authResponseContext_->reply == DM_OK) { + authResponseContext_->state = AuthState::AUTH_RESPONSE_FINISH; + } + authResponseState_->TransitionTo(std::make_shared()); + } + break; + case MSG_TYPE_REQ_PUBLICKEY: + ProcessReqPublicKey(); + break; + case MSG_TYPE_REQ_RECHECK_MSG: + if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_AUTH_FINISH) { + authResponseState_->TransitionTo(std::make_shared()); + break; + } + if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW) { + std::lock_guard lock(srcReqMsgLock_); + isNeedProcCachedSrcReqMsg_ = true; + } + break; + default: + break; + } +} + +void DmAuthManager::OnDataReceived(const int32_t sessionId, const std::string message) +{ + if (authResponseContext_ == nullptr || authMessageProcessor_ == nullptr || + sessionId != authResponseContext_->sessionId) { + LOGE("OnDataReceived failed, authResponseContext or authMessageProcessor_ is nullptr."); + return; + } + + authResponseContext_->sessionId = sessionId; + authMessageProcessor_->SetResponseContext(authResponseContext_); + int32_t ret = authMessageProcessor_->ParseMessage(message); + if (ret != DM_OK) { + LOGE("OnDataReceived failed, parse input message error."); + return; + } + + if ((authRequestState_ != nullptr) && (authResponseState_ == nullptr)) { + // source device auth process + ProcessSourceMsg(); + } else if ((authResponseState_ != nullptr) && (authRequestState_ == nullptr)) { + // sink device auth process + { + std::lock_guard lock(srcReqMsgLock_); + srcReqMsg_ = message; + } + ProcessSinkMsg(); + } else { + LOGE("DmAuthManager::OnDataReceived failed, authRequestState_ or authResponseState_ is invalid."); + } +} + +void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId) +{ + if (authResponseContext_ == nullptr) { + LOGE("failed to OnGroupCreated because authResponseContext_ is nullptr"); + return; + } + if (authResponseState_ == nullptr) { + LOGE("DmAuthManager::AuthenticateDevice end"); + return; + } + LOGI("DmAuthManager::OnGroupCreated start group id %{public}s", GetAnonyString(groupId).c_str()); + if (groupId == "{}") { + authResponseContext_->reply = ERR_DM_CREATE_GROUP_FAILED; + authMessageProcessor_->SetResponseContext(authResponseContext_); + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH); + softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); + return; + } + CompatiblePutAcl(); + std::string pinCode = ""; + if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && !importAuthCode_.empty()) { + GetAuthCode(authResponseContext_->hostPkgName, pinCode); + } else if (authResponseContext_->authType != AUTH_TYPE_IMPORT_AUTH_CODE) { + pinCode = GeneratePincode(); + } else { + LOGE("authType invalied."); + } + JsonObject jsonObj; + jsonObj[PIN_TOKEN] = authResponseContext_->token; + jsonObj[QR_CODE_KEY] = GenerateGroupName(); + jsonObj[NFC_CODE_KEY] = GenerateGroupName(); + authResponseContext_->authToken = SafetyDump(jsonObj); + LOGI("DmAuthManager::OnGroupCreated start group id %{public}s", GetAnonyString(groupId).c_str()); + authResponseContext_->groupId = groupId; + authResponseContext_->code = pinCode; + authMessageProcessor_->SetResponseContext(authResponseContext_); + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH); + softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); + authResponseContext_->isFinish = true; + authResponseState_->TransitionTo(std::make_shared()); +} + +void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status) +{ + isAddingMember_ = false; + if (authResponseContext_ == nullptr || authUiStateMgr_ == nullptr) { + LOGE("failed to OnMemberJoin because authResponseContext_ or authUiStateMgr is nullptr"); + return; + } + LOGI("DmAuthManager OnMemberJoin start authTimes %{public}d", authTimes_); + if ((authRequestState_ != nullptr) && (authResponseState_ == nullptr)) { + MemberJoinAuthRequest(requestId, status); + } else if ((authResponseState_ != nullptr) && (authRequestState_ == nullptr)) { + if (status == DM_OK && authResponseContext_->requestId == requestId && + authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW) { + authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW); + } else { + if (++authTimes_ >= MAX_AUTH_TIMES) { + authResponseContext_->isFinish = false; + authResponseContext_->reply = ERR_DM_BIND_PIN_CODE_ERROR; + authResponseContext_->state = AuthState::AUTH_RESPONSE_SHOW; + isFinishOfLocal_ = false; + authResponseState_->TransitionTo(std::make_shared()); + } + } + } else { + LOGE("DmAuthManager::OnMemberJoin failed, authRequestState_ or authResponseState_ is invalid."); + } +} + +void DmAuthManager::MemberJoinAuthRequest(int64_t requestId, int32_t status) +{ + authTimes_++; + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(ADD_TIMEOUT_TASK)); + } + if (status == DM_OK) { + LOGI("join group success."); + CompatiblePutAcl(); + } + if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { + HandleMemberJoinImportAuthCode(requestId, status); + return; + } + if (status != DM_OK || authResponseContext_->requestId != requestId) { + if (authRequestState_ != nullptr && authTimes_ >= MAX_AUTH_TIMES) { + authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; + authResponseContext_->reply = ERR_DM_BIND_PIN_CODE_ERROR; + authRequestContext_->reason = ERR_DM_BIND_PIN_CODE_ERROR; + authRequestState_->TransitionTo(std::make_shared()); + return; + } + if (timer_ != nullptr) { + timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), + GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + } + authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR); + } else { + authRequestState_->TransitionTo(std::make_shared()); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK)); + } + } +} + +void DmAuthManager::HandleMemberJoinImportAuthCode(const int64_t requestId, const int32_t status) +{ + if (status != DM_OK || authResponseContext_->requestId != requestId) { + authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; + authResponseContext_->reply = ERR_DM_AUTH_CODE_INCORRECT; + authRequestContext_->reason = ERR_DM_AUTH_CODE_INCORRECT; + authRequestState_->TransitionTo(std::make_shared()); + } else { + authRequestState_->TransitionTo(std::make_shared()); + } +} + +void DmAuthManager::HandleAuthenticateTimeout(std::string name) +{ + LOGI("DmAuthManager::HandleAuthenticateTimeout start timer name %{public}s", name.c_str()); + if (authRequestState_ != nullptr && authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) { + if (authResponseContext_ == nullptr) { + authResponseContext_ = std::make_shared(); + } + authResponseContext_->state = authRequestState_->GetStateType(); + authRequestContext_->reason = ERR_DM_TIME_OUT; + authResponseContext_->reply = ERR_DM_TIME_OUT; + authRequestState_->TransitionTo(std::make_shared()); + } + + if (authResponseState_ != nullptr && authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) { + authResponseContext_->state = authResponseState_->GetStateType(); + authResponseContext_->reply = ERR_DM_TIME_OUT; + authResponseState_->TransitionTo(std::make_shared()); + } + LOGI("DmAuthManager::HandleAuthenticateTimeout start complete"); +} + +int32_t DmAuthManager::EstablishAuthChannel(const std::string &deviceId) +{ + if (NeedInsensibleSwitching()) { + return DM_OK; + } + int32_t sessionId = 0; + if (IsHmlSessionType()) { + CHECK_NULL_RETURN(authRequestContext_, ERR_DM_FAILED); + LOGI("hmlActionId %{public}d, hmlReleaseTime %{public}d, hmlEnable160M %{public}d", + authRequestContext_->hmlActionId, authRequestContext_->closeSessionDelaySeconds, + authRequestContext_->hmlEnable160M); + sessionId = softbusConnector_->GetSoftbusSession()->OpenAuthSessionWithPara(deviceId, + authRequestContext_->hmlActionId, authRequestContext_->hmlEnable160M); + } else { + sessionId = softbusConnector_->GetSoftbusSession()->OpenAuthSession(deviceId); + } + struct RadarInfo info = { + .funcName = "EstablishAuthChannel", + .stageRes = (sessionId > 0) ? + static_cast(StageRes::STAGE_IDLE) : static_cast(StageRes::STAGE_FAIL), + .bizState = (sessionId > 0) ? + static_cast(BizState::BIZ_STATE_START) : static_cast(BizState::BIZ_STATE_END), + .localSessName = DM_SESSION_NAME, + .peerSessName = DM_SESSION_NAME, + .isTrust = static_cast(TrustStatus::NOT_TRUST), + .commServ = static_cast(CommServ::USE_SOFTBUS), + .peerUdid = peerTargetId_.deviceId, + .channelId = sessionId, + .errCode = sessionId, + }; + if (!DmRadarHelper::GetInstance().ReportAuthOpenSession(info)) { + LOGE("ReportAuthOpenSession failed"); + } + if (sessionId < 0) { + LOGE("OpenAuthSession failed, stop the authentication"); + if (authResponseContext_ == nullptr) { + authResponseContext_ = std::make_shared(); + } + authResponseContext_->state = AuthState::AUTH_REQUEST_NEGOTIATE; + authResponseContext_->reply = sessionId; + if (authRequestContext_ == nullptr) { + authRequestContext_ = std::make_shared(); + } + authRequestContext_->reason = sessionId; + if (authRequestState_ != nullptr) { + authRequestState_->TransitionTo(std::make_shared()); + } + } + return DM_OK; +} + +void DmAuthManager::StartNegotiate(const int32_t &sessionId) +{ + if (authResponseContext_ == nullptr) { + LOGE("DmAuthManager::StartNegotiate error, authResponseContext_ is nullptr"); + return; + } + LOGI("DmAuthManager::StartNegotiate sessionId %{public}d.", sessionId); + authResponseContext_->localDeviceId = authRequestContext_->localDeviceId; + authResponseContext_->reply = ERR_DM_AUTH_REJECT; + authResponseContext_->authType = authRequestContext_->authType; + authResponseContext_->deviceId = authRequestContext_->deviceId; + authResponseContext_->accountGroupIdHash = GetAccountGroupIdHash(); + authResponseContext_->hostPkgName = authRequestContext_->hostPkgName; + authResponseContext_->bundleName = authRequestContext_->bundleName; + authResponseContext_->peerBundleName = authRequestContext_->peerBundleName; + authResponseContext_->hostPkgLabel = authRequestContext_->hostPkgLabel; + authResponseContext_->tokenId = authRequestContext_->tokenId; + authResponseContext_->bindLevel = authRequestContext_->bindLevel; + authResponseContext_->bindType = authRequestContext_->bindType; + authResponseContext_->isOnline = authRequestContext_->isOnline; + authResponseContext_->authed = authRequestContext_->authed; + authResponseContext_->dmVersion = ""; + authResponseContext_->localAccountId = authRequestContext_->localAccountId; + authResponseContext_->localUserId = authRequestContext_->localUserId; + authResponseContext_->isIdenticalAccount = false; + authResponseContext_->edition = DM_VERSION_5_0_5; + authResponseContext_->remoteDeviceName = authRequestContext_->localDeviceName; + authMessageProcessor_->SetResponseContext(authResponseContext_); + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_NEGOTIATE); + if (!NeedInsensibleSwitching()) { + softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); + } + if (timer_ != nullptr) { + timer_->StartTimer(std::string(NEGOTIATE_TIMEOUT_TASK), + GetTaskTimeout(NEGOTIATE_TIMEOUT_TASK, NEGOTIATE_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + } +} + +void DmAuthManager::AbilityNegotiate() +{ + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + authResponseContext_->remoteAccountId = authResponseContext_->localAccountId; + authResponseContext_->remoteUserId = authResponseContext_->localUserId; + GetBinderInfo(); + bool ret = hiChainConnector_->IsDevicesInP2PGroup(authResponseContext_->localDeviceId, localDeviceId); + if (ret) { + LOGE("DmAuthManager::EstablishAuthChannel device is in group"); + if (!DeviceProfileConnector::GetInstance().CheckSinkDevIdInAclForDevBind(authResponseContext_->hostPkgName, + authResponseContext_->localDeviceId)) { + CompatiblePutAcl(); + } + authResponseContext_->reply = ERR_DM_AUTH_PEER_REJECT; + } else { + authResponseContext_->reply = ERR_DM_AUTH_REJECT; + } + authResponseContext_->localDeviceId = localDeviceId; + + if (!IsAuthTypeSupported(authResponseContext_->authType)) { + LOGE("DmAuthManager::AuthenticateDevice authType %{public}d not support.", authResponseContext_->authType); + authResponseContext_->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; + } else { + authPtr_ = authenticationMap_[authResponseContext_->authType]; + } + + if (IsAuthCodeReady(authResponseContext_->hostPkgName)) { + authResponseContext_->isAuthCodeReady = true; + } else { + authResponseContext_->isAuthCodeReady = false; + } +} + +void DmAuthManager::RespNegotiate(const int32_t &sessionId) +{ + if (authResponseContext_ == nullptr || authRequestState_ != nullptr) { + LOGE("failed to RespNegotiate because authResponseContext_ is nullptr"); + return; + } + LOGI("DmAuthManager::RespNegotiate sessionid %{public}d", sessionId); + remoteDeviceId_ = authResponseContext_->localDeviceId; + authResponseContext_->networkId = softbusConnector_->GetLocalDeviceNetworkId(); + authResponseContext_->targetDeviceName = softbusConnector_->GetLocalDeviceName(); + remoteVersion_ = AuthManagerBase::ConvertSrcVersion(authResponseContext_->dmVersion, authResponseContext_->edition); + NegotiateRespMsg(remoteVersion_); + if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && + (static_cast(authResponseContext_->bindLevel) >= USER && + static_cast(authResponseContext_->bindLevel) <= APP)) { + ProcRespNegotiateExt(sessionId); + timer_->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), + GetTaskTimeout(WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || + static_cast(authResponseContext_->bindLevel) == INVALIED_TYPE) { + ProcRespNegotiate(sessionId); + timer_->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), + GetTaskTimeout(WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + } else { + ProcIncompatible(sessionId); + } +} + +void DmAuthManager::NegotiateRespMsg(const std::string &version) +{ + if (version == DM_VERSION_5_0_1) { + authResponseContext_->dmVersion = DM_VERSION_5_0_1; + } else if (version < DM_VERSION_5_0_1) { + authResponseContext_->dmVersion = ""; + authResponseContext_->bindLevel = INVALIED_TYPE; + } else if (version > DM_VERSION_5_0_1) { + authResponseContext_->dmVersion = dmVersion_; + } +} + +void DmAuthManager::SendAuthRequest(const int32_t &sessionId) +{ + LOGI("DmAuthManager::SendAuthRequest sessionId %{public}d.", sessionId); + if (authResponseContext_ == nullptr) { + LOGE("failed to SendAuthRequest because authResponseContext_ is nullptr"); + return; + } + if (authResponseContext_->reply == ERR_DM_VERSION_INCOMPATIBLE) { + LOGE("The peer device version is not supported"); + authRequestContext_->reason = authResponseContext_->reply; + authRequestState_->TransitionTo(std::make_shared()); + return; + } + remoteDeviceId_ = authResponseContext_->localDeviceId; + authRequestContext_->remoteDeviceName = authResponseContext_->targetDeviceName; + remoteVersion_ = ConvertSinkVersion(authResponseContext_->dmVersion); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(NEGOTIATE_TIMEOUT_TASK)); + } + if (authResponseContext_->cryptoSupport) { + isCryptoSupport_ = true; + } + LOGI("SendAuthRequest dmversion %{public}s, level %{public}d", + authResponseContext_->dmVersion.c_str(), authResponseContext_->bindLevel); + if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && + (static_cast(authResponseContext_->bindLevel) >= USER && + static_cast(authResponseContext_->bindLevel) <= APP)) { + ProcessAuthRequestExt(sessionId); + } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || + static_cast(authResponseContext_->bindLevel) == INVALIED_TYPE) { + ProcessAuthRequest(sessionId); + } else { + LOGE("Invalied bind mode."); + } +} + +void DmAuthManager::ProcessAuthRequest(const int32_t &sessionId) +{ + LOGI("ProcessAuthRequest start."); + if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && + !authResponseContext_->importAuthCode.empty() && !importAuthCode_.empty()) { + if (authResponseContext_->importAuthCode != Crypto::Sha256(importAuthCode_)) { + SetReasonAndFinish(ERR_DM_AUTH_CODE_INCORRECT, AuthState::AUTH_REQUEST_FINISH); + return; + } + } + + if (authResponseContext_->isOnline && softbusConnector_->CheckIsOnline(remoteDeviceId_)) { + authResponseContext_->isOnline = true; + } else { + authResponseContext_->isOnline = false; + } + if (CheckTrustState() != DM_OK) { + LOGI("CheckTrustState end."); + return; + } + + std::vector messageList = authMessageProcessor_->CreateAuthRequestMessage(); + for (auto msg : messageList) { + softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg); + } + + 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); + }); +} + +void DmAuthManager::GetAuthRequestContext() +{ + char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; + Crypto::GetUdidHash(authResponseContext_->localDeviceId, reinterpret_cast(deviceIdHash)); + authRequestContext_->deviceId = static_cast(deviceIdHash); + authResponseContext_->deviceId = authResponseContext_->localDeviceId; + authResponseContext_->localDeviceId = authRequestContext_->localDeviceId; + authRequestContext_->remoteAccountId = authResponseContext_->localAccountId; + authResponseContext_->remoteAccountId = authRequestContext_->remoteAccountId; + authResponseContext_->localAccountId = authRequestContext_->localAccountId; + authRequestContext_->remoteUserId = authResponseContext_->localUserId; + if (authResponseContext_->isOnline && softbusConnector_->CheckIsOnline(remoteDeviceId_)) { + authResponseContext_->isOnline = true; + } else { + authResponseContext_->isOnline = false; + } + authResponseContext_->haveCredential = false; +} + +void DmAuthManager::ProcessAuthRequestExt(const int32_t &sessionId) +{ + LOGI("ProcessAuthRequestExt start."); + if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_3)) && + authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && + !authResponseContext_->importAuthCode.empty() && !importAuthCode_.empty()) { + if (authResponseContext_->importAuthCode != Crypto::Sha256(importAuthCode_)) { + SetReasonAndFinish(ERR_DM_AUTH_CODE_INCORRECT, AuthState::AUTH_REQUEST_FINISH); + return; + } + } + + GetAuthRequestContext(); + std::vector bindType = + DeviceProfileConnector::GetInstance().SyncAclByBindType(authResponseContext_->hostPkgName, + authResponseContext_->bindType, authResponseContext_->localDeviceId, authResponseContext_->deviceId); + authResponseContext_->authed = !bindType.empty(); + if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_3)) && + authResponseContext_->isOnline && authResponseContext_->authed && + authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && + (authResponseContext_->importAuthCode.empty() || importAuthCode_.empty())) { + SetReasonAndFinish(ERR_DM_AUTH_CODE_INCORRECT, AuthState::AUTH_REQUEST_FINISH); + return; + } + authResponseContext_->bindType = bindType; + if (IsAuthFinish()) { + return; + } + + std::vector messageList = authMessageProcessor_->CreateAuthRequestMessage(); + for (auto msg : messageList) { + softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg); + } + 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); + }); +} + +bool DmAuthManager::IsAuthFinish() +{ + if (authResponseContext_->reply == ERR_DM_UNSUPPORTED_AUTH_TYPE) { + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, + authRequestContext_->token, AuthState::AUTH_REQUEST_NEGOTIATE_DONE, ERR_DM_UNSUPPORTED_AUTH_TYPE); + authRequestState_->TransitionTo(std::make_shared()); + return true; + } + + if ((authResponseContext_->isIdenticalAccount && !authResponseContext_->authed) || + (authResponseContext_->authed && !authResponseContext_->isOnline)) { + JoinLnn(authRequestContext_->addr); + authRequestContext_->reason = DM_OK; + authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; + authResponseContext_->reply = DM_OK; + authRequestState_->TransitionTo(std::make_shared()); + return true; + } + + if (authResponseContext_->reply == ERR_DM_UNSUPPORTED_AUTH_TYPE || + (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && + authResponseContext_->isAuthCodeReady == false)) { + authRequestState_->TransitionTo(std::make_shared()); + return true; + } + return false; +} + +int32_t DmAuthManager::ConfirmProcess(const int32_t &action) +{ + LOGI("ConfirmProcess start."); + if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH || action_ == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { + authResponseContext_->reply = USER_OPERATION_TYPE_ALLOW_AUTH; + } else { + authResponseContext_->reply = action_; + } + + if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH && + authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_CONFIRM) { + authResponseState_->TransitionTo(std::make_shared()); + } else { + authMessageProcessor_->SetResponseContext(authResponseContext_); + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH); + softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); + } + return DM_OK; +} + +int32_t DmAuthManager::ConfirmProcessExt(const int32_t &action) +{ + LOGI("ConfirmProcessExt start."); + authResponseContext_->confirmOperation = action; + if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH || action_ == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { + authResponseContext_->reply = USER_OPERATION_TYPE_ALLOW_AUTH; + } else { + authResponseContext_->reply = USER_OPERATION_TYPE_CANCEL_AUTH; + } + authMessageProcessor_->SetResponseContext(authResponseContext_); + if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH && + authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_CONFIRM) { + if (CanUsePincodeFromDp()) { + authResponseContext_->code = serviceInfoProfile_.GetPinCode(); + LOGI("import pincode from dp"); + } else if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && !importAuthCode_.empty()) { + GetAuthCode(authResponseContext_->hostPkgName, authResponseContext_->code); + } else { + authResponseContext_->code = GeneratePincode(); + } + authResponseContext_->requestId = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); + authResponseState_->TransitionTo(std::make_shared()); + } + authMessageProcessor_->SetResponseContext(authResponseContext_); + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH_EXT); + softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); + return DM_OK; +} + +int32_t DmAuthManager::StartAuthProcess(const int32_t &action) +{ + if (authResponseContext_ == nullptr) { + LOGE("failed to StartAuthProcess because authResponseContext_ is nullptr"); + return ERR_DM_AUTH_NOT_START; + } + LOGI("DmAuthManager::StartAuthProcess"); + action_ = action; + struct RadarInfo info = { + .funcName = "StartAuthProcess", + .stageRes = (action_ == USER_OPERATION_TYPE_CANCEL_AUTH) ? + static_cast(StageRes::STAGE_CANCEL) : static_cast(StageRes::STAGE_SUCC), + .bizState = (action_ == USER_OPERATION_TYPE_CANCEL_AUTH) ? + static_cast(BizState::BIZ_STATE_END) : static_cast(BizState::BIZ_STATE_START), + .errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_AUTH_REJECT), + }; + if (!DmRadarHelper::GetInstance().ReportAuthConfirmBox(info)) { + LOGE("ReportAuthConfirmBox failed"); + } + if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && + (static_cast(authResponseContext_->bindLevel) >= USER && + static_cast(authResponseContext_->bindLevel) <= APP)) { + return ConfirmProcessExt(action); + } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || + static_cast(authResponseContext_->bindLevel) == INVALIED_TYPE) { + return ConfirmProcess(action); + } else { + LOGE("Invalied bind mode."); + } + return DM_OK; +} + +void DmAuthManager::StartRespAuthProcess() +{ + if (authResponseContext_ == nullptr) { + LOGE("failed to StartRespAuthProcess because authResponseContext_ is nullptr"); + return; + } + LOGI("DmAuthManager::StartRespAuthProcess sessionId = %{public}d", authResponseContext_->sessionId); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(CONFIRM_TIMEOUT_TASK)); + } + if (authResponseContext_->groupName[CHECK_AUTH_ALWAYS_POS] == AUTH_ALWAYS) { + action_ = USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + } else if (authResponseContext_->groupName[CHECK_AUTH_ALWAYS_POS] == AUTH_ONCE) { + action_ = USER_OPERATION_TYPE_ALLOW_AUTH; + } + if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH) { + timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), + GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + timer_->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), + GetTaskTimeout(SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleSessionHeartbeat(name); + }); + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, + authRequestContext_->token, STATUS_DM_SHOW_PIN_INPUT_UI, DM_OK); + listener_->OnBindResult(processInfo_, peerTargetId_, DM_OK, STATUS_DM_SHOW_PIN_INPUT_UI, ""); + authRequestState_->TransitionTo(std::make_shared()); + } else { + LOGE("do not accept"); + authResponseContext_->state = AuthState::AUTH_REQUEST_REPLY; + authRequestContext_->reason = ERR_DM_AUTH_PEER_REJECT; + authResponseContext_->reply = ERR_DM_AUTH_PEER_REJECT; + authRequestState_->TransitionTo(std::make_shared()); + } +} + +int32_t DmAuthManager::CreateGroup() +{ + if (authResponseContext_ == nullptr) { + LOGE("failed to CreateGroup because authResponseContext_ is nullptr"); + return ERR_DM_FAILED; + } + LOGI("DmAuthManager::CreateGroup start"); + authResponseContext_->groupName = GenerateGroupName(); + authResponseContext_->requestId = GenRandLongLong(MIN_REQUEST_ID, MAX_REQUEST_ID); + hiChainConnector_->CreateGroup(authResponseContext_->requestId, authResponseContext_->groupName); + return DM_OK; +} + +int32_t DmAuthManager::AddMember(const std::string &pinCode) +{ + if (authResponseContext_ == nullptr) { + LOGE("failed to AddMember because authResponseContext_ is nullptr"); + return ERR_DM_FAILED; + } + LOGI("DmAuthManager::AddMember start group id %{public}s", GetAnonyString(authResponseContext_->groupId).c_str()); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK)); + } + JsonObject jsonObject; + jsonObject[TAG_GROUP_ID] = authResponseContext_->groupId; + jsonObject[TAG_GROUP_NAME] = authResponseContext_->groupName; + jsonObject[PIN_CODE_KEY] = pinCode; + jsonObject[TAG_REQUEST_ID] = authResponseContext_->requestId; + jsonObject[TAG_DEVICE_ID] = authResponseContext_->deviceId; + std::string connectInfo = SafetyDump(jsonObject); + if (timer_ != nullptr) { + timer_->StartTimer(std::string(ADD_TIMEOUT_TASK), + GetTaskTimeout(ADD_TIMEOUT_TASK, ADD_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + } + if (authUiStateMgr_ == nullptr) { + LOGE("DmAuthManager::AddMember authUiStateMgr is null."); + return ERR_DM_FAILED; + } + if (isAddingMember_) { + LOGE("DmAuthManager::AddMember doing add member."); + authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_DOING_AUTH); + return ERR_DM_FAILED; + } + isAddingMember_ = true; + int32_t ret = hiChainConnector_->AddMember(authRequestContext_->addr, connectInfo); + struct RadarInfo info = { + .funcName = "AddMember", + .stageRes = (ret == 0) ? + static_cast(StageRes::STAGE_IDLE) : static_cast(StageRes::STAGE_FAIL), + .peerUdid = authResponseContext_ == nullptr ? "" : authResponseContext_->deviceId, + .errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_ADD_GROUP_FAILED), + }; + if (!DmRadarHelper::GetInstance().ReportAuthAddGroup(info)) { + LOGE("ReportAuthAddGroup failed"); + } + if (ret != 0) { + LOGE("DmAuthManager::AddMember failed, ret: %{public}d", ret); + isAddingMember_ = false; + return ERR_DM_ADD_GROUP_FAILED; + } + return DM_OK; +} + +std::string DmAuthManager::GetConnectAddr(std::string deviceId) +{ + std::string connectAddr; + if (softbusConnector_->GetConnectAddr(deviceId, connectAddr) == nullptr) { + LOGE("DmAuthManager::GetConnectAddr error"); + } + return connectAddr; +} + +int32_t DmAuthManager::JoinNetwork() +{ + if (authResponseContext_ == nullptr) { + LOGE("failed to JoinNeWork because authResponseContext_ is nullptr"); + return ERR_DM_FAILED; + } + LOGI("DmAuthManager JoinNetwork start"); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); + } + authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; + authResponseContext_->isFinish = true; + authRequestContext_->reason = DM_OK; + authResponseContext_->reply = DM_OK; + authRequestState_->TransitionTo(std::make_shared()); + return DM_OK; +} + +void DmAuthManager::SinkAuthenticateFinish() +{ + LOGI("DmAuthManager::SinkAuthenticateFinish, isFinishOfLocal: %{public}d", isFinishOfLocal_); + processInfo_.pkgName = authResponseContext_->peerBundleName; + listener_->OnSinkBindResult(processInfo_, peerTargetId_, authResponseContext_->reply, + authResponseContext_->state, GenerateBindResultContent()); + if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_FINISH && + (authResponseContext_->authType == AUTH_TYPE_NFC || authPtr_ != nullptr)) { + authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW); + authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_CONFIRM_SHOW); + } + if (isFinishOfLocal_) { + authMessageProcessor_->SetResponseContext(authResponseContext_); + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE); + softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); + } + authResponseState_ = nullptr; + authTimes_ = 0; +} + +void DmAuthManager::SrcAuthenticateFinish() +{ + LOGI("DmAuthManager::SrcAuthenticateFinish, isFinishOfLocal: %{public}d", isFinishOfLocal_); + if (isFinishOfLocal_) { + authMessageProcessor_->SetResponseContext(authResponseContext_); + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE); + softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); + } else { + authRequestContext_->reason = authResponseContext_->reply; + } + if ((authResponseContext_->state == AuthState::AUTH_REQUEST_JOIN || + authResponseContext_->state == AuthState::AUTH_REQUEST_FINISH) && + (authResponseContext_->authType == AUTH_TYPE_NFC || authPtr_ != nullptr)) { + authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); + } + if (timer_ == nullptr) { + timer_ = std::make_shared(); + } + int32_t closeSessionDelaySeconds = authRequestContext_->closeSessionDelaySeconds; + if (IsHmlSessionType() && closeSessionDelaySeconds == 0 && isWaitingJoinLnnCallback_) { + closeSessionDelaySeconds = SESSION_CLOSE_TIMEOUT; + } + timer_->StartTimer(std::string(WAIT_SESSION_CLOSE_TIMEOUT_TASK) + std::string(CLOSE_SESSION_TASK_SEPARATOR) + + std::to_string(authRequestContext_->sessionId), + closeSessionDelaySeconds, [this] (std::string name) { + int32_t sessionIdIndex = 1; + std::string sessionStr = GetSubStr(name, std::string(CLOSE_SESSION_TASK_SEPARATOR), sessionIdIndex); + if (!sessionStr.empty()) { + int32_t sessionId = std::atoi(sessionStr.c_str()); + DmAuthManager::CloseAuthSession(sessionId); + } + }); + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, authRequestContext_->token, + authResponseContext_->state, authRequestContext_->reason); + listener_->OnBindResult(processInfo_, peerTargetId_, authRequestContext_->reason, + authResponseContext_->state, GenerateBindResultContent()); + + authRequestContext_ = nullptr; + authRequestState_ = nullptr; + authTimes_ = 0; + isWaitingJoinLnnCallback_ = false; +} + +void DmAuthManager::AuthenticateFinish() +{ + { + std::lock_guard lock(srcReqMsgLock_); + srcReqMsg_ = ""; + isNeedProcCachedSrcReqMsg_ = false; + std::lock_guard guard(sessionKeyIdMutex_); + sessionKeyIdAsyncResult_.clear(); + } + pincodeDialogEverShown_ = false; + serviceInfoProfile_ = {}; + authType_ = AUTH_TYPE_UNKNOW; + std::lock_guard autoLock(g_authFinishLock); + if (authResponseContext_ == nullptr || authUiStateMgr_ == nullptr) { + LOGE("failed to AuthenticateFinish because authResponseContext_ or authUiStateMgr is nullptr"); + return; + } + LOGI("DmAuthManager::AuthenticateFinish start"); + isAddingMember_ = false; + isAuthenticateDevice_ = false; + isAuthDevice_ = false; + ClearCallerInfo(); + if (DeviceProfileConnector::GetInstance().GetTrustNumber(remoteDeviceId_) >= 1 && + CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && + softbusConnector_->CheckIsOnline(remoteDeviceId_) && authResponseContext_->isFinish) { + softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); + } + + DeleteAuthCode(); + if (timer_ != nullptr) { + timer_->DeleteAll(); + } + if (authResponseState_ != nullptr) { + SinkAuthenticateFinish(); + } else if (authRequestState_ != nullptr) { + SrcAuthenticateFinish(); + } + isFinishOfLocal_ = true; + authResponseContext_ = nullptr; + authMessageProcessor_ = nullptr; + authPtr_ = nullptr; + authRequestStateTemp_ = nullptr; + authenticationType_ = USER_OPERATION_TYPE_ALLOW_AUTH; + bundleName_ = ""; + if (cleanNotifyCallback_ != nullptr) { + cleanNotifyCallback_(0); + } + LOGI("DmAuthManager::AuthenticateFinish complete"); +} + +int32_t DmAuthManager::RegisterUiStateCallback(const std::string pkgName) +{ + LOGI("DmAuthManager::RegisterUiStateCallback start"); + if (authUiStateMgr_ == nullptr) { + LOGE("DmAuthManager::RegisterUiStateCallback authUiStateMgr_ is null."); + return ERR_DM_FAILED; + } + authUiStateMgr_->RegisterUiStateCallback(pkgName); + return DM_OK; +} + +int32_t DmAuthManager::UnRegisterUiStateCallback(const std::string pkgName) +{ + LOGI("DmAuthManager::UnRegisterUiStateCallback start"); + if (authUiStateMgr_ == nullptr) { + LOGE("DmAuthManager::UnRegisterUiStateCallback authUiStateMgr_ is null."); + return ERR_DM_FAILED; + } + authUiStateMgr_->UnRegisterUiStateCallback(pkgName); + return DM_OK; +} + +std::string DmAuthManager::GeneratePincode() +{ + int32_t pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); + return std::to_string(pinCode); +} + +bool DmAuthManager::IsPinCodeValid(const std::string strpin) +{ + if (strpin.empty()) { + return false; + } + for (size_t i = 0; i < strpin.length(); i++) { + if (!isdigit(strpin[i])) { + return false; + } + } + int32_t pinnum = std::atoi(strpin.c_str()); + return IsPinCodeValid(pinnum); +} + +bool DmAuthManager::IsPinCodeValid(int32_t numpin) +{ + if (numpin < MIN_PIN_CODE || numpin > MAX_PIN_CODE) { + return false; + } + return true; +} + +bool DmAuthManager::CanUsePincodeFromDp() +{ + CHECK_NULL_RETURN(authResponseContext_, false); + return (IsPinCodeValid(serviceInfoProfile_.GetPinCode()) && + serviceInfoProfile_.GetPinExchangeType() == (int32_t)DMLocalServiceInfoPinExchangeType::FROMDP); +} + +bool DmAuthManager::IsServiceInfoAuthTypeValid(int32_t authType) +{ + if (authType != (int32_t)DMLocalServiceInfoAuthType::TRUST_ONETIME && + authType != (int32_t)DMLocalServiceInfoAuthType::TRUST_ALWAYS && + authType != (int32_t)DMLocalServiceInfoAuthType::CANCEL) { + return false; + } + return true; +} + +bool DmAuthManager::IsServiceInfoAuthBoxTypeValid(int32_t authBoxType) +{ + if (authBoxType != (int32_t)DMLocalServiceInfoAuthBoxType::STATE3 && + authBoxType != (int32_t)DMLocalServiceInfoAuthBoxType::SKIP_CONFIRM) { + return false; + } + return true; +} + +bool DmAuthManager::IsServiceInfoPinExchangeTypeValid(int32_t pinExchangeType) +{ + if (pinExchangeType != (int32_t)DMLocalServiceInfoPinExchangeType::PINBOX && + pinExchangeType != (int32_t)DMLocalServiceInfoPinExchangeType::FROMDP && + pinExchangeType != (int32_t)DMLocalServiceInfoPinExchangeType::ULTRASOUND) { + return false; + } + return true; +} + +bool DmAuthManager::IsLocalServiceInfoValid(const DistributedDeviceProfile::LocalServiceInfo &localServiceInfo) +{ + if (!IsServiceInfoAuthTypeValid(localServiceInfo.GetAuthType())) { + LOGE("AuthType not valid, %{public}d", localServiceInfo.GetAuthType()); + return false; + } + if (!IsServiceInfoAuthBoxTypeValid(localServiceInfo.GetAuthBoxType())) { + LOGE("AuthBoxType not valid, %{public}d", localServiceInfo.GetAuthBoxType()); + return false; + } + if (!IsServiceInfoPinExchangeTypeValid(localServiceInfo.GetPinExchangeType())) { + LOGE("PinExchangeType not valid, %{public}d", localServiceInfo.GetPinExchangeType()); + return false; + } + return true; +} + +std::string DmAuthManager::GenerateGroupName() +{ + if (authResponseContext_ == nullptr) { + LOGE("failed to GenerateGroupName because authResponseContext_ is nullptr."); + return ""; + } + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string sLocalDeviceId = localDeviceId; + uint32_t interceptLength = sLocalDeviceId.size() / DEVICE_ID_HALF; + std::string groupName = ""; + if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { + groupName += AUTH_ALWAYS; + } else { + groupName += AUTH_ONCE; + } + groupName += authResponseContext_->targetPkgName + sLocalDeviceId.substr(0, interceptLength) + + authResponseContext_->localDeviceId.substr(0, interceptLength); + return groupName; +} + +bool DmAuthManager::GetIsCryptoSupport() +{ + if (authResponseState_ == nullptr) { + return false; + } + if (authRequestState_ == nullptr) { + if (authResponseState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) { + return false; + } + } else { + if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE || + authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) { + return false; + } + } + + return isCryptoSupport_; +} + +int32_t DmAuthManager::SetAuthRequestState(std::shared_ptr authRequestState) +{ + if (authRequestState == nullptr) { + LOGE("authRequestState is nullptr."); + return ERR_DM_INPUT_PARA_INVALID; + } + // Keep current state, avoid deconstructed during state transitions + authRequestStateTemp_ = authRequestState_; + authRequestState_ = authRequestState; + return DM_OK; +} + +int32_t DmAuthManager::SetAuthResponseState(std::shared_ptr authResponseState) +{ + if (authResponseState == nullptr) { + LOGE("authResponseState is nullptr."); + return ERR_DM_INPUT_PARA_INVALID; + } + authResponseState_ = authResponseState; + return DM_OK; +} + +int32_t DmAuthManager::GetPinCode(std::string &code) +{ + if (authResponseContext_ == nullptr) { + LOGE("failed to GetPinCode because authResponseContext_ is nullptr"); + return ERR_DM_FAILED; + } + LOGI("ShowConfigDialog start add member pin code."); + code = authResponseContext_->code; + return DM_OK; +} + +void DmAuthManager::CheckAndEndTvDream() +{ + NodeBasicInfo nodeBasicInfo; + int32_t result = GetLocalNodeDeviceInfo(DM_PKG_NAME, &nodeBasicInfo); + if (result != SOFTBUS_OK) { + LOGE("GetLocalNodeDeviceInfo from dsofbus fail, result=%{public}d", result); + return; + } + + if (nodeBasicInfo.deviceTypeId == TYPE_TV_ID) { + int32_t ret = AuthManagerBase::EndDream(); + if (ret != DM_OK) { + LOGE("fail to end dream, err:%{public}d", ret); + return; + } + } +} + +void DmAuthManager::ShowConfigDialog() +{ + if (authResponseContext_ == nullptr) { + LOGE("failed to ShowConfigDialog because authResponseContext_ is nullptr"); + return; + } + if (authResponseContext_->authType == AUTH_TYPE_NFC && + serviceInfoProfile_.GetAuthBoxType() == (int32_t)DMLocalServiceInfoAuthBoxType::SKIP_CONFIRM) { + LOGI("no need confirm dialog"); + StartAuthProcess(serviceInfoProfile_.GetAuthType()); + return; + } + if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && !importAuthCode_.empty()) { + LOGI("start auth process"); + StartAuthProcess(authenticationType_); + return; + } + CheckAndEndTvDream(); + LOGI("ShowConfigDialog start"); + JsonObject jsonObj; + jsonObj[TAG_AUTH_TYPE] = AUTH_TYPE_PIN; + jsonObj[TAG_TOKEN] = authResponseContext_->token; + jsonObj[TARGET_PKG_NAME_KEY] = authResponseContext_->targetPkgName; + jsonObj[TAG_CUSTOM_DESCRIPTION] = authResponseContext_->customDesc; + jsonObj[TAG_APP_OPERATION] = authResponseContext_->appOperation; + jsonObj[TAG_LOCAL_DEVICE_TYPE] = authResponseContext_->deviceTypeId; + jsonObj[TAG_REQUESTER] = authResponseContext_->deviceName; + jsonObj[TAG_HOST_PKGLABEL] = authResponseContext_->hostPkgLabel; + const std::string params = SafetyDump(jsonObj); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string localUdid = static_cast(localDeviceId); + DeviceProfileConnector::GetInstance().SyncAclByBindType(authResponseContext_->peerBundleName, + authResponseContext_->bindType, localUdid, remoteDeviceId_); + DmDialogManager::GetInstance().ShowConfirmDialog(params); + struct RadarInfo info = { + .funcName = "ShowConfigDialog", + .stageRes = static_cast(StageRes::STAGE_IDLE), + }; + if (!DmRadarHelper::GetInstance().ReportAuthPullAuthBox(info)) { + LOGE("ReportAuthPullAuthBox failed"); + } + LOGI("ShowConfigDialog end"); +} + +void DmAuthManager::ShowAuthInfoDialog(bool authDeviceError) +{ + if (authResponseContext_ == nullptr) { + LOGE("failed to ShowAuthInfoDialog because authResponseContext_ is nullptr"); + return; + } + LOGI("DmAuthManager::ShowAuthInfoDialog start"); + if (!authDeviceError && CanUsePincodeFromDp()) { + LOGI("pin import from dp, not show dialog"); + return; + } + if (pincodeDialogEverShown_) { + return; + } + if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && !importAuthCode_.empty()) { + LOGI("not show dialog."); + return; + } + struct RadarInfo info = { + .funcName = "ShowAuthInfoDialog", + .stageRes = static_cast(StageRes::STAGE_SUCC), + }; + if (!DmRadarHelper::GetInstance().ReportAuthPullPinBox(info)) { + LOGE("ReportAuthPullPinBox failed"); + } + pincodeDialogEverShown_ = true; + DmDialogManager::GetInstance().ShowPinDialog(authResponseContext_->code); +} + +void DmAuthManager::ShowStartAuthDialog() +{ + if (authResponseContext_ == nullptr) { + LOGE("failed to ShowStartAuthDialog because authResponseContext_ is nullptr"); + return; + } + if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { + LOGI("Add member start"); + std::string pinCode = ""; + if (GetAuthCode(authResponseContext_->hostPkgName, pinCode) != DM_OK) { + LOGE("failed to get auth code"); + return; + } + if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && + (static_cast(authResponseContext_->bindLevel) >= USER && + static_cast(authResponseContext_->bindLevel) <= APP)) { + AuthDevice(pinCode); + } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || + static_cast(authResponseContext_->bindLevel) == INVALIED_TYPE) { + AddMember(pinCode); + } else { + LOGE("Invalied bind mode."); + } + return; + } + if (IsScreenLocked()) { + LOGE("ShowStartAuthDialog screen is locked."); + SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL, STATUS_DM_AUTH_DEFAULT); + return; + } + LOGI("DmAuthManager::ShowStartAuthDialog start"); + std::string pincode = ""; + if (authResponseContext_->authType == AUTH_TYPE_NFC && + GetAuthCode(authResponseContext_->hostPkgName, pincode) == DM_OK) { + LOGI("already has pin code"); + ProcessPincode(pincode); + return; + } + + pincodeDialogEverShown_ = true; + DmDialogManager::GetInstance().ShowInputDialog(authResponseContext_->targetDeviceName); +} + +int32_t DmAuthManager::ProcessPincode(const std::string &pinCode) +{ + if (authResponseContext_ == nullptr) { + LOGE("failed to ProcessPincode because authResponseContext_ is nullptr"); + return ERR_DM_FAILED; + } + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK)); + } + if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && + (static_cast(authResponseContext_->bindLevel) >= USER && + static_cast(authResponseContext_->bindLevel) <= APP)) { + return AuthDevice(pinCode); + } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || + static_cast(authResponseContext_->bindLevel) == INVALIED_TYPE) { + return AddMember(pinCode); + } else { + LOGE("Invalied bind mode."); + } + return ERR_DM_FAILED; +} + +int32_t DmAuthManager::AuthDevice(const std::string &pinCode) +{ + LOGI("DmAuthManager::AuthDevice start."); + if (isAuthDevice_) { + LOGE("DmAuthManager::AuthDevice doing auth device."); + authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_DOING_AUTH); + return ERR_DM_FAILED; + } + isAuthDevice_ = true; + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK)); + timer_->StartTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK), AUTH_DEVICE_TIMEOUT, + [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + } + if (hiChainAuthConnector_->AuthDevice(pinCode, osAccountId, remoteDeviceId_, + authResponseContext_->requestId) != DM_OK) { + LOGE("DmAuthManager::AuthDevice failed."); + isAuthDevice_ = false; + if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { + HandleMemberJoinImportAuthCode(authResponseContext_->requestId, ERR_DM_FAILED); + return ERR_DM_FAILED; + } + } + return DM_OK; +} + +int32_t DmAuthManager::OnUserOperation(int32_t action, const std::string ¶ms) +{ + if (authResponseContext_ == nullptr) { + LOGE("Authenticate is not start"); + return ERR_DM_AUTH_NOT_START; + } + struct RadarInfo info = { + .funcName = "OnUserOperation", + .stageRes = static_cast(StageRes::STAGE_CANCEL), + .bizState = static_cast(BizState::BIZ_STATE_END), + }; + switch (action) { + case USER_OPERATION_TYPE_ALLOW_AUTH: + case USER_OPERATION_TYPE_CANCEL_AUTH: + case USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS: + StartAuthProcess(action); + break; + case USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT: + SetReasonAndFinish(ERR_DM_TIME_OUT, STATUS_DM_AUTH_DEFAULT); + info.errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_TIME_OUT); + break; + case USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY: + SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY, STATUS_DM_AUTH_DEFAULT); + info.errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY); + break; + case USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT: + SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL_ERROR, STATUS_DM_AUTH_DEFAULT); + info.errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_BIND_USER_CANCEL_ERROR); + break; + case USER_OPERATION_TYPE_DONE_PINCODE_INPUT: + ProcessPincode(params); + info.stageRes = static_cast(StageRes::STAGE_SUCC); + break; + default: + LOGE("this action id not support"); + break; + } + if (!DmRadarHelper::GetInstance().ReportAuthConfirmBox(info)) { + LOGE("ReportAuthConfirmBox failed"); + } + return DM_OK; +} + +int32_t DmAuthManager::SetPageId(int32_t pageId) +{ + if (authResponseContext_ == nullptr) { + LOGE("Authenticate is not start"); + return ERR_DM_AUTH_NOT_START; + } + authResponseContext_->pageId = pageId; + return DM_OK; +} + +int32_t DmAuthManager::SetReasonAndFinish(int32_t reason, int32_t state) +{ + if (authResponseContext_ == nullptr) { + LOGE("Authenticate is not start"); + return ERR_DM_AUTH_NOT_START; + } + authResponseContext_->state = state; + authResponseContext_->reply = reason; + if (authRequestState_ != nullptr && authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) { + authRequestContext_->reason = reason; + authRequestState_->TransitionTo(std::make_shared()); + } else if (authResponseState_ != nullptr && authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) { + authResponseState_->TransitionTo(std::make_shared()); + } + return DM_OK; +} + +bool DmAuthManager::IsIdenticalAccount() +{ + JsonObject jsonObj; + jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP; + std::string queryParams = SafetyDump(jsonObj); + + int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); + if (osAccountUserId < 0) { + LOGE("get current process account user id failed"); + return false; + } + std::vector groupList; + if (!hiChainConnector_->GetGroupInfo(osAccountUserId, queryParams, groupList)) { + return false; + } + if (authResponseContext_ == nullptr) { + LOGE("authResponseContext_ is nullptr."); + return false; + } + if (authResponseContext_->accountGroupIdHash == OLD_VERSION_ACCOUNT) { + LOGI("The old version."); + return true; + } + JsonObject jsonPeerGroupIdObj(authResponseContext_->accountGroupIdHash); + if (jsonPeerGroupIdObj.IsDiscarded()) { + LOGE("accountGroupIdHash string not a json type."); + return false; + } + + std::vector items = jsonPeerGroupIdObj.Items(); + for (auto &groupInfo : groupList) { + for (auto it = items.begin(); it != items.end(); ++it) { + if (it->IsString() && it->Get() == Crypto::GetGroupIdHash(groupInfo.groupId)) { + LOGI("Is identical Account."); + return true; + } + } + } + return false; +} + +std::string DmAuthManager::GetAccountGroupIdHash() +{ + JsonObject jsonObj; + jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP; + std::string queryParams = SafetyDump(jsonObj); + + int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); + if (osAccountUserId < 0) { + LOGE("get current process account user id failed"); + return ""; + } + std::vector groupList; + if (!hiChainConnector_->GetGroupInfo(osAccountUserId, queryParams, groupList)) { + return ""; + } + JsonObject jsonAccountObj(JsonCreateType::JSON_CREATE_TYPE_ARRAY); + for (auto &groupInfo : groupList) { + jsonAccountObj.PushBack(Crypto::GetGroupIdHash(groupInfo.groupId)); + } + return SafetyDump(jsonAccountObj); +} + +int32_t DmAuthManager::ImportAuthCode(const std::string &pkgName, const std::string &authCode) +{ + if (authCode.empty() || pkgName.empty()) { + LOGE("ImportAuthCode failed, authCode or pkgName is empty"); + return ERR_DM_INPUT_PARA_INVALID; + } + importAuthCode_ = authCode; + importPkgName_ = pkgName; + return DM_OK; +} + +int32_t DmAuthManager::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, + const std::map &bindParam, int sessionId, uint64_t logicalSessionId) +{ + struct RadarInfo info = { + .funcName = "AuthenticateDevice", + .stageRes = static_cast(StageRes::STAGE_SUCC), + .bizState = static_cast(BizState::BIZ_STATE_END), + }; + if (!DmRadarHelper::GetInstance().ReportDiscoverUserRes(info)) { + LOGE("ReportDiscoverUserRes failed"); + } + if (pkgName.empty()) { + LOGE("DmAuthManager::BindTarget failed, pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + int32_t authType = -1; + if (ParseAuthType(bindParam, authType) != DM_OK) { + LOGE("DmAuthManager::BindTarget failed, key: %{public}s error.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + peerTargetId_ = targetId; + std::string deviceId = ""; + std::string addrType; + if (bindParam.count(PARAM_KEY_CONN_ADDR_TYPE) != 0) { + addrType = bindParam.at(PARAM_KEY_CONN_ADDR_TYPE); + } + if (ParseConnectAddr(targetId, deviceId, addrType) == DM_OK) { + return AuthenticateDevice(pkgName, authType, deviceId, ParseExtraFromMap(bindParam)); + } else if (!targetId.deviceId.empty()) { + return AuthenticateDevice(pkgName, authType, targetId.deviceId, ParseExtraFromMap(bindParam)); + } else { + LOGE("DmAuthManager::BindTarget failed, targetId is error."); + return ERR_DM_INPUT_PARA_INVALID; + } +} + +int32_t DmAuthManager::ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, std::string &addrType) +{ + int32_t index = 0; + std::shared_ptr deviceInfo = std::make_shared(); + ConnectionAddr addr; + if (!targetId.wifiIp.empty() && targetId.wifiIp.length() <= IP_STR_MAX_LEN) { + LOGI("DmAuthManager::ParseConnectAddr parse wifiIp: %{public}s.", GetAnonyString(targetId.wifiIp).c_str()); + if (!addrType.empty()) { + addr.type = static_cast(std::atoi(addrType.c_str())); + } else { + addr.type = ConnectionAddrType::CONNECTION_ADDR_WLAN; + } + memcpy_s(addr.info.ip.ip, IP_STR_MAX_LEN, targetId.wifiIp.c_str(), targetId.wifiIp.length()); + addr.info.ip.port = targetId.wifiPort; + deviceInfo->addr[index] = addr; + deviceId = targetId.wifiIp; + index++; + } else if (!targetId.brMac.empty() && targetId.brMac.length() <= BT_MAC_LEN) { + LOGI("DmAuthManager::ParseConnectAddr parse brMac: %{public}s.", GetAnonyString(targetId.brMac).c_str()); + addr.type = ConnectionAddrType::CONNECTION_ADDR_BR; + memcpy_s(addr.info.br.brMac, BT_MAC_LEN, targetId.brMac.c_str(), targetId.brMac.length()); + deviceInfo->addr[index] = addr; + deviceId = targetId.brMac; + index++; + } else if (!targetId.bleMac.empty() && targetId.bleMac.length() <= BT_MAC_LEN) { + LOGI("DmAuthManager::ParseConnectAddr parse bleMac: %{public}s.", GetAnonyString(targetId.bleMac).c_str()); + addr.type = ConnectionAddrType::CONNECTION_ADDR_BLE; + memcpy_s(addr.info.ble.bleMac, BT_MAC_LEN, targetId.bleMac.c_str(), targetId.bleMac.length()); + if (!targetId.deviceId.empty()) { + Crypto::ConvertHexStringToBytes(addr.info.ble.udidHash, UDID_HASH_LEN, + targetId.deviceId.c_str(), targetId.deviceId.length()); + } + deviceInfo->addr[index] = addr; + deviceId = targetId.bleMac; + index++; + } else { + LOGE("DmAuthManager::ParseConnectAddr failed, not addr."); + return ERR_DM_INPUT_PARA_INVALID; + } + + deviceInfo->addrNum = static_cast(index); + if (softbusConnector_->AddMemberToDiscoverMap(deviceId, deviceInfo) != DM_OK) { + LOGE("DmAuthManager::ParseConnectAddr failed, AddMemberToDiscoverMap failed."); + return ERR_DM_INPUT_PARA_INVALID; + } + deviceInfo = nullptr; + return DM_OK; +} + +std::string DmAuthManager::ParseExtraFromMap(const std::map &bindParam) +{ + auto iter = bindParam.find(PARAM_KEY_BIND_EXTRA_DATA); + if (iter != bindParam.end()) { + return iter->second; + } + return ConvertMapToJsonString(bindParam); +} + +bool DmAuthManager::IsAuthCodeReady(const std::string &pkgName) +{ + if (importAuthCode_.empty() || importPkgName_.empty()) { + LOGE("DmAuthManager::IsAuthCodeReady, auth code not ready."); + return false; + } + if (pkgName != importPkgName_) { + LOGE("IsAuthCodeReady failed, pkgName not supported."); + return false; + } + return true; +} + +int32_t DmAuthManager::DeleteAuthCode() +{ + importAuthCode_ = ""; + importPkgName_ = ""; + return DM_OK; +} + +int32_t DmAuthManager::GetAuthCode(const std::string &pkgName, std::string &pinCode) +{ + if (importAuthCode_.empty() || importPkgName_.empty()) { + LOGE("GetAuthCode failed, auth code not exist."); + return ERR_DM_FAILED; + } + if (pkgName != importPkgName_) { + LOGE("GetAuthCode failed, pkgName not supported."); + return ERR_DM_FAILED; + } + pinCode = std::to_string(std::atoi(importAuthCode_.c_str())); + return DM_OK; +} + +bool DmAuthManager::IsImportedAuthCodeValid() +{ + std::string pinCode = ""; + if (GetAuthCode(authRequestContext_->hostPkgName, pinCode) == DM_OK) { + return true; + } + return false; +} + +bool DmAuthManager::IsSrc() +{ + if (authRequestState_ != nullptr) { + return true; + } else { + return false; + } +} + +bool DmAuthManager::IsAuthTypeSupported(const int32_t &authType) +{ + if (authenticationMap_.find(authType) == authenticationMap_.end()) { + LOGE("IsAuthTypeSupported failed, authType is not supported."); + return false; + } + return true; +} + +std::string DmAuthManager::GenerateBindResultContent() +{ + JsonObject jsonObj; + jsonObj[DM_BIND_RESULT_NETWORK_ID] = authResponseContext_->networkId; + if (remoteDeviceId_.empty()) { + jsonObj[TAG_DEVICE_ID] = ""; + } else { + char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; + Crypto::GetUdidHash(remoteDeviceId_, reinterpret_cast(deviceIdHash)); + jsonObj[TAG_DEVICE_ID] = deviceIdHash; + } + jsonObj[TAG_CONFIRM_OPERATION] = authResponseContext_->confirmOperation; + std::string content = SafetyDump(jsonObj); + return content; +} + +void DmAuthManager::RequestCredential() +{ + LOGI("DmAuthManager::RequestCredential start."); + std::string publicKey = ""; + GenerateCredential(publicKey); + authResponseContext_->publicKey = publicKey; + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_PUBLICKEY); + softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); +} + +void DmAuthManager::GenerateCredential(std::string &publicKey) +{ + LOGI("DmAuthManager::GenerateCredential start."); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string localUdid = localDeviceId; + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + hiChainAuthConnector_->GetCredential(localUdid, osAccountId, publicKey); + if (publicKey == "") { + hiChainAuthConnector_->GenerateCredential(localUdid, osAccountId, publicKey); + } +} + +void DmAuthManager::RequestCredentialDone() +{ + LOGI("DmAuthManager ExchangeCredentailDone start"); + CHECK_NULL_VOID(authResponseContext_); + if (authResponseContext_->publicKey == "" || + ImportCredential(remoteDeviceId_, authResponseContext_->publicKey) != DM_OK) { + LOGE("RequestCredentialDone import credential failed."); + } + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); + } + if (softbusConnector_->CheckIsOnline(remoteDeviceId_) && !authResponseContext_->isOnline) { + JoinLnn(authRequestContext_->addr, true); + } else { + JoinLnn(authRequestContext_->addr, false); + } + authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; + authRequestContext_->reason = DM_OK; + authResponseContext_->reply = DM_OK; + authRequestState_->TransitionTo(std::make_shared()); +} + +int32_t DmAuthManager::ImportCredential(std::string &deviceId, std::string &publicKey) +{ + LOGI("DmAuthManager::ImportCredential, deviceId %{public}s", GetAnonyString(deviceId).c_str()); + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + if ((authRequestState_ != nullptr) && (authResponseState_ == nullptr)) { + // Source Import Credential + LOGI("Source Import Credential remoteUserId: %{public}d", authRequestContext_->remoteUserId); + CHECK_NULL_RETURN(authRequestContext_, ERR_DM_POINT_NULL); + CHECK_NULL_RETURN(hiChainAuthConnector_, ERR_DM_POINT_NULL); + return hiChainAuthConnector_->ImportCredential(osAccountId, authRequestContext_->remoteUserId, deviceId, + publicKey); + } else if ((authResponseState_ != nullptr) && (authRequestState_ == nullptr)) { + // Sink Import Credential + LOGI("Source Import Credential remoteUserId: %{public}d", authResponseContext_->remoteUserId); + CHECK_NULL_RETURN(authResponseContext_, ERR_DM_POINT_NULL); + CHECK_NULL_RETURN(hiChainAuthConnector_, ERR_DM_POINT_NULL); + return hiChainAuthConnector_->ImportCredential(osAccountId, authResponseContext_->remoteUserId, deviceId, + publicKey); + } else { + LOGE("DmAuthManager::ImportCredential failed, authRequestState_ or authResponseState_ is invalid."); + return ERR_DM_AUTH_FAILED; + } +} + +void DmAuthManager::ResponseCredential() +{ + LOGI("DmAuthManager::ResponseCredential start."); + CHECK_NULL_VOID(authResponseContext_); + if (authResponseContext_->publicKey == "") { + LOGE("authResponseContext_->publicKey is empty."); + authResponseContext_->isFinish = false; + isFinishOfLocal_ = false; + authMessageProcessor_->SetEncryptFlag(false); + authResponseContext_->state = authResponseState_->GetStateType(); + authResponseState_->TransitionTo(std::make_shared()); + return; + } + std::string publicKey = ""; + GenerateCredential(publicKey); + if (ImportCredential(remoteDeviceId_, authResponseContext_->publicKey) != DM_OK) { + LOGE("ResponseCredential import credential failed."); + authResponseContext_->state = authResponseState_->GetStateType(); + authResponseState_->TransitionTo(std::make_shared()); + return; + } + authResponseContext_->publicKey = publicKey; + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_PUBLICKEY); + softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); +} + +bool DmAuthManager::AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) +{ + LOGI("DmAuthManager::onTransmit start."); + if (requestId != authResponseContext_->requestId) { + LOGE("DmAuthManager::onTransmit requestId %{public}" PRId64"is error.", requestId); + return false; + } + std::string message = ""; + if (authRequestState_ != nullptr && authResponseState_ == nullptr) { + LOGI("SoftbusSession send msgType %{public}d.", MSG_TYPE_REQ_AUTH_DEVICE_NEGOTIATE); + message = authMessageProcessor_->CreateDeviceAuthMessage(MSG_TYPE_REQ_AUTH_DEVICE_NEGOTIATE, data, dataLen); + } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) { + LOGI("SoftbusSession send msgType %{public}d.", MSG_TYPE_RESP_AUTH_DEVICE_NEGOTIATE); + message = authMessageProcessor_->CreateDeviceAuthMessage(MSG_TYPE_RESP_AUTH_DEVICE_NEGOTIATE, data, dataLen); + } + if (softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message) != DM_OK) { + LOGE("SoftbusSession send data failed."); + return false; + } + return true; +} + +void DmAuthManager::SrcAuthDeviceFinish() +{ + LOGI("DmAuthManager::SrcAuthDeviceFinish Start."); + CHECK_NULL_VOID(authRequestState_); + authRequestState_->TransitionTo(std::make_shared()); + if (authResponseContext_->confirmOperation != USER_OPERATION_TYPE_ALLOW_AUTH && + authResponseContext_->confirmOperation != USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { + LOGE("auth failed %{public}d.", authResponseContext_->confirmOperation); + return; + } + if (authResponseContext_->isOnline && authResponseContext_->haveCredential) { + if (!authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { + SetProcessInfo(); + } + softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); + } + ConverToFinish(); + return; + } + if (authResponseContext_->isOnline && !authResponseContext_->haveCredential) { + authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); + if (!authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { + SetProcessInfo(); + } + softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); + if (CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_2))) { + authRequestState_->TransitionTo(std::make_shared()); + } else { + authRequestState_->TransitionTo(std::make_shared()); + } + return; + } + if (!authResponseContext_->isOnline && authResponseContext_->haveCredential) { + JoinLnn(authRequestContext_->addr); + timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); + ConverToFinish(); + return; + } + if (!authResponseContext_->isOnline && !authResponseContext_->haveCredential) { + authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); + if (CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_2))) { + authRequestState_->TransitionTo(std::make_shared()); + } else { + authRequestState_->TransitionTo(std::make_shared()); + } + return; + } +} + +void DmAuthManager::SinkAuthDeviceFinish() +{ + LOGI("isNeedProcCachedSrcReqMsg %{public}d.", isNeedProcCachedSrcReqMsg_); + CHECK_NULL_VOID(authResponseState_); + authResponseState_->TransitionTo(std::make_shared()); + if (!authResponseContext_->haveCredential) { + authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW); + } + if (authResponseContext_->isOnline) { + LOGI("The device is online."); + SetProcessInfo(); + softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); + } + std::string srcReqMsg = ""; + bool isNeedProcCachedSrcReqMsg = false; + { + std::lock_guard lock(srcReqMsgLock_); + srcReqMsg = srcReqMsg_; + isNeedProcCachedSrcReqMsg = isNeedProcCachedSrcReqMsg_; + srcReqMsg_ = ""; + isNeedProcCachedSrcReqMsg_ = false; + } + if (!isNeedProcCachedSrcReqMsg || srcReqMsg.empty()) { + LOGI("please wait client request."); + return; + } + authMessageProcessor_->SetResponseContext(authResponseContext_); + if (authMessageProcessor_->ParseMessage(srcReqMsg) != DM_OK) { + LOGE("ParseMessage failed."); + return; + } + if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_2))) { + authResponseState_->TransitionTo(std::make_shared()); + } else { + authResponseState_->TransitionTo(std::make_shared()); + } +} + +void DmAuthManager::AuthDeviceFinish(int64_t requestId) +{ + LOGI("DmAuthManager::AuthDeviceFinish start."); + if (requestId != authResponseContext_->requestId) { + LOGE("DmAuthManager::onTransmit requestId %{public}" PRId64 "is error.", requestId); + return; + } + isAuthDevice_ = false; + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK)); + } + if (CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_2))) { + LOGI("Set EncryptFlag true."); + authMessageProcessor_->SetEncryptFlag(true); + } else { + PutAccessControlList(); + } + if (authRequestState_ != nullptr && authResponseState_ == nullptr) { + SrcAuthDeviceFinish(); + } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) { + SinkAuthDeviceFinish(); + } +} + +void DmAuthManager::AuthDeviceError(int64_t requestId, int32_t errorCode) +{ + LOGI("AuthDeviceError start."); + isAuthDevice_ = false; + if (authRequestState_ == nullptr || authResponseState_ != nullptr) { + if (CheckNeedShowAuthInfoDialog(errorCode)) { + return; + } + authTimes_++; + if (authTimes_ >= MAX_AUTH_TIMES) { + authResponseContext_->isFinish = false; + authResponseContext_->reply = ERR_DM_AUTH_CODE_INCORRECT; + authResponseContext_->state = AuthState::AUTH_RESPONSE_SHOW; + isFinishOfLocal_ = false; + authResponseState_->TransitionTo(std::make_shared()); + } + return; + } + if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { + if (requestId != authResponseContext_->requestId) { + LOGE("DmAuthManager::AuthDeviceError requestId %{public}" PRId64 "is error.", requestId); + return; + } + authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; + authRequestContext_->reason = ERR_DM_AUTH_CODE_INCORRECT; + authResponseContext_->reply = ERR_DM_AUTH_CODE_INCORRECT; + authRequestState_->TransitionTo(std::make_shared()); + return; + } + authTimes_++; + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK)); + } + if (errorCode != DM_OK || requestId != authResponseContext_->requestId) { + if (authRequestState_ != nullptr && authTimes_ >= MAX_AUTH_TIMES) { + authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; + authRequestContext_->reason = ERR_DM_INPUT_PARA_INVALID; + authResponseContext_->reply = ERR_DM_INPUT_PARA_INVALID; + authRequestState_->TransitionTo(std::make_shared()); + } else { + if (timer_ != nullptr) { + timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), + GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + } + UpdateInputPincodeDialog(errorCode); + } + } +} + +void DmAuthManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) +{ + LOGI("DmAuthManager::AuthDeviceSessionKey start. keyLen: %{public}u", sessionKeyLen); + if (requestId != authResponseContext_->requestId) { + LOGE("DmAuthManager::onTransmit requestId %{public}" PRId64 "is error.", requestId); + return; + } + CHECK_NULL_VOID(authMessageProcessor_); + if (CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_4))) { + if (authMessageProcessor_->ProcessSessionKey(sessionKey, sessionKeyLen) != DM_OK) { + LOGE("Process session key err."); + return; + } + } else { + if (authMessageProcessor_->SaveSessionKey(sessionKey, sessionKeyLen) != DM_OK) { + LOGE("Save session key err."); + return; + } + } + authResponseContext_->localSessionKeyId = 0; + { + std::lock_guard guard(sessionKeyIdMutex_); + sessionKeyIdAsyncResult_.clear(); + sessionKeyIdAsyncResult_[requestId] = std::optional(); + } + unsigned char hash[SHA256_DIGEST_LENGTH] = { 0 }; + Crypto::DmGenerateStrHash(sessionKey, sessionKeyLen, hash, SHA256_DIGEST_LENGTH, 0); + std::vector hashVector(hash, hash + SHA256_DIGEST_LENGTH); + std::shared_ptr sharePtrThis = shared_from_this(); + auto asyncTaskFunc = [sharePtrThis, requestId, hashVector]() { + sharePtrThis->PutSessionKeyAsync(requestId, hashVector); + }; + ffrt::submit(asyncTaskFunc, ffrt::task_attr().delay(0)); +} + +void DmAuthManager::PutSessionKeyAsync(int64_t requestId, std::vector hash) +{ + { + std::lock_guard guard(sessionKeyIdMutex_); + int32_t sessionKeyId = 0; + int32_t ret = + DeviceProfileConnector::GetInstance().PutSessionKey(MultipleUserConnector::GetCurrentAccountUserID(), + hash, sessionKeyId); + if (ret != DM_OK) { + LOGI("PutSessionKey failed."); + sessionKeyId = 0; + } + sessionKeyIdAsyncResult_[requestId] = sessionKeyId; + } + sessionKeyIdCondition_.notify_one(); +} + +int32_t DmAuthManager::GetSessionKeyIdSync(int64_t requestId) +{ + std::unique_lock guard(sessionKeyIdMutex_); + if (sessionKeyIdAsyncResult_.find(requestId) == sessionKeyIdAsyncResult_.end()) { + LOGW("GetSessionKeyIdSync failed, not find by requestId"); + return 0; + } + if (sessionKeyIdAsyncResult_[requestId].has_value()) { + LOGI("GetSessionKeyIdSync, already ready"); + return sessionKeyIdAsyncResult_[requestId].value(); + } + LOGI("GetSessionKeyIdSync need wait"); + sessionKeyIdCondition_.wait_for(guard, std::chrono::milliseconds(MAX_PUT_SESSIONKEY_TIMEOUT)); + int32_t keyid = sessionKeyIdAsyncResult_[requestId].value_or(0); + LOGI("GetSessionKeyIdSync exit"); + return keyid; +} + +char *DmAuthManager::AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) +{ + LOGI("DmAuthManager::AuthDeviceRequest start."); + (void)requestId; + (void)reqParams; + JsonObject jsonObj; + std::string pinCode = ""; + if (GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == "") { + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED; + } else { + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; + jsonObj[FIELD_PIN_CODE] = pinCode; + } + std::string deviceId = ""; + GetRemoteDeviceId(deviceId); + jsonObj[FIELD_PEER_CONN_DEVICE_ID] = deviceId; + std::string jsonStr = SafetyDump(jsonObj); + char *buffer = strdup(jsonStr.c_str()); + return buffer; +} + +void DmAuthManager::GetRemoteDeviceId(std::string &deviceId) +{ + LOGI("GetRemoteDeviceId start."); + deviceId = remoteDeviceId_; +} + +void DmAuthManager::CompatiblePutAcl() +{ + LOGI("DmAuthManager::CompatiblePutAcl"); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string localUdid = static_cast(localDeviceId); + char mUdidHash[DM_MAX_DEVICE_ID_LEN] = {0}; + Crypto::GetUdidHash(localUdid, reinterpret_cast(mUdidHash)); + std::string localUdidHash = static_cast(mUdidHash); + DmAclInfo aclInfo; + aclInfo.bindLevel = USER; + aclInfo.bindType = DM_POINT_TO_POINT; + aclInfo.trustDeviceId = remoteDeviceId_; + if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { + aclInfo.authenticationType = ALLOW_AUTH_ALWAYS; + } else if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH) { + aclInfo.authenticationType = ALLOW_AUTH_ONCE; + } + aclInfo.deviceIdHash = localUdidHash; + + DmAccesser accesser; + DmAccessee accessee; + if (authRequestState_ != nullptr && authResponseState_ == nullptr) { + accesser.requestBundleName = authResponseContext_->hostPkgName; + accesser.requestDeviceId = localUdid; + accesser.requestUserId = MultipleUserConnector::GetCurrentAccountUserID(); + accesser.requestAccountId = MultipleUserConnector::GetAccountInfoByUserId(accesser.requestUserId).accountId; + accesser.requestTokenId = static_cast(authRequestContext_->tokenId); + accessee.trustBundleName = authResponseContext_->hostPkgName; + accessee.trustDeviceId = remoteDeviceId_; + accessee.trustUserId = -1; + } + if (authRequestState_ == nullptr && authResponseState_ != nullptr) { + accesser.requestBundleName = authResponseContext_->hostPkgName; + accesser.requestDeviceId = remoteDeviceId_; + accesser.requestUserId = authResponseContext_->remoteUserId; + accesser.requestAccountId = authResponseContext_->remoteAccountId; + accesser.requestTokenId = static_cast(authResponseContext_->remoteTokenId); + accessee.trustBundleName = authResponseContext_->hostPkgName; + accessee.trustDeviceId = localUdid; + accessee.trustUserId = MultipleUserConnector::GetCurrentAccountUserID(); + accessee.trustAccountId = MultipleUserConnector::GetAccountInfoByUserId(accessee.trustUserId).accountId; + accessee.trustTokenId = static_cast(authResponseContext_->tokenId); + } + DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, accesser, accessee); +} + +void DmAuthManager::ProcRespNegotiateExt(const int32_t &sessionId) +{ + LOGI("DmAuthManager::ProcRespNegotiateExt start."); + remoteDeviceId_ = authResponseContext_->localDeviceId; + authResponseContext_->remoteAccountId = authResponseContext_->localAccountId; + authResponseContext_->remoteUserId = authResponseContext_->localUserId; + GetBinderInfo(); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + authResponseContext_->deviceId = authResponseContext_->localDeviceId; + authResponseContext_->localDeviceId = static_cast(localDeviceId); + authResponseContext_->bindType = + DeviceProfileConnector::GetInstance().GetBindTypeByPkgName(authResponseContext_->hostPkgName, + authResponseContext_->localDeviceId, authResponseContext_->deviceId); + authResponseContext_->authed = !authResponseContext_->bindType.empty(); + + authResponseContext_->isIdenticalAccount = false; + if (authResponseContext_->localAccountId == authResponseContext_->remoteAccountId && + authResponseContext_->localAccountId != "ohosAnonymousUid" && authResponseContext_->authed) { + authResponseContext_->isIdenticalAccount = true; + } + + authResponseContext_->isOnline = softbusConnector_->CheckIsOnline(remoteDeviceId_); + authResponseContext_->haveCredential = + hiChainAuthConnector_->QueryCredential(authResponseContext_->deviceId, + MultipleUserConnector::GetFirstForegroundUserId(), authResponseContext_->remoteUserId); + if (!IsAuthTypeSupported(authResponseContext_->authType)) { + LOGE("DmAuthManager::AuthenticateDevice authType %{public}d not support.", authResponseContext_->authType); + authResponseContext_->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; + } else { + authPtr_ = authenticationMap_[authResponseContext_->authType]; + } + if (IsAuthCodeReady(authResponseContext_->hostPkgName)) { + authResponseContext_->isAuthCodeReady = true; + } else { + authResponseContext_->isAuthCodeReady = false; + } + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_NEGOTIATE); + softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); + + if (authResponseContext_->authType == AUTH_TYPE_NFC) { + GetLocalServiceInfoInDp(); + } +} + +void DmAuthManager::ProcRespNegotiate(const int32_t &sessionId) +{ + LOGI("DmAuthManager::ProcRespNegotiate session id"); + AbilityNegotiate(); + authResponseContext_->isOnline = softbusConnector_->CheckIsOnline(remoteDeviceId_); + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_NEGOTIATE); + JsonObject jsonObject(message); + if (jsonObject.IsDiscarded()) { + softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); + return; + } + if (!IsBool(jsonObject, TAG_CRYPTO_SUPPORT)) { + LOGE("err json string."); + softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); + return; + } + jsonObject[TAG_ACCOUNT_GROUPID] = GetAccountGroupIdHash(); + authResponseContext_ = authResponseState_->GetAuthContext(); + if (jsonObject[TAG_CRYPTO_SUPPORT].Get() == true && authResponseContext_->cryptoSupport) { + if (IsString(jsonObject, TAG_CRYPTO_NAME) && IsString(jsonObject, TAG_CRYPTO_VERSION)) { + if (jsonObject[TAG_CRYPTO_NAME].Get() == authResponseContext_->cryptoName && + jsonObject[TAG_CRYPTO_VERSION].Get() == authResponseContext_->cryptoVer) { + isCryptoSupport_ = true; + softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); + return; + } + } + } + jsonObject[TAG_CRYPTO_SUPPORT] = false; + message = SafetyDump(jsonObject); + softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); +} + +void DmAuthManager::ProcIncompatible(const int32_t &sessionId) +{ + LOGI("DmAuthManager::ProcIncompatible sessionId %{public}d.", sessionId); + JsonObject respNegotiateMsg; + respNegotiateMsg[TAG_REPLY] = ERR_DM_VERSION_INCOMPATIBLE; + respNegotiateMsg[TAG_VER] = DM_ITF_VER; + respNegotiateMsg[TAG_MSG_TYPE] = MSG_TYPE_RESP_NEGOTIATE; + std::string message = SafetyDump(respNegotiateMsg); + softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); +} + +void DmAuthManager::OnAuthDeviceDataReceived(const int32_t sessionId, const std::string message) +{ + if (authResponseContext_ == nullptr || authMessageProcessor_ == nullptr || hiChainAuthConnector_ == nullptr || + authResponseContext_->sessionId != sessionId) { + LOGE("OnAuthDeviceDataReceived param is invalid"); + return; + } + authResponseContext_->sessionId = sessionId; + authMessageProcessor_->SetResponseContext(authResponseContext_); + JsonObject jsonObject(message); + if (jsonObject.IsDiscarded()) { + LOGE("DecodeRequestAuth jsonStr error"); + return; + } + if (!IsString(jsonObject, TAG_DATA) || !IsInt32(jsonObject, TAG_DATA_LEN) || !IsInt32(jsonObject, TAG_MSG_TYPE)) { + LOGE("Auth device data is error."); + return; + } + LOGI("OnAuthDeviceDataReceived start msgType %{public}d.", jsonObject[TAG_MSG_TYPE].Get()); + std::string authData = jsonObject[TAG_DATA].Get(); + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + hiChainAuthConnector_->ProcessAuthData(authResponseContext_->requestId, authData, osAccountId); +} + +int32_t DmAuthManager::DeleteGroup(const std::string &pkgName, const std::string &deviceId) +{ + LOGI("DmAuthManager::DeleteGroup"); + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return ERR_DM_FAILED; + } + std::vector groupList; + CHECK_NULL_RETURN(hiChainConnector_, ERR_DM_POINT_NULL); + hiChainConnector_->GetRelatedGroups(deviceId, groupList); + for (const auto &item : groupList) { + std::string groupId = item.groupId; + hiChainConnector_->DeleteGroup(groupId); + } + return DM_OK; +} + +int32_t DmAuthManager::DeleteGroup(const std::string &pkgName, int32_t userId, const std::string &deviceId) +{ + LOGI("DmAuthManager::DeleteGroup"); + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return ERR_DM_FAILED; + } + std::vector groupList; + hiChainConnector_->GetRelatedGroups(userId, deviceId, groupList); + if (groupList.size() > 0) { + std::string groupId = ""; + groupId = groupList.front().groupId; + hiChainConnector_->DeleteGroup(userId, groupId); + } else { + LOGE("DmAuthManager::UnAuthenticateDevice groupList.size = 0"); + return ERR_DM_FAILED; + } + if (softbusConnector_ != nullptr) { + softbusConnector_->EraseUdidFromMap(deviceId); + } + return DM_OK; +} + +void DmAuthManager::PutAccessControlList() +{ + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string localUdid = static_cast(localDeviceId); + char mUdidHash[DM_MAX_DEVICE_ID_LEN] = {0}; + Crypto::GetUdidHash(localUdid, reinterpret_cast(mUdidHash)); + std::string localUdidHash = static_cast(mUdidHash); + DmAclInfo aclInfo; + aclInfo.bindType = DM_ACROSS_ACCOUNT; + if (authResponseContext_->localAccountId == "ohosAnonymousUid" || + authResponseContext_->remoteAccountId == "ohosAnonymousUid") { + aclInfo.bindType = DM_POINT_TO_POINT; + authForm_ = DmAuthForm::PEER_TO_PEER; + } + aclInfo.bindLevel = authResponseContext_->bindLevel; + aclInfo.trustDeviceId = remoteDeviceId_; + aclInfo.authenticationType = ALLOW_AUTH_ONCE; + if (authResponseContext_->confirmOperation == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { + aclInfo.authenticationType = ALLOW_AUTH_ALWAYS; + } + aclInfo.deviceIdHash = localUdidHash; + DmAccesser accesser; + accesser.requestBundleName = authResponseContext_->hostPkgName; + DmAccessee accessee; + accessee.trustBundleName = authResponseContext_->peerBundleName; + if (authRequestState_ != nullptr && authResponseState_ == nullptr) { + PutSrcAccessControlList(accesser, accessee, localUdid); + } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) { + PutSinkAccessControlList(accesser, accessee, localUdid); + } + DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, accesser, accessee); +} + +void DmAuthManager::PutSrcAccessControlList(DmAccesser &accesser, DmAccessee &accessee, + const std::string &localUdid) +{ + accesser.requestTokenId = static_cast(authRequestContext_->tokenId); + accesser.requestUserId = authRequestContext_->localUserId; + accesser.requestAccountId = authRequestContext_->localAccountId; + accesser.requestDeviceId = authRequestContext_->localDeviceId; + accesser.requestDeviceName = authRequestContext_->localDeviceName; + if (authResponseContext_->remoteTokenId == authRequestContext_->tokenId) { + accessee.trustTokenId = 0; + } else { + accessee.trustTokenId = static_cast(authResponseContext_->remoteTokenId); + } + accessee.trustUserId = authRequestContext_->remoteUserId; + accessee.trustAccountId = authRequestContext_->remoteAccountId; + accessee.trustDeviceId = remoteDeviceId_; + accessee.trustDeviceName = authRequestContext_->remoteDeviceName; +} + +void DmAuthManager::PutSinkAccessControlList(DmAccesser &accesser, DmAccessee &accessee, + const std::string &localUdid) +{ + accesser.requestTokenId = static_cast(authResponseContext_->remoteTokenId); + accesser.requestUserId = authResponseContext_->remoteUserId; + accesser.requestAccountId = authResponseContext_->remoteAccountId; + accesser.requestDeviceId = remoteDeviceId_; + accesser.requestDeviceName = authResponseContext_->remoteDeviceName; + if (authResponseContext_->remoteTokenId == authResponseContext_->tokenId) { + accessee.trustTokenId = 0; + } else { + accessee.trustTokenId = static_cast(authResponseContext_->tokenId); + } + accessee.trustUserId = authResponseContext_->localUserId; + accessee.trustAccountId = authResponseContext_->localAccountId; + accessee.trustDeviceId = localUdid; + accessee.trustDeviceName = authResponseContext_->targetDeviceName; +} + +void DmAuthManager::HandleSessionHeartbeat(std::string name) +{ + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK)); + } + LOGI("DmAuthManager::HandleSessionHeartbeat name %{public}s", name.c_str()); + JsonObject jsonObj; + jsonObj[TAG_SESSION_HEARTBEAT] = TAG_SESSION_HEARTBEAT; + std::string message = SafetyDump(jsonObj); + softbusConnector_->GetSoftbusSession()->SendHeartbeatData(authResponseContext_->sessionId, message); + + if (authRequestState_ != nullptr) { + if (timer_ != nullptr) { + timer_->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), + GetTaskTimeout(SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleSessionHeartbeat(name); + }); + } + } + LOGI("DmAuthManager::HandleSessionHeartbeat complete"); +} + +int32_t DmAuthManager::CheckTrustState() +{ + bool isSameGroup = false; + if (authResponseContext_->reply == ERR_DM_AUTH_PEER_REJECT && + hiChainConnector_->IsDevicesInP2PGroup(authResponseContext_->localDeviceId, + authRequestContext_->localDeviceId)) { + isSameGroup = true; + } + if (isSameGroup && authResponseContext_->isOnline && authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { + authResponseContext_->isFinish = true; + SetReasonAndFinish(DM_OK, AuthState::AUTH_REQUEST_FINISH); + return ALREADY_BIND; + } + if (authResponseContext_->isIdenticalAccount) { + if (IsIdenticalAccount()) { + JoinLnn(authResponseContext_->deviceId); + authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; + authRequestContext_->reason = DM_OK; + authResponseContext_->reply = DM_OK; + authRequestState_->TransitionTo(std::make_shared()); + return ALREADY_BIND; + } + } + if (isSameGroup) { + if (!DeviceProfileConnector::GetInstance().CheckSrcDevIdInAclForDevBind(authResponseContext_->hostPkgName, + authResponseContext_->localDeviceId)) { + CompatiblePutAcl(); + } + JoinLnn(authResponseContext_->deviceId); + authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; + authRequestState_->TransitionTo(std::make_shared()); + return ALREADY_BIND; + } + if (authResponseContext_->reply == ERR_DM_UNSUPPORTED_AUTH_TYPE || + (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && + authResponseContext_->isAuthCodeReady == false)) { + authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; + authRequestContext_->reason = ERR_DM_BIND_PEER_UNSUPPORTED; + authRequestState_->TransitionTo(std::make_shared()); + return ERR_DM_BIND_PEER_UNSUPPORTED; + } + return DM_OK; +} + +std::string DmAuthManager::GetBundleLable(const std::string &bundleName) +{ + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgr == nullptr) { + LOGE("Get ability manager failed"); + return bundleName; + } + + sptr object = samgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (object == nullptr) { + LOGE("object is NULL."); + return bundleName; + } + + sptr bms = iface_cast(object); + if (bms == nullptr) { + LOGE("bundle manager service is NULL."); + return bundleName; + } + + auto bundleResourceProxy = bms->GetBundleResourceProxy(); + if (bundleResourceProxy == nullptr) { + LOGE("GetBundleResourceProxy fail"); + return bundleName; + } + AppExecFwk::BundleResourceInfo resourceInfo; + auto result = bundleResourceProxy->GetBundleResourceInfo(bundleName, + static_cast(OHOS::AppExecFwk::ResourceFlag::GET_RESOURCE_INFO_ALL), resourceInfo); + if (result != ERR_OK) { + LOGE("GetBundleResourceInfo failed"); + return bundleName; + } + LOGI("bundle resource label is %{public}s ", (resourceInfo.label).c_str()); + return resourceInfo.label; +} + +bool DmAuthManager::IsScreenLocked() +{ + bool isLocked = false; +#if defined(SUPPORT_SCREENLOCK) + isLocked = OHOS::ScreenLock::ScreenLockManager::GetInstance()->IsScreenLocked(); +#endif + LOGI("IsScreenLocked isLocked: %{public}d.", isLocked); + return isLocked; +} + +void DmAuthManager::OnScreenLocked() +{ + if (authResponseContext_ != nullptr && AUTH_TYPE_IMPORT_AUTH_CODE == authResponseContext_->authType) { + LOGI("OnScreenLocked authtype is: %{public}d, no need stop bind.", authResponseContext_->authType); + return; + } + if (authRequestState_ == nullptr) { + LOGE("OnScreenLocked authRequestState_ is nullptr."); + return; + } + if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE || + authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT) { + LOGI("OnScreenLocked stop bind."); + SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL, STATUS_DM_AUTH_DEFAULT); + return; + } + if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_JOIN) { + LOGI("OnScreenLocked stop user input."); + if (authUiStateMgr_ != nullptr) { + authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); + } + SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL, STATUS_DM_AUTH_DEFAULT); + return; + } + if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) { + LOGI("OnScreenLocked stop confirm."); + SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL, STATUS_DM_AUTH_DEFAULT); + } +} + +void DmAuthManager::HandleDeviceNotTrust(const std::string &udid) +{ + LOGI("DmAuthManager::HandleDeviceNotTrust udid: %{public}s.", GetAnonyString(udid).c_str()); + if (udid.empty()) { + LOGE("DmAuthManager::HandleDeviceNotTrust udid is empty."); + return; + } + DeviceProfileConnector::GetInstance().DeleteAccessControlList(udid); + CHECK_NULL_VOID(hiChainConnector_); + hiChainConnector_->DeleteAllGroupByUdid(udid); +} + +std::string DmAuthManager::ConvertSinkVersion(const std::string &version) +{ + std::string sinkVersion = ""; + if (version == "") { + sinkVersion = DM_VERSION_4_1_5_1; + } else { + sinkVersion = version; + } + LOGI("ConvertSinkVersion version %{public}s, sinkVersion is %{public}s.", version.c_str(), sinkVersion.c_str()); + return sinkVersion; +} + +void DmAuthManager::SetAuthType(int32_t authType) +{ + authType_ = authType; +} + +int32_t DmAuthManager::GetTaskTimeout(const char* taskName, int32_t taskTimeOut) +{ + LOGI("GetTaskTimeout, taskName: %{public}s, authType_: %{public}d", taskName, authType_.load()); + if (AUTH_TYPE_IMPORT_AUTH_CODE == authType_) { + auto timeout = TASK_TIME_OUT_MAP.find(std::string(taskName)); + if (timeout != TASK_TIME_OUT_MAP.end()) { + return timeout->second; + } + } + return taskTimeOut; +} + +bool DmAuthManager::IsAllowDeviceBind() +{ + if (AppManager::GetInstance().IsSystemSA()) { + return true; + } + return false; +} + +int32_t DmAuthManager::GetBindLevel(int32_t bindLevel) +{ +#ifdef DEVICE_MANAGER_COMMON_FLAG + LOGI("device_manager_common is true!"); + std::string processName = ""; + int32_t ret = AppManager::GetInstance().GetCallerProcessName(processName); + LOGI("GetBindLevel processName = %{public}s", GetAnonyString(processName).c_str()); + if (ret == DM_OK && CheckProcessNameInWhiteList(processName)) { + return USER; + } +#endif + if (IsAllowDeviceBind()) { + if (static_cast(bindLevel) == INVALIED_TYPE || static_cast(bindLevel) > APP || + static_cast(bindLevel) < USER) { + return USER; + } + return bindLevel; + } + if (static_cast(bindLevel) == INVALIED_TYPE || (static_cast(bindLevel) != APP && + static_cast(bindLevel) != SERVICE)) { + return APP; + } + return bindLevel; +} + +std::string DmAuthManager::GetBundleName(JsonObject &jsonObject) +{ + if (!jsonObject.IsDiscarded() && 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(); + return DM_OK; + } + authResponseContext_->localUserId = MultipleUserConnector::GetFirstForegroundUserId(); + authResponseContext_->localAccountId = + MultipleUserConnector::GetOhosAccountIdByUserId(authResponseContext_->localUserId); + if (authResponseContext_->peerBundleName == authResponseContext_->hostPkgName) { + bundleName_ = authResponseContext_->bundleName; + } else { + bundleName_ = authResponseContext_->peerBundleName; + } + 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_->peerBundleName, 0, authResponseContext_->tokenId); +#ifndef DEVICE_MANAGER_COMMON_FLAG + if (ret == DM_OK && static_cast(authResponseContext_->bindLevel) != APP) { + LOGI("get tokenId by bundleName failed %{public}s", GetAnonyString(authResponseContext_->bundleName).c_str()); + return ERR_DM_FAILED; + } +#endif + return ret; +} + +void DmAuthManager::SetProcessInfo() +{ + CHECK_NULL_VOID(authResponseContext_); + ProcessInfo processInfo; + if (static_cast(authResponseContext_->bindLevel) == APP) { + if ((authRequestState_ != nullptr) && (authResponseState_ == nullptr)) { + processInfo.pkgName = authResponseContext_->hostPkgName; + processInfo.userId = authRequestContext_->localUserId; + } else if ((authRequestState_ == nullptr) && (authResponseState_ != nullptr)) { + processInfo.pkgName = authResponseContext_->peerBundleName; + processInfo.userId = authResponseContext_->localUserId; + } else { + LOGE("DMAuthManager::SetProcessInfo failed, state is invalid."); + } + } else if (static_cast(authResponseContext_->bindLevel) == USER || + static_cast(authResponseContext_->bindLevel) == INVALIED_TYPE) { + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = authResponseContext_->localUserId; + } else { + LOGE("bindlevel error %{public}d.", authResponseContext_->bindLevel); + return; + } + softbusConnector_->SetProcessInfo(processInfo); +} + +void DmAuthManager::ConverToFinish() +{ + authRequestContext_->reason = DM_OK; + authResponseContext_->reply = DM_OK; + authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; + authRequestState_->TransitionTo(std::make_shared()); +} + +void DmAuthManager::RequestReCheckMsg() +{ + LOGI("dmVersion %{public}s.", DM_VERSION_5_0_5); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + uint32_t tokenId = 0; + int32_t localUserId = 0; + MultipleUserConnector::GetTokenIdAndForegroundUserId(tokenId, localUserId); + std::string localAccountId = MultipleUserConnector::GetOhosAccountIdByUserId(localUserId); + authResponseContext_->edition = DM_VERSION_5_0_5; + authResponseContext_->localDeviceId = static_cast(localDeviceId); + authResponseContext_->localUserId = localUserId; + authResponseContext_->bundleName = authRequestContext_->hostPkgName; + authResponseContext_->bindLevel = authRequestContext_->bindLevel; + authResponseContext_->localAccountId = localAccountId; + authResponseContext_->tokenId = authRequestContext_->tokenId; + authMessageProcessor_->SetResponseContext(authResponseContext_); + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_RECHECK_MSG); + softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); +} + +void DmAuthManager::ResponseReCheckMsg() +{ + LOGI("remoteVersion %{public}s, authResponseContext_->edition %{public}s.", + remoteVersion_.c_str(), authResponseContext_->edition.c_str()); + if (!IsSinkMsgValid()) { + LOGE("peer deviceId not trust."); + authResponseContext_->isFinish = false; + isFinishOfLocal_ = false; + authMessageProcessor_->SetEncryptFlag(false); + int32_t sessionId = authResponseContext_->sessionId; + authResponseContext_->state = authResponseState_->GetStateType(); + authResponseState_->TransitionTo(std::make_shared()); + return; + } + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + authResponseContext_->edition = DM_VERSION_5_0_5; + authResponseContext_->localDeviceId = std::string(localDeviceId); + authResponseContext_->localUserId = MultipleUserConnector::GetFirstForegroundUserId(); + authResponseContext_->localAccountId = + MultipleUserConnector::GetOhosAccountIdByUserId(authResponseContext_->localUserId); + if (AppManager::GetInstance().GetNativeTokenIdByName(bundleName_, authResponseContext_->tokenId) != DM_OK) { + LOGE("BundleName %{public}s, GetNativeTokenIdByName failed.", GetAnonyString(bundleName_).c_str()); + if (AppManager::GetInstance().GetHapTokenIdByName(authResponseContext_->localUserId, + bundleName_, 0, authResponseContext_->tokenId) != DM_OK) { + LOGE("get tokenId by bundleName failed %{public}s", GetAnonyString(bundleName_).c_str()); + authResponseContext_->tokenId = 0; + } + } + authResponseContext_->bundleName = authResponseContext_->peerBundleName; + authMessageProcessor_->SetEncryptFlag(true); + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_RECHECK_MSG); + softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); + PutAccessControlList(); +} + +void DmAuthManager::RequestReCheckMsgDone() +{ + LOGI("remoteVersion %{public}s, authResponseContext_->edition %{public}s.", + remoteVersion_.c_str(), authResponseContext_->edition.c_str()); + if (!IsSourceMsgValid()) { + LOGE("peer deviceId not trust."); + authResponseContext_->isFinish = false; + isFinishOfLocal_ = false; + authMessageProcessor_->SetEncryptFlag(false); + authRequestState_->TransitionTo(std::make_shared()); + return; + } + authRequestState_->TransitionTo(std::make_shared()); + PutAccessControlList(); +} + +bool DmAuthManager::IsSinkMsgValid() +{ + if (authResponseContext_->edition != remoteVersion_ || + authResponseContext_->localDeviceId != remoteDeviceId_ || + authResponseContext_->localUserId != authResponseContext_->remoteUserId || + authResponseContext_->bundleName != authResponseContext_->hostPkgName || + authResponseContext_->localBindLevel != authResponseContext_->bindLevel) { + return false; + } + return true; +} + +bool DmAuthManager::IsSourceMsgValid() +{ + if (authResponseContext_->edition != remoteVersion_ || + authResponseContext_->localDeviceId != remoteDeviceId_ || + authResponseContext_->localUserId != authRequestContext_->remoteUserId || + authResponseContext_->bundleName != authResponseContext_->peerBundleName || + authResponseContext_->localBindLevel != authResponseContext_->bindLevel) { + return false; + } + authResponseContext_->localAccountId = authRequestContext_->localAccountId; + return true; +} + +int32_t DmAuthManager::RegisterAuthenticationType(int32_t authenticationType) +{ + authenticationType_ = authenticationType; + return DM_OK; +} + +void DmAuthManager::ProcessReqPublicKey() +{ + if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_AUTH_FINISH || + authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_RECHECK_MSG) { + authResponseState_->TransitionTo(std::make_shared()); + return; + } + if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW) { + std::lock_guard lock(srcReqMsgLock_); + isNeedProcCachedSrcReqMsg_ = true; + } +} + +void DmAuthManager::GetLocalServiceInfoInDp() +{ + DistributedDeviceProfile::LocalServiceInfo localServiceInfo; + int32_t result = DeviceProfileConnector::GetInstance().GetLocalServiceInfoByBundleNameAndPinExchangeType( + authResponseContext_->hostPkgName, (int32_t)DMLocalServiceInfoPinExchangeType::FROMDP, localServiceInfo); + if (result != DM_OK) { + return; + } + if (IsLocalServiceInfoValid(localServiceInfo)) { + serviceInfoProfile_ = localServiceInfo; + LOGI("authBoxType %{public}d, authType %{public}d, pinExchangeType %{public}d", + serviceInfoProfile_.GetAuthBoxType(), serviceInfoProfile_.GetAuthType(), + serviceInfoProfile_.GetPinExchangeType()); + auto updateProfile = serviceInfoProfile_; + updateProfile.SetPinCode("******"); + DeviceProfileConnector::GetInstance().UpdateLocalServiceInfo(updateProfile); + } +} + +bool DmAuthManager::CheckNeedShowAuthInfoDialog(int32_t errorCode) +{ + CHECK_NULL_RETURN(authResponseContext_, false); + if (errorCode == ERR_DM_HICHAIN_PROOFMISMATCH && !pincodeDialogEverShown_ && CanUsePincodeFromDp()) { + authResponseContext_->code = GeneratePincode(); + LOGI("AuthDeviceError, GeneratePincode, ShowAuthInfoDialog"); + authTimes_ = 0; + ShowAuthInfoDialog(true); + return true; + } + return false; +} + +void DmAuthManager::UpdateInputPincodeDialog(int32_t errorCode) +{ + CHECK_NULL_VOID(authResponseContext_); + CHECK_NULL_VOID(authUiStateMgr_); + if (authResponseContext_->authType == AUTH_TYPE_NFC && !pincodeDialogEverShown_ && + IsImportedAuthCodeValid() && errorCode == ERR_DM_HICHAIN_PROOFMISMATCH) { + LOGI("AuthDeviceError, ShowStartAuthDialog"); + authTimes_ = 0; + DeleteAuthCode(); + ShowStartAuthDialog(); + } else { + authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR); + } +} + +void DmAuthManager::JoinLnn(const std::string &deviceId, bool isForceJoin) +{ + CHECK_NULL_VOID(authRequestContext_); + CHECK_NULL_VOID(authResponseContext_); + CHECK_NULL_VOID(softbusConnector_); + if (IsHmlSessionType()) { + if (authRequestContext_->closeSessionDelaySeconds == 0) { + isWaitingJoinLnnCallback_ = true; + } + authResponseContext_->localSessionKeyId = GetSessionKeyIdSync(authResponseContext_->requestId); + softbusConnector_->JoinLnnByHml(authRequestContext_->sessionId, authResponseContext_->localSessionKeyId, + authResponseContext_->remoteSessionKeyId); + return; + } + softbusConnector_->JoinLnn(deviceId, isForceJoin); +} + +int32_t DmAuthManager::GetTokenIdByBundleName(int32_t userId, std::string &bundleName, int64_t &tokenId) +{ + int32_t ret = AppManager::GetInstance().GetNativeTokenIdByName(bundleName, tokenId); + if (ret == DM_OK) { + return DM_OK; + } + ret = AppManager::GetInstance().GetHapTokenIdByName(userId, bundleName, 0, tokenId); + if (ret != DM_OK) { + LOGE("get tokenId by bundleName failed %{public}s", GetAnonyString(bundleName).c_str()); + } + return ret; +} + +void DmAuthManager::OnSoftbusJoinLNNResult(const int32_t sessionId, const char *networkId, int32_t result) +{ + (void)sessionId; + (void)networkId; + (void)result; +} + +void DmAuthManager::CloseAuthSession(const int32_t sessionId) +{ + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(WAIT_SESSION_CLOSE_TIMEOUT_TASK) + std::string(CLOSE_SESSION_TASK_SEPARATOR) + + std::to_string(sessionId)); + } + CHECK_NULL_VOID(softbusConnector_); + CHECK_NULL_VOID(softbusConnector_->GetSoftbusSession()); + softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId); +} + +void DmAuthManager::RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback) +{ + cleanNotifyCallback_ = cleanNotifyCallback; + return; +} + +void DmAuthManager::GetCallerInfo(DmBindCallerInfo &callerInfo) +{ + (void)callerInfo; +} + +void DmAuthManager::SetCallerInfo(const DmBindCallerInfo &callerInfo) +{ + std::lock_guard lock(callerInfoMutex_); + callerInfo_.userId = callerInfo.userId; + callerInfo_.tokenId = callerInfo.tokenId; + callerInfo_.bundleName = callerInfo.bundleName; + callerInfo_.hostPkgLabel = callerInfo.hostPkgLabel; + callerInfoReady_ = true; +} + +void DmAuthManager::GetCallerInfo(const std::string &pkgName, JsonObject &jsonObject) +{ + CHECK_NULL_VOID(authRequestContext_); + std::lock_guard lock(callerInfoMutex_); + if (callerInfoReady_) { + authRequestContext_->localUserId = callerInfo_.userId; + authRequestContext_->tokenId = static_cast(callerInfo_.tokenId); + authRequestContext_->bundleName = callerInfo_.bundleName; + authRequestContext_->hostPkgLabel = callerInfo_.hostPkgLabel; + } else { + authRequestContext_->hostPkgLabel = GetBundleLable(pkgName); + uint32_t tokenId = 0 ; + MultipleUserConnector::GetTokenIdAndForegroundUserId(tokenId, authRequestContext_->localUserId); + authRequestContext_->tokenId = static_cast(tokenId); + authRequestContext_->bundleName = GetBundleName(jsonObject); + } +} + +void DmAuthManager::ClearCallerInfo() +{ + std::lock_guard lock(callerInfoMutex_); + callerInfo_.userId = -1; + callerInfo_.tokenId = -1; + callerInfo_.bundleName = ""; + callerInfo_.hostPkgLabel = ""; + callerInfoReady_ = false; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 662df9c97..9f34cbfaf 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -151,7 +151,10 @@ AuthManager::~AuthManager() context_->timer->DeleteAll(); LOGI("AuthManager context variables destroy successful."); } - bindParam_.clear(); + { + std::lock_guard lock(bindParamMutex_); + bindParam_.clear(); + } LOGI("DmAuthManager destructor"); } @@ -418,10 +421,6 @@ std::string AuthManager::GetBundleName(const JsonObject &jsonObject) void AuthManager::ParseJsonObject(const JsonObject &jsonObject) { - if (jsonObject.IsDiscarded()) { - return; - } - if (jsonObject[APP_OPERATION_KEY].IsString()) { context_->appOperation = jsonObject[APP_OPERATION_KEY].Get(); } @@ -437,10 +436,7 @@ void AuthManager::ParseJsonObject(const JsonObject &jsonObject) context_->connDelayCloseTime = GetCloseSessionDelaySeconds(delaySecondsStr); } - context_->accesser.bundleName = GetBundleName(jsonObject); - bindParam_[BUNDLE_NAME_KEY] = context_->accesser.bundleName; context_->accessee.bundleName = context_->accesser.bundleName; - if (jsonObject[TAG_PEER_BUNDLE_NAME].IsString() && !jsonObject[TAG_PEER_BUNDLE_NAME].Get().empty()) { context_->accessee.bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get(); context_->accessee.oldBundleName = context_->accessee.bundleName; @@ -522,7 +518,7 @@ int32_t GetBindLevel(int32_t bindLevel) std::string processName = ""; int32_t ret = AppManager::GetInstance().GetCallerProcessName(processName); LOGI("GetBindLevel processName = %{public}s", GetAnonyString(processName).c_str()); - if (ret == DM_OK && DmAuthState::CheckProcessNameInWhiteList(processName)) { + if (ret == DM_OK && AuthManagerBase::CheckProcessNameInWhiteList(processName)) { return USER; } #endif @@ -548,7 +544,6 @@ void AuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); context_->accesser.deviceId = std::string(localDeviceId); context_->pkgName = pkgName; - context_->pkgLabel = GetBundleLabel(pkgName); context_->authType = (DmAuthType)authType; context_->accesser.deviceName = context_->listener->GetLocalDisplayDeviceNameForPrivacy(); context_->accesser.deviceType = context_->softbusConnector->GetLocalDeviceTypeId(); @@ -572,15 +567,9 @@ void AuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, CheckBindLevel(jsonObject, TAG_BIND_LEVEL, context_->accesser.oldBindLevel); context_->accesser.oldBindLevel = GetBindLevel(context_->accesser.oldBindLevel); - context_->accesser.bindLevel = DmRole::DM_ROLE_FA; - if (AppManager::GetInstance().IsSystemApp()) { - context_->accesser.bindLevel = DmRole::DM_ROLE_FA; - } - if (AppManager::GetInstance().IsSystemSA()) { - context_->accesser.bindLevel = DmRole::DM_ROLE_SA; - } - if (DmAuthState::CheckProcessNameInWhiteList(context_->accesser.bundleName)) { - context_->accesser.bindLevel = DmRole::DM_ROLE_USER; + { + std::lock_guard lock(bindParamMutex_); + bindParam_["bindCallerOldBindLevel"] = std::to_string(context_->accesser.oldBindLevel); } } @@ -607,12 +596,10 @@ void AuthManager::InitAuthState(const std::string &pkgName, int32_t authType, int32_t AuthManager::AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra) { - LOGI("AuthManager::AuthenticateDevice start auth type %{public}d.", authType); + LOGI("AuthManager::AuthenticateDevice start auth type %{public}d, extra %{public}s.", authType, extra.c_str()); SetAuthType(authType); - int32_t userId = -1; - MultipleUserConnector::GetCallerUserId(userId); context_->processInfo.pkgName = pkgName; - context_->processInfo.userId = userId; + GetBindCallerInfo(); int32_t ret = CheckAuthParamVaild(pkgName, authType, deviceId, extra); if (ret != DM_OK) { LOGE("AuthManager::AuthenticateDevice failed, param is invaild."); @@ -662,7 +649,10 @@ int32_t AuthManager::BindTarget(const std::string &pkgName, const PeerTargetId & return ERR_DM_INPUT_PARA_INVALID; } context_->peerTargetId = targetId_; - bindParam_ = bindParam; + { + std::lock_guard lock(bindParamMutex_); + bindParam_ = bindParam; + } if (!targetId.deviceId.empty()) { ret = AuthenticateDevice(pkgName, authType, targetId.deviceId, ParseExtraFromMap(bindParam)); if (ret != DM_OK) { @@ -1016,8 +1006,11 @@ void AuthManager::GetBindTargetParams(std::string &pkgName, PeerTargetId &target { pkgName = context_->pkgName; targetId = targetId_; - bindParam = bindParam_; + { + std::lock_guard lock(bindParamMutex_); + bindParam = bindParam_; + } LOGI("AuthManager::GetBindTargetParams get pkgName %{public}s to reuse", pkgName.c_str()); return; } @@ -1035,17 +1028,27 @@ void AuthManager::ClearSoftbusSessionCallback() void AuthManager::PrepareSoftbusSessionCallback() {} -void AuthManager::GetCallerInfo(DmBindCallerInfo &callerInfo) +void AuthManager::GetBindCallerInfo() { - callerInfo.userId = context_->accesser.userId; - callerInfo.tokenId = context_->accesser.tokenId; - callerInfo.bundleName = context_->accesser.bundleName; - callerInfo.hostPkgLabel = context_->pkgLabel; -} - -void AuthManager::SetCallerInfo(const DmBindCallerInfo &callerInfo) -{ - (void)callerInfo; + LOGI("start."); + { + std::lock_guard lock(bindParamMutex_); + if (bindParam_.find("bindCallerUserId") != bindParam_.end()) { + context_->processInfo.userId = std::atoi(bindParam_["bindCallerUserId"].c_str()); + } + if (bindParam_.find("bindCallerTokenId") != bindParam_.end()) { + context_->accesser.tokenId = std::atoi(bindParam_["bindCallerTokenId"].c_str()); + } + if (bindParam_.find("bindCallerBindLevel") != bindParam_.end()) { + context_->accesser.bindLevel = std::atoi(bindParam_["bindCallerBindLevel"].c_str()); + } + if (bindParam_.find("bindCallerBundleName") != bindParam_.end()) { + context_->accesser.bindLevel = bindParam_["bindCallerBundleName"]; + } + if (bindParam_.find("bindCallerHostPkgLabel") != bindParam_.end()) { + context_->pkgLabel = bindParam_["bindCallerHostPkgLabel"]; + } + } } } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp.bak b/services/implementation/src/authentication_v2/auth_manager.cpp.bak new file mode 100644 index 000000000..662df9c97 --- /dev/null +++ b/services/implementation/src/authentication_v2/auth_manager.cpp.bak @@ -0,0 +1,1051 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "app_manager.h" +#include "softbus_common.h" +#include "system_ability_definition.h" +#include "iservice_registry.h" +#include "parameter.h" +#include "deviceprofile_connector.h" +#include "multiple_user_connector.h" + +#include "auth_manager.h" +#include "dm_constants.h" +#include "dm_crypto.h" +#include "dm_random.h" +#include "dm_log.h" +#include "dm_timer.h" +#include "dm_radar_helper.h" +#include "dm_device_info.h" +#include "dm_anonymous.h" +#include "dm_auth_state_machine.h" +#include "dm_auth_context.h" +#include "dm_auth_message_processor.h" +#include "dm_auth_state.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { + +constexpr int32_t MIN_PIN_CODE = 100000; +constexpr int32_t MAX_PIN_CODE = 999999; +constexpr int32_t DM_ULTRASONIC_FORWARD = 0; +constexpr int32_t DM_ULTRASONIC_REVERSE = 1; + +int32_t GetCloseSessionDelaySeconds(std::string &delaySecondsStr) +{ + if (!IsNumberString(delaySecondsStr)) { + LOGE("Invalid parameter, param is not number."); + return 0; + } + const int32_t closeSessionDelaySecondsMax = 10; + int32_t delaySeconds = std::atoi(delaySecondsStr.c_str()); + if (delaySeconds < 0 || delaySeconds > closeSessionDelaySecondsMax) { + LOGE("Invalid parameter, param out of range."); + return 0; + } + return delaySeconds; +} + +std::string GetBundleLabel(const std::string &bundleName) +{ + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgr == nullptr) { + LOGE("Get ability manager failed"); + return bundleName; + } + + sptr object = samgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (object == nullptr) { + LOGE("object is NULL."); + return bundleName; + } + + sptr bms = iface_cast(object); + if (bms == nullptr) { + LOGE("bundle manager service is NULL."); + return bundleName; + } + + auto bundleResourceProxy = bms->GetBundleResourceProxy(); + if (bundleResourceProxy == nullptr) { + LOGE("GetBundleResourceProxy fail"); + return bundleName; + } + AppExecFwk::BundleResourceInfo resourceInfo; + auto result = bundleResourceProxy->GetBundleResourceInfo(bundleName, + static_cast(OHOS::AppExecFwk::ResourceFlag::GET_RESOURCE_INFO_ALL), resourceInfo); + if (result != ERR_OK) { + LOGE("GetBundleResourceInfo failed"); + return bundleName; + } + LOGI("bundle resource label is %{public}s ", (resourceInfo.label).c_str()); + return resourceInfo.label; +} + +std::string ParseExtraFromMap(const std::map &bindParam) +{ + auto iter = bindParam.find(PARAM_KEY_BIND_EXTRA_DATA); + if (iter != bindParam.end()) { + return iter->second; + } + return ConvertMapToJsonString(bindParam); +} + +bool IsAllowDeviceBind() +{ + if (AppManager::GetInstance().IsSystemSA()) { + return true; + } + return false; +} + +} // namespace + +bool AuthManager::IsHmlSessionType(const std::string &sessionType) +{ + return sessionType == CONN_SESSION_TYPE_HML; +} + +AuthManager::AuthManager(std::shared_ptr softbusConnector, + std::shared_ptr hiChainConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector) +{ + LOGI("DmAuthManager constructor"); + context_ = std::make_shared(); + context_->softbusConnector = softbusConnector; + context_->listener = listener; + context_->hiChainConnector = hiChainConnector; + context_->hiChainAuthConnector = hiChainAuthConnector; + context_->authUiStateMgr = std::make_shared(context_->listener); + context_->authenticationMap[AUTH_TYPE_PIN] = nullptr; + context_->authenticationMap[AUTH_TYPE_IMPORT_AUTH_CODE] = nullptr; + context_->authenticationMap[AUTH_TYPE_PIN_ULTRASONIC] = nullptr; + context_->authenticationMap[AUTH_TYPE_NFC] = nullptr; + context_->accesser.dmVersion = DM_VERSION_5_1_0; + context_->accessee.dmVersion = DM_VERSION_5_1_0; + context_->timer = std::make_shared(); + context_->authMessageProcessor = std::make_shared(); +} + +AuthManager::~AuthManager() +{ + if (context_ != nullptr) { + context_->successFinished = true; + context_->authStateMachine->Stop(); // Stop statemMachine thread + context_->timer->DeleteAll(); + LOGI("AuthManager context variables destroy successful."); + } + bindParam_.clear(); + LOGI("DmAuthManager destructor"); +} + +void AuthManager::RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback) +{ + context_->cleanNotifyCallback = cleanNotifyCallback; + return; +} + +void AuthManager::SetAuthContext(std::shared_ptr context) +{ + this->context_ = context; +} + +std::shared_ptr AuthManager::GetAuthContext() +{ + return this->context_; +} + +std::string AuthManager::GeneratePincode() +{ + LOGI("AuthManager::GeneratePincode start"); + int32_t pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); + context_->pinCode = std::to_string(pinCode); + return context_->pinCode; +} + +int32_t AuthManager::RegisterUiStateCallback(const std::string pkgName) +{ + LOGI("AuthManager::RegisterUiStateCallback start"); + if (context_->authUiStateMgr == nullptr) { + LOGE("AuthManager::RegisterUiStateCallback context_->authUiStateMgr is null."); + return ERR_DM_FAILED; + } + context_->authUiStateMgr->RegisterUiStateCallback(pkgName); + return DM_OK; +} + +int32_t AuthManager::UnRegisterUiStateCallback(const std::string pkgName) +{ + LOGI("AuthManager::UnRegisterUiStateCallback start"); + if (context_->authUiStateMgr == nullptr) { + LOGE("AuthManager::UnRegisterUiStateCallback context_->authUiStateMgr is null."); + return ERR_DM_FAILED; + } + context_->authUiStateMgr->UnRegisterUiStateCallback(pkgName); + return DM_OK; +} + +int32_t AuthManager::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) +{ + LOGI("AuthManager::UnAuthenticateDevice start"); + return ERR_DM_FAILED; +} + +int32_t AuthManager::ImportAuthCode(const std::string &pkgName, const std::string &authCode) +{ + if (authCode.empty() || pkgName.empty()) { + LOGE("ImportAuthCode failed, authCode or pkgName is empty"); + return ERR_DM_INPUT_PARA_INVALID; + } + context_->importAuthCode = authCode; + context_->importPkgName = pkgName; + context_->pinCode = authCode; + LOGI("AuthManager::ImportAuthCode ok"); + return DM_OK; +} + +int32_t AuthManager::UnBindDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel, const std::string &extra) +{ + LOGI("AuthManager::UnBindDevice start"); + return ERR_DM_FAILED; +} + +int32_t AuthManager::StopAuthenticateDevice(const std::string &pkgName) +{ + (void)pkgName; + LOGI("AuthManager::StopAuthenticateDevice start"); + + context_->reason = STOP_BIND; + if (context_->direction == DM_AUTH_SOURCE) { + context_->authStateMachine->TransitionTo(std::make_shared()); + } else { + context_->authStateMachine->TransitionTo(std::make_shared()); + } + return DM_OK; +} + +void AuthManager::OnScreenLocked() +{ + LOGI("AuthManager::OnScreenLocked start"); + if (DmAuthState::IsImportAuthCodeCompatibility(context_->authType)) { + LOGI("OnScreenLocked authtype is: %{public}d, no need stop bind.", context_->authType); + return; + } + context_->reason = ERR_DM_BIND_USER_CANCEL; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); +} + +void AuthManager::HandleDeviceNotTrust(const std::string &udid) +{ + LOGI("AuthManager::HandleDeviceNotTrust start"); +} + +int32_t AuthManager::RegisterAuthenticationType(int32_t authenticationType) +{ + context_->confirmOperation = static_cast(authenticationType); + return DM_OK; +} + +int32_t AuthManager::GetReason() +{ + return context_->reason; +} + +// Save the key +void AuthSrcManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) +{ + LOGI("AuthSrcManager::AuthDeviceSessionKey start. keyLen: %{public}u", sessionKeyLen); + if (context_ == nullptr || context_->authMessageProcessor == nullptr || context_->authStateMachine == nullptr) { + LOGE("AuthSrcManager::AuthDeviceSessionKey failed, auth context not initial."); + return; + } + if (requestId != context_->requestId) { + LOGE("AuthSrcManager::onTransmit requestId %{public}" PRId64 "is error.", requestId); + return; + } + int32_t ret = context_->authMessageProcessor->SaveSessionKey(sessionKey, sessionKeyLen); + if (ret != DM_OK) { + LOGE("AuthSrcManager::AuthDeviceSessionKey, save session key error, ret: %{public}d", ret); + } + + context_->authStateMachine->NotifyEventFinish(ON_SESSION_KEY_RETURNED); + LOGI("AuthSrcManager::AuthDeviceSessionKey leave."); +} + +char *AuthSrcManager::AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) +{ + LOGI("AuthSrcManager::AuthDeviceRequest start"); + return nullptr; +} + +void AuthManager::SetAuthType(int32_t authType) +{ + context_->authType = (DmAuthType)authType; +} + +bool AuthManager::IsAuthTypeSupported(const int32_t &authType) +{ + if (context_->authenticationMap.find(authType) == context_->authenticationMap.end()) { + LOGE("IsAuthTypeSupported failed, authType is not supported."); + return false; + } + return true; +} + +bool AuthManager::IsAuthCodeReady(const std::string &pkgName) +{ + if (context_->importAuthCode.empty() || context_->importPkgName.empty()) { + LOGE("AuthManager::IsAuthCodeReady, auth code not ready with authCode %{public}s and pkgName %{public}s.", + GetAnonyString(context_->importAuthCode).c_str(), context_->importPkgName.c_str()); + return false; + } + if (pkgName != context_->importPkgName) { + LOGE("AuthManager::IsAuthCodeReady pkgName %{public}s not supported with import pkgName %{public}s.", + pkgName.c_str(), context_->importPkgName.c_str()); + return false; + } + return true; +} + +int32_t AuthManager::CheckAuthParamVaild(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + LOGI("AuthManager::CheckAuthParamVaild start."); + if (authType < DM_AUTH_TYPE_MIN || authType > DM_AUTH_TYPE_MAX) { + LOGE("CheckAuthParamVaild failed, authType is illegal."); + return ERR_DM_AUTH_FAILED; + } + if (pkgName.empty() || deviceId.empty()) { + LOGE("AuthManager::CheckAuthParamVaild failed, pkgName is %{public}s, deviceId is %{public}s, extra is" + "%{public}s.", pkgName.c_str(), GetAnonyString(deviceId).c_str(), extra.c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + if (context_->listener == nullptr || context_->authUiStateMgr == nullptr) { + LOGE("AuthManager::CheckAuthParamVaild listener or authUiStateMgr is nullptr."); + return ERR_DM_INPUT_PARA_INVALID; + } + + if (!IsAuthTypeSupported(authType)) { + LOGE("AuthManager::CheckAuthParamVaild authType %{public}d not support.", authType); + context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", + STATUS_DM_AUTH_DEFAULT, + ERR_DM_UNSUPPORTED_AUTH_TYPE); + context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, + ERR_DM_UNSUPPORTED_AUTH_TYPE, STATUS_DM_AUTH_DEFAULT, ""); + return ERR_DM_UNSUPPORTED_AUTH_TYPE; + } + JsonObject jsonObject(extra); + if ((jsonObject.IsDiscarded() || !IsString(jsonObject, PARAM_KEY_CONN_SESSIONTYPE) || + jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get() != CONN_SESSION_TYPE_HML) && + !context_->softbusConnector->HaveDeviceInMap(deviceId)) { + LOGE("CheckAuthParamVaild failed, the discoveryDeviceInfoMap_ not have this device."); + context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", + STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID); + context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, + ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, ""); + return ERR_DM_INPUT_PARA_INVALID; + } + + if (DmAuthState::IsImportAuthCodeCompatibility(static_cast(authType)) && + (!IsAuthCodeReady(pkgName))) { + LOGE("Auth code not exist."); + context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", + STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID); + context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, + ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, ""); + return ERR_DM_INPUT_PARA_INVALID; + } + return DM_OK; +} + +void AuthManager::ParseHmlInfoInJsonObject(const JsonObject &jsonObject) +{ + if (jsonObject[PARAM_KEY_CONN_SESSIONTYPE].IsString()) { + context_->connSessionType = jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get(); + LOGI("connSessionType %{public}s", context_->connSessionType.c_str()); + } + if (!IsHmlSessionType(context_->connSessionType)) { + return; + } + if (context_->connDelayCloseTime == 0) { + context_->connDelayCloseTime = HML_SESSION_TIMEOUT; + } + if (jsonObject[PARAM_KEY_HML_ENABLE_160M].IsBoolean()) { + context_->hmlEnable160M = jsonObject[PARAM_KEY_HML_ENABLE_160M].Get(); + LOGI("hmlEnable160M %{public}d", context_->hmlEnable160M); + } + if (jsonObject[PARAM_KEY_HML_ACTIONID].IsString()) { + std::string actionIdStr = jsonObject[PARAM_KEY_HML_ACTIONID].Get(); + if (IsNumberString(actionIdStr)) { + context_->hmlActionId = std::atoi(actionIdStr.c_str()); + } + if (context_->hmlActionId <= 0) { + context_->hmlActionId = 0; + } + LOGI("hmlActionId %{public}d", context_->hmlActionId); + } + + return; +} + +std::string AuthManager::GetBundleName(const JsonObject &jsonObject) +{ + if (!jsonObject.IsDiscarded() && jsonObject[BUNDLE_NAME_KEY].IsString()) { + return jsonObject[BUNDLE_NAME_KEY].Get(); + } + bool isSystemSA = false; + std::string bundleName; + AppManager::GetInstance().GetCallerName(isSystemSA, bundleName); + return bundleName; +} + +void AuthManager::ParseJsonObject(const JsonObject &jsonObject) +{ + if (jsonObject.IsDiscarded()) { + return; + } + + if (jsonObject[APP_OPERATION_KEY].IsString()) { + context_->appOperation = jsonObject[APP_OPERATION_KEY].Get(); + } + if (jsonObject[CUSTOM_DESCRIPTION_KEY].IsString()) { + context_->customData = jsonObject[CUSTOM_DESCRIPTION_KEY].Get(); + } + if (jsonObject[TAG_APP_THUMBNAIL2].IsString()) { + context_->appThumbnail = jsonObject[TAG_APP_THUMBNAIL2].Get(); + } + context_->connDelayCloseTime = 0; + if (jsonObject[PARAM_CLOSE_SESSION_DELAY_SECONDS].IsString()) { + std::string delaySecondsStr = jsonObject[PARAM_CLOSE_SESSION_DELAY_SECONDS].Get(); + context_->connDelayCloseTime = GetCloseSessionDelaySeconds(delaySecondsStr); + } + + context_->accesser.bundleName = GetBundleName(jsonObject); + bindParam_[BUNDLE_NAME_KEY] = context_->accesser.bundleName; + context_->accessee.bundleName = context_->accesser.bundleName; + + if (jsonObject[TAG_PEER_BUNDLE_NAME].IsString() && !jsonObject[TAG_PEER_BUNDLE_NAME].Get().empty()) { + context_->accessee.bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get(); + context_->accessee.oldBundleName = context_->accessee.bundleName; + } else { + context_->accessee.oldBundleName = context_->pkgName; + } + + context_->accesser.pkgName = context_->pkgName; + context_->accessee.pkgName = context_->accesser.pkgName; + + if (jsonObject[TAG_PEER_PKG_NAME].IsString()) { + context_->accessee.pkgName = jsonObject[TAG_PEER_PKG_NAME].Get(); + } + + if (jsonObject[TAG_PEER_DISPLAY_ID].IsNumberInteger()) { + context_->accessee.displayId = jsonObject[TAG_PEER_DISPLAY_ID].Get(); + } + if (jsonObject[TAG_LOCAL_USERID].IsNumberInteger()) { + context_->accesser.userId = jsonObject[TAG_LOCAL_USERID].Get(); + } else { + context_->accesser.userId = MultipleUserConnector::GetFirstForegroundUserId(); + } + + if (context_->authType == AUTH_TYPE_PIN_ULTRASONIC) { + ParseUltrasonicSide(jsonObject); + } + + ParseHmlInfoInJsonObject(jsonObject); + return; +} + +void AuthManager::ParseUltrasonicSide(const JsonObject &jsonObject) +{ + if (jsonObject[TAG_ULTRASONIC_SIDE].IsString()) { + std::string tempInfo = jsonObject[TAG_ULTRASONIC_SIDE].Get(); + if (tempInfo.length() > 0 && isdigit(tempInfo[0])) { + int32_t intTempInfo = std::atoi(tempInfo.c_str()); + if (intTempInfo == DM_ULTRASONIC_REVERSE) { + context_->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Reverse; + } else if (intTempInfo == DM_ULTRASONIC_FORWARD) { + context_->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Forward; + } else { + context_->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Invalid; + } + } + } +} + +int32_t AuthManager::GetTokenIdByBundleName(int32_t userId, std::string &bundleName, int64_t &tokenId) +{ + int32_t ret = AppManager::GetInstance().GetNativeTokenIdByName(bundleName, tokenId); + if (ret == DM_OK) { + return DM_OK; + } + ret = AppManager::GetInstance().GetHapTokenIdByName(userId, bundleName, 0, tokenId); + if (ret != DM_OK) { + LOGE("get tokenId by bundleName failed %{public}s", GetAnonyString(bundleName).c_str()); + } + return ret; +} + +bool CheckBindLevel(const JsonItemObject &jsonObj, const std::string &key, int32_t &bindLevel) +{ + if (IsJsonValIntegerString(jsonObj, TAG_BIND_LEVEL)) { + bindLevel = std::atoi(jsonObj[TAG_BIND_LEVEL].Get().c_str()); + return true; + } + if (IsInt32(jsonObj, TAG_BIND_LEVEL)) { + bindLevel = jsonObj[TAG_BIND_LEVEL].Get(); + return true; + } + return false; +} + +int32_t GetBindLevel(int32_t bindLevel) +{ +#ifdef DEVICE_MANAGER_COMMON_FLAG + LOGI("device_manager_common is true!"); + std::string processName = ""; + int32_t ret = AppManager::GetInstance().GetCallerProcessName(processName); + LOGI("GetBindLevel processName = %{public}s", GetAnonyString(processName).c_str()); + if (ret == DM_OK && DmAuthState::CheckProcessNameInWhiteList(processName)) { + return USER; + } +#endif + if (IsAllowDeviceBind()) { + if (static_cast(bindLevel) == INVALIED_TYPE || static_cast(bindLevel) > APP || + static_cast(bindLevel) < USER) { + return USER; + } + return bindLevel; + } + if (static_cast(bindLevel) == INVALIED_TYPE || (static_cast(bindLevel) != APP && + static_cast(bindLevel) != SERVICE)) { + return APP; + } + return bindLevel; +} + +void AuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + LOGI("Get auth param with pkgName %{public}s and extra %{public}s.", pkgName.c_str(), extra.c_str()); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + context_->accesser.deviceId = std::string(localDeviceId); + context_->pkgName = pkgName; + context_->pkgLabel = GetBundleLabel(pkgName); + context_->authType = (DmAuthType)authType; + context_->accesser.deviceName = context_->listener->GetLocalDisplayDeviceNameForPrivacy(); + context_->accesser.deviceType = context_->softbusConnector->GetLocalDeviceTypeId(); + context_->accesser.isOnline = false; + uint32_t callingTokenId = 0; + MultipleUserConnector::GetCallingTokenId(callingTokenId); + context_->accesser.tokenId = static_cast(callingTokenId); + + context_->accessee.deviceId = deviceId; + context_->accessee.addr = deviceId; + JsonObject jsonObject(extra); + if (jsonObject.IsDiscarded()) { + LOGE("extra string not a json type."); + return; + } + ParseJsonObject(jsonObject); + context_->accesser.accountId = MultipleUserConnector::GetOhosAccountIdByUserId(context_->accesser.userId); + + // compatible for old version + context_->accesser.oldBindLevel = INVALIED_TYPE; + CheckBindLevel(jsonObject, TAG_BIND_LEVEL, context_->accesser.oldBindLevel); + context_->accesser.oldBindLevel = GetBindLevel(context_->accesser.oldBindLevel); + + context_->accesser.bindLevel = DmRole::DM_ROLE_FA; + if (AppManager::GetInstance().IsSystemApp()) { + context_->accesser.bindLevel = DmRole::DM_ROLE_FA; + } + if (AppManager::GetInstance().IsSystemSA()) { + context_->accesser.bindLevel = DmRole::DM_ROLE_SA; + } + if (DmAuthState::CheckProcessNameInWhiteList(context_->accesser.bundleName)) { + context_->accesser.bindLevel = DmRole::DM_ROLE_USER; + } +} + +void AuthManager::InitAuthState(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + auto iter = context_->authenticationMap.find(authType); + if (iter != context_->authenticationMap.end()) { + context_->authPtr = iter->second; + } + + context_->timer->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), + AUTHENTICATE_TIMEOUT, + [this] (std::string name) { + DmAuthState::HandleAuthenticateTimeout(context_, name); + }); + GetAuthParam(pkgName, authType, deviceId, extra); + context_->authStateMachine->TransitionTo(std::make_shared()); + LOGI("AuthManager::AuthenticateDevice complete"); + + return; +} + +int32_t AuthManager::AuthenticateDevice(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + LOGI("AuthManager::AuthenticateDevice start auth type %{public}d.", authType); + SetAuthType(authType); + int32_t userId = -1; + MultipleUserConnector::GetCallerUserId(userId); + context_->processInfo.pkgName = pkgName; + context_->processInfo.userId = userId; + int32_t ret = CheckAuthParamVaild(pkgName, authType, deviceId, extra); + if (ret != DM_OK) { + LOGE("AuthManager::AuthenticateDevice failed, param is invaild."); + return ret; + } + context_->isAuthenticateDevice = true; + if (authType == AUTH_TYPE_CRE) { + LOGI("AuthManager::AuthenticateDevice for credential type, joinLNN directly."); + context_->softbusConnector->JoinLnn(deviceId, true); + context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, + "", STATUS_DM_AUTH_DEFAULT, DM_OK); + context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, + DM_OK, STATUS_DM_AUTH_DEFAULT, ""); + return DM_OK; + } + InitAuthState(pkgName, authType, deviceId, extra); + if (context_->ultrasonicInfo == DmUltrasonicInfo::DM_Ultrasonic_Invalid) { + return ERR_DM_INPUT_PARA_INVALID; + } + return DM_OK; +} + +int32_t AuthManager::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, + const std::map &bindParam, int sessionId, uint64_t logicalSessionId) +{ + int ret = DM_OK; + LOGI("AuthManager::BindTarget start. pkgName: %{public}s", pkgName.c_str()); + for (auto iter = bindParam.begin(); iter != bindParam.end(); iter++) { + LOGI("AuthManager::BindTarget para: %{public}s : %{public}s ", iter->first.c_str(), iter->second.c_str()); + } + + struct RadarInfo info = { + .funcName = "AuthenticateDevice", + .stageRes = static_cast(StageRes::STAGE_SUCC), + .bizState = static_cast(BizState::BIZ_STATE_END), + }; + if (!DmRadarHelper::GetInstance().ReportDiscoverUserRes(info)) { + LOGE("ReportDiscoverUserRes failed"); + } + if (pkgName.empty()) { + LOGE("AuthManager::BindTarget failed, pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + int32_t authType = -1; + if (ParseAuthType(bindParam, authType) != DM_OK) { + LOGE("AuthManager::BindTarget failed, key: %{public}s error.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + context_->peerTargetId = targetId_; + bindParam_ = bindParam; + if (!targetId.deviceId.empty()) { + ret = AuthenticateDevice(pkgName, authType, targetId.deviceId, ParseExtraFromMap(bindParam)); + if (ret != DM_OK) { + return ret; + } + } else { + LOGE("AuthManager::BindTarget failed, targetId is error."); + return ERR_DM_INPUT_PARA_INVALID; + } + + context_->sessionId = sessionId; + context_->logicalSessionId = logicalSessionId; + context_->requestId = static_cast(logicalSessionId); + context_->authStateMachine->TransitionTo(std::make_shared()); + info = { .funcName = "BindTarget" }; + info.channelId = sessionId; + DmRadarHelper::GetInstance().ReportAuthSendRequest(info); + return ret; +} + +AuthSinkManager::AuthSinkManager(std::shared_ptr softbusConnector, + std::shared_ptr hiChainConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector) + : AuthManager(softbusConnector, hiChainConnector, listener, hiChainAuthConnector) +{ + context_->direction = DM_AUTH_SINK; + context_->authStateMachine = std::make_shared(context_); +} + +void AuthSinkManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) +{ + LOGI("sessionId = %{public}d and sessionSide = %{public}d result = %{public}d", sessionId, sessionSide, result); +} + +void AuthSinkManager::OnSessionClosed(int32_t sessionId) +{ + LOGI("AuthSrcManager::OnSessionClosed sessionId = %{public}d", sessionId); + context_->reason = ERR_DM_SESSION_CLOSED; + context_->authStateMachine->TransitionTo(std::make_shared()); +} + +void AuthSinkManager::OnDataReceived(int32_t sessionId, std::string message) +{ + context_->sessionId = sessionId; + int32_t ret = context_->authMessageProcessor->ParseMessage(context_, message); + if (ret != DM_OK) { + LOGE("OnDataReceived failed, parse input message error."); + context_->reason = ERR_DM_PARSE_MESSAGE_FAILED; + context_->authStateMachine->TransitionTo(std::make_shared()); + } + + return; +} + +bool AuthSinkManager::GetIsCryptoSupport() +{ + return false; +} + +void AuthManager::GetRemoteDeviceId(std::string &deviceId) +{ + deviceId = (context_->direction == DM_AUTH_SOURCE) ? context_->accessee.deviceId : context_->accesser.deviceId; + return; +} + +int32_t AuthSinkManager::OnUserOperation(int32_t action, const std::string ¶ms) +{ + LOGI("AuthSinkManager::OnUserOperation start."); + if (context_ == nullptr || context_->authStateMachine == nullptr) { + LOGE("OnUserOperation: Authenticate is not start"); + return ERR_DM_AUTH_NOT_START; + } + + switch (action) { + case USER_OPERATION_TYPE_CANCEL_AUTH: + case USER_OPERATION_TYPE_ALLOW_AUTH: + case USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS: + context_->confirmOperation = static_cast(action); + context_->reply = USER_OPERATION_TYPE_ALLOW_AUTH; + if (action == USER_OPERATION_TYPE_CANCEL_AUTH) { + LOGI("AuthSinkManager::OnUserOperation USER_OPERATION_TYPE_CANCEL_AUTH."); + context_->reply = USER_OPERATION_TYPE_CANCEL_AUTH; + } + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_USER_OPERATION); + break; + case USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT: + LOGI("AuthSinkManager::OnUserOperation USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT."); + context_->confirmOperation = USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT; + context_->reason = ERR_DM_TIME_OUT; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + break; + case USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY: + LOGI("AuthSinkManager::OnUserOperation USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY."); + context_->confirmOperation = USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY; + context_->reason = ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + break; + default: + LOGE("this action id not support"); + break; + } + LOGI("AuthSinkManager::OnUserOperation leave."); + return DM_OK; +} + +AuthSrcManager::AuthSrcManager(std::shared_ptr softbusConnector, + std::shared_ptr hiChainConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector) + : AuthManager(softbusConnector, hiChainConnector, listener, hiChainAuthConnector) +{ + context_->direction = DM_AUTH_SOURCE; + context_->authStateMachine = std::make_shared(context_); +} + +void AuthSrcManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) +{ + LOGI("sessionId = %{public}d and sessionSide = %{public}d result = %{public}d", sessionId, sessionSide, result); +} + +void AuthSrcManager::OnSessionClosed(int32_t sessionId) +{ + LOGI("AuthSrcManager::OnSessionClosed sessionId = %{public}d", sessionId); + context_->reason = ERR_DM_SESSION_CLOSED; + context_->authStateMachine->TransitionTo(std::make_shared()); +} + +void AuthSrcManager::OnSessionDisable() +{ + context_->sessionId = -1; +} + +void AuthSrcManager::OnDataReceived(int32_t sessionId, std::string message) +{ + context_->sessionId = sessionId; + int32_t ret = context_->authMessageProcessor->ParseMessage(context_, message); + if (ret != DM_OK) { + LOGE("OnDataReceived failed, parse input message error."); + context_->reason = ERR_DM_PARSE_MESSAGE_FAILED; + context_->authStateMachine->TransitionTo(std::make_shared()); + } + + return; +} + +bool AuthSrcManager::GetIsCryptoSupport() +{ + return false; +} + +int32_t AuthSrcManager::OnUserOperation(int32_t action, const std::string ¶ms) +{ + LOGI("AuthSrcManager::OnUserOperation start."); + if (context_ == nullptr || context_->authStateMachine == nullptr) { + LOGE("OnUserOperation: Authenticate is not start"); + return ERR_DM_AUTH_NOT_START; + } + + switch (action) { + case USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT: + LOGE("AuthSrcManager OnUserOperation user cancel"); + context_->pinInputResult = USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT; + context_->reason = ERR_DM_BIND_USER_CANCEL_ERROR; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + break; + case USER_OPERATION_TYPE_DONE_PINCODE_INPUT: + LOGE("AuthSrcManager OnUserOperation user input done"); + context_->pinInputResult = USER_OPERATION_TYPE_DONE_PINCODE_INPUT; + { + if (!IsNumberString(params)) { + LOGE("OnUserOperation jsonStr error"); + return ERR_DM_INPUT_PARA_INVALID; + } + context_->pinCode = params; + } + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_USER_OPERATION); + break; + default: + LOGE("this action id not support"); + break; + } + LOGI("AuthSrcManager::OnUserOperation leave."); + return DM_OK; +} + +void AuthSrcManager::AuthDeviceError(int64_t requestId, int32_t errorCode) +{ + LOGI("AuthSrcManager::AuthDeviceError start."); + auto curState = context_->authStateMachine->GetCurState(); + if (curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE || + curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE || + curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE) { + LOGI("AuthSrcManager::AuthDeviceError Auth pin err."); + if (context_->authType == DmAuthType::AUTH_TYPE_PIN) { + context_->inputPinAuthFailTimes++; + } + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ERROR); + context_->authStateMachine->TransitionTo(std::make_shared()); + } else { + LOGI("AuthSrcManager::AuthDeviceError unexpected err."); + context_->reason = errorCode; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + } + LOGI("AuthSrcManager::AuthDeviceError leave."); +} + +void AuthSinkManager::AuthDeviceError(int64_t requestId, int32_t errorCode) +{ + LOGI("AuthSinkManager::AuthDeviceError start."); + auto curState = context_->authStateMachine->GetCurState(); + if (curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE || + curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE) { + LOGI("AuthSrcManager::AuthDeviceError Auth pin err."); + if (context_->authType == DmAuthType::AUTH_TYPE_PIN) { + context_->inputPinAuthFailTimes++; + } + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ERROR); + context_->authStateMachine->TransitionTo(std::make_shared()); + } else { + LOGI("AuthSinkManager::AuthDeviceError unexpected err."); + context_->reason = errorCode; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + } + LOGI("AuthSinkManager::AuthDeviceError leave."); +} + +bool AuthSrcManager::AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) +{ + LOGI("AuthSrcManager::AuthDeviceTransmit start."); + // check request id first + if (requestId != context_->requestId) { + LOGE("AuthSrcManager::onTransmit requestId %{public}" PRId64"is error.", requestId); + return false; + } + + context_->transmitData = std::string(reinterpret_cast(data), dataLen); + context_->authStateMachine->NotifyEventFinish(ON_TRANSMIT); + LOGI("AuthSrcManager::AuthDeviceTransmit leave."); + return true; +} + +bool AuthSinkManager::AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) +{ + LOGI("AuthSinkManager::AuthDeviceTransmit start."); + // check request id first + if (requestId != context_->requestId) { + LOGE("AuthSinkManager::onTransmit requestId %{public}" PRId64"is error.", requestId); + return false; + } + + context_->transmitData = std::string(reinterpret_cast(data), dataLen); + context_->authStateMachine->NotifyEventFinish(ON_TRANSMIT); + LOGI("AuthSinkManager::AuthDeviceTransmit leave."); + return true; +} + +void AuthSrcManager::AuthDeviceFinish(int64_t requestId) +{ + LOGI("AuthSrcManager::AuthDeviceFinish start."); + context_->authStateMachine->NotifyEventFinish(ON_FINISH); + // Perform business processing based on the current state + DmAuthStateType curState = context_->authStateMachine->GetCurState(); + switch (curState) { + case DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE: + // ON_FINISH event occurs, start credential exchange + context_->authStateMachine->TransitionTo(std::make_shared()); + break; + default: + break; + } + LOGI("AuthSrcManager::AuthDeviceFinish leave."); +} + +void AuthSinkManager::AuthDeviceFinish(int64_t requestId) +{ + LOGI("AuthSinkManager::AuthDeviceFinish start."); + context_->authStateMachine->NotifyEventFinish(ON_FINISH); + LOGI("AuthSinkManager::AuthDeviceFinish leave."); +} + +void AuthSinkManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) +{ + LOGI("AuthSrcManager::AuthDeviceSessionKey start. keyLen: %{public}u", sessionKeyLen); + if (context_ == nullptr || context_->authMessageProcessor == nullptr || context_->authStateMachine == nullptr) { + LOGE("AuthSrcManager::AuthDeviceSessionKey failed, auth context not initial."); + return; + } + if (requestId != context_->requestId) { + LOGE("AuthSrcManager::onTransmit requestId %{public}" PRId64 "is error.", requestId); + return; + } + int32_t ret = context_->authMessageProcessor->SaveSessionKey(sessionKey, sessionKeyLen); + if (ret != DM_OK) { + LOGE("AuthSrcManager::AuthDeviceSessionKey, save session key error, ret: %{public}d", ret); + } + + context_->authStateMachine->NotifyEventFinish(ON_SESSION_KEY_RETURNED); +} + +char *AuthSinkManager::AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) +{ + LOGI("AuthSinkManager::AuthDeviceRequest start"); + (void)requestId; + (void)reqParams; + JsonObject jsonObj; + + DmAuthStateType curState = context_->authStateMachine->GetCurState(); + if (curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE || + curState == DmAuthStateType::AUTH_SINK_REVERSE_ULTRASONIC_DONE_STATE|| + curState == DmAuthStateType::AUTH_SINK_FORWARD_ULTRASONIC_DONE_STATE) { + std::string pinCode = ""; + if (GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == "") { + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED; + } else { + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; + jsonObj[FIELD_PIN_CODE] = pinCode; + } + } else if (curState == DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE) { + if (context_->isOnline) { // Non-first time certification + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; + jsonObj[FIELD_CRED_ID] = context_->accessee.transmitCredentialId; + } else if (!context_->isAppCredentialVerified) { // First-time authentication && appCred auth + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; + jsonObj[FIELD_CRED_ID] = context_->accessee.transmitCredentialId; + } else { // First-time authentication && User credential authentication + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; + jsonObj[FIELD_CRED_ID] = context_->accessee.lnnCredentialId; + } + } + jsonObj[FIELD_SERVICE_PKG_NAME] = std::string(DM_PKG_NAME); + std::string jsonStr = jsonObj.Dump(); + char *buffer = strdup(jsonStr.c_str()); + return buffer; +} + +int32_t AuthManager::GetPinCode(std::string &code) +{ + if (context_ == nullptr) { + LOGE("AuthManager failed to GetPinCode because context_ is nullptr"); + return ERR_DM_FAILED; + } + LOGI("GetPinCode called."); + code = context_->pinCode; + return DM_OK; +} + +// Reacquire BindParams to rebuild the link, generally used when switching between old and new protocol objects +void AuthManager::GetBindTargetParams(std::string &pkgName, PeerTargetId &targetId, + std::map &bindParam) +{ + pkgName = context_->pkgName; + targetId = targetId_; + bindParam = bindParam_; + + LOGI("AuthManager::GetBindTargetParams get pkgName %{public}s to reuse", pkgName.c_str()); + return; +} + +void AuthManager::SetBindTargetParams(const PeerTargetId &targetId) +{ + targetId_ = targetId; + LOGI("AuthManager::SetBindTargetParams set targetId to reuse"); + return; +} + +void AuthManager::ClearSoftbusSessionCallback() +{} + +void AuthManager::PrepareSoftbusSessionCallback() +{} + +void AuthManager::GetCallerInfo(DmBindCallerInfo &callerInfo) +{ + callerInfo.userId = context_->accesser.userId; + callerInfo.tokenId = context_->accesser.tokenId; + callerInfo.bundleName = context_->accesser.bundleName; + callerInfo.hostPkgLabel = context_->pkgLabel; +} + +void AuthManager::SetCallerInfo(const DmBindCallerInfo &callerInfo) +{ + (void)callerInfo; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index fa963619f..061259ec9 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -148,7 +148,7 @@ int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptraccessee.bundleName.c_str()); return ERR_DM_GET_TOKENID_FAILED; } - if (DmAuthState::CheckProcessNameInWhiteList(context->accessee.bundleName)) { + if (AuthManagerBase::CheckProcessNameInWhiteList(context->accessee.bundleName)) { context->accessee.bindLevel = DmRole::DM_ROLE_USER; } context->accessee.tokenIdHash = Crypto::GetTokenIdHash(std::to_string(context->accessee.tokenId)); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp.bak b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp.bak new file mode 100644 index 000000000..fa963619f --- /dev/null +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp.bak @@ -0,0 +1,534 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "accesstoken_kit.h" +#include "access_control_profile.h" +#include "accesser.h" +#include "accessee.h" +#include "auth_manager.h" +#include "app_manager.h" +#include "dm_crypto.h" +#include "dm_log.h" +#include "dm_timer.h" +#include "dm_radar_helper.h" +#include "dm_language_manager.h" +#include "dm_constants.h" +#include "dm_anonymous.h" +#include "dm_random.h" +#include "dm_auth_context.h" +#include "dm_auth_state.h" +#include "deviceprofile_connector.h" +#include "distributed_device_profile_errors.h" +#include "device_auth.h" +#include "hap_token_info.h" +#include "json_object.h" +#include "multiple_user_connector.h" +#include "os_account_manager.h" +#include "parameter.h" + +using namespace OHOS::Security::AccessToken; + +namespace OHOS { +namespace DistributedHardware { + +DmAuthStateType AuthSrcStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_START_STATE; +} + +int32_t AuthSrcStartState::Action(std::shared_ptr context) +{ + return DM_OK; +} + +DmAuthStateType AuthSrcNegotiateStateMachine::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE; +} + +std::string AuthSrcNegotiateStateMachine::GetAccountGroupIdHash(std::shared_ptr context) +{ + JsonObject jsonObj; + jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP; + std::string queryParams = SafetyDump(jsonObj); + + int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); + if (osAccountUserId < 0) { + LOGE("get current process account user id failed"); + return ""; + } + std::vector groupList; + if (!context->hiChainConnector->GetGroupInfo(osAccountUserId, queryParams, groupList)) { + return ""; + } + JsonObject jsonAccountObj(JsonCreateType::JSON_CREATE_TYPE_ARRAY); + for (auto &groupInfo : groupList) { + jsonAccountObj.PushBack(Crypto::GetGroupIdHash(groupInfo.groupId)); + } + return SafetyDump(jsonAccountObj); +} + +int32_t AuthSrcNegotiateStateMachine::Action(std::shared_ptr context) +{ + LOGI("AuthSrcNegotiateStateMachine::Action sessionId %{public}d.", context->sessionId); + + context->reply = ERR_DM_AUTH_REJECT; + context->accessee.dmVersion = ""; + + // Calculate the hash value + context->accesser.deviceIdHash = Crypto::GetUdidHash(context->accesser.deviceId); + context->accesser.accountIdHash = Crypto::GetAccountIdHash16(context->accesser.accountId); + context->accesser.tokenIdHash = Crypto::GetTokenIdHash(std::to_string(context->accesser.tokenId)); + + // Create old message for compatible + context->accesser.accountGroupIdHash = GetAccountGroupIdHash(context); + + std::string message = context->authMessageProcessor->CreateMessage(MSG_TYPE_REQ_ACL_NEGOTIATE, context); + context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); + if (context->timer != nullptr) { + context->timer->StartTimer(std::string(NEGOTIATE_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, NEGOTIATE_TIMEOUT_TASK, NEGOTIATE_TIMEOUT), + [this, context] (std::string name) { + DmAuthState::HandleAuthenticateTimeout(context, name); + }); + } + + return DM_OK; +} + +DmAuthStateType AuthSinkNegotiateStateMachine::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE; +} + +int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + // 1. Get deviceId + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + context->accessee.deviceId = std::string(localDeviceId); + context->accessee.deviceIdHash = Crypto::GetUdidHash(context->accessee.deviceId); + + // 2. Get userId + context->accessee.userId = MultipleUserConnector::GetUserIdByDisplayId( + static_cast(context->accessee.displayId)); + if (context->accessee.userId < 0) { + LOGE("get userId failed."); + return ERR_DM_GET_LOCAL_USERID_FAILED; + } + + // 3. Get accountId + context->accessee.accountId = MultipleUserConnector::GetOhosAccountIdByUserId(context->accessee.userId); + context->accessee.accountIdHash = Crypto::GetAccountIdHash16(context->accessee.accountId); + + // 4. Get tokenId + if (AppManager::GetInstance().GetNativeTokenIdByName(context->accessee.bundleName, + context->accessee.tokenId) == DM_OK) { + context->accessee.bindLevel = DmRole::DM_ROLE_SA; + } else if (AppManager::GetInstance().GetHapTokenIdByName(context->accessee.userId, context->accessee.bundleName, 0, + context->accessee.tokenId) == DM_OK) { + context->accessee.bindLevel = DmRole::DM_ROLE_FA; + } else { + LOGE("sink not contain the bundlename %{public}s.", context->accessee.bundleName.c_str()); + return ERR_DM_GET_TOKENID_FAILED; + } + if (DmAuthState::CheckProcessNameInWhiteList(context->accessee.bundleName)) { + context->accessee.bindLevel = DmRole::DM_ROLE_USER; + } + context->accessee.tokenIdHash = Crypto::GetTokenIdHash(std::to_string(context->accessee.tokenId)); + context->accesser.isOnline = context->softbusConnector->CheckIsOnline(context->accesser.deviceIdHash, true); + context->accessee.language = DmLanguageManager::GetInstance().GetSystemLanguage(); + context->accessee.deviceName = context->listener->GetLocalDisplayDeviceNameForPrivacy(); + context->accessee.networkId = context->softbusConnector->GetLocalDeviceNetworkId(); + return DM_OK; +} + +int32_t AuthSinkNegotiateStateMachine::ProcRespNegotiate5_1_0(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + int32_t ret = RespQueryAcceseeIds(context); + if (ret != DM_OK) { + LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to get all id."); + return ret; + } + JsonObject credInfo; + GetSinkCredentialInfo(context, credInfo); + JsonObject aclTypeJson; + GetSinkAclInfo(context, credInfo, aclTypeJson); + context->accessee.aclTypeList = aclTypeJson.Dump(); + JsonObject credTypeJson; + GetSinkCredType(context, credInfo, aclTypeJson, credTypeJson); + context->accessee.credTypeList = credTypeJson.Dump(); + return DM_OK; +} + +int32_t AuthSinkNegotiateStateMachine::Action(std::shared_ptr context) +{ + LOGI("AuthSinkNegotiateStateMachine::Action sessionid %{public}d", context->sessionId); + + // 1. Create an authorization timer + if (context->timer != nullptr) { + context->timer->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), + AUTHENTICATE_TIMEOUT, + [this, context] (std::string name) { + DmAuthState::HandleAuthenticateTimeout(context, name); + }); + } + + // To be compatible with historical versions, use ConvertSrcVersion to get the actual version on the source side. + std::string preVersion = std::string(DM_VERSION_5_0_OLD_MAX); + LOGI("AuthSinkNegotiateStateMachine::Action start version compare %{public}s to %{public}s", + context->accesser.dmVersion.c_str(), preVersion.c_str()); + if (CompareVersion(context->accesser.dmVersion, preVersion) == false) { + LOGE("AuthSinkNegotiateStateMachine::Action incompatible version"); + context->reason = ERR_DM_VERSION_INCOMPATIBLE; + return ERR_DM_VERSION_INCOMPATIBLE; + } + + int32_t ret = ProcRespNegotiate5_1_0(context); + if (ret != DM_OK) { + LOGE("AuthSinkNegotiateStateMachine::Action proc response negotiate failed"); + context->reason = ret; + return ret; + } + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_ACL_NEGOTIATE, context); + context->timer->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), + [this, context] (std::string name) { + DmAuthState::HandleAuthenticateTimeout(context, name); + }); + return DM_OK; +} + +void AuthSinkNegotiateStateMachine::GetSinkCredType(std::shared_ptr context, + JsonObject &credInfo, JsonObject &aclInfo, JsonObject &credTypeJson) +{ + CHECK_NULL_VOID(context); + std::vector deleteCredInfo; + for (const auto &item : credInfo.Items()) { + if (!item.Contains(FILED_CRED_TYPE) || !item[FILED_CRED_TYPE].IsNumberInteger() || + !item.Contains(FILED_CRED_ID) || !item[FILED_CRED_ID].IsString()) { + deleteCredInfo.push_back(item[FILED_CRED_ID].Get()); + continue; + } + int32_t credType = item[FILED_CRED_TYPE].Get(); + LOGI("credType %{public}d.", credType); + switch (credType) { + case DM_IDENTICAL_ACCOUNT: + credTypeJson["identicalCredType"] = credType; + context->accessee.credentialInfos[credType] = item.Dump(); + break; + case DM_SHARE: + credTypeJson["shareCredType"] = credType; + context->accessee.credentialInfos[credType] = item.Dump(); + break; + case DM_POINT_TO_POINT: + GetSinkCredTypeForP2P(context, item, aclInfo, credTypeJson, credType, deleteCredInfo); + break; + case DM_LNN: + if (!aclInfo.Contains("lnnAcl") || + (context->accessee.aclProfiles[DM_LNN].GetAccessee().GetAccesseeCredentialIdStr() != + item[FILED_CRED_ID].Get() && + context->accessee.aclProfiles[DM_LNN].GetAccesser().GetAccesserCredentialIdStr() != + item[FILED_CRED_ID].Get())) { + deleteCredInfo.push_back(item[FILED_CRED_ID].Get()); + } else { + credTypeJson["lnnCredType"] = credType; + context->accessee.credentialInfos[credType] = item.Dump(); + } + break; + default: + LOGE("invalid credType %{public}d.", credType); + break; + } + } + for (const auto &item : deleteCredInfo) { + credInfo.Erase(item); + context->hiChainAuthConnector->DeleteCredential(context->accessee.userId, item); + } +} + +void AuthSinkNegotiateStateMachine::GetSinkCredTypeForP2P(std::shared_ptr context, + const JsonItemObject &credObj, JsonObject &aclInfo, JsonObject &credTypeJson, + int32_t credType, std::vector &deleteCredInfo) +{ + CHECK_NULL_VOID(context); + if (!aclInfo.Contains("pointTopointAcl") || + (context->accessee.aclProfiles[DM_POINT_TO_POINT].GetAccessee().GetAccesseeCredentialIdStr() != + credObj[FILED_CRED_ID].Get() && + context->accessee.aclProfiles[DM_POINT_TO_POINT].GetAccesser().GetAccesserCredentialIdStr() != + credObj[FILED_CRED_ID].Get())) { + deleteCredInfo.push_back(credObj[FILED_CRED_ID].Get()); + } else { + credTypeJson["pointTopointCredType"] = credType; + context->accessee.credentialInfos[credType] = credObj.Dump(); + } +} + +void AuthSinkNegotiateStateMachine::GetSinkAclInfo(std::shared_ptr context, + JsonObject &credInfo, JsonObject &aclInfo) +{ + CHECK_NULL_VOID(context); + std::vector profiles = + DeviceProfileConnector::GetInstance().GetAllAclIncludeLnnAcl(); + int32_t bindLevel = DM_INVALIED_TYPE; + for (const auto &item : profiles) { + std::string trustDeviceId = item.GetTrustDeviceId(); + std::string trustDeviceIdHash = Crypto::GetUdidHash(trustDeviceId); + if (trustDeviceIdHash != context->accesser.deviceIdHash && + trustDeviceIdHash != context->accessee.deviceIdHash) { + LOGE("devId %{public}s hash %{public}s, er devId %{public}s.", GetAnonyString(trustDeviceId).c_str(), + GetAnonyString(trustDeviceIdHash).c_str(), GetAnonyString(context->accesser.deviceIdHash).c_str()); + continue; + } + bindLevel = item.GetBindLevel(); + switch (item.GetBindType()) { + case DM_IDENTICAL_ACCOUNT: + if (IdenticalAccountAclCompare(context, item.GetAccesser(), item.GetAccessee())) { + aclInfo["identicalAcl"] = DM_IDENTICAL_ACCOUNT; + context->accessee.aclProfiles[DM_IDENTICAL_ACCOUNT] = item; + } + break; + case DM_SHARE: + if (ShareAclCompare(context, item.GetAccesser(), item.GetAccessee()) && + CheckCredIdInAcl(context, item, credInfo, DM_SHARE)) { + aclInfo["shareAcl"] = DM_SHARE; + context->accessee.aclProfiles[DM_SHARE] = item; + } + break; + case DM_POINT_TO_POINT: + GetSinkAclInfoForP2P(context, item, credInfo, aclInfo); + break; + default: + LOGE("invalid bindType %{public}d.", item.GetBindType()); + break; + } + } + if (aclInfo.Contains("pointTopointAcl") && !aclInfo.Contains("lnnAcl") && bindLevel != USER) { + aclInfo.Erase("pointTopointAcl"); + DeleteAcl(context, context->accessee.aclProfiles[DM_POINT_TO_POINT]); + } +} + +void AuthSinkNegotiateStateMachine::GetSinkAclInfoForP2P(std::shared_ptr context, + const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, JsonObject &aclInfo) +{ + CHECK_NULL_VOID(context); + if (Point2PointAclCompare(context, profile.GetAccesser(), profile.GetAccessee()) && + CheckCredIdInAcl(context, profile, credInfo, DM_POINT_TO_POINT)) { + aclInfo["pointTopointAcl"] = DM_POINT_TO_POINT; + context->accessee.aclProfiles[DM_POINT_TO_POINT] = profile; + } + if (LnnAclCompare(context, profile.GetAccesser(), profile.GetAccessee()) && + CheckCredIdInAcl(context, profile, credInfo, DM_LNN) && profile.GetBindLevel() == USER) { + aclInfo["lnnAcl"] = DM_LNN; + context->accessee.aclProfiles[DM_LNN] = profile; + } +} + +bool AuthSinkNegotiateStateMachine::CheckCredIdInAcl(std::shared_ptr context, + const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, uint32_t bindType) +{ + std::string credId = profile.GetAccessee().GetAccesseeCredentialIdStr(); + if (!credInfo.Contains(credId)) { + credId = profile.GetAccesser().GetAccesserCredentialIdStr(); + if (!credInfo.Contains(credId)) { + LOGE("credInfoJson not contain credId %{public}s.", credId.c_str()); + DeleteAcl(context, profile); + return false; + } + } + if (credInfo.Contains(credId) && (!credInfo[credId].IsObject() || !credInfo[credId].Contains(FILED_CRED_TYPE) || + !credInfo[credId][FILED_CRED_TYPE].IsNumberInteger())) { + LOGE("credId %{public}s contain credInfoJson invalid.", credId.c_str()); + credInfo.Erase(credId); + DeleteAcl(context, profile); + return false; + } + bool checkResult = false; + switch (bindType) { + LOGI("bindType %{public}d.", bindType); + case DM_IDENTICAL_ACCOUNT: + case DM_SHARE: + case DM_LNN: + if (credInfo[credId][FILED_CRED_TYPE].Get() == bindType) { + checkResult = true; + } else { + DeleteAcl(context, profile); + } + break; + case DM_POINT_TO_POINT: + CheckCredIdInAclForP2P(context, credId, profile, credInfo, bindType, checkResult); + break; + default: + break; + } + return checkResult; +} + +void AuthSinkNegotiateStateMachine::CheckCredIdInAclForP2P(std::shared_ptr context, + std::string &credId, const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, + uint32_t bindType, bool &checkResult) +{ + if (credInfo[credId][FILED_CRED_TYPE].Get() == bindType) { + std::vector appList; + credInfo[credId][FILED_AUTHORIZED_APP_LIST].Get(appList); + const size_t APP_LIST_SIZE = 2; + if (appList.size() >= APP_LIST_SIZE && + ((std::to_string(profile.GetAccesser().GetAccesserTokenId()) == appList[0] && + std::to_string(profile.GetAccessee().GetAccesseeTokenId()) == appList[1]) || + (std::to_string(profile.GetAccessee().GetAccesseeTokenId()) == appList[0] && + std::to_string(profile.GetAccesser().GetAccesserTokenId()) == appList[1]))) { + checkResult = true; + } else { + DeleteAcl(context, profile); + } + } else { + DeleteAcl(context, profile); + } +} + +bool AuthSinkNegotiateStateMachine::IdenticalAccountAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + LOGI("start"); + return accesser.GetAccesserDeviceId() == context->accessee.deviceId && + accesser.GetAccesserUserId() == context->accessee.userId && + Crypto::GetUdidHash(accessee.GetAccesseeDeviceId()) == context->accesser.deviceIdHash; +} + +bool AuthSinkNegotiateStateMachine::ShareAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + LOGI("start"); + return accessee.GetAccesseeDeviceId() == context->accessee.deviceId && + accessee.GetAccesseeUserId() == context->accessee.userId && + Crypto::GetUdidHash(accesser.GetAccesserDeviceId()) == context->accesser.deviceIdHash; +} + +bool AuthSinkNegotiateStateMachine::Point2PointAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + LOGI("start"); + return (accessee.GetAccesseeDeviceId() == context->accessee.deviceId && + accessee.GetAccesseeUserId() == context->accessee.userId && + accessee.GetAccesseeTokenId() == context->accessee.tokenId && + Crypto::GetUdidHash(accesser.GetAccesserDeviceId()) == context->accesser.deviceIdHash && + Crypto::GetTokenIdHash(std::to_string(accesser.GetAccesserTokenId())) == context->accesser.tokenIdHash) || + (accesser.GetAccesserDeviceId() == context->accessee.deviceId && + accesser.GetAccesserUserId() == context->accessee.userId && + accesser.GetAccesserTokenId() == context->accessee.tokenId && + Crypto::GetUdidHash(accessee.GetAccesseeDeviceId()) == context->accesser.deviceIdHash && + Crypto::GetTokenIdHash(std::to_string(accessee.GetAccesseeTokenId())) == context->accesser.tokenIdHash); +} + +bool AuthSinkNegotiateStateMachine::LnnAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + LOGI("start"); + return ((accessee.GetAccesseeDeviceId() == context->accessee.deviceId && + accessee.GetAccesseeUserId() == context->accessee.userId) || + (accesser.GetAccesserDeviceId() == context->accessee.deviceId && + accesser.GetAccesserUserId() == context->accessee.userId)) && + accessee.GetAccesseeTokenId() == 0 && accessee.GetAccesseeBundleName() == "" && + (Crypto::GetUdidHash(accesser.GetAccesserDeviceId()) == context->accesser.deviceIdHash || + Crypto::GetUdidHash(accessee.GetAccesseeDeviceId()) == context->accesser.deviceIdHash) && + accesser.GetAccesserTokenId() == 0 && accesser.GetAccesserBundleName() == ""; +} + +void AuthSinkNegotiateStateMachine::GetSinkCredentialInfo(std::shared_ptr context, + JsonObject &credInfo) +{ + CHECK_NULL_VOID(context); + // get identical credential + if (context->accesser.accountIdHash == context->accessee.accountIdHash) { + GetIdenticalCredentialInfo(context, credInfo); + } + // get share credential + if (context->accesser.accountIdHash != context->accessee.accountIdHash && + context->accesser.accountIdHash != Crypto::GetAccountIdHash16("ohosAnonymousUid") && + context->accessee.accountIdHash != Crypto::GetAccountIdHash16("ohosAnonymousUid")) { + GetShareCredentialInfo(context, credInfo); + GetP2PCredentialInfo(context, credInfo); + } + // get point_to_point credential + if (context->accesser.accountIdHash == Crypto::GetAccountIdHash16("ohosAnonymousUid") || + context->accessee.accountIdHash == Crypto::GetAccountIdHash16("ohosAnonymousUid")) { + GetP2PCredentialInfo(context, credInfo); + } + std::vector deleteCredInfo; + for (auto& item : credInfo.Items()) { // id1:json1, id2:json2, id3:json3 + uint32_t credType = DmAuthState::GetCredentialType(context, item); + if (credType == DM_INVALIED_TYPE || !item.Contains(FILED_CRED_TYPE) || + !item[FILED_CRED_TYPE].IsNumberInteger() || !item.Contains(FILED_CRED_ID) || + !item[FILED_CRED_ID].IsString()) { + deleteCredInfo.push_back(item[FILED_CRED_ID].Get()); + continue; + } + item[FILED_CRED_TYPE] = credType; + } + for (const auto &item : deleteCredInfo) { + credInfo.Erase(item); + } +} + +void AuthSinkNegotiateStateMachine::GetIdenticalCredentialInfo(std::shared_ptr context, + JsonObject &credInfo) +{ + CHECK_NULL_VOID(context); + JsonObject queryParams; + queryParams[FILED_DEVICE_ID] = context->accessee.deviceId; + queryParams[FILED_USER_ID] = MultipleUserConnector::GetOhosAccountNameByUserId(context->accessee.userId); + queryParams[FILED_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_RELATED; + CHECK_NULL_VOID(context->hiChainAuthConnector); + if (context->hiChainAuthConnector->QueryCredentialInfo(context->accessee.userId, queryParams, credInfo) != DM_OK) { + LOGE("QueryCredentialInfo failed credInfo %{public}s.", credInfo.Dump().c_str()); + } +} + +void AuthSinkNegotiateStateMachine::GetShareCredentialInfo(std::shared_ptr context, + JsonObject &credInfo) +{ + CHECK_NULL_VOID(context); + JsonObject queryParams; + queryParams[FILED_DEVICE_ID_HASH] = context->accesser.deviceIdHash; + queryParams[FILED_PEER_USER_SPACE_ID] = std::to_string(context->accesser.userId); + queryParams[FILED_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS; + CHECK_NULL_VOID(context->hiChainAuthConnector); + if (context->hiChainAuthConnector->QueryCredentialInfo(context->accessee.userId, queryParams, credInfo) != DM_OK) { + LOGE("QueryCredentialInfo failed credInfo %{public}s.", credInfo.Dump().c_str()); + } +} + +void AuthSinkNegotiateStateMachine::GetP2PCredentialInfo(std::shared_ptr context, + JsonObject &credInfo) +{ + CHECK_NULL_VOID(context); + JsonObject queryParams; + queryParams[FILED_DEVICE_ID_HASH] = context->accesser.deviceIdHash; + queryParams[FILED_PEER_USER_SPACE_ID] = std::to_string(context->accesser.userId); + queryParams[FILED_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; + queryParams[FILED_CRED_OWNER] = "DM"; + CHECK_NULL_VOID(context->hiChainAuthConnector); + if (context->hiChainAuthConnector->QueryCredentialInfo(context->accessee.userId, queryParams, credInfo) != DM_OK) { + LOGE("QueryCredentialInfo failed credInfo %{public}s.", credInfo.Dump().c_str()); + } +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp index 49eb28e17..6eb16828c 100644 --- a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp @@ -98,6 +98,15 @@ const int32_t SESSION_HEARTBEAT_TIMEOUT = 50; const int32_t PIN_AUTH_TIMEOUT = 60; const int32_t EVENT_TIMEOUT = 5000; // 5000 ms +constexpr int32_t OPEN_PROCESS_NAME_WHITE_LIST_NUM = 1; +constexpr int32_t CLOSE_PROCESS_NAME_WHITE_LIST_NUM = 2; +constexpr const static char* OPEN_PROCESS_NAME_WHITE_LIST[OPEN_PROCESS_NAME_WHITE_LIST_NUM] = { + "com.example.myapplication" +}; +constexpr const static char* CLOSE_PROCESS_NAME_WHITE_LIST[CLOSE_PROCESS_NAME_WHITE_LIST_NUM] = { + "CollaborationFwk", + "gameservice_server" +}; int32_t AuthManagerBase::AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra) @@ -510,5 +519,34 @@ int32_t AuthManagerBase::EndDream() LOGI("end dream success"); return DM_OK; } + +bool AuthManagerBase::CheckProcessNameInWhiteList(const std::string &processName) +{ + LOGI("AuthManagerBase::CheckProcessNameInWhiteList start"); + if (processName.empty()) { + LOGE("processName is empty"); + return false; + } + uint16_t index = 0; +#ifdef DEVICE_MANAGER_COMMON_FLAG + for (; index < OPEN_PROCESS_NAME_WHITE_LIST_NUM; ++index) { + std::string whitePkgName(OPEN_PROCESS_NAME_WHITE_LIST[index]); + if (processName == whitePkgName) { + LOGI("processName = %{public}s in whiteList.", processName.c_str()); + return true; + } + } +#else + for (; index < CLOSE_PROCESS_NAME_WHITE_LIST_NUM; ++index) { + std::string whitePkgName(CLOSE_PROCESS_NAME_WHITE_LIST[index]); + if (processName == whitePkgName) { + LOGI("processName = %{public}s in whiteList.", processName.c_str()); + return true; + } + } +#endif + LOGI("CheckProcessNameInWhiteList: %{public}s invalid.", processName.c_str()); + return false; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp.bak b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp.bak new file mode 100644 index 000000000..49eb28e17 --- /dev/null +++ b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp.bak @@ -0,0 +1,514 @@ +/* + * Copyright (c) 2025 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 "multiple_user_connector.h" +#include "os_account_manager.h" + +#include "dm_constants.h" +#include "dm_error_type.h" +#include "dm_auth_manager_base.h" +#include "power_mgr_client.h" +#if defined(SUPPORT_SCREENLOCK) +#include "screenlock_manager.h" +#endif + +#ifdef OS_ACCOUNT_PART_EXISTS +#include "os_account_manager.h" +using namespace OHOS::AccountSA; +#endif // OS_ACCOUNT_PART_EXISTS + +namespace OHOS { +namespace DistributedHardware { +const char* TAG_DMVERSION = "dmVersion"; +const char* TAG_DM_VERSION_V2 = "dmVersionV2"; +const char* TAG_EDITION = "edition"; +const char* TAG_DATA = "data"; +const char* TAG_DATA_LEN = "dataLen"; +const char* TAG_BUNDLE_NAME = "bundleName"; +const char* TAG_BUNDLE_NAME_V2 = "bundleNameV2"; +const char* TAG_PEER_BUNDLE_NAME = "PEER_BUNDLE_NAME"; +const char* TAG_PEER_BUNDLE_NAME_V2 = "PEER_BUNDLE_NAME_V2"; +const char* TAG_PEER_PKG_NAME = "PEER_PKG_NAME"; +const char* TAG_BIND_LEVEL = "bindLevel"; +const char* TAG_REPLY = "REPLY"; +const char* TAG_APP_THUMBNAIL2 = "appThumbnail"; // Naming Add 2 to resolve conflicts with TAG_APP_THUMBNAIL +const char* TAG_AUTH_FINISH = "isFinish"; +const char* TAG_LOCAL_USERID = "localUserId"; +const char* TAG_LOCAL_DEVICE_ID = "LOCALDEVICEID"; +const char* TAG_IDENTICAL_ACCOUNT = "IDENTICALACCOUNT"; +const char* TAG_ACCOUNT_GROUPID = "ACCOUNTGROUPID"; +const char* TAG_HAVE_CREDENTIAL = "haveCredential"; +const char* TAG_ISONLINE = "isOnline"; +const char* TAG_AUTHED = "authed"; +const char* TAG_LOCAL_ACCOUNTID = "localAccountId"; +const char* TAG_TOKENID = "tokenId"; +const char* TAG_HOST_PKGLABEL = "hostPkgLabel"; +const char* TAG_REMOTE_DEVICE_NAME = "REMOTE_DEVICE_NAME"; +const char* TAG_HOST = "HOST"; + +const char* APP_OPERATION_KEY = "appOperation"; +const char* TARGET_PKG_NAME_KEY = "targetPkgName"; +const char* CUSTOM_DESCRIPTION_KEY = "customDescription"; +const char* CANCEL_DISPLAY_KEY = "cancelPinCodeDisplay"; +const char* BUNDLE_NAME_KEY = "bundleName"; + +const char* AUTHENTICATE_TIMEOUT_TASK = "deviceManagerTimer:authenticate"; +const char* NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:negotiate"; +const char* CONFIRM_TIMEOUT_TASK = "deviceManagerTimer:confirm"; +const char* INPUT_TIMEOUT_TASK = "deviceManagerTimer:input"; +const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessionHeartbeat"; +const char* WAIT_REQUEST_TIMEOUT_TASK = "deviceManagerTimer:waitRequest"; +const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_"; +const char* WAIT_PIN_AUTH_TIMEOUT_TASK = "deviceManagerTimer:waitPinAuth"; +const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNegotiate"; +const char* GET_ULTRASONIC_PIN_TIMEOUT_TASK = "deviceManagerTimer:getUltrasonicPin"; +const char* ADD_TIMEOUT_TASK = "deviceManagerTimer:add"; +const char* WAIT_SESSION_CLOSE_TIMEOUT_TASK = "deviceManagerTimer:waitSessionClose"; +const char* CLOSE_SESSION_TASK_SEPARATOR = "#"; + +const int32_t AUTHENTICATE_TIMEOUT = 120; +const int32_t CONFIRM_TIMEOUT = 60; +const int32_t NEGOTIATE_TIMEOUT = 10; +const int32_t INPUT_TIMEOUT = 60; +const int32_t ADD_TIMEOUT = 10; +const int32_t WAIT_NEGOTIATE_TIMEOUT = 10; +const int32_t WAIT_REQUEST_TIMEOUT = 10; +const int32_t CLONE_AUTHENTICATE_TIMEOUT = 20; +const int32_t CLONE_CONFIRM_TIMEOUT = 10; +const int32_t CLONE_NEGOTIATE_TIMEOUT = 10; +const int32_t CLONE_ADD_TIMEOUT = 10; +const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT = 10; +const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 10; +const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT = 20; +const int32_t CLONE_PIN_AUTH_TIMEOUT = 10; +const int32_t HML_SESSION_TIMEOUT = 10; +const int32_t SESSION_HEARTBEAT_TIMEOUT = 50; +const int32_t PIN_AUTH_TIMEOUT = 60; +const int32_t EVENT_TIMEOUT = 5000; // 5000 ms + + +int32_t AuthManagerBase::AuthenticateDevice(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + LOGE("AuthenticateDevice is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) +{ + LOGE("UnAuthenticateDevice is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::UnBindDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel, const std::string &extra) +{ + LOGE("UnBindDevice is not implemented in the current version"); + return ERR_DM_FAILED; +} + +void AuthManagerBase::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) +{ + LOGE("OnSessionOpened is not implemented in the current version"); +} + +void AuthManagerBase::OnSessionClosed(const int32_t sessionId) +{ + LOGE("OnSessionClosed is not implemented in the current version"); +} + +void AuthManagerBase::OnSessionDisable() +{ + LOGE("OnSessionDisable is not implemented in the current version"); +} + +void AuthManagerBase::OnDataReceived(const int32_t sessionId, const std::string message) +{ + LOGE("OnDataReceived is not implemented in the current version"); +} + +void AuthManagerBase::OnSoftbusJoinLNNResult(const int32_t sessionId, const char *networkId, int32_t result) +{ + LOGE("OnSoftbusJoinLNNResult is not implemented in the current version"); +} + +void AuthManagerBase::OnGroupCreated(int64_t requestId, const std::string &groupId) +{ + LOGE("OnGroupCreated is not implemented in the current version"); +} + +void AuthManagerBase::OnMemberJoin(int64_t requestId, int32_t status) +{ + LOGE("OnMemberJoin is not implemented in the current version"); +} + +int32_t AuthManagerBase::EstablishAuthChannel(const std::string &deviceId) +{ + LOGE("EstablishAuthChannel is not implemented in the current version"); + return ERR_DM_FAILED; +} + +void AuthManagerBase::StartNegotiate(const int32_t &sessionId) +{ + LOGE("StartNegotiate is not implemented in the current version"); +} + +void AuthManagerBase::RespNegotiate(const int32_t &sessionId) +{ + LOGE("RespNegotiate is not implemented in the current version"); +} + +void AuthManagerBase::SendAuthRequest(const int32_t &sessionId) +{ + LOGE("SendAuthRequest is not implemented in the current version"); +} + +int32_t AuthManagerBase::StartAuthProcess(const int32_t &action) +{ + LOGE("StartAuthProcess is not implemented in the current version"); + return ERR_DM_FAILED; +} + +void AuthManagerBase::StartRespAuthProcess() +{ + LOGE("StartRespAuthProcess is not implemented in the current version"); +} + +int32_t AuthManagerBase::CreateGroup() +{ + LOGE("CreateGroup is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::ProcessPincode(const std::string &pinCode) +{ + LOGE("ProcessPincode is not implemented in the current version"); + return ERR_DM_FAILED; +} + +std::string AuthManagerBase::GetConnectAddr(std::string deviceId) +{ + LOGE("GetConnectAddr is not implemented in the current version"); + return ""; +} + +int32_t AuthManagerBase::JoinNetwork() +{ + LOGE("JoinNetwork is not implemented in the current version"); + return ERR_DM_FAILED; +} + +void AuthManagerBase::AuthenticateFinish() +{ + LOGE("AuthenticateFinish is not implemented in the current version"); +} + +bool AuthManagerBase::GetIsCryptoSupport() +{ + LOGE("GetIsCryptoSupport is not implemented in the current version"); + return false; +} + +int32_t AuthManagerBase::SetAuthRequestState(std::shared_ptr authRequestState) +{ + LOGE("SetAuthRequestState is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::SetAuthResponseState(std::shared_ptr authResponseState) +{ + LOGE("SetAuthResponseState is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::GetPinCode(std::string &code) +{ + LOGE("GetPinCode is not implemented in the current version"); + return ERR_DM_FAILED; +} + +std::string AuthManagerBase::GenerateGroupName() +{ + LOGE("GenerateGroupName is not implemented in the current version"); + return ""; +} + +void AuthManagerBase::HandleAuthenticateTimeout(std::string name) +{ + LOGE("HandleAuthenticateTimeout is not implemented in the current version"); +} + +std::string AuthManagerBase::GeneratePincode() +{ + LOGE("GeneratePincode is not implemented in the current version"); + return ""; +} + +void AuthManagerBase::ShowConfigDialog() +{ + LOGE("ShowConfigDialog is not implemented in the current version"); +} + +void AuthManagerBase::ShowAuthInfoDialog(bool authDeviceError) +{ + LOGE("ShowAuthInfoDialog is not implemented in the current version"); +} + +void AuthManagerBase::ShowStartAuthDialog() +{ + LOGE("ShowStartAuthDialog is not implemented in the current version"); +} + +int32_t AuthManagerBase::OnUserOperation(int32_t action, const std::string ¶ms) +{ + LOGE("OnUserOperation is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::SetPageId(int32_t pageId) +{ + LOGE("SetPageId is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::SetReasonAndFinish(int32_t reason, int32_t state) +{ + LOGE("SetReasonAndFinish is not implemented in the current version"); + return ERR_DM_FAILED; +} + +bool AuthManagerBase::IsIdenticalAccount() +{ + LOGE("IsIdenticalAccount is not implemented in the current version"); + return false; +} + +int32_t AuthManagerBase::RegisterUiStateCallback(const std::string pkgName) +{ + LOGE("RegisterUiStateCallback is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::UnRegisterUiStateCallback(const std::string pkgName) +{ + LOGE("UnRegisterUiStateCallback is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::ImportAuthCode(const std::string &pkgName, const std::string &authCode) +{ + LOGE("ImportAuthCode is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, + const std::map &bindParam, int sessionId, uint64_t logicalSessionId) +{ + LOGE("BindTarget is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::RegisterAuthenticationType(int32_t authenticationType) +{ + LOGE("RegisterAuthenticationType is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::StopAuthenticateDevice(const std::string &pkgName) +{ + LOGE("StopAuthenticateDevice is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::DeleteGroup(const std::string &pkgName, const std::string &deviceId) +{ + LOGE("DeleteGroup is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::GetReason() +{ + LOGE("GetReason is not implemented in the current version"); + return ERR_DM_FAILED; +} + +void AuthManagerBase::GetBindTargetParams(std::string &pkgName, PeerTargetId &targetId, + std::map &bindParam) +{ + LOGE("GetBindTargetParams is not implemented in the current version"); + return; +} + +void AuthManagerBase::SetBindTargetParams(const PeerTargetId &targetId) +{ + LOGE("SetBindTargetParams is not implemented in the current version"); + return; +} + +void AuthManagerBase::RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback) +{ + LOGE("RegisterCleanNotifyCallback is not implemented in the current version"); + return; +} + +std::string AuthManagerBase::ConvertSrcVersion(const std::string &version, const std::string &edition) +{ + std::string srcVersion = ""; + if (version == "" && edition != "") { + srcVersion = edition; + } else if (version == "" && edition == "") { + srcVersion = DM_VERSION_5_1_0; + } else if (version != "" && edition == "") { + srcVersion = version; + } + LOGI("ConvertSrcVersion version %{public}s, edition %{public}s, srcVersion is %{public}s.", + version.c_str(), edition.c_str(), srcVersion.c_str()); + return srcVersion; +} + +// Scenario 1: The remote side specifies userId -> Verify if it is a front-end user +// Scenario 2: The remote side does not specify userId +// Scenario 2.1: Single user -> Use the current unique front-end user +// Scenario 2.2: Multiple users -> Use the current main screen user +int32_t AuthManagerBase::DmGetUserId(int32_t displayId) +{ + int32_t ret; + int32_t userId = -1; + + std::vector userIds; + ret = MultipleUserConnector::GetForegroundUserIds(userIds); + if (ret != DM_OK) { + LOGE("RespQueryTokenId: GetForegroundUserIds failed, ret: %{public}d", ret); + return -1; + } + // Scenario 1: The remote side specifies userId -> Verify if it is a front-end user + // Scenario 2: The remote side does not specify userId + // Scenario 2.1: Single user -> Use the current unique front-end user + // Scenario 2.2: Multiple users -> Use the current main screen user + if (userIds.size() == 0) { + LOGE("RespQueryTokenId: GetForegroundUserIds no foreground users"); + return -1; + } + + if (displayId != -1) { + ret = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(displayId, userId); + if (ret != DM_OK) { + LOGE("RespQueryTokenId: fail to get userId by displayId %{public}d", displayId); + return -1; + } + return userId; + } + if (userIds.size() == 1) { + return userIds[0]; + } else { + // If userIds.size() > 1, we need to find the main screen user +#ifdef OS_ACCOUNT_PART_EXISTS + ret = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId); + if (ret != DM_OK) { + LOGE("AuthManagerBase::DmGetUserId: get foreground user failed in multi users with error %{public}d", ret); + return -1; + } + return userId; +#else + LOGE("AuthManagerBase::DmGetUserId: get foreground user failed because no OsAcccountManager"); + return -1; +#endif + } +} + +bool AuthManagerBase::IsTransferReady() +{ + return isTransferReady_; +} + +void AuthManagerBase::SetTransferReady(bool version) +{ + isTransferReady_ = version; +} + +void AuthManagerBase::ClearSoftbusSessionCallback() +{} + +void AuthManagerBase::PrepareSoftbusSessionCallback() +{} + +void AuthManagerBase::EnableInsensibleSwitching() +{ + insensibleSwitching = true; +} + +void AuthManagerBase::DisableInsensibleSwitching() +{ + insensibleSwitching = false; +} + +bool AuthManagerBase::NeedInsensibleSwitching() +{ + return insensibleSwitching; +} + +int32_t AuthManagerBase::ParseAuthType(const std::map &bindParam, int32_t &authType) +{ + auto iter = bindParam.find(PARAM_KEY_AUTH_TYPE); + if (iter == bindParam.end()) { + LOGE("AuthManagerBase::ParseAuthType bind param key: %{public}s not exist.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + std::string authTypeStr = iter->second; + if (authTypeStr.empty()) { + LOGE("AuthManagerBase::ParseAuthType bind param %{public}s is empty.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + if (authTypeStr.length() > 1) { + LOGE("AuthManagerBase::ParseAuthType bind param %{public}s length is unsupported.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + if (!isdigit(authTypeStr[0])) { + LOGE("AuthManagerBase::ParseAuthType bind param %{public}s fromat is unsupported.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + authType = std::atoi(authTypeStr.c_str()); + return DM_OK; +} + +void AuthManagerBase::OnAuthDeviceDataReceived(int32_t sessionId, std::string message) +{ + LOGE("OnAuthDeviceDataReceived is not used in the new protocol"); +} + +int32_t AuthManagerBase::EndDream() +{ + auto &powerMgrClient = OHOS::PowerMgr::PowerMgrClient::GetInstance(); + if (!powerMgrClient.IsScreenOn()) { + LOGW("screen not on"); + return ERR_DM_FAILED; + } +#if defined(SUPPORT_SCREENLOCK) + if (!OHOS::ScreenLock::ScreenLockManager::GetInstance()->IsScreenLocked()) { + LOGI("screen not locked"); + return DM_OK; + } +#endif + PowerMgr::PowerErrors ret = + powerMgrClient.WakeupDevice(PowerMgr::WakeupDeviceType::WAKEUP_DEVICE_END_DREAM, "end_dream"); + if (ret != OHOS::PowerMgr::PowerErrors::ERR_OK) { + LOGE("fail to end dream, err:%{public}d", ret); + return ERR_DM_FAILED; + } + LOGI("end dream success"); + return DM_OK; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index e10b392e0..87ed256a5 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -61,17 +61,6 @@ const std::map NEW_AND_OLD_REPLAY_MAPPING = { { SOFTBUS_OK, SOFTBUS_OK } }; -constexpr int32_t OPEN_PROCESS_NAME_WHITE_LIST_NUM = 1; -constexpr int32_t CLOSE_PROCESS_NAME_WHITE_LIST_NUM = 2; -constexpr const static char* OPEN_PROCESS_NAME_WHITE_LIST[OPEN_PROCESS_NAME_WHITE_LIST_NUM] = { - "com.example.myapplication" -}; -constexpr const static char* CLOSE_PROCESS_NAME_WHITE_LIST[CLOSE_PROCESS_NAME_WHITE_LIST_NUM] = { - "CollaborationFwk", - "gameservice_server" -}; - - int32_t DmAuthState::GetTaskTimeout(std::shared_ptr context, const char* taskName, int32_t taskTimeOut) { LOGI("GetTaskTimeout, taskName: %{public}s, authType_: %{public}d", taskName, context->authType); @@ -339,35 +328,6 @@ bool DmAuthState::HaveSameTokenId(std::shared_ptr context, const (srcTokenIdHash == context->accessee.tokenIdHash)); } -bool DmAuthState::CheckProcessNameInWhiteList(const std::string &processName) -{ - LOGI("DmAuthState::CheckProcessNameInWhiteList start"); - if (processName.empty()) { - LOGE("processName is empty"); - return false; - } - uint16_t index = 0; -#ifdef DEVICE_MANAGER_COMMON_FLAG - for (; index < OPEN_PROCESS_NAME_WHITE_LIST_NUM; ++index) { - std::string whitePkgName(OPEN_PROCESS_NAME_WHITE_LIST[index]); - if (processName == whitePkgName) { - LOGI("processName = %{public}s in whiteList.", processName.c_str()); - return true; - } - } -#else - for (; index < CLOSE_PROCESS_NAME_WHITE_LIST_NUM; ++index) { - std::string whitePkgName(CLOSE_PROCESS_NAME_WHITE_LIST[index]); - if (processName == whitePkgName) { - LOGI("processName = %{public}s in whiteList.", processName.c_str()); - return true; - } - } -#endif - LOGI("CheckProcessNameInWhiteList: %{public}s invalid.", processName.c_str()); - return false; -} - int32_t DmAuthState::GetOutputState(const std::string &processName, int32_t state) { LOGI("state %{public}d.", state); diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp.bak b/services/implementation/src/authentication_v2/dm_auth_state.cpp.bak new file mode 100644 index 000000000..e10b392e0 --- /dev/null +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp.bak @@ -0,0 +1,461 @@ +/* + * Copyright (c) 2025 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 "access_control_profile.h" +#include "hichain_auth_connector.h" +#include "multiple_user_connector.h" +#include "dm_crypto.h" +#include "dm_auth_state.h" +#include "dm_auth_context.h" +#include "dm_auth_manager_base.h" +#include "dm_auth_state_machine.h" +#include "dm_crypto.h" +#include "dm_softbus_cache.h" +#if defined(SUPPORT_SCREENLOCK) +#include "screenlock_manager.h" +#endif +#include "dm_log.h" +#include + +namespace OHOS { +namespace DistributedHardware { +// clone task timeout map +const std::map TASK_TIME_OUT_MAP = { + { std::string(AUTHENTICATE_TIMEOUT_TASK), CLONE_AUTHENTICATE_TIMEOUT }, + { std::string(NEGOTIATE_TIMEOUT_TASK), CLONE_NEGOTIATE_TIMEOUT }, + { std::string(CONFIRM_TIMEOUT_TASK), CLONE_CONFIRM_TIMEOUT }, + { std::string(ADD_TIMEOUT_TASK), CLONE_ADD_TIMEOUT }, + { std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), CLONE_WAIT_NEGOTIATE_TIMEOUT }, + { std::string(WAIT_REQUEST_TIMEOUT_TASK), CLONE_WAIT_REQUEST_TIMEOUT }, + { std::string(WAIT_PIN_AUTH_TIMEOUT_TASK), CLONE_PIN_AUTH_TIMEOUT }, + { std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), CLONE_SESSION_HEARTBEAT_TIMEOUT } +}; + +constexpr int32_t ONBINDRESULT_MAPPING_NUM = 2; +constexpr int32_t MS_PER_SECOND = 1000; +constexpr int32_t US_PER_MSECOND = 1000; +constexpr const static char* ONBINDRESULT_MAPPING_LIST[ONBINDRESULT_MAPPING_NUM] = { + "CollaborationFwk", + "cast_engine_service", +}; + +const std::map NEW_AND_OLD_STATE_MAPPING = { + { DmAuthStateType::AUTH_SRC_FINISH_STATE, DmAuthStatus::STATUS_DM_AUTH_FINISH }, + { DmAuthStateType::AUTH_SINK_FINISH_STATE, DmAuthStatus::STATUS_DM_SINK_AUTH_FINISH } +}; + +const std::map NEW_AND_OLD_REPLAY_MAPPING = { + { DM_ALREADY_AUTHED, SOFTBUS_OK }, + { SOFTBUS_OK, SOFTBUS_OK } +}; + +constexpr int32_t OPEN_PROCESS_NAME_WHITE_LIST_NUM = 1; +constexpr int32_t CLOSE_PROCESS_NAME_WHITE_LIST_NUM = 2; +constexpr const static char* OPEN_PROCESS_NAME_WHITE_LIST[OPEN_PROCESS_NAME_WHITE_LIST_NUM] = { + "com.example.myapplication" +}; +constexpr const static char* CLOSE_PROCESS_NAME_WHITE_LIST[CLOSE_PROCESS_NAME_WHITE_LIST_NUM] = { + "CollaborationFwk", + "gameservice_server" +}; + + +int32_t DmAuthState::GetTaskTimeout(std::shared_ptr context, const char* taskName, int32_t taskTimeOut) +{ + LOGI("GetTaskTimeout, taskName: %{public}s, authType_: %{public}d", taskName, context->authType); + if (DmAuthState::IsImportAuthCodeCompatibility(context->authType)) { + auto timeout = TASK_TIME_OUT_MAP.find(std::string(taskName)); + if (timeout != TASK_TIME_OUT_MAP.end()) { + return timeout->second; + } + } + return taskTimeOut; +} + +void DmAuthState::HandleAuthenticateTimeout(std::shared_ptr context, std::string name) +{ + LOGI("DmAuthContext::HandleAuthenticateTimeout start timer name %{public}s", name.c_str()); + context->timer->DeleteTimer(name); + context->reason = ERR_DM_TIME_OUT; + context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + LOGI("DmAuthContext::HandleAuthenticateTimeout complete"); +} + +bool DmAuthState::IsScreenLocked() +{ + bool isLocked = false; +#if defined(SUPPORT_SCREENLOCK) + isLocked = OHOS::ScreenLock::ScreenLockManager::GetInstance()->IsScreenLocked(); +#endif + LOGI("IsScreenLocked isLocked: %{public}d.", isLocked); + return isLocked; +} + +void DmAuthState::SourceFinish(std::shared_ptr context) +{ + LOGI("SourceFinish reason:%{public}d", context->reason); + context->listener->OnAuthResult(context->processInfo, context->peerTargetId.deviceId, context->accessee.tokenIdHash, + GetOutputState(context->accesser.bundleName, context->state), context->reason); + context->listener->OnBindResult(context->processInfo, context->peerTargetId, + GetOutputReplay(context->accesser.bundleName, context->reason), + GetOutputState(context->accesser.bundleName, context->state), GenerateBindResultContent(context)); + context->successFinished = true; + + if (context->reason != DM_OK && context->reason != DM_ALREADY_AUTHED) { + // 根据凭据id 删除sink端多余的凭据 + context->hiChainAuthConnector->DeleteCredential(context->accesser.userId, + context->accesser.lnnCredentialId); + context->hiChainAuthConnector->DeleteCredential(context->accesser.userId, + context->accesser.transmitCredentialId); + // 根据skid删除sk,删除skid + DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accesser.userId, + context->accesser.lnnSessionKeyId); + DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accesser.userId, + context->accesser.transmitSessionKeyId); + } + LOGI("SourceFinish notify online"); + char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; + Crypto::GetUdidHash(context->accessee.deviceId, reinterpret_cast(deviceIdHash)); + if (SoftbusCache::GetInstance().CheckIsOnline(std::string(deviceIdHash))) { + SetProcessInfo(context); + int32_t authForm = context->accesser.transmitBindType == DM_POINT_TO_POINT_TYPE ? + DmAuthForm::PEER_TO_PEER : context->accesser.transmitBindType; + context->softbusConnector->HandleDeviceOnline(context->accessee.deviceId, authForm); + } + + context->authUiStateMgr->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); + context->timer->DeleteAll(); +} + +void DmAuthState::SinkFinish(std::shared_ptr context) +{ + LOGI("SinkFinish reason:%{public}d", context->reason); + context->processInfo.pkgName = context->accessee.pkgName; + context->listener->OnSinkBindResult(context->processInfo, context->peerTargetId, + GetOutputReplay(context->accessee.bundleName, context->reason), + GetOutputState(context->accessee.bundleName, context->state), GenerateBindResultContent(context)); + context->successFinished = true; + if (context->reason != DM_OK) { + // 根据凭据id 删除sink端多余的凭据 + context->hiChainAuthConnector->DeleteCredential(context->accessee.userId, + context->accessee.lnnCredentialId); + context->hiChainAuthConnector->DeleteCredential(context->accessee.userId, + context->accessee.transmitCredentialId); + // 根据skid删除sk,删除skid + DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accessee.userId, + context->accessee.lnnSessionKeyId); + DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accessee.userId, + context->accessee.transmitSessionKeyId); + } else { + SetAclInfo(context); + if (NeedAgreeAcl(context)) { + context->authMessageProcessor->PutAccessControlList(context, + context->accessee, context->accesser.deviceId); + } + LOGI("SinkFinish notify online"); + char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; + Crypto::GetUdidHash(context->accesser.deviceId, reinterpret_cast(deviceIdHash)); + if (SoftbusCache::GetInstance().CheckIsOnline(std::string(deviceIdHash))) { + SetProcessInfo(context); + int32_t authForm = context->accessee.transmitBindType == DM_POINT_TO_POINT_TYPE ? + DmAuthForm::PEER_TO_PEER : context->accessee.transmitBindType; + context->softbusConnector->HandleDeviceOnline(context->accesser.deviceId, authForm); + } + } + + context->authUiStateMgr->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW); + context->timer->DeleteAll(); + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_RESP_FINISH, context); // 发送201给source侧 +} + +std::string DmAuthState::GenerateBindResultContent(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ""); + DmAccess access = context->direction == DmAuthDirection::DM_AUTH_SOURCE ? + context->accessee : context->accesser; + JsonObject jsonObj; + jsonObj[DM_BIND_RESULT_NETWORK_ID] = access.networkId; + if (access.deviceId.empty()) { + jsonObj[TAG_DEVICE_ID] = ""; + } else { + char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; + Crypto::GetUdidHash(access.deviceId, reinterpret_cast(deviceIdHash)); + jsonObj[TAG_DEVICE_ID] = deviceIdHash; + } + jsonObj[TAG_CONFIRM_OPERATION_V2] = context->confirmOperation; + std::string content = jsonObj.Dump(); + return content; +} + +bool DmAuthState::NeedReqUserConfirm(std::shared_ptr context) +{ + // 不管是否有可信关系,都需要走pin码认证,主要指鸿蒙环PIN码导入场景 + if (DmAuthState::IsImportAuthCodeCompatibility(context->authType)) { + return true; + } + + // 有ACL,跳转到结束状态,发200报文,直接组网 + DmAccess access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; + if (access.isAuthed) { + return false; + } + + return true; +} + +bool DmAuthState::NeedAgreeCredential(std::shared_ptr context) +{ + return context->needAgreeCredential; +} + +bool DmAuthState::NeedAgreeAcl(std::shared_ptr context) +{ + return (context->direction == DM_AUTH_SOURCE) ? !context->accesser.isAuthed : !context->accessee.isAuthed; +} + +bool DmAuthState::IsImportAuthCodeCompatibility(DmAuthType authType) +{ + if (authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE || + authType == DmAuthType::AUTH_TYPE_NFC) { + return true; + } + return false; +} + +void DmAuthState::SetAclExtraInfo(std::shared_ptr context) +{ + DmAccess &access = (context->direction == DM_AUTH_SOURCE) ? context->accesser : context->accessee; + DmAccess &remoteAccess = (context->direction == DM_AUTH_SOURCE) ? context->accessee : context->accesser; + JsonObject jsonObj; + jsonObj[TAG_DMVERSION] = access.dmVersion; + access.extraInfo = jsonObj.Dump(); + remoteAccess.extraInfo = jsonObj.Dump(); +} + +void DmAuthState::SetAclInfo(std::shared_ptr context) +{ + DmAccess &access = (context->direction == DM_AUTH_SOURCE) ? context->accesser : context->accessee; + DmAccess &remoteAccess = (context->direction == DM_AUTH_SOURCE) ? context->accessee : context->accesser; + SetAclExtraInfo(context); + access.lnnBindType = GetAclBindType(context, access.lnnCredentialId); + remoteAccess.lnnBindType = GetAclBindType(context, remoteAccess.lnnCredentialId); + + access.transmitBindType = GetAclBindType(context, access.transmitCredentialId); + remoteAccess.transmitBindType = GetAclBindType(context, remoteAccess.transmitCredentialId); +} + +int32_t DmAuthState::GetAclBindType(std::shared_ptr context, std::string credId) +{ + DmAccess &access = (context->direction == DM_AUTH_SOURCE) ? context->accesser : context->accessee; + JsonObject result; + int32_t ret = context->hiChainAuthConnector->QueryCredInfoByCredId(access.userId, credId, result); + if (ret != DM_OK) { + LOGE("GetAclBindType QueryCredInfoByCredId failed, ret: %{public}d.", ret); + return DM_UNKNOWN_TYPE; + } + if (!result.Contains(credId)) { + LOGE("GetAclBindType result not contains credId."); + return DM_UNKNOWN_TYPE; + } + int32_t credType = result[credId][FILED_CRED_TYPE].Get(); + if (credType == DM_AUTH_CREDENTIAL_ACCOUNT_RELATED) { + return DM_SAME_ACCOUNT_TYPE; + } + if (credType == DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED) { + return DM_POINT_TO_POINT_TYPE; + } + if (credType == DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS) { + return DM_SHARE_TYPE; + } + return DM_UNKNOWN_TYPE; +} + +uint32_t DmAuthState::GetCredType(std::shared_ptr context, const JsonItemObject &credInfo) +{ + int32_t credType = credInfo[FILED_CRED_TYPE].Get(); + int32_t authorizedScope = credInfo[FILED_AUTHORIZED_SCOPE].Get(); + int32_t subject = credInfo[FILED_SUBJECT].Get(); + std::vector appList; + credInfo[FILED_AUTHORIZED_APP_LIST].Get(appList); + if (credType == ACCOUNT_RELATED && authorizedScope == SCOPE_USER) { + return DM_IDENTICAL_ACCOUNT; + } + if (credType == ACCOUNT_ACROSS && authorizedScope == SCOPE_USER && + context->direction == DM_AUTH_SOURCE && subject == SUBJECT_PRIMARY) { + return DM_SHARE; + } + if (credType == ACCOUNT_ACROSS && authorizedScope == SCOPE_USER && + context->direction == DM_AUTH_SINK && subject == SUBJECT_SECONDARY) { + return DM_SHARE; + } + if (credType == ACCOUNT_UNRELATED && authorizedScope == SCOPE_APP && HaveSameTokenId(context, appList)) { + return DM_POINT_TO_POINT; + } + if (credType == ACCOUNT_UNRELATED && authorizedScope == SCOPE_USER && appList.empty()) { + return DM_LNN; + } + return DM_INVALIED_TYPE; +} + +uint32_t DmAuthState::GetCredentialType(std::shared_ptr context, const JsonItemObject &credInfo) +{ + CHECK_NULL_RETURN(context, DM_INVALIED_TYPE); + if (!credInfo.Contains(FILED_CRED_TYPE) || !credInfo[FILED_CRED_TYPE].IsNumberInteger() || + !credInfo.Contains(FILED_AUTHORIZED_SCOPE) || !credInfo[FILED_AUTHORIZED_SCOPE].IsNumberInteger() || + !credInfo.Contains(FILED_SUBJECT) || !credInfo[FILED_SUBJECT].IsNumberInteger()) { + LOGE("credType or authorizedScope invalid."); + return DM_INVALIED_TYPE; + } + return GetCredType(context, credInfo); +} + +bool DmAuthState::HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList) +{ + // Store the token of src and sink. The size must be 2. + if (tokenList.size() != 2) { + LOGE("HaveSameTokenId invalid tokenList size."); + return false; + } + + // tokenIdList = [srcTokenId, sinkTokenId] + std::string srcTokenIdHash = Crypto::GetTokenIdHash(tokenList[0]); + std::string sinkTokenIdHash = Crypto::GetTokenIdHash(tokenList[1]); + + return ((srcTokenIdHash == context->accesser.tokenIdHash) && + (sinkTokenIdHash == context->accessee.tokenIdHash)) || + ((sinkTokenIdHash == context->accesser.tokenIdHash) && + (srcTokenIdHash == context->accessee.tokenIdHash)); +} + +bool DmAuthState::CheckProcessNameInWhiteList(const std::string &processName) +{ + LOGI("DmAuthState::CheckProcessNameInWhiteList start"); + if (processName.empty()) { + LOGE("processName is empty"); + return false; + } + uint16_t index = 0; +#ifdef DEVICE_MANAGER_COMMON_FLAG + for (; index < OPEN_PROCESS_NAME_WHITE_LIST_NUM; ++index) { + std::string whitePkgName(OPEN_PROCESS_NAME_WHITE_LIST[index]); + if (processName == whitePkgName) { + LOGI("processName = %{public}s in whiteList.", processName.c_str()); + return true; + } + } +#else + for (; index < CLOSE_PROCESS_NAME_WHITE_LIST_NUM; ++index) { + std::string whitePkgName(CLOSE_PROCESS_NAME_WHITE_LIST[index]); + if (processName == whitePkgName) { + LOGI("processName = %{public}s in whiteList.", processName.c_str()); + return true; + } + } +#endif + LOGI("CheckProcessNameInWhiteList: %{public}s invalid.", processName.c_str()); + return false; +} + +int32_t DmAuthState::GetOutputState(const std::string &processName, int32_t state) +{ + LOGI("state %{public}d.", state); + bool needMapFlag = false; + for (uint16_t index = 0; index < ONBINDRESULT_MAPPING_NUM; ++index) { + if (std::string(ONBINDRESULT_MAPPING_LIST[index]) == processName) { + LOGI("processName %{public}s new protocol param convert to old protocol param.", processName.c_str()); + needMapFlag = true; + break; + } + } + if (needMapFlag) { + auto it = NEW_AND_OLD_STATE_MAPPING.find(static_cast(state)); + if (it != NEW_AND_OLD_STATE_MAPPING.end()) { + return static_cast(it->second); + } + } + return state; +} + +int32_t DmAuthState::GetOutputReplay(const std::string &processName, int32_t replay) +{ + LOGI("replay %{public}d.", replay); + bool needMapFlag = false; + for (uint16_t index = 0; index < ONBINDRESULT_MAPPING_NUM; ++index) { + if (std::string(ONBINDRESULT_MAPPING_LIST[index]) == processName) { + LOGI("processName %{public}s new protocol param convert to old protocol param.", processName.c_str()); + needMapFlag = true; + break; + } + } + if (needMapFlag) { + auto it = NEW_AND_OLD_REPLAY_MAPPING.find(replay); + if (it != NEW_AND_OLD_REPLAY_MAPPING.end()) { + return static_cast(it->second); + } + } + return replay; +} + +uint64_t DmAuthState::GetSysTimeMs() +{ + struct timeval time; + time.tv_sec = 0; + time.tv_usec = 0; + if (gettimeofday(&time, nullptr) != 0) { + LOGE("GetSysTimeMs failed."); + return 0; + } + return (uint64_t) time.tv_sec * MS_PER_SECOND + (uint64_t)time.tv_usec / US_PER_MSECOND; +} + +void DmAuthState::DeleteAcl(std::shared_ptr context, + const DistributedDeviceProfile::AccessControlProfile &profile) +{ + CHECK_NULL_VOID(context); + LOGI("direction %{public}d.", static_cast(context->direction)); + CHECK_NULL_VOID(context->authMessageProcessor); + CHECK_NULL_VOID(context->hiChainAuthConnector); + int32_t userId = context->direction == DmAuthDirection::DM_AUTH_SOURCE ? + profile.GetAccesser().GetAccesserUserId() : profile.GetAccessee().GetAccesseeUserId(); + int32_t sessionKeyId = context->direction == DmAuthDirection::DM_AUTH_SOURCE ? + profile.GetAccesser().GetAccesserSessionKeyId() : profile.GetAccessee().GetAccesseeSessionKeyId(); + std::string credId = context->direction == DmAuthDirection::DM_AUTH_SOURCE ? + profile.GetAccesser().GetAccesserCredentialIdStr() : profile.GetAccessee().GetAccesseeCredentialIdStr(); + + context->authMessageProcessor->DeleteSessionKeyToDP(userId, sessionKeyId); + context->hiChainAuthConnector->DeleteCredential(userId, credId); + DeviceProfileConnector::GetInstance().DeleteAccessControlById(profile.GetAccessControlId()); +} + +void DmAuthState::SetProcessInfo(std::shared_ptr context) +{ + CHECK_NULL_VOID(context); + DmAccess localAccess = context->direction == DmAuthDirection::DM_AUTH_SOURCE ? + context->accesser : context->accessee; + ProcessInfo processInfo; + processInfo.userId = localAccess.userId; + uint32_t bindLevel = static_cast(localAccess.bindLevel); + if (bindLevel == APP || bindLevel == SERVICE) { + processInfo.pkgName = localAccess.pkgName; + } else if (bindLevel == USER) { + processInfo.pkgName = std::string(DM_PKG_NAME); + } else { + LOGE("bindlevel error %{public}d.", bindLevel); + return; + } + context->softbusConnector->SetProcessInfo(processInfo); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 326615429..af1fa73ed 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -21,6 +21,8 @@ #include #include "app_manager.h" +#include "bundle_mgr_interface.h" +#include "bundle_mgr_proxy.h" #include "dm_error_type.h" #include "dm_anonymous.h" #include "dm_constants.h" @@ -37,6 +39,8 @@ #include "common_event_support.h" using namespace OHOS::EventFwk; #endif +#include "iservice_registry.h" +#include "system_ability_definition.h" namespace OHOS { namespace DistributedHardware { @@ -843,8 +847,6 @@ int32_t DeviceManagerServiceImpl::TransferSrcOldAuthMgr(std::shared_ptr std::map bindParam; auto authMgr = GetAuthMgrByTokenId(tokenId); authMgr->GetBindTargetParams(pkgName, peerTargetId, bindParam); - DmBindCallerInfo callerInfo; - authMgr->GetCallerInfo(callerInfo); int32_t authType = -1; authMgr->ParseAuthType(bindParam, authType); authMgrMap_.erase(tokenId); @@ -858,7 +860,6 @@ int32_t DeviceManagerServiceImpl::TransferSrcOldAuthMgr(std::shared_ptr return ret; } authMgr = nullptr; - authMgr_->SetCallerInfo(callerInfo); if (authMgr_->BindTarget(pkgName, peerTargetId, bindParam, sessionId, 0) != DM_OK) { LOGE("DeviceManagerServiceImpl::TransferSrcOldAuthMgr authManager BindTarget failed"); return ERR_DM_AUTH_FAILED; @@ -1536,14 +1537,9 @@ int32_t DeviceManagerServiceImpl::ParseConnectAddr(const PeerTargetId &targetId, return DM_OK; } -int32_t DeviceManagerServiceImpl::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, - const std::map &bindParam) +void DeviceManagerServiceImpl::BindTargetImpl(uint64_t tokenId, const std::string &pkgName, + const PeerTargetId &targetId, const std::map &bindParam) { - if (pkgName.empty()) { - LOGE("BindTarget failed, pkgName is empty."); - return ERR_DM_INPUT_PARA_INVALID; - } - std::string deviceId = ""; PeerTargetId targetIdTmp = const_cast(targetId); if (ParseConnectAddr(targetId, deviceId, bindParam) == DM_OK) { @@ -1593,7 +1589,31 @@ int32_t DeviceManagerServiceImpl::BindTarget(const std::string &pkgName, const P LOGE("authMgr BindTarget failed, ret %{public}d.", ret); CleanAuthMgrByLogicalSessionId(logicalSessionId); } - return ret; + LOGI("DeviceManagerServiceImpl BindTargetImpl thread end, tokenId %{public}" PRID64".", tokenId); + return; +} + +int32_t DeviceManagerServiceImpl::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, + const std::map &bindParam) +{ + if (pkgName.empty()) { + LOGE("BindTarget failed, pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + DmBindCallerInfo bindCallerInfo; + GetBindCallerInfo(bindCallerInfo); + std::map bindParamTmp; + SetBindCallerInfoToBindParam(bindParam, bindParamTmp, bindCallerInfo); + uint64_t tokenId = IPCSkeleton::GetCallingTokenID(); + if (authMgrMap_.find(tokenId) == authMgrMap_.end()) { + std::thread newThread(&DeviceManagerServiceImpl::BindTargetImpl, this, tokenId, pkgName, + targetId, bindParamTmp); + newThread.detach(); + } else { + LOGE("BindTarget failed, this device is being bound. please try again later."); + return ERR_DM_AUTH_BUSINESS_BUSY; + } + return DM_OK; } int32_t DeviceManagerServiceImpl::DpAclAdd(const std::string &udid) @@ -2430,6 +2450,84 @@ void DeviceManagerServiceImpl::HandleCommonEventBroadCast(const std::vector(DmRole::DM_ROLE_FA); + if (AppManager::GetInstance().IsSystemApp()) { + bindLevel = static_cast(DmRole::DM_ROLE_FA); + } + if (AppManager::GetInstance().IsSystemSA()) { + bindLevel = static_cast(DmRole::DM_ROLE_SA); + } + if (AuthManagerBase::CheckProcessNameInWhiteList(bundleName)) { + bindLevel = static_cast(DmRole::DM_ROLE_USER); + } + std::string hostPkgLabel = GetBundleLable(bundleName); + bindCallerInfo.userId = userId; + bindCallerInfo.tokenId = callingTokenId; + bindCallerInfo.bindLevel = bindLevel; + bindCallerInfo.bundleName = bundleName; + bindCallerInfo.hostPkgLabel = hostPkgLabel; + LOGI("userId %{public}d, tokenId %{public}d, bindLevel %{public}d, bundleName %{public}s, hostPkgLabel %{public}s", + userId, callingTokenId, bindLevel, GetAnonyString(bundleName).c_str(), GetAnonyString(hostPkgLabel).c_str()); +} + +std::string DeviceManagerServiceImpl::GetBundleLable(const std::string &bundleName) +{ + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgr == nullptr) { + LOGE("Get ability manager failed"); + return bundleName; + } + + sptr object = samgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (object == nullptr) { + LOGE("object is NULL."); + return bundleName; + } + + sptr bms = iface_cast(object); + if (bms == nullptr) { + LOGE("bundle manager service is NULL."); + return bundleName; + } + + auto bundleResourceProxy = bms->GetBundleResourceProxy(); + if (bundleResourceProxy == nullptr) { + LOGE("GetBundleResourceProxy fail"); + return bundleName; + } + AppExecFwk::BundleResourceInfo resourceInfo; + auto result = bundleResourceProxy->GetBundleResourceInfo(bundleName, + static_cast(OHOS::AppExecFwk::ResourceFlag::GET_RESOURCE_INFO_ALL), resourceInfo); + if (result != ERR_OK) { + LOGE("GetBundleResourceInfo failed"); + return bundleName; + } + LOGI("bundle resource label is %{public}s ", (resourceInfo.label).c_str()); + return resourceInfo.label; +} + +void DeviceManagerServiceImpl::SetBindCallerInfoToBindParam(const std::map &bindParam, + std::map &bindParamTmp, const DmBindCallerInfo &bindCallerInfo) +{ + LOGI("start."); + bindParamTmp = const_cast &>(bindParam); + bindParamTmp["bindCallerUserId"] = std::to_string(bindCallerInfo.userId); + bindParamTmp["bindCallerTokenId"] = std::to_string(bindCallerInfo.tokenId); + bindParamTmp["bindCallerBindLevel"] = std::to_string(bindCallerInfo.bindLevel); + bindParamTmp["bindCallerBundleName"] = bindCallerInfo.bundleName; + bindParamTmp["bindCallerHostPkgLabel"] = bindCallerInfo.hostPkgLabel; +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/implementation/src/device_manager_service_impl.cpp.bak b/services/implementation/src/device_manager_service_impl.cpp.bak new file mode 100644 index 000000000..326615429 --- /dev/null +++ b/services/implementation/src/device_manager_service_impl.cpp.bak @@ -0,0 +1,2438 @@ +/* + * Copyright (c) 2022-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "device_manager_service_impl.h" + +#include +#include +#include +#include + +#include "app_manager.h" +#include "dm_error_type.h" +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_crypto.h" +#include "dm_distributed_hardware_load.h" +#include "dm_log.h" +#include "dm_radar_helper.h" +#include "dm_softbus_cache.h" +#include "multiple_user_connector.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "dm_common_event_manager.h" +#include "parameter.h" +#include "dm_random.h" +#include "common_event_support.h" +using namespace OHOS::EventFwk; +#endif + +namespace OHOS { +namespace DistributedHardware { + +namespace { + +// One year 365 * 24 * 60 * 60 +constexpr int32_t MAX_ALWAYS_ALLOW_SECONDS = 31536000; +constexpr int32_t MIN_PIN_CODE = 100000; +constexpr int32_t MAX_PIN_CODE = 999999; +// New protocol field definition. To avoid dependency on the new protocol header file, +// do not directly depend on the new protocol header file. +constexpr int32_t MSG_TYPE_REQ_ACL_NEGOTIATE = 80; +constexpr int32_t MSG_TYPE_RESP_ACL_NEGOTIATE = 90; +constexpr int32_t MSG_TYPE_REQ_AUTH_TERMINATE = 104; +constexpr int32_t AUTH_SRC_FINISH_STATE = 12; +constexpr int32_t MAX_DATA_LEN = 65535; +constexpr int32_t ULTRASONIC_AUTHTYPE = 6; +constexpr const char* DM_TAG_LOGICAL_SESSION_ID = "logicalSessionId"; +constexpr const char* DM_TAG_PEER_DISPLAY_ID = "peerDisplayId"; +constexpr const char* DM_TAG_ACCESSEE_USER_ID = "accesseeUserId"; +constexpr const char* DM_TAG_EXTRA_INFO = "extraInfo"; +constexpr const char* CHANGE_PINTYPE = "1"; +// currently, we just support one bind session in one device at same time +constexpr size_t MAX_NEW_PROC_SESSION_COUNT_TEMP = 1; +const int32_t USLEEP_TIME_US_500000 = 500000; // 500ms + +const std::map BUNDLENAME_MAPPING = { + { "wear_link_service", "watch_system_service" } +}; + +static bool IsMessageOldVersion(const JsonObject &jsonObject, std::shared_ptr session) +{ + std::string dmVersion = ""; + std::string edition = ""; + if (jsonObject[TAG_DMVERSION].IsString()) { + dmVersion = jsonObject[TAG_DMVERSION].Get(); + } + if (jsonObject[TAG_EDITION].IsString()) { + edition = jsonObject[TAG_EDITION].Get(); + } + dmVersion = AuthManagerBase::ConvertSrcVersion(dmVersion, edition); + + // Assign the physical session version and release the semaphore. + session->version_ = dmVersion; + + // If the version number is higher than 5.0.4 (the highest version of the old protocol), + // there is no need to switch to the old protocol. + if (CompareVersion(dmVersion, DM_VERSION_5_0_OLD_MAX) == true) { + return false; + } + + return true; +} + +std::string CreateTerminateMessage(void) +{ + JsonObject jsonObject; + jsonObject[TAG_MSG_TYPE] = MSG_TYPE_REQ_AUTH_TERMINATE; + jsonObject[TAG_REPLY] = ERR_DM_VERSION_INCOMPATIBLE; + jsonObject[TAG_AUTH_FINISH] = false; + + return jsonObject.Dump(); +} + +} + +std::condition_variable DeviceManagerServiceImpl::cleanEventCv_; +std::mutex DeviceManagerServiceImpl::cleanEventMutex_; +std::queue DeviceManagerServiceImpl::cleanEventQueue_; + +Session::Session(int sessionId, std::string deviceId) +{ + sessionId_ = sessionId; + deviceId_ = deviceId; +} + +DeviceManagerServiceImpl::DeviceManagerServiceImpl() +{ + running_ = true; + thread_ = std::thread(&DeviceManagerServiceImpl::CleanWorker, this); + LOGI("DeviceManagerServiceImpl constructor"); +} + +DeviceManagerServiceImpl::~DeviceManagerServiceImpl() +{ + Stop(); + thread_.join(); + LOGI("DeviceManagerServiceImpl destructor"); +} + +static uint64_t StringToUint64(const std::string& str) +{ + // Calculate the length of the substring, taking the minimum of the string length and 8 + size_t subStrLength = std::min(str.length(), static_cast(8U)); + + // Extract substring + std::string substr = str.substr(str.length() - subStrLength); + + // Convert substring to uint64_t + uint64_t result = 0; + for (size_t i = 0; i < subStrLength; ++i) { + result <<= 8; // Shift left 8 bits + result |= static_cast(substr[i]); + } + + return result; +} + + +static uint64_t GetTokenId(bool isSrcSide, int32_t displayId, std::string &bundleName) +{ + uint64_t tokenId = 0; + if (isSrcSide) { + // src end + tokenId = IPCSkeleton::GetCallingTokenID(); + } else { + // sink end + int64_t tmpTokenId; + // get userId + int32_t targetUserId = AuthManagerBase::DmGetUserId(displayId); + if (targetUserId == -1) { + return tokenId; + } + if (AppManager::GetInstance().GetHapTokenIdByName(targetUserId, bundleName, 0, tmpTokenId) == DM_OK) { + tokenId = static_cast(tmpTokenId); + } else if (AppManager::GetInstance().GetNativeTokenIdByName(bundleName, tmpTokenId) == DM_OK) { + tokenId = static_cast(tmpTokenId); + } else { + // get deviceId, take the 8 character value as tokenId + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string deviceId = std::string(localDeviceId); + if (deviceId.length() != 0) { + tokenId = StringToUint64(deviceId); + } + } + } + return tokenId; +} + +uint64_t DeviceManagerServiceImpl::FetchCleanEvent() +{ + std::unique_lock lock(cleanEventMutex_); + cleanEventCv_.wait(lock, [&] { + return !running_.load() || !cleanEventQueue_.empty(); + }); + + if (!running_.load()) return 0; + + uint64_t logicalSessionId = cleanEventQueue_.front(); + cleanEventQueue_.pop(); + return logicalSessionId; +} + +void DeviceManagerServiceImpl::CleanWorker() +{ + while (running_.load()) { + auto logicalSessionId = FetchCleanEvent(); + LOGI("DeviceManagerServiceImpl::CleanWorker clean auth_mgr, its logicalSessionId: %{public}" PRIu64 "", + logicalSessionId); + CleanAuthMgrByLogicalSessionId(logicalSessionId); + } + while (!cleanEventQueue_.empty()) { + uint64_t logicalSessionId = cleanEventQueue_.front(); + cleanEventQueue_.pop(); + CleanAuthMgrByLogicalSessionId(logicalSessionId); + } + LOGI("DeviceManagerServiceImpl::CleanWorker end"); +} + +void DeviceManagerServiceImpl::Stop() +{ + std::lock_guard lock(cleanEventMutex_); + running_.store(false); + cleanEventCv_.notify_all(); +} + +void DeviceManagerServiceImpl::NotifyCleanEvent(uint64_t logicalSessionId) +{ + LOGI("DeviceManagerServiceImpl::NotifyCleanEvent logicalSessionId: %{public}" PRIu64 ".", logicalSessionId); + std::lock_guard lock(cleanEventMutex_); + // Store into the queue + cleanEventQueue_.push(logicalSessionId); + cleanEventCv_.notify_one(); +} + +void DeviceManagerServiceImpl::ImportConfig(std::shared_ptr authMgr, uint64_t tokenId) +{ + // Import configuration + if (configsMap_.find(tokenId) != configsMap_.end()) { + authMgr->ImportAuthCode(configsMap_[tokenId]->pkgName, configsMap_[tokenId]->authCode); + authMgr->RegisterAuthenticationType(configsMap_[tokenId]->authenticationType); + LOGI("DeviceManagerServiceImpl::ImportConfig import authCode Successful."); + } + return; +} + +int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide, uint64_t tokenId, + std::shared_ptr session, uint64_t logicalSessionId) +{ + if (session == nullptr) { + LOGE("InitAndRegisterAuthMgr, The physical link is not created."); + return ERR_DM_AUTH_OPEN_SESSION_FAILED; + } + // If version is empty, allow creation for the first time, create a new protocol auth_mgr to negotiate version; + // subsequent creations wait, and directly use version to create the corresponding auth_mgr after release. + if (session->version_ == "") { + bool expected = false; + if (session->flag_.compare_exchange_strong(expected, true)) { + LOGI("The physical link is being created and the dual-end device version is aligned."); + } else { + // Do not allow simultaneous version negotiation, return error directly + LOGE("Version negotiation is not allowed at the same time."); + return ERR_DM_AUTH_BUSINESS_BUSY; + } + } + + std::lock_guard lock(authMgrMtx_); + if (authMgrMap_.find(tokenId) == authMgrMap_.end()) { + if (session->version_ == "" || CompareVersion(session->version_, DM_VERSION_5_0_OLD_MAX)) { + if (authMgrMap_.size() > MAX_NEW_PROC_SESSION_COUNT_TEMP) { + LOGE("Other bind session exist, can not start new one."); + return ERR_DM_AUTH_BUSINESS_BUSY; + } + // Create a new auth_mgr, create authMgrMap_[tokenId] + if (isSrcSide) { + // src end + authMgrMap_[tokenId] = std::make_shared(softbusConnector_, hiChainConnector_, + listener_, hiChainAuthConnector_); + } else { + // sink end + authMgrMap_[tokenId] = std::make_shared(softbusConnector_, hiChainConnector_, + listener_, hiChainAuthConnector_); + } + // Register resource destruction notification function + authMgrMap_[tokenId]->RegisterCleanNotifyCallback(&DeviceManagerServiceImpl::NotifyCleanEvent); + hiChainAuthConnector_->RegisterHiChainAuthCallbackById(logicalSessionId, authMgrMap_[tokenId]); + LOGI("DeviceManagerServiceImpl::Initialize authMgrMap_ token: %{public}" PRId64 ".", tokenId); + ImportConfig(authMgrMap_[tokenId], tokenId); + return DM_OK; + } else { + LOGI("DeviceManagerServiceImpl::InitAndRegisterAuthMgr old authMgr."); + if (authMgr_ == nullptr) { + CreateGlobalClassicalAuthMgr(); + } + authMgr_->PrepareSoftbusSessionCallback(); + authMgrMap_[tokenId] = authMgr_; + ImportConfig(authMgr_, tokenId); + // The value of logicalSessionId in the old protocol is always 0. + logicalSessionId2TokenIdMap_[0] = tokenId; + return DM_OK; + } + } + // authMgr_ has been created, indicating that a binding event already exists. + // Other requests are rejected, and an error code is returned. + LOGE("BindTarget failed, this device is being bound. Please try again later."); + return ERR_DM_AUTH_BUSINESS_BUSY; +} + +void DeviceManagerServiceImpl::CleanSessionMap(int sessionId, std::shared_ptr session) +{ + session->logicalSessionCnt_.fetch_sub(1); + if (session->logicalSessionCnt_.load(std::memory_order_relaxed) == 0) { + usleep(USLEEP_TIME_US_500000); + softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId); + std::lock_guard lock(mapMutex_); + if (sessionsMap_.find(sessionId) != sessionsMap_.end()) { + sessionsMap_[sessionId] = nullptr; + sessionsMap_.erase(sessionId); + } + if (deviceId2SessionIdMap_.find(session->deviceId_) != deviceId2SessionIdMap_.end()) { + deviceId2SessionIdMap_.erase(session->deviceId_); + } + } + return; +} + +void DeviceManagerServiceImpl::CleanSessionMapByLogicalSessionId(uint64_t logicalSessionId) +{ + if (logicalSessionId2SessionIdMap_.find(logicalSessionId) != logicalSessionId2SessionIdMap_.end()) { + auto sessionId = logicalSessionId2SessionIdMap_[logicalSessionId]; + auto session = GetCurSession(sessionId); + if (session != nullptr) { + CleanSessionMap(sessionId, session); + } + logicalSessionId2SessionIdMap_.erase(logicalSessionId); + } + logicalSessionId2TokenIdMap_.erase(logicalSessionId); + return; +} + +void DeviceManagerServiceImpl::CleanAuthMgrByLogicalSessionId(uint64_t logicalSessionId) +{ + uint64_t tokenId = 0; + if (logicalSessionId2TokenIdMap_.find(logicalSessionId) != logicalSessionId2TokenIdMap_.end()) { + tokenId = logicalSessionId2TokenIdMap_[logicalSessionId]; + } else { + LOGE("logicalSessionId(%{public}" PRIu64 ") can not find the tokenId.", logicalSessionId); + return; + } + + if (configsMap_.find(tokenId) != configsMap_.end()) { + configsMap_[tokenId] = nullptr; + configsMap_.erase(tokenId); + } + + CleanSessionMapByLogicalSessionId(logicalSessionId); + if (logicalSessionId == 0 && authMgr_ != nullptr) { + authMgr_->SetTransferReady(true); + authMgr_->ClearSoftbusSessionCallback(); + } + hiChainAuthConnector_->UnRegisterHiChainAuthCallbackById(logicalSessionId); + if (authMgrMap_.find(tokenId) != authMgrMap_.end()) { + authMgrMap_[tokenId] = nullptr; + authMgrMap_.erase(tokenId); + } + return; +} + +std::shared_ptr DeviceManagerServiceImpl::GetAuthMgr() +{ + uint64_t tokenId = IPCSkeleton::GetCallingTokenID(); + if (authMgrMap_.find(tokenId) != authMgrMap_.end()) { + LOGI("DeviceManagerServiceImpl::GetAuthMgr authMgrMap_ token: %{public}" PRId64 ".", tokenId); + return authMgrMap_[tokenId]; + } + LOGE("DeviceManagerServiceImpl::GetAuthMgr authMgrMap_ not found, token: %{public}" PRId64 ".", tokenId); + return nullptr; +} + +// Needed in the callback function +std::shared_ptr DeviceManagerServiceImpl::GetAuthMgrByTokenId(uint64_t tokenId) +{ + if (authMgrMap_.find(tokenId) != authMgrMap_.end()) { + LOGI("DeviceManagerServiceImpl::GetAuthMgrByTokenId authMgrMap_ token: %{public}" PRId64 ".", tokenId); + return authMgrMap_[tokenId]; + } + LOGE("DeviceManagerServiceImpl::GetAuthMgrByTokenId authMgrMap_ not found, token: %{public}" PRId64 ".", tokenId); + return nullptr; +} + +std::shared_ptr DeviceManagerServiceImpl::GetCurrentAuthMgr() +{ + uint64_t tokenId = 0; + if (logicalSessionId2TokenIdMap_.find(0) != logicalSessionId2TokenIdMap_.end()) { + tokenId = logicalSessionId2TokenIdMap_[0]; + } + for (auto &pair : authMgrMap_) { + if (pair.first != tokenId) { + return pair.second; + } + } + return authMgr_; +} + +static uint64_t GenerateRandNum(int sessionId) +{ + // Get the current timestamp + auto timestamp = std::chrono::duration_cast(std::chrono::high_resolution_clock::now(). + time_since_epoch()).count(); + + // Generate random numbers + std::random_device rd; + std::mt19937 gen(rd()); + std::uniform_int_distribution<> rand_dis(1, 0xFFFFFFFF); + uint32_t randomNumber = rand_dis(gen); + + // Combination of random numbers + uint64_t randNum = (static_cast(timestamp) << 32) | + (static_cast(sessionId) << 16) | + static_cast(randomNumber); + + return randNum; +} + +int32_t DeviceManagerServiceImpl::Initialize(const std::shared_ptr &listener) +{ + LOGI("DeviceManagerServiceImpl Initialize"); + if (softbusConnector_ == nullptr) { + softbusConnector_ = std::make_shared(); + } + if (hiChainConnector_ == nullptr) { + hiChainConnector_ = std::make_shared(); + } + if (mineHiChainConnector_ == nullptr) { + mineHiChainConnector_ = std::make_shared(); + } + if (hiChainAuthConnector_ == nullptr) { + hiChainAuthConnector_ = std::make_shared(); + } + if (deviceStateMgr_ == nullptr) { + deviceStateMgr_ = std::make_shared(softbusConnector_, listener, + hiChainConnector_, hiChainAuthConnector_); + deviceStateMgr_->RegisterSoftbusStateCallback(); + } + if (credentialMgr_ == nullptr) { + credentialMgr_ = std::make_shared(hiChainConnector_, listener); + } + if (dpInitedCallback_ == nullptr) { + dpInitedCallback_ = sptr(new DpInitedCallback()); + DeviceProfileConnector::GetInstance().SubscribeDeviceProfileInited(dpInitedCallback_); + } + listener_ = listener; + CreateGlobalClassicalAuthMgr(); + if (authMgr_ != nullptr) { + authMgr_->ClearSoftbusSessionCallback(); + } + LOGI("Init success, singleton initialized"); + return DM_OK; +} + +void DeviceManagerServiceImpl::Release() +{ + LOGI("DeviceManagerServiceImpl Release"); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + commonEventManager_ = nullptr; +#endif + softbusConnector_->UnRegisterConnectorCallback(); + softbusConnector_->UnRegisterSoftbusStateCallback(); + softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback(); + hiChainConnector_->UnRegisterHiChainCallback(); + hiChainAuthConnector_->UnRegisterHiChainAuthCallback(); + authMgr_ = nullptr; + for (auto& pair : authMgrMap_) { + pair.second = nullptr; + } + authMgrMap_.clear(); + for (auto& pair : sessionsMap_) { + pair.second = nullptr; + } + sessionsMap_.clear(); + for (auto& pair : configsMap_) { + pair.second = nullptr; + } + configsMap_.clear(); + deviceId2SessionIdMap_.clear(); + deviceIdMutexMap_.clear(); + sessionEnableMutexMap_.clear(); + sessionEnableCvMap_.clear(); + logicalSessionId2TokenIdMap_.clear(); + logicalSessionId2SessionIdMap_.clear(); + deviceStateMgr_ = nullptr; + softbusConnector_ = nullptr; + abilityMgr_ = nullptr; + hiChainConnector_ = nullptr; + DeviceProfileConnector::GetInstance().UnSubscribeDeviceProfileInited(); + dpInitedCallback_ = nullptr; +} + +int32_t DeviceManagerServiceImpl::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel) +{ + if (pkgName.empty() || udid.empty()) { + LOGE("DeviceManagerServiceImpl::UnAuthenticateDevice failed, pkgName is %{public}s, udid is %{public}s", + pkgName.c_str(), GetAnonyString(udid).c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + LOGE("authMgr is nullptr, invoke the old protocal."); + if (authMgr_ == nullptr) { + LOGE("classical authMgr_ is nullptr"); + return ERR_DM_POINT_NULL; + } + return authMgr_->UnAuthenticateDevice(pkgName, udid, bindLevel); + } + return authMgr->UnAuthenticateDevice(pkgName, udid, bindLevel); +} + +int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("DeviceManagerServiceImpl::StopAuthenticateDevice failed"); + return ERR_DM_INPUT_PARA_INVALID; + } + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + LOGE("authMgr is nullptr"); + return ERR_DM_POINT_NULL; + } + return authMgr->StopAuthenticateDevice(pkgName); +} + +int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel) +{ + if (pkgName.empty() || udid.empty()) { + LOGE("DeviceManagerServiceImpl::UnBindDevice failed, pkgName is %{public}s, udid is %{public}s", + pkgName.c_str(), GetAnonyString(udid).c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + std::string extra = ""; + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + return DeleteAclV2(pkgName, std::string(localDeviceId), udid, bindLevel, extra); +} + +int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel, const std::string &extra) +{ + if (pkgName.empty() || udid.empty()) { + LOGE("DeviceManagerServiceImpl::UnBindDevice failed, pkgName is %{public}s, udid is %{public}s", + pkgName.c_str(), GetAnonyString(udid).c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + return DeleteAclV2(pkgName, std::string(localDeviceId), udid, bindLevel, extra); +} + +int32_t DeviceManagerServiceImpl::SetUserOperation(std::string &pkgName, int32_t action, + const std::string ¶ms) +{ + if (pkgName.empty() || params.empty()) { + LOGE("DeviceManagerServiceImpl::SetUserOperation error: Invalid parameter, pkgName: %{public}s, extra:" + "%{public}s", pkgName.c_str(), params.c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + auto authMgr = GetCurrentAuthMgr(); + if (authMgr != nullptr) { + authMgr->OnUserOperation(action, params); + } + return DM_OK; +} + +void DeviceManagerServiceImpl::CreateGlobalClassicalAuthMgr() +{ + LOGI("global classical authMgr_ not exit, create one"); + // Create old auth_mar, only create an independent one + authMgr_ = std::make_shared(softbusConnector_, hiChainConnector_, listener_, + hiChainAuthConnector_); + authMgr_->RegisterCleanNotifyCallback(&DeviceManagerServiceImpl::NotifyCleanEvent); + softbusConnector_->RegisterConnectorCallback(authMgr_); + softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); + hiChainConnector_->RegisterHiChainCallback(authMgr_); + hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_); +} + +void DeviceManagerServiceImpl::HandleOffline(DmDeviceState devState, DmDeviceInfo &devInfo) +{ + LOGI("DeviceManagerServiceImpl::HandleOffline"); + std::string trustDeviceId = deviceStateMgr_->GetUdidByNetWorkId(std::string(devInfo.networkId)); + LOGI("deviceStateMgr Udid: %{public}s", GetAnonyString(trustDeviceId).c_str()); + if (trustDeviceId == "") { + LOGE("HandleOffline not get udid in deviceStateMgr."); + return; + } + std::string udisHash = softbusConnector_->GetDeviceUdidHashByUdid(trustDeviceId); + if (memcpy_s(devInfo.deviceId, DM_MAX_DEVICE_ID_LEN, udisHash.c_str(), udisHash.length()) != 0) { + LOGE("get deviceId: %{public}s failed", GetAnonyString(udisHash).c_str()); + return; + } + char localUdid[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdid, DEVICE_UUID_LENGTH); + std::string requestDeviceId = std::string(localUdid); + std::map userIdAndBindLevel = + DeviceProfileConnector::GetInstance().GetUserIdAndBindLevel(requestDeviceId, trustDeviceId); + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); + if (userIdAndBindLevel.empty() || userIdAndBindLevel.find(processInfo.userId) == userIdAndBindLevel.end()) { + userIdAndBindLevel[processInfo.userId] = INVALIED_TYPE; + } + for (const auto &item : userIdAndBindLevel) { + if (static_cast(item.second) == INVALIED_TYPE) { + LOGI("The offline device is identical account bind type."); + devInfo.authForm = DmAuthForm::IDENTICAL_ACCOUNT; + processInfo.userId = item.first; + softbusConnector_->SetProcessInfo(processInfo); + } else if (static_cast(item.second) == USER) { + LOGI("The offline device is device bind type."); + devInfo.authForm = DmAuthForm::PEER_TO_PEER; + processInfo.userId = item.first; + softbusConnector_->SetProcessInfo(processInfo); + } else if (static_cast(item.second) == SERVICE || static_cast(item.second) == APP) { + LOGI("The offline device is PEER_TO_PEER_TYPE bind type, %{public}" PRIu32, item.second); + std::vector processInfoVec = + DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, + item.first); + softbusConnector_->SetProcessInfoVec(processInfoVec); + } + deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); + } +} + +void DeviceManagerServiceImpl::HandleOnline(DmDeviceState devState, DmDeviceInfo &devInfo) +{ + LOGI("DeviceManagerServiceImpl::HandleOnline networkId: %{public}s.", + GetAnonyString(devInfo.networkId).c_str()); + std::string trustDeviceId = ""; + if (softbusConnector_->GetUdidByNetworkId(devInfo.networkId, trustDeviceId) != DM_OK) { + LOGE("HandleOnline get udid failed."); + return; + } + std::string udisHash = softbusConnector_->GetDeviceUdidHashByUdid(trustDeviceId); + if (memcpy_s(devInfo.deviceId, DM_MAX_DEVICE_ID_LEN, udisHash.c_str(), udisHash.length()) != 0) { + LOGE("get deviceId: %{public}s failed", GetAnonyString(udisHash).c_str()); + return; + } + char localUdid[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdid, DEVICE_UUID_LENGTH); + std::string requestDeviceId = std::string(localUdid); + uint32_t bindType = DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); + LOGI("The online device bind type is %{public}" PRIu32, bindType); + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); + 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 || bindType == SERVICE_PEER_TO_PEER_TYPE) { + std::vector processInfoVec = + DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, + MultipleUserConnector::GetFirstForegroundUserId()); + softbusConnector_->SetProcessInfoVec(processInfoVec); + devInfo.authForm = DmAuthForm::PEER_TO_PEER; + } else if (bindType == APP_ACROSS_ACCOUNT_TYPE || bindType == SERVICE_ACROSS_ACCOUNT_TYPE) { + std::vector processInfoVec = + DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, + MultipleUserConnector::GetFirstForegroundUserId()); + softbusConnector_->SetProcessInfoVec(processInfoVec); + devInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; + } + LOGI("DeviceManagerServiceImpl::HandleOnline success devInfo auform %{public}d.", devInfo.authForm); + deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); +} + +void DeviceManagerServiceImpl::HandleDeviceStatusChange(DmDeviceState devState, DmDeviceInfo &devInfo) +{ + LOGI("DeviceManagerServiceImpl::HandleDeviceStatusChange start, devState = %{public}d, networkId: %{public}s.", + devState, GetAnonyString(devInfo.networkId).c_str()); + if (deviceStateMgr_ == nullptr) { + LOGE("deviceStateMgr_ is nullpter!"); + return; + } + if (devState == DEVICE_STATE_ONLINE) { + HandleOnline(devState, devInfo); + } else if (devState == DEVICE_STATE_OFFLINE) { + HandleOffline(devState, devInfo); + } else { + std::string udiddHash = GetUdidHashByNetworkId(devInfo.networkId); + if (memcpy_s(devInfo.deviceId, DM_MAX_DEVICE_ID_LEN, udiddHash.c_str(), udiddHash.length()) != 0) { + LOGE("get deviceId: %{public}s failed", GetAnonyString(udiddHash).c_str()); + return; + } + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); + softbusConnector_->SetProcessInfo(processInfo); + deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); + } +} + +std::string DeviceManagerServiceImpl::GetUdidHashByNetworkId(const std::string &networkId) +{ + if (softbusConnector_ == nullptr) { + LOGE("softbusConnector_ is nullpter!"); + return ""; + } + std::string udid = ""; + int32_t ret = softbusConnector_->GetUdidByNetworkId(networkId.c_str(), udid); + if (ret != DM_OK) { + LOGE("GetUdidByNetworkId failed ret: %{public}d", ret); + return ""; + } + return softbusConnector_->GetDeviceUdidHashByUdid(udid); +} + +int DeviceManagerServiceImpl::OnSessionOpened(int sessionId, int result) +{ + { + std::lock_guard lock(sessionEnableMutexMap_[sessionId]); + if (result == 0) { + LOGE("OnSessionOpened successful, sessionId: %{public}d", sessionId); + } else { + LOGE("OnSessionOpened failed, sessionId: %{public}d, res: %{public}d", sessionId, result); + } + sessionEnableCvReadyMap_[sessionId] = true; + sessionEnableCvMap_[sessionId].notify_all(); + } + std::string peerUdid = ""; + softbusConnector_->GetSoftbusSession()->GetPeerDeviceId(sessionId, peerUdid); + struct RadarInfo info = { + .funcName = "OnSessionOpened", + .stageRes = static_cast(StageRes::STAGE_SUCC), + .isTrust = static_cast(TrustStatus::NOT_TRUST), + .peerUdid = peerUdid, + .channelId = sessionId, + }; + if (!DmRadarHelper::GetInstance().ReportAuthSessionOpenCb(info)) { + LOGE("ReportAuthSessionOpenCb failed"); + } + + // Get the remote deviceId, sink end gives sessionsMap[deviceId] = session; + { + std::lock_guard lock(mapMutex_); + if (sessionsMap_.find(sessionId) == sessionsMap_.end()) { + sessionsMap_[sessionId] = std::make_shared(sessionId, peerUdid); + } + } + + return SoftbusSession::OnSessionOpened(sessionId, result); +} + +void DeviceManagerServiceImpl::OnSessionClosed(int sessionId) +{ + SoftbusSession::OnSessionClosed(sessionId); +} + +static JsonObject GetJsonObjectFromData(const void *data, unsigned int dataLen) +{ + std::string message = std::string(reinterpret_cast(data), dataLen); + return JsonObject(message); +} + +// When downgrading the version, determine whether it is src or sink based on the message. +// src: Received 90 message. +// sink: Received 80 message. +static bool IsAuthManagerSourceByMessage(int32_t msgType) +{ + return msgType == MSG_TYPE_RESP_ACL_NEGOTIATE; +} + +// Get the current session object +std::shared_ptr DeviceManagerServiceImpl::GetCurSession(int sessionId) +{ + std::shared_ptr curSession = nullptr; + // Get the remote deviceId, sink end gives sessionsMap[deviceId] = session; + { + std::lock_guard lock(mapMutex_); + if (sessionsMap_.find(sessionId) != sessionsMap_.end()) { + curSession = sessionsMap_[sessionId]; + } else { + LOGE("OnBytesReceived, The local session cannot be found."); + } + } + return curSession; +} + +std::shared_ptr DeviceManagerServiceImpl::GetAuthMgrByMessage(int32_t msgType, + uint64_t logicalSessionId, const JsonObject &jsonObject, std::shared_ptr curSession) +{ + uint64_t tokenId = 0; + if (msgType == MSG_TYPE_REQ_ACL_NEGOTIATE) { + std::string bundleName; + int32_t displayId = 0; + if (jsonObject[TAG_PEER_BUNDLE_NAME_V2].IsString()) { + bundleName = jsonObject[TAG_PEER_BUNDLE_NAME_V2].Get(); + } + if (jsonObject[DM_TAG_PEER_DISPLAY_ID].IsNumberInteger()) { + displayId = jsonObject[DM_TAG_PEER_DISPLAY_ID].Get(); + } + tokenId = GetTokenId(false, displayId, bundleName); + if (tokenId == 0) { + LOGE("GetAuthMgrByMessage, Get tokenId failed."); + return nullptr; + } + if (InitAndRegisterAuthMgr(false, tokenId, curSession, logicalSessionId) != DM_OK) { + return nullptr; + } + curSession->logicalSessionSet_.insert(logicalSessionId); + if (logicalSessionId2TokenIdMap_.find(logicalSessionId) != logicalSessionId2TokenIdMap_.end()) { + LOGE("GetAuthMgrByMessage, logicalSessionId exists in logicalSessionId2TokenIdMap_."); + return nullptr; + } + logicalSessionId2TokenIdMap_[logicalSessionId] = tokenId; + } else { + if (curSession->logicalSessionSet_.find(logicalSessionId) == curSession->logicalSessionSet_.end()) { + LOGE("GetAuthMgrByMessage, The logical session ID does not exist in the physical session."); + return nullptr; + } + tokenId = logicalSessionId2TokenIdMap_[logicalSessionId]; + } + + return GetAuthMgrByTokenId(tokenId); +} + +int32_t DeviceManagerServiceImpl::TransferSrcOldAuthMgr(std::shared_ptr curSession) +{ + // New Old Receive 90, destroy new authMgr, create old authMgr, source side + // The old protocol has only one session, reverse lookup logicalSessionId and tokenId + int sessionId = curSession->sessionId_; + uint64_t logicalSessionId = 0; + uint64_t tokenId = 0; + for (auto& pair : logicalSessionId2SessionIdMap_) { + if (pair.second == sessionId) { + logicalSessionId = pair.first; + tokenId = logicalSessionId2TokenIdMap_[logicalSessionId]; + } + } + if (logicalSessionId == 0 || tokenId == 0) { + LOGE("DeviceManagerServiceImpl::TransferSrcOldAuthMgr can not find logicalSessionId and tokenId."); + return ERR_DM_AUTH_FAILED; + } + std::string pkgName; + PeerTargetId peerTargetId; + std::map bindParam; + auto authMgr = GetAuthMgrByTokenId(tokenId); + authMgr->GetBindTargetParams(pkgName, peerTargetId, bindParam); + DmBindCallerInfo callerInfo; + authMgr->GetCallerInfo(callerInfo); + int32_t authType = -1; + authMgr->ParseAuthType(bindParam, authType); + authMgrMap_.erase(tokenId); + if (InitAndRegisterAuthMgr(true, tokenId, curSession, logicalSessionId) != DM_OK) { + return ERR_DM_AUTH_FAILED; + } + + int ret = TransferByAuthType(authType, curSession, authMgr, bindParam, logicalSessionId); + if (ret != DM_OK) { + LOGE("DeviceManagerServiceImpl::TransferByAuthType TransferByAuthType failed."); + return ret; + } + authMgr = nullptr; + authMgr_->SetCallerInfo(callerInfo); + if (authMgr_->BindTarget(pkgName, peerTargetId, bindParam, sessionId, 0) != DM_OK) { + LOGE("DeviceManagerServiceImpl::TransferSrcOldAuthMgr authManager BindTarget failed"); + return ERR_DM_AUTH_FAILED; + } + + if (authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + int32_t sessionSide = GetSessionSide(curSession->sessionId_); + authMgr_->OnSessionOpened(curSession->sessionId_, sessionSide, 0); + } + + LOGI("DeviceManagerServiceImpl::TransferSrcOldAuthMgr src transfer to old version success"); + authMgr_->SetTransferReady(false); + return DM_OK; +} + +int32_t DeviceManagerServiceImpl::TransferByAuthType(int32_t authType, + std::shared_ptr curSession, std::shared_ptr authMgr, + std::map &bindParam, uint64_t logicalSessionId) +{ + int sessionId = curSession->sessionId_; + if (authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + authMgr_->EnableInsensibleSwitching(); + curSession->logicalSessionSet_.insert(0); + curSession->logicalSessionCnt_.fetch_add(1); + logicalSessionId2SessionIdMap_[0] = sessionId; + authMgr->OnSessionDisable(); + } else { + authMgr_->DisableInsensibleSwitching(); + // send stop message + // Cannot stop using the new protocol. The new protocol is a signal mechanism and cannot be stopped serially. + // There will be a delay, causing new objects to be created before the stop is complete. + // Then the timeout mechanism of the new protocol will stop SoftBus again. + std::string endMessage = CreateTerminateMessage(); + (void)softbusConnector_->GetSoftbusSession()->SendData(sessionId, endMessage); + // Close new protocol session + CleanAuthMgrByLogicalSessionId(logicalSessionId); + } + if (authType == ULTRASONIC_AUTHTYPE) { + int32_t ret = ChangeUltrasonicTypeToPin(bindParam); + if (ret != DM_OK) { + LOGE("DeviceManagerServiceImpl::TransferSrcOldAuthMgr ChangeUltrasonicTypeToPin failed."); + return ret; + } + } + return DM_OK; +} + +int32_t DeviceManagerServiceImpl::ChangeUltrasonicTypeToPin(std::map &bindParam) +{ + auto iter = bindParam.find(PARAM_KEY_AUTH_TYPE); + if (iter == bindParam.end()) { + LOGE("DeviceManagerServiceImpl::ChangeUltrasonicTypeToPin bindParam:%{public}s not exist.", + PARAM_KEY_AUTH_TYPE); + return ERR_DM_AUTH_FAILED; + } + iter->second = CHANGE_PINTYPE; + LOGI("DeviceManagerServiceImpl::ChangeUltrasonicTypeToPin bindParam:%{public}s PINTYPE.", PARAM_KEY_AUTH_TYPE); + return DM_OK; +} + +int32_t DeviceManagerServiceImpl::TransferSinkOldAuthMgr(const JsonObject &jsonObject, + std::shared_ptr curSession) +{ + // Old New Received 80, New Old authMgr, Sink End + std::string bundleName; + if (jsonObject[TAG_BUNDLE_NAME].IsString()) { + bundleName = jsonObject[TAG_BUNDLE_NAME].Get(); + } else if (jsonObject[TAG_PEER_BUNDLE_NAME].IsString()) { + bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get(); + } else if (jsonObject[TAG_HOST_PKGLABEL].IsString()) { + bundleName = jsonObject[TAG_HOST_PKGLABEL].Get(); + } else { + LOGE("DeviceManagerServiceImpl::TransferSinkOldAuthMgr can not find bundleName."); + return ERR_DM_AUTH_FAILED; + } + if (softbusConnector_ == nullptr) { + LOGE("softbusConnector_ is nullpter!"); + return ERR_DM_AUTH_FAILED; + } + int32_t deviceType = softbusConnector_->GetLocalDeviceTypeId(); + if (deviceType == DmDeviceType::DEVICE_TYPE_WATCH && + BUNDLENAME_MAPPING.find(bundleName) != BUNDLENAME_MAPPING.end()) { + bundleName = BUNDLENAME_MAPPING.find(bundleName)->second; + } + uint64_t tokenId = GetTokenId(false, -1, bundleName); + if (InitAndRegisterAuthMgr(false, tokenId, curSession, 0) != DM_OK) { + // Internal error log printing completed + return ERR_DM_AUTH_FAILED; + } + + // Parameter 2 sessionSide is 0, authMgr_ is empty, it must be the sink end. + // The src end will create the protocol object when BindTarget. + authMgr_->OnSessionOpened(curSession->sessionId_, 0, 0); + LOGI("DeviceManagerServiceImpl::TransferSinkOldAuthMgr sink transfer to old version success"); + authMgr_->SetTransferReady(false); + return DM_OK; +} + +int32_t DeviceManagerServiceImpl::TransferOldAuthMgr(int32_t msgType, const JsonObject &jsonObject, + std::shared_ptr curSession) +{ + int ret = DM_OK; + if ((authMgr_ == nullptr || authMgr_->IsTransferReady()) && + (msgType == MSG_TYPE_REQ_ACL_NEGOTIATE || msgType == MSG_TYPE_RESP_ACL_NEGOTIATE)) { + if (IsMessageOldVersion(jsonObject, curSession)) { + if (IsAuthManagerSourceByMessage(msgType)) { + ret = TransferSrcOldAuthMgr(curSession); + } else { + ret = TransferSinkOldAuthMgr(jsonObject, curSession); + } + } + } + + return ret; +} + + +void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, unsigned int dataLen) +{ + if (sessionId < 0 || data == nullptr || dataLen <= 0 || dataLen > MAX_DATA_LEN) { + LOGE("[OnBytesReceived] Fail to receive data from softbus with sessionId: %{public}d, dataLen: %{public}d.", + sessionId, dataLen); + return; + } + + LOGI("start, sessionId: %{public}d, dataLen: %{public}d.", sessionId, dataLen); + + JsonObject jsonObject = GetJsonObjectFromData(data, dataLen); + if (jsonObject.IsDiscarded() || !IsInt32(jsonObject, TAG_MSG_TYPE)) { + LOGE("OnBytesReceived, MSG_TYPE parse failed."); + return; + } + int32_t msgType = jsonObject[TAG_MSG_TYPE].Get(); + uint64_t logicalSessionId = 0; + if (IsUint64(jsonObject, DM_TAG_LOGICAL_SESSION_ID)) { + logicalSessionId = jsonObject[DM_TAG_LOGICAL_SESSION_ID].Get(); + } + + std::shared_ptr curSession = GetCurSession(sessionId); + if (curSession == nullptr) { + LOGE("InitAndRegisterAuthMgr, The physical link is not created."); + return; + } + + std::shared_ptr authMgr = nullptr; + if (logicalSessionId != 0) { + authMgr = GetAuthMgrByMessage(msgType, logicalSessionId, jsonObject, curSession); + if (authMgr == nullptr) { + return; + } + if (msgType == MSG_TYPE_REQ_ACL_NEGOTIATE || msgType == MSG_TYPE_RESP_ACL_NEGOTIATE) { + curSession->version_ = DM_CURRENT_VERSION; + } + } else { + /** +        Monitor old messages on ports 80/90 +        1. New-to-old: When the src side receives a 90 message and detects a version mismatch, it receives + the 90 message, destroys the current new authMgr, creates a new old protocol authMgr, and re-BindTarget. +        2. Old-to-new: When the sink side receives an 80 message and detects a version mismatch, it receives the 80 + message, directly creates a new old protocol authMgr, and re-OnSessionOpened and OnBytesReceived. +        */ + if (curSession->version_ == "") { + if (TransferOldAuthMgr(msgType, jsonObject, curSession) != DM_OK) { + LOGE("DeviceManagerServiceImpl::OnBytesReceived TransferOldAuthMgr failed"); + return; + } + } else { + LOGI("DeviceManagerServiceImpl::OnBytesReceived Reuse Old AuthMgr, sessionId: %{public}d.", sessionId); + } + authMgr = authMgr_; + } + + std::string message = std::string(reinterpret_cast(data), dataLen); + if (msgType == AUTH_DEVICE_REQ_NEGOTIATE || msgType == AUTH_DEVICE_RESP_NEGOTIATE) { + authMgr->OnAuthDeviceDataReceived(sessionId, message); + } else { + authMgr->OnDataReceived(sessionId, message); + } + return; +} + +int32_t DeviceManagerServiceImpl::RequestCredential(const std::string &reqJsonStr, std::string &returnJsonStr) +{ + if (reqJsonStr.empty()) { + LOGE("reqJsonStr is empty"); + return ERR_DM_INPUT_PARA_INVALID; + } + if (credentialMgr_== nullptr) { + LOGE("credentialMgr_ is nullptr"); + return ERR_DM_POINT_NULL; + } + return credentialMgr_->RequestCredential(reqJsonStr, returnJsonStr); +} + +int32_t DeviceManagerServiceImpl::ImportCredential(const std::string &pkgName, const std::string &credentialInfo) +{ + if (pkgName.empty() || credentialInfo.empty()) { + LOGE("DeviceManagerServiceImpl::ImportCredential failed, pkgName is %{public}s, credentialInfo is %{public}s", + pkgName.c_str(), GetAnonyString(credentialInfo).c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + if (credentialMgr_== nullptr) { + LOGE("credentialMgr_ is nullptr"); + return ERR_DM_POINT_NULL; + } + isCredentialType_.store(true); + return credentialMgr_->ImportCredential(pkgName, credentialInfo); +} + +int32_t DeviceManagerServiceImpl::DeleteCredential(const std::string &pkgName, const std::string &deleteInfo) +{ + if (pkgName.empty() || deleteInfo.empty()) { + LOGE("DeviceManagerServiceImpl::DeleteCredential failed, pkgName is %{public}s, deleteInfo is %{public}s", + pkgName.c_str(), GetAnonyString(deleteInfo).c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + if (credentialMgr_== nullptr) { + LOGE("credentialMgr_ is nullptr"); + return ERR_DM_POINT_NULL; + } + isCredentialType_.store(false); + return credentialMgr_->DeleteCredential(pkgName, deleteInfo); +} + +int32_t DeviceManagerServiceImpl::MineRequestCredential(const std::string &pkgName, std::string &returnJsonStr) +{ + (void)pkgName; + if (mineHiChainConnector_->RequestCredential(returnJsonStr) != DM_OK) { + LOGE("failed to get device credential from hichain"); + return ERR_DM_HICHAIN_CREDENTIAL_REQUEST_FAILED; + } + return DM_OK; +} + +int32_t DeviceManagerServiceImpl::CheckCredential(const std::string &pkgName, const std::string &reqJsonStr, + std::string &returnJsonStr) +{ + (void)pkgName; + if (reqJsonStr.empty()) { + LOGE("reqJsonStr is empty"); + return ERR_DM_INPUT_PARA_INVALID; + } + if (mineHiChainConnector_->CheckCredential(reqJsonStr, returnJsonStr) != DM_OK) { + LOGE("failed to check devices credential status"); + return ERR_DM_HICHAIN_CREDENTIAL_CHECK_FAILED; + } + return DM_OK; +} + +int32_t DeviceManagerServiceImpl::ImportCredential(const std::string &pkgName, const std::string &reqJsonStr, + std::string &returnJsonStr) +{ + (void)pkgName; + if (reqJsonStr.empty()) { + LOGE("reqJsonStr is empty"); + return ERR_DM_INPUT_PARA_INVALID; + } + if (mineHiChainConnector_->ImportCredential(reqJsonStr, returnJsonStr) != DM_OK) { + LOGE("failed to import devices credential"); + return ERR_DM_HICHAIN_CREDENTIAL_IMPORT_FAILED; + } + isCredentialType_.store(true); + return DM_OK; +} + +int32_t DeviceManagerServiceImpl::DeleteCredential(const std::string &pkgName, const std::string &reqJsonStr, + std::string &returnJsonStr) +{ + (void)pkgName; + if (reqJsonStr.empty()) { + LOGE("reqJsonStr is empty"); + return ERR_DM_INPUT_PARA_INVALID; + } + if (mineHiChainConnector_->DeleteCredential(reqJsonStr, returnJsonStr) != DM_OK) { + LOGE("failed to delete devices credential"); + return ERR_DM_HICHAIN_CREDENTIAL_DELETE_FAILED; + } + isCredentialType_.store(false); + return DM_OK; +} + +int32_t DeviceManagerServiceImpl::RegisterCredentialCallback(const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("RegisterCredentialCallback failed, pkgName is empty"); + return ERR_DM_INPUT_PARA_INVALID; + } + if (credentialMgr_ == nullptr) { + LOGE("credentialMgr_ is nullptr"); + return ERR_DM_POINT_NULL; + } + return credentialMgr_->RegisterCredentialCallback(pkgName); +} + +int32_t DeviceManagerServiceImpl::UnRegisterCredentialCallback(const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("UnRegisterCredentialCallback failed, pkgName is empty"); + return ERR_DM_INPUT_PARA_INVALID; + } + if (credentialMgr_== nullptr) { + LOGE("credentialMgr_ is nullptr"); + return ERR_DM_POINT_NULL; + } + return credentialMgr_->UnRegisterCredentialCallback(pkgName); +} + +int32_t DeviceManagerServiceImpl::RegisterUiStateCallback(const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("RegisterUiStateCallback failed, pkgName is empty"); + return ERR_DM_INPUT_PARA_INVALID; + } + auto authMgr = GetCurrentAuthMgr(); + if (authMgr == nullptr) { + LOGE("authMgr is nullptr"); + return ERR_DM_POINT_NULL; + } + return authMgr->RegisterUiStateCallback(pkgName); +} + +int32_t DeviceManagerServiceImpl::UnRegisterUiStateCallback(const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("UnRegisterUiStateCallback failed, pkgName is empty"); + return ERR_DM_INPUT_PARA_INVALID; + } + auto authMgr = GetCurrentAuthMgr(); + if (authMgr == nullptr) { + LOGE("authMgr is nullptr"); + return ERR_DM_POINT_NULL; + } + return authMgr->UnRegisterUiStateCallback(pkgName); +} + +int32_t DeviceManagerServiceImpl::PraseNotifyEventJson(const std::string &event, JsonObject &jsonObject) +{ + jsonObject.Parse(event); + if (jsonObject.IsDiscarded()) { + LOGE("event prase error."); + return ERR_DM_FAILED; + } + if ((!jsonObject.Contains("extra")) || (!jsonObject["extra"].IsObject())) { + LOGE("extra error"); + return ERR_DM_FAILED; + } + if ((!jsonObject["extra"].Contains("deviceId")) || (!jsonObject["extra"]["deviceId"].IsString())) { + LOGE("NotifyEvent deviceId invalid"); + return ERR_DM_FAILED; + } + return DM_OK; +} + +int32_t DeviceManagerServiceImpl::NotifyEvent(const std::string &pkgName, const int32_t eventId, + const std::string &event) +{ + LOGI("NotifyEvent begin, pkgName : %{public}s, eventId : %{public}d", pkgName.c_str(), eventId); + if ((eventId <= DM_NOTIFY_EVENT_START) || (eventId >= DM_NOTIFY_EVENT_BUTT)) { + LOGE("NotifyEvent eventId invalid"); + return ERR_DM_INPUT_PARA_INVALID; + } + if (eventId == DM_NOTIFY_EVENT_ONDEVICEREADY) { + JsonObject jsonObject; + if (PraseNotifyEventJson(event, jsonObject) != DM_OK) { + LOGE("NotifyEvent json invalid"); + return ERR_DM_INPUT_PARA_INVALID; + } + std::string deviceId; + jsonObject["extra"]["deviceId"].GetTo(deviceId); + if (deviceStateMgr_== nullptr) { + LOGE("deviceStateMgr_ is nullptr"); + return ERR_DM_POINT_NULL; + } + if (deviceStateMgr_->ProcNotifyEvent(eventId, deviceId) != DM_OK) { + LOGE("NotifyEvent failed"); + return ERR_DM_INPUT_PARA_INVALID; + }; + } + return DM_OK; +} + +int32_t DeviceManagerServiceImpl::GetGroupType(std::vector &deviceList) +{ + LOGI("GetGroupType begin"); + if (softbusConnector_ == nullptr || hiChainConnector_ == nullptr) { + LOGE("softbusConnector_ or hiChainConnector_ is nullptr"); + return ERR_DM_POINT_NULL; + } + + for (auto it = deviceList.begin(); it != deviceList.end(); ++it) { + std::string udid = ""; + int32_t ret = softbusConnector_->GetUdidByNetworkId(it->networkId, udid); + if (ret != DM_OK) { + LOGE("GetUdidByNetworkId failed ret: %{public}d", ret); + return ret; + } + std::string deviceId = softbusConnector_->GetDeviceUdidHashByUdid(udid); + if (memcpy_s(it->deviceId, DM_MAX_DEVICE_ID_LEN, deviceId.c_str(), deviceId.length()) != 0) { + LOGE("get deviceId: %{public}s failed", GetAnonyString(deviceId).c_str()); + return ERR_DM_SECURITY_FUNC_FAILED; + } + it->authForm = hiChainConnector_->GetGroupType(udid); + } + return DM_OK; +} + +int32_t DeviceManagerServiceImpl::GetUdidHashByNetWorkId(const char *networkId, std::string &deviceId) +{ + if (softbusConnector_ == nullptr || hiChainConnector_ == nullptr) { + LOGE("softbusConnector_ or hiChainConnector_ is nullptr"); + return ERR_DM_POINT_NULL; + } + std::string udid = ""; + int32_t ret = softbusConnector_->GetUdidByNetworkId(networkId, udid); + if (ret != DM_OK) { + LOGE("GetUdidByNetworkId failed ret: %{public}d", ret); + return ret; + } + deviceId = softbusConnector_->GetDeviceUdidHashByUdid(udid); + return DM_OK; +} + +std::shared_ptr DeviceManagerServiceImpl::GetConfigByTokenId() +{ + uint64_t tokenId = IPCSkeleton::GetCallingTokenID(); + if (configsMap_.find(tokenId) == configsMap_.end()) { + configsMap_[tokenId] = std::make_shared(); + } + return configsMap_[tokenId]; +} + +int32_t DeviceManagerServiceImpl::ImportAuthCode(const std::string &pkgName, const std::string &authCode) +{ + if (pkgName.empty() || authCode.empty()) { + LOGE("ImportAuthCode failed, pkgName or authCode is empty"); + return ERR_DM_INPUT_PARA_INVALID; + } + + LOGI("DeviceManagerServiceImpl::ImportAuthCode pkgName is %{public}s, authCode is %{public}s", + pkgName.c_str(), GetAnonyString(authCode).c_str()); + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + auto config = GetConfigByTokenId(); + config->pkgName = pkgName; + config->authCode = authCode; // If registered multiple times, only the last one is kept + return DM_OK; + } + + return authMgr->ImportAuthCode(pkgName, authCode); +} + +int32_t DeviceManagerServiceImpl::ExportAuthCode(std::string &authCode) +{ + int32_t ret = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); + authCode = std::to_string(ret); + LOGI("ExportAuthCode success, authCode: %{public}s.", GetAnonyString(authCode).c_str()); + return DM_OK; +} + +static JsonObject GetExtraJsonObject(const std::map &bindParam) +{ + std::string extra; + auto iter = bindParam.find(PARAM_KEY_BIND_EXTRA_DATA); + if (iter != bindParam.end()) { + extra = iter->second; + } else { + extra = ConvertMapToJsonString(bindParam); + } + + return JsonObject(extra); +} + +static int32_t GetHmlInfo(const JsonObject &jsonObject, bool &hmlEnable160M, int32_t &hmlActionId) +{ + if (jsonObject[PARAM_KEY_HML_ENABLE_160M].IsBoolean()) { + hmlEnable160M = jsonObject[PARAM_KEY_HML_ENABLE_160M].Get(); + LOGI("hmlEnable160M %{public}d", hmlEnable160M); + } + if (!IsString(jsonObject, PARAM_KEY_HML_ACTIONID)) { + LOGE("PARAM_KEY_HML_ACTIONID is not string"); + return ERR_DM_INPUT_PARA_INVALID; + } + std::string actionIdStr = jsonObject[PARAM_KEY_HML_ACTIONID].Get(); + if (!IsNumberString(actionIdStr)) { + LOGE("PARAM_KEY_HML_ACTIONID is not number"); + return ERR_DM_INPUT_PARA_INVALID; + } + int32_t actionId = std::atoi(actionIdStr.c_str()); + if (actionId <= 0) { + LOGE("PARAM_KEY_HML_ACTIONID is <= 0"); + return ERR_DM_INPUT_PARA_INVALID; + } + hmlActionId = actionId; + return DM_OK; +} + +static bool IsHmlSessionType(const JsonObject &jsonObject) +{ + std::string connSessionType; + if (jsonObject[PARAM_KEY_CONN_SESSIONTYPE].IsString()) { + connSessionType = jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get(); + LOGI("connSessionType %{public}s", connSessionType.c_str()); + } + return connSessionType == CONN_SESSION_TYPE_HML; +} + +int DeviceManagerServiceImpl::OpenAuthSession(const std::string& deviceId, + const std::map &bindParam) +{ + bool hmlEnable160M = false; + int32_t hmlActionId = 0; + JsonObject jsonObject = GetExtraJsonObject(bindParam); + if (jsonObject.IsDiscarded()) { + LOGE("extra string not a json type."); + return -1; + } + if (IsHmlSessionType(jsonObject)) { + auto ret = GetHmlInfo(jsonObject, hmlEnable160M, hmlActionId); + if (ret != DM_OK) { + LOGE("OpenAuthSession failed, GetHmlInfo failed."); + return ret; + } + LOGI("hmlActionId %{public}d, hmlEnable160M %{public}d", hmlActionId, hmlEnable160M); + return softbusConnector_->GetSoftbusSession()->OpenAuthSessionWithPara(deviceId, + hmlActionId, hmlEnable160M); + } else { + return softbusConnector_->GetSoftbusSession()->OpenAuthSession(deviceId); + } +} + +std::shared_ptr DeviceManagerServiceImpl::GetOrCreateSession(const std::string& deviceId, + const std::map &bindParam) +{ + std::shared_ptr instance; + int sessionId = -1; + // Acquire global lock to ensure thread safety for maps + { + std::lock_guard lock(mapMutex_); + if (deviceId2SessionIdMap_.find(deviceId) != deviceId2SessionIdMap_.end()) { + sessionId = deviceId2SessionIdMap_[deviceId]; + } + if (sessionsMap_.find(sessionId) != sessionsMap_.end()) { + return sessionsMap_[sessionId]; + } + } + + // Get the lock corresponding to deviceId + std::mutex& device_mutex = deviceIdMutexMap_[deviceId]; + std::lock_guard lock(device_mutex); + + // Check again whether the corresponding object already exists (because other threads may have created it during + // the lock acquisition in the previous step) + { + std::lock_guard lock(mapMutex_); + if (deviceId2SessionIdMap_.find(deviceId) != deviceId2SessionIdMap_.end()) { + sessionId = deviceId2SessionIdMap_[deviceId]; + } + if (sessionsMap_.find(sessionId) != sessionsMap_.end()) { + return sessionsMap_[sessionId]; + } + + sessionId = OpenAuthSession(deviceId, bindParam); + if (sessionId < 0) { + LOGE("OpenAuthSession failed, stop the authentication"); + return nullptr; + } + + std::unique_lock cvLock(sessionEnableMutexMap_[sessionId]); + if (sessionEnableCvMap_[sessionId].wait_for(cvLock, std::chrono::milliseconds(EVENT_TIMEOUT), + [&] { return sessionEnableCvReadyMap_[sessionId]; })) { + LOGI("session enable, sessionId: %{public}d.", sessionId); + } else { + LOGE("wait session enable timeout or enable fail, sessionId: %{public}d.", sessionId); + return nullptr; + } + sessionEnableCvReadyMap_.erase(sessionId); + instance = std::make_shared(sessionId, deviceId); + deviceId2SessionIdMap_[deviceId] = sessionId; + sessionsMap_[sessionId] = instance; + } + return instance; +} + +int32_t DeviceManagerServiceImpl::GetDeviceInfo(const PeerTargetId &targetId, std::string &addrType, + std::string &deviceId, std::shared_ptr deviceInfo, int32_t &index) +{ + ConnectionAddr addr; + if (!targetId.wifiIp.empty() && targetId.wifiIp.length() <= IP_STR_MAX_LEN) { + LOGI("parse wifiIp: %{public}s.", GetAnonyString(targetId.wifiIp).c_str()); + if (!addrType.empty()) { + addr.type = static_cast(std::atoi(addrType.c_str())); + } else { + addr.type = ConnectionAddrType::CONNECTION_ADDR_WLAN; + } + if (memcpy_s(addr.info.ip.ip, IP_STR_MAX_LEN, targetId.wifiIp.c_str(), targetId.wifiIp.length()) != 0) { + LOGE("get ip addr: %{public}s failed", GetAnonyString(targetId.wifiIp).c_str()); + return ERR_DM_SECURITY_FUNC_FAILED; + } + addr.info.ip.port = targetId.wifiPort; + deviceInfo->addr[index] = addr; + deviceId = targetId.wifiIp; + index++; + } else if (!targetId.brMac.empty() && targetId.brMac.length() <= BT_MAC_LEN) { + LOGI("parse brMac: %{public}s.", GetAnonyString(targetId.brMac).c_str()); + addr.type = ConnectionAddrType::CONNECTION_ADDR_BR; + if (memcpy_s(addr.info.br.brMac, BT_MAC_LEN, targetId.brMac.c_str(), targetId.brMac.length()) != 0) { + LOGE("get brMac addr: %{public}s failed", GetAnonyString(targetId.brMac).c_str()); + return ERR_DM_SECURITY_FUNC_FAILED; + } + deviceInfo->addr[index] = addr; + deviceId = targetId.brMac; + index++; + } else if (!targetId.bleMac.empty() && targetId.bleMac.length() <= BT_MAC_LEN) { + LOGI("parse bleMac: %{public}s.", GetAnonyString(targetId.bleMac).c_str()); + addr.type = ConnectionAddrType::CONNECTION_ADDR_BLE; + if (memcpy_s(addr.info.ble.bleMac, BT_MAC_LEN, targetId.bleMac.c_str(), targetId.bleMac.length()) != 0) { + LOGE("get bleMac addr: %{public}s failed", GetAnonyString(targetId.bleMac).c_str()); + return ERR_DM_SECURITY_FUNC_FAILED; + } + if (!targetId.deviceId.empty()) { + Crypto::ConvertHexStringToBytes(addr.info.ble.udidHash, UDID_HASH_LEN, + targetId.deviceId.c_str(), targetId.deviceId.length()); + } + deviceInfo->addr[index] = addr; + deviceId = targetId.bleMac; + index++; + } else { + LOGE("DeviceManagerServiceImpl::GetDeviceInfo failed, not addr."); + return ERR_DM_INPUT_PARA_INVALID; + } + return DM_OK; +} + +bool DeviceManagerServiceImpl::IsAuthNewVersion(int32_t bindLevel, std::string localUdid, std::string remoteUdid, + int32_t tokenId, int32_t userId) +{ + std::string extraInfo = DeviceProfileConnector::GetInstance().IsAuthNewVersion( + bindLevel, localUdid, remoteUdid, tokenId, userId); + JsonObject extraInfoJson(extraInfo); + if (extraInfoJson.IsDiscarded()) { + LOGE("IsAuthNewVersion extraInfoJson error"); + return false; + } + if (!extraInfoJson[TAG_DMVERSION].IsString()) { + LOGE("IsAuthNewVersion PARAM_KEY_OS_VERSION error"); + return false; + } + std::string dmVersion = extraInfoJson[TAG_DMVERSION].Get(); + if (CompareVersion(dmVersion, std::string(DM_VERSION_5_1_0)) || dmVersion == std::string(DM_VERSION_5_1_0)) { + return true; + } + return false; +} + +int32_t DeviceManagerServiceImpl::ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, + const std::map &bindParam) +{ + std::string addrType; + if (bindParam.count(PARAM_KEY_CONN_ADDR_TYPE) != 0) { + addrType = bindParam.at(PARAM_KEY_CONN_ADDR_TYPE); + } + + std::shared_ptr deviceInfo = std::make_shared(); + int32_t index = 0; + int32_t ret = GetDeviceInfo(targetId, addrType, deviceId, deviceInfo, index); + if (ret != DM_OK) { + LOGE("GetDeviceInfo failed, ret: %{public}d", ret); + } + deviceInfo->addrNum = static_cast(index); + if (softbusConnector_->AddMemberToDiscoverMap(deviceId, deviceInfo) != DM_OK) { + LOGE("DeviceManagerServiceImpl::ParseConnectAddr failed, AddMemberToDiscoverMap failed."); + return ERR_DM_INPUT_PARA_INVALID; + } + deviceInfo = nullptr; + return DM_OK; +} + +int32_t DeviceManagerServiceImpl::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, + const std::map &bindParam) +{ + if (pkgName.empty()) { + LOGE("BindTarget failed, pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + + std::string deviceId = ""; + PeerTargetId targetIdTmp = const_cast(targetId); + if (ParseConnectAddr(targetId, deviceId, bindParam) == DM_OK) { + targetIdTmp.deviceId = deviceId; + } else { + if (targetId.deviceId.empty()) { + LOGE("DeviceManagerServiceImpl::BindTarget failed, ParseConnectAddr failed."); + return ERR_DM_INPUT_PARA_INVALID; + } + } + // Created only at the source end. The same target device will not be created repeatedly with the new protocol. + std::shared_ptr curSession = GetOrCreateSession(targetIdTmp.deviceId, bindParam); + if (curSession == nullptr) { + LOGE("Failed to create the session. Target deviceId: %{public}s.", targetIdTmp.deviceId.c_str()); + return ERR_DM_AUTH_OPEN_SESSION_FAILED; + } + + // Logical session random number + int sessionId = curSession->sessionId_; + uint64_t logicalSessionId = 0; + if (curSession->version_ == "" || CompareVersion(curSession->version_, DM_VERSION_5_0_OLD_MAX)) { + logicalSessionId = GenerateRandNum(sessionId); + if (curSession->logicalSessionSet_.find(logicalSessionId) != curSession->logicalSessionSet_.end()) { + LOGE("Failed to create the logical session."); + return ERR_DM_LOGIC_SESSION_CREATE_FAILED; + } + } + + // Create on the src end. + uint64_t tokenId = IPCSkeleton::GetCallingTokenID(); + int32_t ret = InitAndRegisterAuthMgr(true, tokenId, curSession, logicalSessionId); + if (ret != DM_OK) { + LOGE("InitAndRegisterAuthMgr failed, ret %{public}d.", ret); + return ret; + } + curSession->logicalSessionSet_.insert(logicalSessionId); + curSession->logicalSessionCnt_.fetch_add(1); + logicalSessionId2TokenIdMap_[logicalSessionId] = tokenId; + logicalSessionId2SessionIdMap_[logicalSessionId] = sessionId; + + auto authMgr = GetAuthMgrByTokenId(tokenId); + if (authMgr == nullptr) { + return ERR_DM_POINT_NULL; + } + authMgr->SetBindTargetParams(targetId); + if ((ret = authMgr->BindTarget(pkgName, targetIdTmp, bindParam, sessionId, logicalSessionId)) != DM_OK) { + LOGE("authMgr BindTarget failed, ret %{public}d.", ret); + CleanAuthMgrByLogicalSessionId(logicalSessionId); + } + return ret; +} + +int32_t DeviceManagerServiceImpl::DpAclAdd(const std::string &udid) +{ + LOGI("DeviceManagerServiceImpl DpAclAdd start."); + MultipleUserConnector::SetSwitchOldUserId(MultipleUserConnector::GetCurrentAccountUserID()); + 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::GetFirstForegroundUserId(); + softbusConnector_->SetProcessInfo(processInfo); + deviceStateMgr_->OnDeviceOnline(udid, DmAuthForm::IDENTICAL_ACCOUNT); + } + LOGI("DeviceManagerServiceImpl::DpAclAdd completed"); + return DM_OK; +} + +int32_t DeviceManagerServiceImpl::IsSameAccount(const std::string &udid) +{ + if (udid.empty()) { + LOGE("DeviceManagerServiceImpl::IsSameAccount error: udid: %{public}s", GetAnonyString(udid).c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + + return DeviceProfileConnector::GetInstance().IsSameAccount(udid); +} + +uint64_t DeviceManagerServiceImpl::GetTokenIdByNameAndDeviceId(std::string pkgName, + std::string requestDeviceId) +{ + if (pkgName.empty()) { + LOGE("DeviceManagerServiceImpl::GetTokenIdByNameAndDeviceId error: pkgName."); + return ERR_DM_INPUT_PARA_INVALID; + } + + if (requestDeviceId.empty()) { + LOGE("DeviceManagerServiceImpl::GetTokenIdByNameAndDeviceId error: requestDeviceId."); + return ERR_DM_INPUT_PARA_INVALID; + } + + return DeviceProfileConnector::GetInstance().GetTokenIdByNameAndDeviceId(pkgName, requestDeviceId); +} + +std::unordered_map DeviceManagerServiceImpl::GetAppTrustDeviceIdList( + std::string pkgname) +{ + char localDeviceId[DEVICE_UUID_LENGTH]; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string deviceId = reinterpret_cast(localDeviceId); + return DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgname, deviceId); +} + +void DeviceManagerServiceImpl::LoadHardwareFwkService() +{ + DmDistributedHardwareLoad::GetInstance().LoadDistributedHardwareFwk(); +} + +void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, + const std::string &peerUdid, int32_t peerUserId) +{ + LOGI("localUdid %{public}s, localUserId %{public}d, peerUdid %{public}s, peerUserId %{public}d.", + GetAnonyString(localUdid).c_str(), localUserId, GetAnonyString(peerUdid).c_str(), peerUserId); + DmOfflineParam offlineParam; + bool notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, + peerUdid, peerUserId, offlineParam); + if (notifyOffline) { + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = localUserId; + CHECK_NULL_VOID(softbusConnector_); + softbusConnector_->SetProcessInfo(processInfo); + CHECK_NULL_VOID(deviceStateMgr_); + deviceStateMgr_->OnDeviceOffline(peerUdid); + } + CHECK_NULL_VOID(hiChainConnector_); + hiChainConnector_->DeleteAllGroup(localUserId); + CHECK_NULL_VOID(hiChainAuthConnector_); + hiChainAuthConnector_->DeleteCredential(peerUdid, localUserId, peerUserId); + LOGE("DeleteSkCredAndAcl start"); + DeleteSkCredAndAcl(offlineParam.needDelAclInfos); +} + +void DeviceManagerServiceImpl::HandleUserRemoved(std::vector peerUdids, int32_t preUserId) +{ + LOGI("PreUserId %{public}d.", preUserId); + char localDeviceId[DEVICE_UUID_LENGTH]; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string localUdid = reinterpret_cast(localDeviceId); + std::multimap peerUserIdMap; // key: peerUdid value: peerUserId + DmOfflineParam offlineParam; + DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(localUdid, preUserId, peerUdids, peerUserIdMap, + offlineParam); + CHECK_NULL_VOID(hiChainConnector_); + hiChainConnector_->DeleteAllGroup(preUserId); + + if (peerUserIdMap.empty()) { + LOGE("peerUserIdMap is empty"); + return; + } + CHECK_NULL_VOID(hiChainAuthConnector_); + for (const auto &item : peerUserIdMap) { + hiChainAuthConnector_->DeleteCredential(item.first, preUserId, item.second); + } + LOGE("DeleteSkCredAndAcl start"); + DeleteSkCredAndAcl(offlineParam.needDelAclInfos); +} + +void DeviceManagerServiceImpl::HandleRemoteUserRemoved(int32_t userId, const std::string &remoteUdid) +{ + LOGI("remoteUdid %{public}s, userId %{public}d", GetAnonyString(remoteUdid).c_str(), userId); + std::vector localUserIds; + DmOfflineParam offlineParam; + DeviceProfileConnector::GetInstance().DeleteAclForRemoteUserRemoved(remoteUdid, userId, localUserIds, offlineParam); + if (localUserIds.empty()) { + return; + } + CHECK_NULL_VOID(hiChainAuthConnector_); + std::vector> delInfoVec; + for (int32_t localUserId : localUserIds) { + delInfoVec.push_back(std::pair(localUserId, remoteUdid)); + hiChainAuthConnector_->DeleteCredential(remoteUdid, localUserId, userId); + } + CHECK_NULL_VOID(hiChainConnector_); + hiChainConnector_->DeleteGroupByACL(delInfoVec, localUserIds); + LOGE("DeleteSkCredAndAcl start"); + DeleteSkCredAndAcl(offlineParam.needDelAclInfos); +} + +void DeviceManagerServiceImpl::HandleUserSwitched(const std::vector &deviceVec, + 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); + DeviceProfileConnector::GetInstance().HandleUserSwitched(localUdid, deviceVec, currentUserId, beforeUserId); +} + +void DeviceManagerServiceImpl::ScreenCommonEventCallback(std::string commonEventType) +{ + if (commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED) { + LOGI("DeviceManagerServiceImpl::ScreenCommonEventCallback on screen locked."); + for (auto& pair : authMgrMap_) { + if (pair.second != nullptr) { + LOGI("DeviceManagerServiceImpl::ScreenCommonEventCallback tokenId: %{public}" PRId64 ".", pair.first); + pair.second->OnScreenLocked(); + } + } + return; + } + LOGI("DeviceManagerServiceImpl::ScreenCommonEventCallback error."); +} + +int32_t DeviceManagerServiceImpl::CheckIsSameAccount(const DmAccessCaller &caller, const std::string &srcUdid, + const DmAccessCallee &callee, const std::string &sinkUdid) +{ + return DeviceProfileConnector::GetInstance().CheckIsSameAccount(caller, srcUdid, callee, sinkUdid); +} + +int32_t DeviceManagerServiceImpl::CheckAccessControl(const DmAccessCaller &caller, const std::string &srcUdid, + const DmAccessCallee &callee, const std::string &sinkUdid) +{ + CHECK_NULL_RETURN(hiChainConnector_, ERR_DM_POINT_NULL); + bool ret = hiChainConnector_->IsDevicesInP2PGroup(srcUdid, sinkUdid); + if (!ret) { + int32_t checkRet = DeviceProfileConnector::GetInstance().CheckAccessControl(caller, + srcUdid, callee, sinkUdid); + return checkRet; + } else { + return DM_OK; + } +} + +void DeviceManagerServiceImpl::HandleDeviceNotTrust(const std::string &udid) +{ + LOGI("DeviceManagerServiceImpl::HandleDeviceNotTrust udid: %{public}s.", GetAnonyString(udid).c_str()); + if (udid.empty()) { + LOGE("HandleDeviceNotTrust udid is empty."); + return; + } + DeviceProfileConnector::GetInstance().DeleteAccessControlList(udid); + CHECK_NULL_VOID(hiChainConnector_); + hiChainConnector_->DeleteAllGroupByUdid(udid); +} + +int32_t DeviceManagerServiceImpl::GetBindLevel(const std::string &pkgName, const std::string &localUdid, + const std::string &udid, uint64_t &tokenId) +{ + 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::multimap DeviceManagerServiceImpl::GetDeviceIdAndUserId(int32_t userId, + const std::string &accountId) +{ + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + return DeviceProfileConnector::GetInstance().GetDeviceIdAndUserId(userId, accountId, localUdid); +} + +void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, + const std::string &remoteUdid) +{ + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + std::multimap devIdAndUserMap = + DeviceProfileConnector::GetInstance().GetDevIdAndUserIdByActHash(localUdid, remoteUdid, + remoteUserId, remoteAccountHash); + CHECK_NULL_VOID(listener_); + std::string uuid = ""; + SoftbusCache::GetInstance().GetUuidByUdid(remoteUdid, uuid); + listener_->OnDeviceTrustChange(remoteUdid, uuid, DmAuthForm::IDENTICAL_ACCOUNT); + for (const auto &item : devIdAndUserMap) { + DmOfflineParam offlineParam; + LOGI("remoteUdid %{public}s.", GetAnonyString(remoteUdid).c_str()); + bool notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(item.first, item.second, + remoteUdid, remoteUserId, offlineParam); + if (notifyOffline) { + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = item.second; + CHECK_NULL_VOID(softbusConnector_); + softbusConnector_->SetProcessInfo(processInfo); + CHECK_NULL_VOID(deviceStateMgr_); + deviceStateMgr_->OnDeviceOffline(remoteUdid); + } + CHECK_NULL_VOID(hiChainConnector_); + hiChainConnector_->DeleteAllGroup(item.second); + CHECK_NULL_VOID(hiChainAuthConnector_); + hiChainAuthConnector_->DeleteCredential(remoteUdid, item.second, remoteUserId); + LOGE("DeleteSkCredAndAcl start"); + DeleteSkCredAndAcl(offlineParam.needDelAclInfos); + } +} + +DmAuthForm DeviceManagerServiceImpl::ConvertBindTypeToAuthForm(int32_t bindType) +{ + LOGI("BindType %{public}d.", bindType); + DmAuthForm authForm = DmAuthForm::INVALID_TYPE; + if (static_cast(bindType) == DM_IDENTICAL_ACCOUNT) { + authForm = IDENTICAL_ACCOUNT; + } else if (static_cast(bindType) == DM_POINT_TO_POINT) { + authForm = PEER_TO_PEER; + } else if (static_cast(bindType) == DM_ACROSS_ACCOUNT) { + authForm = ACROSS_ACCOUNT; + } else { + LOGE("Invalied bindType."); + } + return authForm; +} + +int32_t DeviceManagerServiceImpl::DeleteGroup(const std::string &pkgName, const std::string &deviceId) +{ + LOGI("DeviceManagerServiceImpl::DeleteGroup"); + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return ERR_DM_FAILED; + } + std::vector groupList; + CHECK_NULL_RETURN(hiChainConnector_, ERR_DM_POINT_NULL); + hiChainConnector_->GetRelatedGroups(deviceId, groupList); + for (const auto &item : groupList) { + std::string groupId = item.groupId; + hiChainConnector_->DeleteGroup(groupId); + } + return DM_OK; +} + +void DeviceManagerServiceImpl::HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid) +{ + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + DmOfflineParam offlineParam; + int32_t bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent( + remoteUserId, remoteUdid, localUdid, offlineParam); + if (static_cast(bindType) == DM_INVALIED_TYPE) { + LOGE("Invalied bindtype."); + return; + } + int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); + DeleteGroup(DM_PKG_NAME, remoteUdid); + DeleteSkCredAndAcl(offlineParam.needDelAclInfos); +} + +void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + int32_t tokenId) +{ + LOGI("HandleAppUnBindEvent tokenId = %{public}d.", tokenId); + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); + DmOfflineParam offlineParam = + DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); + if (offlineParam.leftAclNumber != 0) { + LOGI("HandleAppUnBindEvent app-level type leftAclNumber not zero."); + CHECK_NULL_VOID(softbusConnector_); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + softbusConnector_->HandleDeviceOffline(remoteUdid); + DeleteSkCredAndAcl(offlineParam.needDelAclInfos); + return; + } + if (offlineParam.leftAclNumber == 0) { + LOGI("HandleAppUnBindEvent app-level type leftAclNumber is zero."); + CHECK_NULL_VOID(softbusConnector_); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + if (!offlineParam.hasLnnAcl) { + CHECK_NULL_VOID(hiChainAuthConnector_); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(), + remoteUserId); + } else { + DeleteSkCredAndAcl(offlineParam.needDelAclInfos); + } + return; + } +} + +void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + int32_t tokenId, int32_t peerTokenId) +{ + LOGI("HandleAppUnBindEvent peerTokenId = %{public}d.", peerTokenId); + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); + DmOfflineParam offlineParam = + DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, + tokenId, localUdid, peerTokenId); + if (offlineParam.leftAclNumber != 0) { + LOGI("HandleAppUnBindEvent app-level type leftAclNumber not zero."); + CHECK_NULL_VOID(softbusConnector_); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + softbusConnector_->HandleDeviceOffline(remoteUdid); + DeleteSkCredAndAcl(offlineParam.needDelAclInfos); + return; + } + if (offlineParam.leftAclNumber == 0) { + LOGI("HandleAppUnBindEvent app-level type leftAclNumber is zero."); + CHECK_NULL_VOID(softbusConnector_); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + if (!offlineParam.hasLnnAcl) { + CHECK_NULL_VOID(hiChainAuthConnector_); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(), + remoteUserId); + } else { + DeleteSkCredAndAcl(offlineParam.needDelAclInfos); + } + return; + } +} + +void DeviceManagerServiceImpl::HandleServiceUnBindEvent(int32_t userId, const std::string &remoteUdid, + int32_t remoteTokenId) +{ + LOGI("HandleServiceUnBindEvent remoteTokenId = %{public}d, userId: %{public}d, remoteUdid: %{public}s.", + remoteTokenId, userId, GetAnonyString(remoteUdid).c_str()); + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + int32_t localUserId = MultipleUserConnector::GetCurrentAccountUserID(); + DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().HandleServiceUnBindEvent( + userId, remoteUdid, localUdid, remoteTokenId); + + CHECK_NULL_VOID(softbusConnector_); + if (offlineParam.hasLnnAcl) { + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + } else { + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + softbusConnector_->HandleDeviceOffline(remoteUdid); + } + DeleteSkCredAndAcl(offlineParam.needDelAclInfos); +} + +void DeviceManagerServiceImpl::HandleSyncUserIdEvent(const std::vector &foregroundUserIds, + const std::vector &backgroundUserIds, const std::string &remoteUdid, bool isCheckUserStatus) +{ + LOGI("remote udid: %{public}s, foregroundUserIds: %{public}s, backgroundUserIds: %{public}s", + GetAnonyString(remoteUdid).c_str(), GetIntegerList(foregroundUserIds).c_str(), + GetIntegerList(backgroundUserIds).c_str()); + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + std::vector rmtFrontUserIdsTemp(foregroundUserIds.begin(), foregroundUserIds.end()); + std::vector rmtBackUserIdsTemp(backgroundUserIds.begin(), backgroundUserIds.end()); + std::vector localUserIds; + int32_t ret = MultipleUserConnector::GetForegroundUserIds(localUserIds); + if (ret != DM_OK) { + LOGE("Get foreground userids failed, ret: %{public}d", ret); + return; + } + if (isCheckUserStatus) { + MultipleUserConnector::ClearLockedUser(localUserIds); + } + DmOfflineParam offlineParam; + DeviceProfileConnector::GetInstance().UpdateACL(localUdid, localUserIds, remoteUdid, + rmtFrontUserIdsTemp, rmtBackUserIdsTemp, offlineParam); + DeleteSkCredAndAcl(offlineParam.needDelAclInfos); + DeviceProfileConnector::GetInstance().HandleSyncBackgroundUserIdEvent(rmtBackUserIdsTemp, remoteUdid, + localUserIds, localUdid); + DeviceProfileConnector::GetInstance().HandleSyncForegroundUserIdEvent(rmtFrontUserIdsTemp, remoteUdid, + localUserIds, localUdid); +} + +void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) +{ + LOGI("In"); + CHECK_NULL_VOID(deviceStateMgr_); + CHECK_NULL_VOID(softbusConnector_); + std::string trustDeviceId = ""; + if (softbusConnector_->GetUdidByNetworkId(devInfo.networkId, trustDeviceId) != DM_OK) { + LOGE("get udid failed."); + return; + } + std::string udidHash = softbusConnector_->GetDeviceUdidHashByUdid(trustDeviceId); + if (memcpy_s(devInfo.deviceId, DM_MAX_DEVICE_ID_LEN, udidHash.c_str(), udidHash.length()) != 0) { + LOGE("get deviceId: %{public}s failed", GetAnonyString(udidHash).c_str()); + return; + } + char localUdid[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdid, DEVICE_UUID_LENGTH); + std::string requestDeviceId = static_cast(localUdid); + uint32_t bindType = DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); + LOGI("bind type is %{public}d.", bindType); + if (bindType == INVALIED_TYPE) { + return; + } else if (bindType == IDENTICAL_ACCOUNT_TYPE || bindType == DEVICE_PEER_TO_PEER_TYPE || + bindType == DEVICE_ACROSS_ACCOUNT_TYPE) { + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); + softbusConnector_->SetProcessInfo(processInfo); + } else if (bindType == APP_PEER_TO_PEER_TYPE || bindType == APP_ACROSS_ACCOUNT_TYPE) { + std::vector processInfoVec = + DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, + MultipleUserConnector::GetFirstForegroundUserId()); + softbusConnector_->SetProcessInfoVec(processInfoVec); + } + deviceStateMgr_->HandleDeviceScreenStatusChange(devInfo); +} + +int32_t DeviceManagerServiceImpl::SyncLocalAclListProcess(const DevUserInfo &localDevUserInfo, + const DevUserInfo &remoteDevUserInfo, std::string remoteAclList) +{ + CHECK_NULL_RETURN(softbusConnector_, ERR_DM_POINT_NULL); + return softbusConnector_->SyncLocalAclListProcess(localDevUserInfo, remoteDevUserInfo, remoteAclList); +} + +int32_t DeviceManagerServiceImpl::GetAclListHash(const DevUserInfo &localDevUserInfo, + const DevUserInfo &remoteDevUserInfo, std::string &aclList) +{ + CHECK_NULL_RETURN(softbusConnector_, ERR_DM_POINT_NULL); + return softbusConnector_->GetAclListHash(localDevUserInfo, remoteDevUserInfo, aclList); +} + +void DeviceManagerServiceImpl::HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, + int32_t errcode) +{ + CHECK_NULL_VOID(credentialMgr_); + credentialMgr_->HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode); +} + +int32_t DeviceManagerServiceImpl::ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) +{ + CHECK_NULL_RETURN(listener_, ERR_DM_POINT_NULL); + std::vector profiles = + DeviceProfileConnector::GetInstance().GetAllAclIncludeLnnAcl(); + LOGI("delete ACL size is %{public}zu, appId %{public}s", profiles.size(), GetAnonyString(appId).c_str()); + if (profiles.size() == 0) { + return DM_OK; + } + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localDeviceId); + std::vector> delACLInfoVec; + std::vector userIdVec; + std::map delProfileMap; + DeleteAclByTokenId(accessTokenId, profiles, delProfileMap, delACLInfoVec, userIdVec); + for (auto item : delProfileMap) { + DmOfflineParam lnnAclParam; + bool isLastLnnAcl = false; + for (auto it : profiles) { + CheckIsLastLnnAcl(it, item.second, lnnAclParam, isLastLnnAcl, localUdid); + } + if (!isLastLnnAcl) { + DeleteSkCredAndAcl(lnnAclParam.needDelAclInfos); + } + } + + if (delACLInfoVec.size() == 0) { + return DM_OK; + } + if (userIdVec.size() == 0) { + return DM_OK; + } + CHECK_NULL_RETURN(hiChainConnector_, ERR_DM_POINT_NULL); + hiChainConnector_->DeleteGroupByACL(delACLInfoVec, userIdVec); + return DM_OK; +} + +void DeviceManagerServiceImpl::CheckIsLastLnnAcl(DistributedDeviceProfile::AccessControlProfile profile, + DistributedDeviceProfile::AccessControlProfile delProfile, DmOfflineParam &lnnAclParam, bool &isLastLnnAcl, + const std::string &localUdid) +{ + if (DeviceProfileConnector::GetInstance().IsLnnAcl(profile) && CheckLnnAcl(delProfile, profile)) { + if (profile.GetAccesser().GetAccesserDeviceId() == localUdid) { + DeviceProfileConnector::GetInstance().CacheAcerAclId(profile, lnnAclParam.needDelAclInfos); + } + if (profile.GetAccessee().GetAccesseeDeviceId() == localUdid) { + DeviceProfileConnector::GetInstance().CacheAceeAclId(profile, lnnAclParam.needDelAclInfos); + } + } + if (!DeviceProfileConnector::GetInstance().IsLnnAcl(profile) && CheckLnnAcl(delProfile, profile)) { + isLastLnnAcl = true; + } +} + +void DeviceManagerServiceImpl::DeleteAclByTokenId(const int32_t accessTokenId, + std::vector &profiles, + std::map &delProfileMap, + std::vector> &delACLInfoVec, std::vector &userIdVec) +{ + for (auto &item : profiles) { + int64_t accesssertokenId = item.GetAccesser().GetAccesserTokenId(); + int64_t accessseetokenId = item.GetAccessee().GetAccesseeTokenId(); + if (accessTokenId != static_cast(accesssertokenId) && + accessTokenId != static_cast(accessseetokenId)) { + continue; + } + if (accessTokenId == static_cast(accesssertokenId)) { + DmOfflineParam offlineParam; + delProfileMap[item.GetAccessControlId()] = item; + DeviceProfileConnector::GetInstance().CacheAcerAclId(item, offlineParam.needDelAclInfos); + DeleteSkCredAndAcl(offlineParam.needDelAclInfos); + listener_->OnAppUnintall(item.GetAccesser().GetAccesserBundleName()); + if (item.GetBindLevel() == USER) { + userIdVec.push_back(item.GetAccesser().GetAccesserUserId()); + delACLInfoVec.push_back(std::pair(item.GetAccesser().GetAccesserUserId(), + item.GetAccessee().GetAccesseeDeviceId())); + } + } + if (accessTokenId == static_cast(accessseetokenId)) { + DmOfflineParam offlineParam; + DeviceProfileConnector::GetInstance().CacheAceeAclId(item, offlineParam.needDelAclInfos); + delProfileMap[item.GetAccessControlId()] = item; + DeleteSkCredAndAcl(offlineParam.needDelAclInfos); + listener_->OnAppUnintall(item.GetAccessee().GetAccesseeBundleName()); + if (item.GetBindLevel() == USER) { + userIdVec.push_back(item.GetAccessee().GetAccesseeUserId()); + delACLInfoVec.push_back(std::pair(item.GetAccessee().GetAccesseeUserId(), + item.GetAccesser().GetAccesserDeviceId())); + } + } + } + for (auto item : delProfileMap) { + for (auto it = profiles.begin(); it != profiles.end();) { + if (item.first == it->GetAccessControlId()) { + it = profiles.erase(it); + } else { + it++; + } + } + } +} + +bool DeviceManagerServiceImpl::CheckLnnAcl(DistributedDeviceProfile::AccessControlProfile delProfile, + DistributedDeviceProfile::AccessControlProfile lastprofile) +{ + if ((delProfile.GetAccesser().GetAccesserDeviceId() == lastprofile.GetAccesser().GetAccesserDeviceId() && + delProfile.GetAccesser().GetAccesserUserId() == lastprofile.GetAccesser().GetAccesserUserId() && + delProfile.GetAccessee().GetAccesseeDeviceId() == lastprofile.GetAccessee().GetAccesseeDeviceId() && + delProfile.GetAccessee().GetAccesseeUserId() == lastprofile.GetAccessee().GetAccesseeUserId()) || + (delProfile.GetAccesser().GetAccesserDeviceId() == lastprofile.GetAccessee().GetAccesseeDeviceId() && + delProfile.GetAccesser().GetAccesserUserId() == lastprofile.GetAccessee().GetAccesseeUserId() && + delProfile.GetAccessee().GetAccesseeDeviceId() == lastprofile.GetAccesser().GetAccesserDeviceId() && + delProfile.GetAccessee().GetAccesseeUserId() == lastprofile.GetAccesser().GetAccesserUserId())) { + return true; + } + return false; +} + +std::multimap DeviceManagerServiceImpl::GetDeviceIdAndUserId(int32_t localUserId) +{ + LOGI("localUserId %{public}d.", localUserId); + char localdeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localdeviceId, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localdeviceId); + return DeviceProfileConnector::GetInstance().GetDeviceIdAndUserId(localUdid, localUserId); +} + +int32_t DeviceManagerServiceImpl::SaveOnlineDeviceInfo(const std::vector &deviceList) +{ + CHECK_NULL_RETURN(deviceStateMgr_, ERR_DM_POINT_NULL); + for (auto item : deviceList) { + deviceStateMgr_->SaveOnlineDeviceInfo(item); + } + return DM_OK; +} + +void DeviceManagerServiceImpl::HandleDeviceUnBind(int32_t bindType, const std::string &peerUdid, + const std::string &localUdid, int32_t localUserId, const std::string &localAccountId) +{ + return DeviceProfileConnector::GetInstance().HandleDeviceUnBind(bindType, peerUdid, + localUdid, localUserId, localAccountId); +} + +int32_t DeviceManagerServiceImpl::RegisterAuthenticationType(int32_t authenticationType) +{ + if (authenticationType != USER_OPERATION_TYPE_ALLOW_AUTH && + authenticationType != USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { + LOGE("Invalid parameter."); + return ERR_DM_INPUT_PARA_INVALID; + } + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + auto config = GetConfigByTokenId(); + config->authenticationType = authenticationType; // only the last registration is retained + return DM_OK; + } + return authMgr->RegisterAuthenticationType(authenticationType); +} + +void DeviceManagerServiceImpl::DeleteAlwaysAllowTimeOut() +{ + LOGI("Start DeleteAlwaysAllowTimeOut"); + std::vector profiles = + DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); + std::string remoteUdid = ""; + int32_t remoteUserId = -1; + int64_t currentTime = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + int32_t currentUserId = MultipleUserConnector::GetCurrentAccountUserID(); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localDeviceId); + for (auto &item : profiles) { + if (item.GetBindType() == DM_IDENTICAL_ACCOUNT) { + continue; + } + if ((currentTime - item.GetLastAuthTime()) > MAX_ALWAYS_ALLOW_SECONDS && item.GetLastAuthTime() > 0) { + DeviceProfileConnector::GetInstance().DeleteAccessControlById(item.GetAccessControlId()); + if (item.GetAccesser().GetAccesserUserId() == currentUserId && + item.GetAccesser().GetAccesserDeviceId() == localUdid) { + remoteUserId = item.GetAccessee().GetAccesseeUserId(); + } + if (item.GetAccessee().GetAccesseeUserId() == currentUserId && + item.GetAccessee().GetAccesseeDeviceId() == localUdid) { + remoteUserId = item.GetAccesser().GetAccesserUserId(); + } + remoteUdid = item.GetTrustDeviceId(); + CheckDeleteCredential(remoteUdid, remoteUserId); + } + } +} + +void DeviceManagerServiceImpl::CheckDeleteCredential(const std::string &remoteUdid, int32_t remoteUserId) +{ + std::vector profiles = + DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); + bool leftAcl = false; + for (auto &item : profiles) { + if (item.GetTrustDeviceId() == remoteUdid) { + leftAcl = true; + } + } + if (!leftAcl) { + LOGI("CheckDeleteCredential delete credential"); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(), + remoteUserId); + } +} + +int32_t DeviceManagerServiceImpl::CheckDeviceInfoPermission(const std::string &localUdid, + const std::string &peerDeviceId) +{ + int32_t ret = DeviceProfileConnector::GetInstance().CheckDeviceInfoPermission(localUdid, peerDeviceId); + if (ret != DM_OK) { + LOGE("CheckDeviceInfoPermission failed, ret: %{public}d", ret); + return ret; + } + return DM_OK; +} + +int32_t DeviceManagerServiceImpl::DeleteAcl(const std::string &pkgName, const std::string &localUdid, + const std::string &remoteUdid, int32_t bindLevel, const std::string &extra) +{ + LOGI("DeleteAcl pkgName %{public}s, localUdid %{public}s, remoteUdid %{public}s, bindLevel %{public}d.", + pkgName.c_str(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str(), bindLevel); + if (static_cast(bindLevel) == USER) { + DeleteGroup(pkgName, remoteUdid); + } + DmOfflineParam offlineParam = + DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localUdid, remoteUdid, bindLevel, extra); + if (offlineParam.bindType == INVALIED_TYPE) { + LOGE("Acl not contain the pkgname bind data."); + return ERR_DM_FAILED; + } + CHECK_NULL_RETURN(softbusConnector_, ERR_DM_POINT_NULL); + CHECK_NULL_RETURN(hiChainAuthConnector_, ERR_DM_POINT_NULL); + if (static_cast(bindLevel) == APP) { + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); + 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(), + offlineParam.peerUserId); + return DM_OK; + } + } + if (static_cast(bindLevel) == USER && offlineParam.leftAclNumber != 0) { + LOGI("Unbind deivce-level, retain identical account bind type."); + return DM_OK; + } + if (static_cast(bindLevel) == USER && offlineParam.leftAclNumber == 0) { + LOGI("Unbind deivce-level, retain null."); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(), + offlineParam.peerUserId); + return DM_OK; + } + return ERR_DM_FAILED; +} + +int32_t DeviceManagerServiceImpl::DeleteSkCredAndAcl(const std::vector &acls) +{ + LOGI("DeleteSkCredAndAcl start."); + int32_t ret = DM_OK; + if (acls.empty()) { + return ret; + } + CHECK_NULL_RETURN(hiChainAuthConnector_, ERR_DM_POINT_NULL); + for (auto item : acls) { + ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(item.userId, item.skId); + if (ret != DM_OK) { + LOGE("DeleteSessionKey err, userId:%{public}d, skId:%{public}d, ret:%{public}d", item.userId, item.skId, + ret); + } + ret = hiChainAuthConnector_->DeleteCredential(item.userId, item.credId); + if (ret != DM_OK) { + LOGE("DeletecredId err, userId:%{public}d, credId:%{public}s, ret:%{public}d", item.userId, + item.credId.c_str(), ret); + } + DeviceProfileConnector::GetInstance().DeleteAccessControlById(item.accessControlId); + } + return ret; +} + +int32_t DeviceManagerServiceImpl::DeleteAclForProcV2(const std::string &localUdid, uint32_t localTokenId, + const std::string &remoteUdid, int32_t bindLevel, const std::string &extra, int32_t userId) +{ + DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().FilterNeedDeleteACL( + localUdid, localTokenId, remoteUdid, extra); + + // first, clear the unbind sk/cred/acl + DeleteSkCredAndAcl(offlineParam.needDelAclInfos); + + // second, determin if need clear lnn acl + if (offlineParam.allLeftAppOrSvrAclInfos.empty()) { + LOGI("No app or service acl exist, clear lnn acl"); + DeleteSkCredAndAcl(offlineParam.allLnnAclInfos); + } + + // third, determin if need report offline to unbind bundle + if (offlineParam.allUserAclInfos.empty()) { + LOGI("after clear target acl, No user acl exist, report offline"); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + softbusConnector_->HandleDeviceOffline(remoteUdid); + } + + return DM_OK; +} + +int32_t DeviceManagerServiceImpl::DeleteAclV2(const std::string &pkgName, const std::string &localUdid, + const std::string &remoteUdid, int32_t bindLevel, const std::string &extra) +{ + LOGI("DeleteAclV2 pkgName %{public}s, localUdid %{public}s, remoteUdid %{public}s, bindLevel %{public}d.", + pkgName.c_str(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str(), bindLevel); + uint32_t tokenId = 0; + MultipleUserConnector::GetTokenId(tokenId); + int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); + bool isNewVersion = IsAuthNewVersion(bindLevel, localUdid, remoteUdid, tokenId, userId); + if (!isNewVersion) { + return DeleteAcl(pkgName, localUdid, remoteUdid, bindLevel, extra); + } + return DeleteAclForProcV2(localUdid, tokenId, remoteUdid, bindLevel, extra, userId); +} + +void DeviceManagerServiceImpl::HandleCommonEventBroadCast(const std::vector &foregroundUserIds, + const std::vector &backgroundUserIds, const std::string &remoteUdid) +{ + LOGI("remote udid: %{public}s, foregroundUserIds: %{public}s, backgroundUserIds: %{public}s", + GetAnonyString(remoteUdid).c_str(), GetIntegerList(foregroundUserIds).c_str(), + GetIntegerList(backgroundUserIds).c_str()); + std::vector rmtFrontUserIdsTemp(foregroundUserIds.begin(), foregroundUserIds.end()); + std::vector rmtBackUserIdsTemp(backgroundUserIds.begin(), backgroundUserIds.end()); + std::vector localUserIds; + int32_t ret = MultipleUserConnector::GetForegroundUserIds(localUserIds); + if (ret != DM_OK) { + LOGE("Get foreground userids failed, ret: %{public}d", ret); + return; + } + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + MultipleUserConnector::ClearLockedUser(localUserIds); + DmOfflineParam offlineParam; + DeviceProfileConnector::GetInstance().UpdateACL(localUdid, localUserIds, remoteUdid, + rmtFrontUserIdsTemp, rmtBackUserIdsTemp, offlineParam); + DeleteSkCredAndAcl(offlineParam.needDelAclInfos); + DeviceProfileConnector::GetInstance().HandleSyncBackgroundUserIdEvent(rmtBackUserIdsTemp, remoteUdid, + localUserIds, localUdid); + DeviceProfileConnector::GetInstance().HandleSyncForegroundUserIdEvent(rmtFrontUserIdsTemp, remoteUdid, + localUserIds, localUdid); +} + +extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) +{ + return new DeviceManagerServiceImpl; +} +} // namespace DistributedHardware +} // namespace OHOS -- Gitee From 211a3bffac98d7d9f94c98a57d9f34a7d1875a16 Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Tue, 6 May 2025 14:01:23 +0800 Subject: [PATCH 2/4] =?UTF-8?q?=E5=90=8C=E6=AD=A5=E9=BB=84=E5=8C=BA?= =?UTF-8?q?=E4=B8=BB=E5=B9=B2=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- .../authentication/dm_auth_manager.h.bak | 660 ---- .../authentication_v2/auth_manager.h.bak | 210 - .../authentication_v2/dm_auth_context.h.bak | 257 -- .../dm_auth_manager_base.h.bak | 258 -- .../authentication_v2/dm_auth_state.h.bak | 509 --- .../authentication/dm_auth_manager.cpp.bak | 3404 ----------------- .../authentication_v2/auth_manager.cpp.bak | 1051 ----- .../auth_stages/auth_negotiate.cpp.bak | 534 --- .../dm_auth_manager_base.cpp.bak | 514 --- .../authentication_v2/dm_auth_state.cpp.bak | 461 --- .../src/device_manager_service_impl.cpp.bak | 2438 ------------ 11 files changed, 10296 deletions(-) delete mode 100644 services/implementation/include/authentication/dm_auth_manager.h.bak delete mode 100644 services/implementation/include/authentication_v2/auth_manager.h.bak delete mode 100644 services/implementation/include/authentication_v2/dm_auth_context.h.bak delete mode 100644 services/implementation/include/authentication_v2/dm_auth_manager_base.h.bak delete mode 100644 services/implementation/include/authentication_v2/dm_auth_state.h.bak delete mode 100644 services/implementation/src/authentication/dm_auth_manager.cpp.bak delete mode 100644 services/implementation/src/authentication_v2/auth_manager.cpp.bak delete mode 100644 services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp.bak delete mode 100644 services/implementation/src/authentication_v2/dm_auth_manager_base.cpp.bak delete mode 100644 services/implementation/src/authentication_v2/dm_auth_state.cpp.bak delete mode 100644 services/implementation/src/device_manager_service_impl.cpp.bak diff --git a/services/implementation/include/authentication/dm_auth_manager.h.bak b/services/implementation/include/authentication/dm_auth_manager.h.bak deleted file mode 100644 index a9631252f..000000000 --- a/services/implementation/include/authentication/dm_auth_manager.h.bak +++ /dev/null @@ -1,660 +0,0 @@ -/* - * 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 - * - * 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_AUTH_MANAGER_H -#define OHOS_DM_AUTH_MANAGER_H -#define TYPE_TV_ID 0x9C - -#include -#include -#include - -#include "auth_request_state.h" -#include "auth_response_state.h" -#include "auth_ui_state_manager.h" -#include "authentication.h" -#include "idevice_manager_service_listener.h" -#include "deviceprofile_connector.h" -#include "dm_ability_manager.h" -#include "dm_adapter_manager.h" -#include "dm_auth_manager_base.h" -#include "dm_constants.h" -#include "dm_device_info.h" -#include "dm_timer.h" -#include "hichain_auth_connector.h" -#include "hichain_connector.h" -#include "service_info_unique_key.h" -#include "softbus_connector.h" -#include "softbus_session.h" - -namespace OHOS { -namespace DistributedHardware { -typedef enum AuthState { - AUTH_REQUEST_INIT = 1, - AUTH_REQUEST_NEGOTIATE, - AUTH_REQUEST_NEGOTIATE_DONE, - AUTH_REQUEST_REPLY, - AUTH_REQUEST_JOIN, - AUTH_REQUEST_NETWORK, - AUTH_REQUEST_FINISH, - AUTH_REQUEST_CREDENTIAL, - AUTH_REQUEST_CREDENTIAL_DONE, - AUTH_REQUEST_AUTH_FINISH, - AUTH_REQUEST_RECHECK_MSG, - AUTH_REQUEST_RECHECK_MSG_DONE, - - AUTH_RESPONSE_INIT = 20, - AUTH_RESPONSE_NEGOTIATE, - AUTH_RESPONSE_CONFIRM, - AUTH_RESPONSE_GROUP, - AUTH_RESPONSE_SHOW, - AUTH_RESPONSE_FINISH, - AUTH_RESPONSE_CREDENTIAL, - AUTH_RESPONSE_AUTH_FINISH, - AUTH_RESPONSE_RECHECK_MSG, -} AuthState; - -enum DmMsgType : int32_t { - MSG_TYPE_UNKNOWN = 0, - MSG_TYPE_NEGOTIATE = 80, - MSG_TYPE_RESP_NEGOTIATE = 90, - MSG_TYPE_REQ_AUTH = 100, - MSG_TYPE_INVITE_AUTH_INFO = 102, - MSG_TYPE_REQ_AUTH_TERMINATE = 104, - MSG_TYPE_RESP_AUTH = 200, - MSG_TYPE_JOIN_AUTH_INFO = 201, - MSG_TYPE_RESP_AUTH_TERMINATE = 205, - MSG_TYPE_CHANNEL_CLOSED = 300, - MSG_TYPE_SYNC_GROUP = 400, - MSG_TYPE_AUTH_BY_PIN = 500, - - MSG_TYPE_RESP_AUTH_EXT, - MSG_TYPE_REQ_PUBLICKEY, - MSG_TYPE_RESP_PUBLICKEY, - MSG_TYPE_REQ_RECHECK_MSG, - MSG_TYPE_RESP_RECHECK_MSG, - MSG_TYPE_REQ_AUTH_DEVICE_NEGOTIATE = 600, - MSG_TYPE_RESP_AUTH_DEVICE_NEGOTIATE = 700, -}; - -enum DmAuthType : int32_t { - AUTH_TYPE_CRE = 0, - AUTH_TYPE_PIN, - AUTH_TYPE_QR_CODE, - AUTH_TYPE_NFC, - AUTH_TYPE_NO_INTER_ACTION, - AUTH_TYPE_IMPORT_AUTH_CODE, - AUTH_TYPE_UNKNOW, -}; - -typedef struct DmAuthRequestContext { - int32_t authType; - std::string localDeviceId; - std::string localDeviceName; - int32_t localDeviceTypeId; - std::string deviceId; - std::string deviceName; - std::string deviceTypeId; - int32_t sessionId; - int32_t groupVisibility; - bool cryptoSupport; - std::string cryptoName; - std::string cryptoVer; - std::string hostPkgName; - std::string targetPkgName; - std::string bundleName; - std::string peerBundleName; - std::string appOperation; - std::string appDesc; - std::string appName; - std::string customDesc; - std::string appThumbnail; - std::string token; - int32_t reason; - std::vector syncGroupList; - std::string dmVersion; - int32_t localUserId; - std::string localAccountId; - std::vector bindType; - bool isOnline; - bool authed; - int32_t bindLevel; - int64_t tokenId; - std::string remoteAccountId; - int32_t remoteUserId; - std::string addr; - std::string hostPkgLabel; - int32_t closeSessionDelaySeconds = 0; - std::string remoteDeviceName; - std::string connSessionType; - int32_t hmlActionId = 0; - bool hmlEnable160M = false; -} DmAuthRequestContext; - -typedef struct DmAuthResponseContext { - int32_t authType; - std::string deviceId; - std::string localDeviceId; - std::string deviceName; - int32_t deviceTypeId; - int32_t msgType; - int32_t sessionId; - bool cryptoSupport; - bool isIdenticalAccount; - bool isAuthCodeReady; - bool isShowDialog; - std::string cryptoName; - std::string cryptoVer; - int32_t reply; - std::string networkId; - std::string groupId; - std::string groupName; - std::string hostPkgName; - std::string targetPkgName; - std::string bundleName; - std::string peerBundleName; - std::string appOperation; - std::string appDesc; - std::string customDesc; - std::string appIcon; - std::string appThumbnail; - std::string token; - std::string authToken; - int32_t pageId; - int64_t requestId; - std::string code = ""; - int32_t state; - std::vector syncGroupList; - std::string accountGroupIdHash; - std::string publicKey; - bool isOnline; - int32_t bindLevel; - bool haveCredential; - int32_t confirmOperation; - std::string localAccountId; - int32_t localUserId; - int64_t tokenId; - int64_t remoteTokenId; - bool authed; - std::string dmVersion; - std::vector bindType; - std::string remoteAccountId; - int32_t remoteUserId; - std::string targetDeviceName; - std::string importAuthCode; - std::string hostPkgLabel; - bool isFinish = false; - std::string edition; - int32_t localBindLevel; - std::string remoteDeviceName; - int32_t localSessionKeyId = 0; - int32_t remoteSessionKeyId = 0; -} DmAuthResponseContext; - -class AuthMessageProcessor; - -class DmAuthManager final : public AuthManagerBase, - public std::enable_shared_from_this { -public: - DmAuthManager(std::shared_ptr softbusConnector, - std::shared_ptr hiChainConnector, - std::shared_ptr listener, - std::shared_ptr hiChainAuthConnector); - ~DmAuthManager(); - - /** - * @tc.name: DmAuthManager::AuthenticateDevice - * @tc.desc: Authenticate Device of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, - const std::string &extra); - - /** - * @tc.name: DmAuthManager::UnAuthenticateDevice - * @tc.desc: UnAuthenticate Device of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel); - - /** - * @brief UnBind device. - * @param pkgName package name. - * @param deviceId device id. - * @return Return 0 if success. - */ - int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, - int32_t bindLevel, const std::string &extra); - - /** - * @tc.name: DmAuthManager::OnSessionOpened - * @tc.desc: Opened Session of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - void OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result); - - /** - * @tc.name: DmAuthManager::OnSessionClosed - * @tc.desc: Closed Session of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - void OnSessionClosed(const int32_t sessionId); - - /** - * @tc.name: DmAuthManager::OnDataReceived - * @tc.desc: Received Data of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - void OnDataReceived(const int32_t sessionId, const std::string message); - - /** - * @tc.name: DmAuthManager::OnSoftbusJoinLNNResult - * @tc.desc: OnSoftbus JoinLNN Result of the SoftbusConnector - * @tc.type: FUNC - */ - void OnSoftbusJoinLNNResult(const int32_t sessionId, const char *networkId, int32_t result); - - /** - * @tc.name: DmAuthManager::OnGroupCreated - * @tc.desc: Created Group of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - void OnGroupCreated(int64_t requestId, const std::string &groupId); - - /** - * @tc.name: DmAuthManager::OnMemberJoin - * @tc.desc: Join Member of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - void OnMemberJoin(int64_t requestId, int32_t status); - - /** - * @tc.name: DmAuthManager::EstablishAuthChannel - * @tc.desc: Establish Auth Channel of the DeviceManager Authenticate Manager, auth state machine - * @tc.type: FUNC - */ - int32_t EstablishAuthChannel(const std::string &deviceId); - - /** - * @tc.name: DmAuthManager::StartNegotiate - * @tc.desc: Start Negotiate of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - void StartNegotiate(const int32_t &sessionId); - - /** - * @tc.name: DmAuthManager::RespNegotiate - * @tc.desc: Resp Negotiate of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - void RespNegotiate(const int32_t &sessionId); - - /** - * @tc.name: DmAuthManager::SendAuthRequest - * @tc.desc: Send Auth Request of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - void SendAuthRequest(const int32_t &sessionId); - - /** - * @tc.name: DmAuthManager::StartAuthProcess - * @tc.desc: Start Auth Process of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - int32_t StartAuthProcess(const int32_t &action); - - /** - * @tc.name: DmAuthManager::StartRespAuthProcess - * @tc.desc: Start Resp Auth Process of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - void StartRespAuthProcess(); - - /** - * @tc.name: DmAuthManager::CreateGroup - * @tc.desc: Create Group of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - int32_t CreateGroup(); - - /** - * @tc.name: DmAuthManager::ProcessPincode - * @tc.desc: Process pin code of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - int32_t ProcessPincode(const std::string &pinCode); - - /** - * @tc.name: DmAuthManager::GetConnectAddr - * @tc.desc: Get Connect Addr of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - std::string GetConnectAddr(std::string deviceId); - - /** - * @tc.name: DmAuthManager::JoinNetwork - * @tc.desc: Join Net work of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - int32_t JoinNetwork(); - - /** - * @tc.name: DmAuthManager::AuthenticateFinish - * @tc.desc: Finish Authenticate of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - void AuthenticateFinish(); - - /** - * @tc.name: DmAuthManager::GetIsCryptoSupport - * @tc.desc: Get Cryp to Support of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - bool GetIsCryptoSupport(); - - /** - * @tc.name: DmAuthManager::SetAuthRequestState - * @tc.desc: Set Auth Request State of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - int32_t SetAuthRequestState(std::shared_ptr authRequestState); - - /** - * @tc.name: DmAuthManager::SetAuthResponseState - * @tc.desc: Set Auth Response State of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - int32_t SetAuthResponseState(std::shared_ptr authResponseState); - - /** - * @tc.name: DmAuthManager::GetPinCode - * @tc.desc: Get Pin Code of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - int32_t GetPinCode(std::string &code); - - /** - * @tc.name: DmAuthManager::GenerateGroupName - * @tc.desc: Generate Group Name of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - std::string GenerateGroupName(); - - /** - * @tc.name: DmAuthManager::HandleAuthenticateTimeout - * @tc.desc: Handle Authenticate Timeout of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - void HandleAuthenticateTimeout(std::string name); - - /** - * @tc.name: DmAuthManager::GeneratePincode - * @tc.desc: Generate Pincode of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - std::string GeneratePincode(); - - /** - * @tc.name: DmAuthManager::ShowConfigDialog - * @tc.desc: Show Config Dialog of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - void ShowConfigDialog(); - - /** - * @tc.name: DmAuthManager::ShowAuthInfoDialog - * @tc.desc: Show AuthInfo Dialog of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - void ShowAuthInfoDialog(bool authDeviceError = false); - - /** - * @tc.name: DmAuthManager::ShowStartAuthDialog - * @tc.desc: Show Start Auth Dialog of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - void ShowStartAuthDialog(); - - /** - * @tc.name: DmAuthManager::OnUserOperation - * @tc.desc: User Operation of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - int32_t OnUserOperation(int32_t action, const std::string ¶ms); - - /** - * @tc.name: DmAuthManager::SetPageId - * @tc.desc: Set PageId of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - int32_t SetPageId(int32_t pageId); - - /** - * @tc.name: DmAuthManager::SetReasonAndFinish - * @tc.desc: Set Reason of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - int32_t SetReasonAndFinish(int32_t reason, int32_t state); - - /** - * @tc.name: DmAuthManager::IsIdenticalAccount - * @tc.desc: judge IdenticalAccount or not - * @tc.type: FUNC - */ - bool IsIdenticalAccount(); - - /** - * @tc.name: DmAuthManager::RegisterUiStateCallback - * @tc.desc: Register ui state callback - * @tc.type: FUNC - */ - int32_t RegisterUiStateCallback(const std::string pkgName); - - /** - * @tc.name: DmAuthManager::UnRegisterUiStateCallback - * @tc.desc: Unregister ui state callback - * @tc.type: FUNC - */ - int32_t UnRegisterUiStateCallback(const std::string pkgName); - - /** - * @tc.name: DmAuthManager::ImportAuthCode - * @tc.desc: Import auth code - * @tc.type: FUNC - */ - int32_t ImportAuthCode(const std::string &pkgName, const std::string &authCode); - - /** - * @tc.name: DmAuthManager::BindTarget - * @tc.desc: Bind Target - * @tc.type: FUNC - */ - int32_t BindTarget(const std::string &pkgName, const PeerTargetId &targetId, - const std::map &bindParam, int sessionId, uint64_t logicalSessionId); - - void ClearSoftbusSessionCallback(); - void PrepareSoftbusSessionCallback(); - - void HandleSessionHeartbeat(std::string name); - - int32_t RegisterAuthenticationType(int32_t authenticationType); - static bool IsPinCodeValid(const std::string strpin); - static bool IsPinCodeValid(int32_t numpin); - bool IsImportedAuthCodeValid(); - bool IsSrc(); - void GetCallerInfo(DmBindCallerInfo &callerInfo); - void SetCallerInfo(const DmBindCallerInfo &callerInfo); - void ClearCallerInfo(); - -private: - bool IsHmlSessionType(); - bool CanUsePincodeFromDp(); - bool IsServiceInfoAuthTypeValid(int32_t authType); - bool IsServiceInfoAuthBoxTypeValid(int32_t authBoxType); - bool IsServiceInfoPinExchangeTypeValid(int32_t pinExchangeType); - bool IsLocalServiceInfoValid(const DistributedDeviceProfile::LocalServiceInfo &localServiceInfo); - void GetLocalServiceInfoInDp(); - bool CheckNeedShowAuthInfoDialog(int32_t errorCode); - void UpdateInputPincodeDialog(int32_t errorCode); - void JoinLnn(const std::string &deviceId, bool isForceJoin = false); - int32_t CheckAuthParamVaild(const std::string &pkgName, int32_t authType, const std::string &deviceId, - const std::string &extra); - int32_t CheckAuthParamVaildExtra(const std::string &extra, const std::string &deviceId); - bool CheckHmlParamValid(JsonObject &jsonObject); - bool CheckProcessNameInWhiteList(const std::string &processName); - void ProcessSourceMsg(); - void ProcessSinkMsg(); - std::string GetAccountGroupIdHash(); - void AbilityNegotiate(); - void HandleMemberJoinImportAuthCode(const int64_t requestId, const int32_t status); - int32_t DeleteAuthCode(); - int32_t GetAuthCode(const std::string &pkgName, std::string &pinCode); - bool IsAuthTypeSupported(const int32_t &authType); - bool IsAuthCodeReady(const std::string &pkgName); - int32_t ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, std::string &addrType); - std::string ParseExtraFromMap(const std::map &bindParam); - std::string GenerateBindResultContent(); - void InitAuthState(const std::string &pkgName, int32_t authType, const std::string &deviceId, - const std::string &extra); - void CompatiblePutAcl(); - void ProcRespNegotiateExt(const int32_t &sessionId); - void ProcRespNegotiate(const int32_t &sessionId); - void GetAuthRequestContext(); - void SinkAuthDeviceFinish(); - void SrcAuthDeviceFinish(); - int32_t CheckTrustState(); - void ProcIncompatible(const int32_t &sessionId); - void MemberJoinAuthRequest(int64_t requestId, int32_t status); - void PutSrcAccessControlList(DmAccesser &accesser, DmAccessee &accessee, const std::string &localUdid); - void PutSinkAccessControlList(DmAccesser &accesser, DmAccessee &accessee, const std::string &localUdid); - void GetCallerInfo(const std::string &pkgName, JsonObject &jsonObject); - -public: - void RequestCredential(); - void GenerateCredential(std::string &publicKey); - void RequestCredentialDone(); - void ResponseCredential(); - bool AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen); - void AuthDeviceFinish(int64_t requestId); - void AuthDeviceError(int64_t requestId, int32_t errorCode); - void GetRemoteDeviceId(std::string &deviceId); - void AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen); - char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams); - int32_t GetSessionKeyIdSync(int64_t requestId); - void OnAuthDeviceDataReceived(const int32_t sessionId, const std::string message); - void OnScreenLocked(); - void HandleDeviceNotTrust(const std::string &udid); - int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); - int32_t DeleteGroup(const std::string &pkgName, int32_t userId, const std::string &deviceId); - int32_t StopAuthenticateDevice(const std::string &pkgName); - void RequestReCheckMsg(); - void ResponseReCheckMsg(); - void RequestReCheckMsgDone(); - void CloseAuthSession(const int32_t sessionId); -private: - int32_t ImportCredential(std::string &deviceId, std::string &publicKey); - void GetAuthParam(const std::string &pkgName, int32_t authType, const std::string &deviceId, - const std::string &extra); - void ParseJsonObject(JsonObject &jsonObject); - void ParseHmlInfoInJsonObject(JsonObject &jsonObject); - void PutSessionKeyAsync(int64_t requestId, std::vector hash); - int32_t DeleteAcl(const std::string &pkgName, const std::string &localUdid, const std::string &remoteUdid, - int32_t bindLevel, const std::string &extra); - void ProcessAuthRequestExt(const int32_t &sessionId); - bool IsAuthFinish(); - void ProcessAuthRequest(const int32_t &sessionId); - int32_t ConfirmProcess(const int32_t &action); - int32_t ConfirmProcessExt(const int32_t &action); - int32_t AddMember(const std::string &pinCode); - int32_t AuthDevice(const std::string &pinCode); - void PutAccessControlList(); - void SinkAuthenticateFinish(); - void SrcAuthenticateFinish(); - std::string GetBundleLable(const std::string &bundleName); - bool IsScreenLocked(); - void CheckAndEndTvDream(); - std::string ConvertSinkVersion(const std::string &version); - void NegotiateRespMsg(const std::string &version); - void SetAuthType(int32_t authType); - int32_t GetTaskTimeout(const char* taskName, int32_t taskTimeOut); - void GetPeerUdidHash(int32_t sessionId, std::string &peerUdidHash); - void DeleteOffLineTimer(int32_t sessionId); - bool IsAllowDeviceBind(); - int32_t GetBindLevel(int32_t bindLevel); - std::string GetBundleName(JsonObject &jsonObject); - int32_t GetBinderInfo(); - void SetProcessInfo(); - int32_t GetCloseSessionDelaySeconds(std::string &delaySecondsStr); - void ConverToFinish(); - bool IsSinkMsgValid(); - bool IsSourceMsgValid(); - void ProcessReqPublicKey(); - int32_t GetTokenIdByBundleName(int32_t userId, std::string &bundleName, int64_t &tokenId); - bool CheckBindLevel(const JsonItemObject &jsonObj, const std::string &key, int32_t &bindLevel); - void RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback); - -private: - std::shared_ptr softbusConnector_; - std::shared_ptr hiChainConnector_; - std::shared_ptr authUiStateMgr_; - std::shared_ptr listener_; - std::shared_ptr adapterMgr_; - std::map> authenticationMap_; - std::shared_ptr authRequestState_ = nullptr; - std::shared_ptr authRequestStateTemp_ = nullptr; - std::shared_ptr authResponseState_ = nullptr; - std::shared_ptr authRequestContext_; - std::shared_ptr authResponseContext_; - std::shared_ptr authMessageProcessor_; - std::shared_ptr timer_; - std::shared_ptr dmAbilityMgr_; - std::shared_ptr hiChainAuthConnector_; - bool isCryptoSupport_ = false; - bool isFinishOfLocal_ = true; - int32_t authTimes_ = 0; - int32_t action_ = USER_OPERATION_TYPE_CANCEL_AUTH; - std::shared_ptr authPtr_; - bool isAddingMember_ = false; - std::string importPkgName_ = ""; - std::string importAuthCode_ = ""; - PeerTargetId peerTargetId_; - std::string remoteDeviceId_ = ""; - std::string dmVersion_ = ""; - bool isAuthDevice_ = false; - bool isAuthenticateDevice_ = false; - int32_t authForm_ = DmAuthForm::ACROSS_ACCOUNT; - std::string remoteVersion_ = ""; - std::atomic authType_ = AUTH_TYPE_UNKNOW; - std::string remoteUdidHash_ = ""; - ProcessInfo processInfo_; - std::mutex srcReqMsgLock_; - bool isNeedProcCachedSrcReqMsg_ = false; - std::string srcReqMsg_ = ""; - int32_t authenticationType_ = USER_OPERATION_TYPE_ALLOW_AUTH; - DistributedDeviceProfile::LocalServiceInfo serviceInfoProfile_; - bool pincodeDialogEverShown_ = false; - std::string bundleName_ = ""; - std::mutex sessionKeyIdMutex_; - std::condition_variable sessionKeyIdCondition_; - std::map> sessionKeyIdAsyncResult_; - bool isWaitingJoinLnnCallback_ = false; - CleanNotifyCallback cleanNotifyCallback_{nullptr}; - std::mutex callerInfoMutex_; - DmBindCallerInfo callerInfo_; - bool callerInfoReady_ = false; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_AUTH_MANAGER_H diff --git a/services/implementation/include/authentication_v2/auth_manager.h.bak b/services/implementation/include/authentication_v2/auth_manager.h.bak deleted file mode 100644 index f0cb9b39d..000000000 --- a/services/implementation/include/authentication_v2/auth_manager.h.bak +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Copyright (c) 2025 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_AUTH_MANAGER_V2_H -#define OHOS_DM_AUTH_MANAGER_V2_H - -#include - -#include "auth_ui_state_manager.h" -#include "dm_auth_manager_base.h" -#include "hichain_auth_connector.h" -#include "hichain_connector.h" -#include "json_object.h" -#include "softbus_connector.h" -#include "softbus_session.h" - -namespace OHOS { -namespace DistributedHardware { -struct DmAuthContext; - -class AuthManager : public AuthManagerBase, - public std::enable_shared_from_this { -public: - AuthManager(std::shared_ptr softbusConnector, - std::shared_ptr hiChainConnector, - std::shared_ptr listener, - std::shared_ptr hiChainAuthConnector); - virtual ~AuthManager(); - - // External API begin - /** - * @tc.name: DmAuthManager::OnUserOperation - * @tc.desc: User Operation of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - virtual int32_t OnUserOperation(int32_t action, const std::string ¶ms) = 0; - - /** - * @tc.name: AuthManager::GeneratePincode - * @tc.desc: Generate Pincode of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - int32_t BindTarget(const std::string &sessionName, const PeerTargetId &targetId, - const std::map &bindParam, int sessionId, uint64_t logicalSessionId); - - /** - * @tc.name: AuthManager::OnUserOperation - * @tc.desc: User Operation of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - std::string GeneratePincode(); - - /** - * @tc.name: AuthManager::ImportAuthCode - * @tc.desc: Import auth code - * @tc.type: FUNC - */ - int32_t ImportAuthCode(const std::string &sessionName, const std::string &authCode); - - /** - * @tc.name: AuthManager::RegisterUiStateCallback - * @tc.desc: Register ui state callback - * @tc.type: FUNC - */ - int32_t RegisterUiStateCallback(const std::string sessionName); - - /** - * @tc.name: AuthManager::UnRegisterUiStateCallback - * @tc.desc: Unregister ui state callback - * @tc.type: FUNC - */ - int32_t UnRegisterUiStateCallback(const std::string sessionName); - - /** - * @tc.name: AuthManager::UnAuthenticateDevice - * @tc.desc: UnAuthenticate Device of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - int32_t UnAuthenticateDevice(const std::string &sessionName, const std::string &udid, int32_t bindLevel); - - /** - * @brief UnBind device. - * @param sessionName package name. - * @param deviceId device id. - * @return Return 0 if success. - */ - int32_t UnBindDevice(const std::string &sessionName, const std::string &udid, - int32_t bindLevel, const std::string &extra); - - void HandleDeviceNotTrust(const std::string &udid); - - int32_t RegisterAuthenticationType(int32_t authenticationType); - void OnScreenLocked(); - int32_t StopAuthenticateDevice(const std::string &sessionName); - // External API begin end - - // Internal API begin - void SetAuthContext(std::shared_ptr context); - std::shared_ptr GetAuthContext(); - static bool IsHmlSessionType(const std::string &sessionType); - int32_t GetTokenIdByBundleName(int32_t userId, std::string &bundleName, int64_t &tokenId); - void GetBindTargetParams(std::string &pkgName, PeerTargetId &targetId, - std::map &bindParam); - void SetBindTargetParams(const PeerTargetId &targetId); - int32_t GetReason(); - - // Internal API end - void RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback); - void ClearSoftbusSessionCallback(); - void PrepareSoftbusSessionCallback(); - void GetCallerInfo(DmBindCallerInfo &callerInfo); - void SetCallerInfo(const DmBindCallerInfo &callerInfo); - -protected: - std::shared_ptr context_; - std::map bindParam_; - PeerTargetId targetId_; - - int32_t GetPinCode(std::string &code); - void GetRemoteDeviceId(std::string &deviceId); -private: - void ParseHmlInfoInJsonObject(const JsonObject &jsonObject); - void ParseJsonObject(const JsonObject &jsonObject); - void GetAuthParam(const std::string &sessionName, int32_t authType, - const std::string &deviceId, const std::string &extra); - std::string GetBundleName(const JsonObject &jsonObject); - void SetAuthType(int32_t authType); - bool IsAuthTypeSupported(const int32_t &authType); - bool IsAuthCodeReady(const std::string &sessionName); - int32_t CheckAuthParamVaild(const std::string &sessionName, int32_t authType, - const std::string &deviceId, const std::string &extra); - void InitAuthState(const std::string &sessionName, int32_t authType, - const std::string &deviceId, const std::string &extra); - int32_t AuthenticateDevice(const std::string &sessionName, int32_t authType, - const std::string &deviceId, const std::string &extra); - void ParseUltrasonicSide(const JsonObject &jsonObject); -}; - -class AuthSrcManager : public AuthManager { -public: - AuthSrcManager(std::shared_ptr softbusConnector, - std::shared_ptr hiChainConnector, - std::shared_ptr listener, - std::shared_ptr hiChainAuthConnector); - virtual ~AuthSrcManager() override = default; - - // External API begin - int32_t OnUserOperation(int32_t action, const std::string ¶ms) override; - // External API end - - // IDmDeviceAuthCallback implement begin - bool AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) override; - void AuthDeviceError(int64_t requestId, int32_t errorCode) override; - void AuthDeviceFinish(int64_t requestId) override; - void AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) override; - char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) override; - // IDmDeviceAuthCallback implement end - - // ISoftbusSessionCallback implement begin - void OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) override; - void OnSessionClosed(int32_t sessionId) override; - void OnSessionDisable() override; - void OnDataReceived(int32_t sessionId, std::string message) override; - - bool GetIsCryptoSupport() override; - // ISoftbusSessionCallback implement end -}; - -class AuthSinkManager : public AuthManager { -public: - AuthSinkManager(std::shared_ptr softbusConnector, - std::shared_ptr hiChainConnector, - std::shared_ptr listener, - std::shared_ptr hiChainAuthConnector); - virtual ~AuthSinkManager() override = default; - - // External API begin - int32_t OnUserOperation(int32_t action, const std::string ¶ms) override; - // External API end - - // IDmDeviceAuthCallback implement begin - bool AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) override; - void AuthDeviceError(int64_t requestId, int32_t errorCode) override; - void AuthDeviceFinish(int64_t requestId) override; - void AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) override; - char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) override; - // IDmDeviceAuthCallback implement end - - // ISoftbusSessionCallback implement begin - void OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) override; - void OnSessionClosed(int32_t sessionId) override; - void OnDataReceived(int32_t sessionId, std::string message) override; - bool GetIsCryptoSupport() override; - // ISoftbusSessionCallback implement end -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_AUTH_MANAGER_V2_H \ No newline at end of file diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h.bak b/services/implementation/include/authentication_v2/dm_auth_context.h.bak deleted file mode 100644 index e54240926..000000000 --- a/services/implementation/include/authentication_v2/dm_auth_context.h.bak +++ /dev/null @@ -1,257 +0,0 @@ -/* - * Copyright (c) 2025 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_AUTH_CONTEXT_V2_H -#define OHOS_DM_AUTH_CONTEXT_V2_H -#include -#include - -#include "access_control_profile.h" -#include "authentication.h" -#include "auth_ui_state_manager.h" -#include "dm_ability_manager.h" -#include "dm_anonymous.h" -#include "dm_auth_message_processor.h" -#include "dm_constants.h" -#include "dm_device_info.h" -#include "dm_log.h" -#include "dm_timer.h" -#include "hichain_auth_connector.h" -#include "hichain_connector.h" -#include "softbus_connector.h" -#include "softbus_session.h" - -namespace OHOS { -namespace DistributedHardware { - -class DmAuthStateMachine; -class DmAuthMessageProcessor; - -using CleanNotifyCallback = std::function; - -// PIN Code Authentication Type -enum DmAuthType : int32_t { - AUTH_TYPE_CRE = 0, - AUTH_TYPE_PIN, // Input PIN code - AUTH_TYPE_QR_CODE, // Not used in the new protocol - AUTH_TYPE_NFC, - AUTH_TYPE_NO_INTER_ACTION, // Not used in the new protocol - AUTH_TYPE_IMPORT_AUTH_CODE, // Import PIN code - AUTH_TYPE_PIN_ULTRASONIC, // Ultrasonic PIN code - AUTH_TYPE_UNKNOW, // Not used in the new protocol -}; - -enum DmAuthDirection { - DM_AUTH_SOURCE = 0, - DM_AUTH_SINK, -}; - -enum DmBindType { - DM_AUTH_USERID = 1, - DM_AUTH_SYSTEM_SERVICE, - DM_AUTH_APP_SERVICE, - DM_AUTH_DEVICEID, -}; - -enum DmAuthSide { - DM_AUTH_LOCAL_SIDE = 0, - DM_AUTH_REMOTE_SIDE, -}; - -enum DmAuthScope { - DM_AUTH_SCOPE_DEVICE = 1, - DM_AUTH_SCOPE_USER, - DM_AUTH_SCOPE_APP, -}; - -enum DmRole { - DM_ROLE_UNKNOWN = 0, - DM_ROLE_USER = 1, - DM_ROLE_SA, - DM_ROLE_FA, -}; - -enum { - DM_UNKNOWN_TYPE = 0, - DM_SAME_ACCOUNT_TYPE = 1, - DM_SHARE_TYPE = 2, - DM_POINT_TO_POINT_TYPE = 256, - DM_SAME_GROUP_TYPE = 3, -}; - -enum DmUltrasonicInfo { - // Forward means the pincode is generated at sink side, then send by ultrasonic from sink to source side. - DM_Ultrasonic_Forward = 0, - // Reverse means the pincode is generated at source side, then send by ultrasonic from source to sink side. - DM_Ultrasonic_Reverse = 1, - DM_Ultrasonic_Invalid = 2, -}; - -// Used for one-touch pairing -struct DmPeerTargetAddress { - // directly establish a Bluetooth connection - std::string peerBrMacAddress; - std::string peerBleMacAddress; - std::string peerWifiMacAddress; - std::string peerActionMacAddress; - - std::string peerWifiChannel; - std::string peerWifiIp; - uint16_t peerWifiPort; -}; - -struct DmPeerTarget { - DmBindType peerType; - std::string peerDeviceId; - int64_t peerServiceId; - int64_t peerSaTokenId; - std::string peerBundleName; - DmPeerTargetAddress peerTargetAddress; -}; - -struct DmAccess { - std::string deviceName; - int32_t deviceType; // Device types such as PC, mobile, watch, large screen, etc. - std::string deviceId; - std::string deviceIdHash; - std::string addr; - int32_t userId{-1}; - int32_t displayId{-1}; // Logical screen ID, used for query userId - std::string accountId; - std::string accountIdHash; - int64_t tokenId; - std::string tokenIdHash; - std::string networkId; - std::string bundleName; // Stores the bundleName, HAP -> bundleName in BMS, SA -> process name - std::string pkgName; // store pkgName set by client - std::string language; - int64_t serviceId; // Reserved field, to be used in HM 6.0 - std::string accesserHapSignature; - int32_t bindLevel; - int32_t lnnBindType; - int32_t transmitBindType; - std::string lnnCredentialId; // User-level credential ID - std::string transmitCredentialId; // Application-level credential ID - std::string lnnPublicKey; // User-level public key - std::string transmitPublicKey; // Application-level public key - std::vector bindType; // such as DM_AUTH_CREDENTIAL_ACCOUNT_RELATED - std::string publicKey; - int32_t status; // Indicates whether the service is in the foreground or background - int32_t sessionKeyId; // Used as key delivery material, retrieves the SK from the bus - int32_t transmitSessionKeyId; // Permanent application SKID on this end, returned by DP for ACL updates and aging - int32_t lnnSessionKeyId{0}; // Permanent user SKID on this end, returned by DP for ACL updates and aging - int64_t transmitSkTimeStamp; // Used for aging, time is 2 days, application-level credential timestamp - int64_t lnnSkTimeStamp{0}; // Used for aging, time is 2 days, user-level credential timestamp - int64_t skTimeStamp; // Used for aging, time is 2 days - bool isAuthed; - bool isOnline; - bool isGenerateLnnCredential{true}; - bool isPutLnnAcl{true}; - std::string dmVersion; - std::string edition; // Used for compatibility before version 5.1.0, assists in version negotiation - std::string aclTypeList; // Trust relationship list, used for data aging, KV format - std::string credTypeList; - std::string aclStrList; - std::map credentialInfos; // map: , cred is string tranformed by json - std::map aclProfiles; - // construct for old version compatible start - // In the scenario of compatibility between the new and old protocols, it is necessary to - // send both the new and old protocol messages simultaneously in the 80 message when - // authType == import. Therefore, it is required to define these fields for compatibility processing. - std::string accountGroupIdHash; - int32_t oldBindLevel; - std::string oldBundleName; - // construct for old version compatible end - std::string extraInfo; // Expandable field, JSON format, KV structure -}; - -struct DmAuthContext { - bool isOnline; - uint64_t logicalSessionId; - DmMessageType msgType; - int32_t sessionId; - int64_t requestId; // HiChain authentication ID - DMLocalServiceInfoAuthBoxType authBoxType{DMLocalServiceInfoAuthBoxType::STATE3}; // Authentication box type - UiAction pinInputResult; - // Authorization result (using 0, 1, 6, representing single use, cancel, and always trust, enum UiAction) - UiAction confirmOperation{UiAction::USER_OPERATION_TYPE_ALLOW_AUTH}; - DmAuthType authType{DmAuthType::AUTH_TYPE_PIN}; // PIN code, ultrasonic PIN code, imported PIN code - std::vector authTypeList; - uint32_t currentAuthTypeIdx{0}; - int32_t inputPinAuthFailTimes{0}; // Number of failed PIN authentication attempts, exceeding 3 results in failure - std::string pinCode{""}; - bool serviceInfoFound{false}; - // Link delay release time, does not automatically disconnect after - // authorization (used for specific business needs), reserved field - int32_t connDelayCloseTime; - int32_t reason{DM_OK}; - int32_t reply; - int32_t state; - int32_t hmlActionId = 0; - bool authenticating; // Indicator whether authentication is in progress - bool successFinished{false}; - bool isAppCredentialVerified{false}; // Whether the application credential has been verified - bool hmlEnable160M{false}; - std::string pkgName; // Business-provided identifier, custom-defined by business, carries risk of spoofing - std::string pkgLabel; - std::string importCodeBundleName; // Bundle name for imported PIN code - std::string appThumbnail; // Application thumbnail - // Description of the operation this binding is used for, displayed in authorization dialog - std::string appOperation; - // Custom business field, provides detailed information to the user about this binding operation - std::string customData; - std::string connSessionType; - std::string extraInfo; // Expandable field, key-value structure - DmAuthDirection direction; // Indicator of authentication direction - ProcessInfo processInfo; - DmPeerTarget peerTarget; - DmUltrasonicInfo ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Forward; // Ultrasonic information - DmAccess accesser; - DmAccess accessee; - std::multimap proxy; // Multimap where the key is the accessor and the value is the accesssee - - std::shared_ptr authStateMachine; - std::shared_ptr authUiStateMgr; - std::shared_ptr hiChainConnector; - std::shared_ptr hiChainAuthConnector; - std::shared_ptr authMessageProcessor; - std::shared_ptr softbusConnector; - std::shared_ptr listener; - std::shared_ptr authPtr; // Pointer to authentication interface - std::shared_ptr timer; - std::string transmitData; // Data returned from onTransmit function - std::string importPkgName = ""; - std::string importAuthCode = ""; - std::map> authenticationMap; - PeerTargetId peerTargetId; - bool pinNegotiateStarted{false}; - bool isAuthenticateDevice{false}; // Whether device authentication is in progress - bool needBind{true}; - bool needAgreeCredential{true}; - bool needAuth{true}; - - CleanNotifyCallback cleanNotifyCallback{nullptr}; - - std::string GetDeviceId(DmAuthSide side); - int32_t GetUserId(DmAuthSide side); - std::string GetCredentialId(DmAuthSide side, DmAuthScope authorizedScope); - std::string GetPublicKey(DmAuthSide side, DmAuthScope authorizedScope); - void SetCredentialId(DmAuthSide side, DmAuthScope authorizedScope, const std::string &credentialId); - void SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope, const std::string &publicKey); - std::string GetAccountId(DmAuthSide side); -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_AUTH_CONTEXT_V2_H diff --git a/services/implementation/include/authentication_v2/dm_auth_manager_base.h.bak b/services/implementation/include/authentication_v2/dm_auth_manager_base.h.bak deleted file mode 100644 index 2ceff22d2..000000000 --- a/services/implementation/include/authentication_v2/dm_auth_manager_base.h.bak +++ /dev/null @@ -1,258 +0,0 @@ -/* - * Copyright (c) 2025 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_AUTH_ADAPTER_V2_H -#define OHOS_DM_AUTH_ADAPTER_V2_H - -#include -#include -#include -#include - -#include "softbus_session_callback.h" -#include "softbus_connector_callback.h" -#include "hichain_connector_callback.h" -#include "auth_request_state.h" -#include "auth_response_state.h" -#include "dm_device_info.h" - -namespace OHOS { -namespace DistributedHardware { -extern const char* TAG_DMVERSION; -extern const char* TAG_DM_VERSION_V2; // compatible for new and old protocol -extern const char* TAG_EDITION; -extern const char* TAG_DATA; -extern const char* TAG_DATA_LEN; -extern const char* TAG_BUNDLE_NAME; -extern const char* TAG_BUNDLE_NAME_V2; -extern const char* TAG_PEER_BUNDLE_NAME; -extern const char* TAG_PEER_BUNDLE_NAME_V2; -extern const char* TAG_PEER_PKG_NAME; -extern const char* TAG_BIND_LEVEL; -extern const char* TAG_REPLY; -extern const char* TAG_APP_THUMBNAIL2; // Naming Add 2 to resolve conflicts with TAG_APP_THUMBNAIL -extern const char* TAG_AUTH_FINISH; -extern const char* TAG_LOCAL_USERID; -extern const char* TAG_LOCAL_DEVICE_ID; -extern const char* TAG_IDENTICAL_ACCOUNT; -extern const char* TAG_ACCOUNT_GROUPID; -extern const char* TAG_HAVE_CREDENTIAL; -extern const char* TAG_ISONLINE; -extern const char* TAG_AUTHED; -extern const char* TAG_LOCAL_ACCOUNTID; -extern const char* TAG_TOKENID; -extern const char* TAG_HOST_PKGLABEL; -extern const char* TAG_REMOTE_DEVICE_NAME; -extern const char* TAG_HOST; - -extern const char* APP_OPERATION_KEY; -extern const char* TARGET_PKG_NAME_KEY; -extern const char* CUSTOM_DESCRIPTION_KEY; -extern const char* CANCEL_DISPLAY_KEY; -extern const char* BUNDLE_NAME_KEY; - -extern const char* AUTHENTICATE_TIMEOUT_TASK; -extern const char* NEGOTIATE_TIMEOUT_TASK; -extern const char* CONFIRM_TIMEOUT_TASK; -extern const char* INPUT_TIMEOUT_TASK; -extern const char* SESSION_HEARTBEAT_TIMEOUT_TASK; -extern const char* WAIT_REQUEST_TIMEOUT_TASK; -extern const char* AUTH_DEVICE_TIMEOUT_TASK; -extern const char* WAIT_PIN_AUTH_TIMEOUT_TASK; -extern const char* WAIT_NEGOTIATE_TIMEOUT_TASK; -extern const char* ADD_TIMEOUT_TASK; -extern const char* WAIT_SESSION_CLOSE_TIMEOUT_TASK; -extern const char* CLOSE_SESSION_TASK_SEPARATOR; - -extern const int32_t AUTHENTICATE_TIMEOUT; -extern const int32_t CONFIRM_TIMEOUT; -extern const int32_t NEGOTIATE_TIMEOUT; -extern const int32_t INPUT_TIMEOUT; -extern const int32_t ADD_TIMEOUT; -extern const int32_t WAIT_NEGOTIATE_TIMEOUT; -extern const int32_t WAIT_REQUEST_TIMEOUT; -extern const int32_t CLONE_AUTHENTICATE_TIMEOUT; -extern const int32_t CLONE_CONFIRM_TIMEOUT; -extern const int32_t CLONE_NEGOTIATE_TIMEOUT; -extern const int32_t CLONE_ADD_TIMEOUT; -extern const char* GET_ULTRASONIC_PIN_TIMEOUT_TASK; -extern const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT; -extern const int32_t CLONE_WAIT_REQUEST_TIMEOUT; -extern const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT; -extern const int32_t CLONE_PIN_AUTH_TIMEOUT; -extern const int32_t HML_SESSION_TIMEOUT; -extern const int32_t SESSION_HEARTBEAT_TIMEOUT; -extern const int32_t PIN_AUTH_TIMEOUT; -extern const int32_t EVENT_TIMEOUT; - -extern const int32_t DM_AUTH_TYPE_MAX; -extern const int32_t DM_AUTH_TYPE_MIN; -extern const int32_t MIN_PIN_TOKEN; -extern const int32_t MAX_PIN_TOKEN; - -typedef struct DmBindCallerInfo { - int32_t userId = -1; - int32_t tokenId = -1; - std::string bundleName = ""; - std::string hostPkgLabel = ""; -} DmBindCallerInfo; - -using CleanNotifyCallback = std::function; - -class AuthManagerBase : public ISoftbusSessionCallback, - public ISoftbusConnectorCallback, - public IHiChainConnectorCallback, - public IDmDeviceAuthCallback { -public: - virtual int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, - const std::string &extra); - - virtual int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel); - - virtual int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, - int32_t bindLevel, const std::string &extra); - - virtual void OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result); - - virtual void OnSessionClosed(const int32_t sessionId); - - virtual void OnSessionDisable(); - - virtual void OnDataReceived(const int32_t sessionId, const std::string message); - - virtual void OnAuthDeviceDataReceived(int32_t sessionId, std::string message); - - virtual void OnSoftbusJoinLNNResult(const int32_t sessionId, const char *networkId, int32_t result); - - virtual void OnGroupCreated(int64_t requestId, const std::string &groupId); - - virtual void OnMemberJoin(int64_t requestId, int32_t status); - - virtual int32_t EstablishAuthChannel(const std::string &deviceId); - - virtual void StartNegotiate(const int32_t &sessionId); - - virtual void RespNegotiate(const int32_t &sessionId); - - virtual void SendAuthRequest(const int32_t &sessionId); - - virtual int32_t StartAuthProcess(const int32_t &action); - - virtual void StartRespAuthProcess(); - - virtual int32_t CreateGroup(); - - virtual int32_t ProcessPincode(const std::string &pinCode); - - virtual std::string GetConnectAddr(std::string deviceId); - - virtual int32_t JoinNetwork(); - - virtual void AuthenticateFinish(); - - virtual bool GetIsCryptoSupport(); - - virtual int32_t SetAuthRequestState(std::shared_ptr authRequestState); - - virtual int32_t SetAuthResponseState(std::shared_ptr authResponseState); - - virtual int32_t GetPinCode(std::string &code); - - virtual std::string GenerateGroupName(); - - virtual void HandleAuthenticateTimeout(std::string name); - - virtual std::string GeneratePincode(); - - virtual void ShowConfigDialog(); - - virtual void ShowAuthInfoDialog(bool authDeviceError = false); - - virtual void ShowStartAuthDialog(); - - virtual int32_t OnUserOperation(int32_t action, const std::string ¶ms); - - virtual int32_t SetPageId(int32_t pageId); - - virtual int32_t SetReasonAndFinish(int32_t reason, int32_t state); - - virtual bool IsIdenticalAccount(); - - virtual int32_t RegisterUiStateCallback(const std::string pkgName); - - virtual int32_t UnRegisterUiStateCallback(const std::string pkgName); - - virtual int32_t ImportAuthCode(const std::string &pkgName, const std::string &authCode); - - virtual int32_t BindTarget(const std::string &pkgName, const PeerTargetId &targetId, - const std::map &bindParam, int sessionId, uint64_t logicalSessionId); - - virtual int32_t RegisterAuthenticationType(int32_t authenticationType); - - virtual int32_t StopAuthenticateDevice(const std::string &pkgName); - - virtual void OnScreenLocked() = 0; - - virtual void HandleDeviceNotTrust(const std::string &udid) = 0; - - virtual int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); - - // New interface added in version 5.1.0 - virtual int32_t GetReason(); - // When switching from the new protocol to the old protocol, the previous parameters - // need to be obtained for use by the old protocol - virtual void GetBindTargetParams(std::string &pkgName, PeerTargetId &targetId, - std::map &bindParam); - - virtual void SetBindTargetParams(const PeerTargetId &targetId); - // Register the notification function when the auth_mgr event is complete. - virtual void RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback); - - /** - * @brief Classical authMgr is global, single-frame collabration with double-frame device - * need it. If we start bind with single-frame device, we need clear dsoftbus callback - * to avoid the classical authMgr affect the single to single logical. - * For new protocal, the source and sink authMgr lifecycle obey the bind session, no need - * to process it. - */ - virtual void ClearSoftbusSessionCallback(); - /** - * @brief Classical authMgr is global, if we use classical logic, we need prepare the callback. - */ - virtual void PrepareSoftbusSessionCallback(); - - // Public functions - static std::string ConvertSrcVersion(const std::string &version, const std::string &edition); - static int32_t DmGetUserId(int32_t displayId); - static int32_t EndDream(); - bool IsTransferReady(); - void SetTransferReady(bool version); - void EnableInsensibleSwitching(); - void DisableInsensibleSwitching(); - int32_t ParseAuthType(const std::map &bindParam, int32_t &authType); - virtual void GetCallerInfo(DmBindCallerInfo &callerInfo) = 0; - virtual void SetCallerInfo(const DmBindCallerInfo &callerInfo) = 0; -protected: - bool NeedInsensibleSwitching(); - bool isTransferReady_{true}; - /** - For old protocol, when insensible switching is true, no new session needs to be created, - and the actual method 80 message is not sent. - */ - bool insensibleSwitching{false}; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_AUTH_ADAPTER_V2_H diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h.bak b/services/implementation/include/authentication_v2/dm_auth_state.h.bak deleted file mode 100644 index 51ed72ec0..000000000 --- a/services/implementation/include/authentication_v2/dm_auth_state.h.bak +++ /dev/null @@ -1,509 +0,0 @@ -/* - * Copyright (c) 2025 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_AUTH_STATE_V2_H -#define OHOS_DM_AUTH_STATE_V2_H -#define TYPE_TV_ID 0x9C - -#include - -#include "access_control_profile.h" -#include "dm_auth_context.h" - -namespace OHOS { -namespace DistributedHardware { -const char* const FILED_CRED_OWNER = "credOwner"; -const char* const FILED_DEVICE_ID = "deviceId"; -const char* const FILED_USER_ID = "userId"; -const char* const FILED_DEVICE_ID_HASH = "deviceIdHash"; -const char* const FILED_PEER_USER_SPACE_ID = "peerUserSpaceId"; -const char* const FILED_CRED_ID = "credId"; -const char* const FILED_CRED_TYPE = "credType"; -const char* const FILED_AUTHORIZED_SCOPE = "authorizedScope"; -const char* const FILED_AUTHORIZED_APP_LIST = "authorizedAppList"; -const char* const FILED_SUBJECT = "subject"; - -// State Types -enum class DmAuthStateType { - AUTH_IDLE_STATE = 0, // When the device is initialized - // source end state - AUTH_SRC_START_STATE = 1, // User triggers BindTarget - AUTH_SRC_NEGOTIATE_STATE = 2, // Receive softbus callback OnSessionOpened, send 80 message - AUTH_SRC_CONFIRM_STATE = 3, // Receive 90 authorization result message, send 100 message - AUTH_SRC_PIN_NEGOTIATE_START_STATE = 4, // Start negotiating PIN code, receive 110 authorization message - // or rollback or 90 jump - AUTH_SRC_PIN_INPUT_STATE = 5, // Enter PIN - AUTH_SRC_REVERSE_ULTRASONIC_START_STATE = 6, - AUTH_SRC_REVERSE_ULTRASONIC_DONE_STATE = 7, - AUTH_SRC_FORWARD_ULTRASONIC_START_STATE = 8, - AUTH_SRC_FORWARD_ULTRASONIC_DONE_STATE = 9, - AUTH_SRC_PIN_AUTH_START_STATE = 10, // Start authentication and send 120 message. - AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE = 11, // Receive 130 authentication PIN result message, send 121 message - AUTH_SRC_PIN_AUTH_DONE_STATE = 12, // Receive 131 authentication PIN result message, call processData - AUTH_SRC_CREDENTIAL_EXCHANGE_STATE = 13, // Trigger the Onfinish callback event and send a 140 message - AUTH_SRC_CREDENTIAL_AUTH_START_STATE = 14, // Received 150 encrypted messages, sent 160 messages - AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE = 15, // 收到170凭据认证报文,发送161报文 - AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE = 16, // Received 170 credential authentication message, sent 161 message - AUTH_SRC_DATA_SYNC_STATE = 17, // Received 190 message, sent 200 message - AUTH_SRC_FINISH_STATE = 18, // Received 201 message - - // sink end state - AUTH_SINK_START_STATE = 50, // Bus trigger OnSessionOpened - AUTH_SINK_NEGOTIATE_STATE = 51, // Received 80 trusted relationship negotiation message, send 90 message - AUTH_SINK_CONFIRM_STATE = 52, // Received 100 user authorization messages, sent 110 messages - AUTH_SINK_PIN_NEGOTIATE_START_STATE = 53, // Start negotiating PIN code, active migration or error rollback - AUTH_SINK_PIN_DISPLAY_STATE = 54, // Generate and display PIN - AUTH_SINK_REVERSE_ULTRASONIC_START_STATE = 55, - AUTH_SINK_REVERSE_ULTRASONIC_DONE_STATE = 56, - AUTH_SINK_FORWARD_ULTRASONIC_START_STATE = 57, - AUTH_SINK_FORWARD_ULTRASONIC_DONE_STATE = 58, - AUTH_SINK_PIN_AUTH_START_STATE = 59, // Receive 120 authentication PIN message, send 130 message - AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE = 60, // Received 121 authentication PIN message, send 131 message - AUTH_SINK_PIN_AUTH_DONE_STATE = 61, // Trigger the Onfinish callback event - AUTH_SINK_CREDENTIAL_EXCHANGE_STATE = 62, // Received 140 encrypted messages, sent 150 messages - AUTH_SINK_CREDENTIAL_AUTH_START_STATE = 63, // Receive 160 authentication message, send 170 message - AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE = 64, // Received 161 credential negotiation message, - AUTH_SINK_DATA_SYNC_STATE = 65, // Received 180 synchronization message, send 190 message - AUTH_SINK_FINISH_STATE = 66, // Received 200 end message, send 201 message -}; - -// Credential Addition Method -enum DmAuthCredentialAddMethod : uint8_t { - DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE = 1, // Generate - DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT, // Import -}; - -// Credential Subject -enum DmAuthCredentialSubject : uint8_t { - DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY = 1, // Main Control - DM_AUTH_CREDENTIAL_SUBJECT_SUPPLEMENT, // Accessories -}; - -// Credentials and account association -enum DmAuthCredentialAccountRelation : uint8_t { - DM_AUTH_CREDENTIAL_INVALID = 0, // Invalid - DM_AUTH_CREDENTIAL_ACCOUNT_RELATED = 1, // Account related - DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED = 2, // Account independent - DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS = 3, // Share -}; - -// Key Type -enum DmAuthKeyFormat : uint8_t { - DM_AUTH_KEY_FORMAT_SYMM_IMPORT = 1, // Symmetric key (supported only for import) - DM_AUTH_KEY_FORMAT_ASYMM_IMPORT, // Asymmetric key public key (supported only for import) - DM_AUTH_KEY_FORMAT_ASYMM_GENERATE, // Asymmetric key (supported only for generation) - DM_AUTH_KEY_FORMAT_X509, // X509 certificate -}; - -// Algorithm type -enum DmAuthAlgorithmType : uint8_t { - DM_AUTH_ALG_TYPE_AES256 = 1, // AES256 - DM_AUTH_ALG_TYPE_AES128, // AES128 - DM_AUTH_ALG_TYPE_P256, // P256 - DM_AUTH_ALG_TYPE_ED25519 // ED25519 -}; - -// Credential proof type -enum DmAuthCredentialProofType : uint8_t { - DM_AUTH_CREDENTIAL_PROOF_PSK = 1, // PSK - DM_AUTH_CREDENTIAL_PROOF_PKI, // PKI -}; - -enum DmCredType : uint8_t { - ACCOUNT_RELATED = 1, - ACCOUNT_UNRELATED, - ACCOUNT_ACROSS -}; - -enum DmAuthorizedScope : uint8_t { - SCOPE_DEVICE = 1, - SCOPE_USER, - SCOPE_APP, -}; - -enum DM_SUBJECT : uint8_t { - SUBJECT_PRIMARY = 1, - SUBJECT_SECONDARY, -}; - -class DmAuthState { -public: - virtual ~DmAuthState() {}; - virtual DmAuthStateType GetStateType() = 0; - virtual int32_t Action(std::shared_ptr context) = 0; - void SourceFinish(std::shared_ptr context); - void SinkFinish(std::shared_ptr context); - std::string GenerateBindResultContent(std::shared_ptr context); - static bool IsScreenLocked(); - static int32_t GetTaskTimeout(std::shared_ptr context, const char* taskName, int32_t taskTimeOut); - static void HandleAuthenticateTimeout(std::shared_ptr context, std::string name); - static bool IsImportAuthCodeCompatibility(DmAuthType authType); - - void SetAclExtraInfo(std::shared_ptr context); - void SetAclInfo(std::shared_ptr context); - int32_t GetAclBindType(std::shared_ptr context, std::string credId); - static bool CheckProcessNameInWhiteList(const std::string &processName); - int32_t GetOutputState(const std::string &processName, int32_t state); - int32_t GetOutputReplay(const std::string &processName, int32_t replay); - static uint64_t GetSysTimeMs(); - static void DeleteAcl(std::shared_ptr context, - const DistributedDeviceProfile::AccessControlProfile &profile); -protected: - bool NeedReqUserConfirm(std::shared_ptr context); - bool NeedAgreeCredential(std::shared_ptr context); - bool NeedAgreeAcl(std::shared_ptr context); - uint32_t GetCredType(std::shared_ptr context, const JsonItemObject &credInfo); - uint32_t GetCredentialType(std::shared_ptr context, const JsonItemObject &credInfo); - bool HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList); - void SetProcessInfo(std::shared_ptr context); -}; - -class AuthSrcConfirmState : public DmAuthState { -public: - virtual ~AuthSrcConfirmState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -private: - void NegotiateCredential(std::shared_ptr context, JsonObject &credTypeNegoRsult); - void NegotiateAcl(std::shared_ptr context, JsonObject &aclNegoRsult); - void GetSrcCredentialInfo(std::shared_ptr context, JsonObject &credInfo); - void GetIdenticalCredentialInfo(std::shared_ptr context, JsonObject &credInfo); - void GetShareCredentialInfo(std::shared_ptr context, JsonObject &credInfo); - void GetP2PCredentialInfo(std::shared_ptr context, JsonObject &credInfo); - void GetSrcAclInfo(std::shared_ptr context, JsonObject &credInfo, JsonObject &aclInfo); - void GetSrcAclInfoForP2P(std::shared_ptr context, - const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, JsonObject &aclInfo); - bool IdenticalAccountAclCompare(std::shared_ptr context, - const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); - bool ShareAclCompare(std::shared_ptr context, - const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); - bool Point2PointAclCompare(std::shared_ptr context, - const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); - bool LnnAclCompare(std::shared_ptr context, - const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); - bool CheckCredIdInAcl(std::shared_ptr context, - const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, uint32_t bindType); - void CheckCredIdInAclForP2P(std::shared_ptr context, std::string &credId, - const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, uint32_t bindType, - bool &checkResult); - void GetSrcCredType(std::shared_ptr context, JsonObject &credInfo, JsonObject &aclInfo, - JsonObject &credTypeJson); - void GetSrcCredTypeForP2P(std::shared_ptr context, const JsonItemObject &credObj, - JsonObject &aclInfo, JsonObject &credTypeJson, int32_t credType, std::vector &deleteCredInfo); -}; - -class AuthSinkStatePinAuthComm { -public: - static bool IsPinCodeValid(int32_t numpin); - static bool IsPinCodeValid(const std::string& strpin); - static bool IsAuthCodeReady(std::shared_ptr context); - static void GeneratePincode(std::shared_ptr context); - static int32_t ShowAuthInfoDialog(std::shared_ptr context); -private: - static void HandleSessionHeartbeat(std::shared_ptr context, std::string name); -}; - -class AuthSinkConfirmState : public DmAuthState { -public: - virtual ~AuthSinkConfirmState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -private: - void NegotiateCredential(std::shared_ptr context, JsonObject &credTypeNegoRsult); - void NegotiateAcl(std::shared_ptr context, JsonObject &aclNegoRsult); - int32_t ShowConfigDialog(std::shared_ptr context); - void ReadServiceInfo(std::shared_ptr context); - void MatchFallBackCandidateList(std::shared_ptr context, DmAuthType authType); - int32_t ProcessBindAuthorize(std::shared_ptr context); - int32_t ProcessNoBindAuthorize(std::shared_ptr context); - std::string GetCredIdByCredType(std::shared_ptr context, int32_t credType); -}; - -class AuthSrcPinNegotiateStartState : public DmAuthState { -public: - virtual ~AuthSrcPinNegotiateStartState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -private: - int32_t NegotiatePinAuth(std::shared_ptr context, bool firstTime); - int32_t ProcessCredAuth(std::shared_ptr context); - int32_t ProcessPinBind(std::shared_ptr context); - std::string GetCredIdByCredType(std::shared_ptr context, int32_t credType); -}; - -class AuthSrcPinInputState : public DmAuthState { -public: - virtual ~AuthSrcPinInputState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -private: - int32_t ShowStartAuthDialog(std::shared_ptr context); -}; - -class AuthSinkPinNegotiateStartState : public DmAuthState { -public: - virtual ~AuthSinkPinNegotiateStartState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSinkPinDisplayState : public DmAuthState { -public: - virtual ~AuthSinkPinDisplayState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSrcReverseUltrasonicStartState : public DmAuthState { -public: - virtual ~AuthSrcReverseUltrasonicStartState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSrcReverseUltrasonicDoneState : public DmAuthState { -public: - virtual ~AuthSrcReverseUltrasonicDoneState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSrcForwardUltrasonicStartState : public DmAuthState { -public: - virtual ~AuthSrcForwardUltrasonicStartState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSrcForwardUltrasonicDoneState : public DmAuthState { -public: - virtual ~AuthSrcForwardUltrasonicDoneState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSinkReverseUltrasonicStartState : public DmAuthState { -public: - virtual ~AuthSinkReverseUltrasonicStartState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSinkReverseUltrasonicDoneState : public DmAuthState { -public: - virtual ~AuthSinkReverseUltrasonicDoneState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSinkForwardUltrasonicStartState : public DmAuthState { -public: - virtual ~AuthSinkForwardUltrasonicStartState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSinkForwardUltrasonicDoneState : public DmAuthState { -public: - virtual ~AuthSinkForwardUltrasonicDoneState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSrcPinAuthStartState : public DmAuthState { -public: - virtual ~AuthSrcPinAuthStartState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -private: - int32_t ShowStartAuthDialog(std::shared_ptr context); // Display PIN input box to user -}; - -class AuthSinkPinAuthStartState : public DmAuthState { -public: - virtual ~AuthSinkPinAuthStartState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSrcPinAuthMsgNegotiateState : public DmAuthState { -public: - virtual ~AuthSrcPinAuthMsgNegotiateState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSinkPinAuthMsgNegotiateState : public DmAuthState { -public: - virtual ~AuthSinkPinAuthMsgNegotiateState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSinkPinAuthDoneState : public DmAuthState { -public: - virtual ~AuthSinkPinAuthDoneState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSrcPinAuthDoneState : public DmAuthState { -public: - virtual ~AuthSrcPinAuthDoneState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSrcStartState : public DmAuthState { -public: - virtual ~AuthSrcStartState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSrcNegotiateStateMachine : public DmAuthState { -public: - virtual ~AuthSrcNegotiateStateMachine() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -private: - std::string GetAccountGroupIdHash(std::shared_ptr context); -}; - -// Middle class encapsulates public interfaces related to business. -class AuthCredentialAgreeState : public DmAuthState { -public: - virtual ~AuthCredentialAgreeState() {}; -protected: - std::string CreateAuthParamsString(DmAuthScope authorizedScope, DmAuthCredentialAddMethod method, - const std::shared_ptr &authContext); - int32_t GenerateCredIdAndPublicKey(DmAuthScope authorizedScope, std::shared_ptr &authContext); - int32_t AgreeCredential(DmAuthScope authorizedScope, std::shared_ptr &authContext); -}; - -class AuthSrcCredentialExchangeState : public AuthCredentialAgreeState { -public: - virtual ~AuthSrcCredentialExchangeState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSinkCredentialExchangeState : public AuthCredentialAgreeState { -public: - virtual ~AuthSinkCredentialExchangeState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSrcCredentialAuthStartState : public AuthCredentialAgreeState { -public: - virtual ~AuthSrcCredentialAuthStartState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSrcCredentialAuthNegotiateState : public DmAuthState { -public: - virtual ~AuthSrcCredentialAuthNegotiateState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSrcCredentialAuthDoneState : public DmAuthState { -public: - virtual ~AuthSrcCredentialAuthDoneState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSinkCredentialAuthStartState : public DmAuthState { -public: - virtual ~AuthSinkCredentialAuthStartState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSinkCredentialAuthNegotiateState : public DmAuthState { -public: - virtual ~AuthSinkCredentialAuthNegotiateState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSinkNegotiateStateMachine : public DmAuthState { -public: - virtual ~AuthSinkNegotiateStateMachine() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; - -private: - int32_t RespQueryAcceseeIds(std::shared_ptr context); - int32_t ProcRespNegotiate5_1_0(std::shared_ptr context); - void GetSinkCredentialInfo(std::shared_ptr context, JsonObject &credInfo); - void GetIdenticalCredentialInfo(std::shared_ptr context, JsonObject &credInfo); - void GetShareCredentialInfo(std::shared_ptr context, JsonObject &credInfo); - void GetP2PCredentialInfo(std::shared_ptr context, JsonObject &credInfo); - void GetSinkAclInfo(std::shared_ptr context, JsonObject &credInfo, JsonObject &aclInfo); - void GetSinkAclInfoForP2P(std::shared_ptr context, - const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, JsonObject &aclInfo); - bool IdenticalAccountAclCompare(std::shared_ptr context, - const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); - bool ShareAclCompare(std::shared_ptr context, - const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); - bool Point2PointAclCompare(std::shared_ptr context, - const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); - bool LnnAclCompare(std::shared_ptr context, - const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); - bool CheckCredIdInAcl(std::shared_ptr context, - const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, uint32_t bindType); - void CheckCredIdInAclForP2P(std::shared_ptr context, std::string &credId, - const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, uint32_t bindType, - bool &checkResult); - void GetSinkCredType(std::shared_ptr context, JsonObject &credInfo, JsonObject &aclInfo, - JsonObject &credTypeJson); - void GetSinkCredTypeForP2P(std::shared_ptr context, const JsonItemObject &credObj, - JsonObject &aclInfo, JsonObject &credTypeJson, int32_t credType, std::vector &deleteCredInfo); -}; - -class AuthSinkDataSyncState : public DmAuthState { -public: - virtual ~AuthSinkDataSyncState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSrcDataSyncState : public DmAuthState { -public: - virtual ~AuthSrcDataSyncState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSinkFinishState : public DmAuthState { -public: - virtual ~AuthSinkFinishState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; - -class AuthSrcFinishState : public DmAuthState { -public: - virtual ~AuthSrcFinishState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_AUTH_STATE_V2_H \ No newline at end of file diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp.bak b/services/implementation/src/authentication/dm_auth_manager.cpp.bak deleted file mode 100644 index 0ef4020de..000000000 --- a/services/implementation/src/authentication/dm_auth_manager.cpp.bak +++ /dev/null @@ -1,3404 +0,0 @@ -/* - * 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 - * - * 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_auth_manager.h" - -#include -#include -#include -#include - -#include "iservice_registry.h" -#if defined(SUPPORT_SCREENLOCK) -#include "screenlock_manager.h" -#endif - -#include "app_manager.h" -#include "auth_message_processor.h" -#include "common_event_support.h" -#include "dm_ability_manager.h" -#include "dm_anonymous.h" -#include "dm_config_manager.h" -#include "dm_constants.h" -#include "dm_crypto.h" -#include "dm_dialog_manager.h" -#include "dm_language_manager.h" -#include "dm_log.h" -#include "dm_radar_helper.h" -#include "dm_random.h" -#include "multiple_user_connector.h" -#include "json_object.h" -#include "openssl/sha.h" -#include "parameter.h" -#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) -#include "multiple_user_connector.h" -#endif - -namespace OHOS { -namespace DistributedHardware { -const int32_t CANCEL_PIN_CODE_DISPLAY = 1; -const int32_t DEVICE_ID_HALF = 2; -const int32_t MAX_AUTH_TIMES = 3; -const int32_t MIN_PIN_TOKEN = 10000000; -const int32_t MAX_PIN_TOKEN = 90000000; -const int32_t MIN_PIN_CODE = 100000; -const int32_t MAX_PIN_CODE = 999999; -const int32_t DM_AUTH_TYPE_MAX = 6; -const int32_t DM_AUTH_TYPE_MIN = 0; -const int32_t AUTH_SESSION_SIDE_SERVER = 0; -const int32_t USLEEP_TIME_US_500000 = 500000; // 500ms -const int32_t AUTH_DEVICE_TIMEOUT = 10; -const int32_t ALREADY_BIND = 1; -const int32_t STRTOLL_BASE_10 = 10; -const int32_t MAX_PUT_SESSIONKEY_TIMEOUT = 100; //ms -const int32_t SESSION_CLOSE_TIMEOUT = 2; - -// clone task timeout map -const std::map TASK_TIME_OUT_MAP = { - { std::string(AUTHENTICATE_TIMEOUT_TASK), CLONE_AUTHENTICATE_TIMEOUT }, - { std::string(NEGOTIATE_TIMEOUT_TASK), CLONE_NEGOTIATE_TIMEOUT }, - { std::string(CONFIRM_TIMEOUT_TASK), CLONE_CONFIRM_TIMEOUT }, - { std::string(ADD_TIMEOUT_TASK), CLONE_ADD_TIMEOUT }, - { std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), CLONE_WAIT_NEGOTIATE_TIMEOUT }, - { std::string(WAIT_REQUEST_TIMEOUT_TASK), CLONE_WAIT_REQUEST_TIMEOUT }, - { std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), CLONE_SESSION_HEARTBEAT_TIMEOUT } -}; -constexpr int32_t PROCESS_NAME_WHITE_LIST_NUM = 1; -constexpr const static char* PROCESS_NAME_WHITE_LIST[PROCESS_NAME_WHITE_LIST_NUM] = { - "com.example.myapplication" -}; - -constexpr const char* DM_VERSION_4_1_5_1 = "4.1.5.1"; -std::mutex g_authFinishLock; - -DmAuthManager::DmAuthManager(std::shared_ptr softbusConnector, - std::shared_ptr hiChainConnector, - std::shared_ptr listener, - std::shared_ptr hiChainAuthConnector) - : softbusConnector_(softbusConnector), hiChainConnector_(hiChainConnector), listener_(listener), - hiChainAuthConnector_(hiChainAuthConnector) -{ - LOGI("DmAuthManager constructor"); - DmConfigManager &dmConfigManager = DmConfigManager::GetInstance(); - dmConfigManager.GetAuthAdapter(authenticationMap_); - authUiStateMgr_ = std::make_shared(listener_); - authenticationMap_[AUTH_TYPE_IMPORT_AUTH_CODE] = nullptr; - authenticationMap_[AUTH_TYPE_CRE] = nullptr; - authenticationMap_[AUTH_TYPE_NFC] = nullptr; - dmVersion_ = DM_VERSION_5_0_5; -} - -DmAuthManager::~DmAuthManager() -{ - LOGI("DmAuthManager destructor"); -} - -bool DmAuthManager::IsHmlSessionType() -{ - CHECK_NULL_RETURN(authRequestContext_, false); - return authRequestContext_->connSessionType == CONN_SESSION_TYPE_HML; -} - -int32_t DmAuthManager::CheckAuthParamVaild(const std::string &pkgName, int32_t authType, - const std::string &deviceId, const std::string &extra) -{ - LOGI("DmAuthManager::CheckAuthParamVaild start."); - if (authType < DM_AUTH_TYPE_MIN || authType > DM_AUTH_TYPE_MAX) { - LOGE("CheckAuthParamVaild failed, authType is illegal."); - return ERR_DM_AUTH_FAILED; - } - if (pkgName.empty() || deviceId.empty()) { - LOGE("DmAuthManager::CheckAuthParamVaild failed, pkgName is %{public}s, deviceId is %{public}s, extra is" - "%{public}s.", pkgName.c_str(), GetAnonyString(deviceId).c_str(), extra.c_str()); - return ERR_DM_INPUT_PARA_INVALID; - } - if (listener_ == nullptr || authUiStateMgr_ == nullptr) { - LOGE("DmAuthManager::CheckAuthParamVaild listener or authUiStateMgr is nullptr."); - return ERR_DM_INPUT_PARA_INVALID; - } - - if (!IsAuthTypeSupported(authType)) { - LOGE("DmAuthManager::CheckAuthParamVaild authType %{public}d not support.", authType); - listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, - ERR_DM_UNSUPPORTED_AUTH_TYPE); - listener_->OnBindResult(processInfo_, peerTargetId_, ERR_DM_UNSUPPORTED_AUTH_TYPE, STATUS_DM_AUTH_DEFAULT, ""); - return ERR_DM_UNSUPPORTED_AUTH_TYPE; - } - - if (authRequestState_ != nullptr || authResponseState_ != nullptr) { - LOGE("DmAuthManager::CheckAuthParamVaild %{public}s is request authentication.", pkgName.c_str()); - return ERR_DM_AUTH_BUSINESS_BUSY; - } - - if ((authType == AUTH_TYPE_IMPORT_AUTH_CODE || authType == AUTH_TYPE_NFC) && (!IsAuthCodeReady(pkgName))) { - LOGE("Auth code not exist."); - 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; -} - -int32_t DmAuthManager::CheckAuthParamVaildExtra(const std::string &extra, const std::string &deviceId) -{ - JsonObject jsonObject(extra); - if ((jsonObject.IsDiscarded() || !IsString(jsonObject, PARAM_KEY_CONN_SESSIONTYPE) || - jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get() != CONN_SESSION_TYPE_HML) && - !softbusConnector_->HaveDeviceInMap(deviceId)) { - LOGE("CheckAuthParamVaild failed, the discoveryDeviceInfoMap_ not have this device."); - 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 (jsonObject.IsDiscarded()) { - return DM_OK; - } - std::string connSessionType; - if (IsString(jsonObject, PARAM_KEY_CONN_SESSIONTYPE)) { - connSessionType = jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get(); - } - if (connSessionType == CONN_SESSION_TYPE_HML && !CheckHmlParamValid(jsonObject)) { - LOGE("CONN_SESSION_TYPE_HML, CheckHmlParamValid failed"); - return ERR_DM_INPUT_PARA_INVALID; - } - - if (jsonObject.IsDiscarded() || !jsonObject.Contains(TAG_BIND_LEVEL)) { - return DM_OK; - } - int32_t bindLevel = INVALID_TYPE; - if (!CheckBindLevel(jsonObject, TAG_BIND_LEVEL, bindLevel)) { - LOGE("TAG_BIND_LEVEL is not integer string or int32."); - return ERR_DM_INPUT_PARA_INVALID; - } - if (static_cast(bindLevel) > APP || bindLevel < INVALID_TYPE) { - LOGE("bindlevel error %{public}d.", bindLevel); - return ERR_DM_INPUT_PARA_INVALID; - } - - if (static_cast(bindLevel) == USER && !IsAllowDeviceBind()) { - LOGE("not allowd user level bind bindlevel: %{public}d.", bindLevel); - return ERR_DM_INPUT_PARA_INVALID; - } - return DM_OK; -} - -bool DmAuthManager::CheckBindLevel(const JsonItemObject &jsonObj, const std::string &key, int32_t &bindLevel) -{ - if (IsJsonValIntegerString(jsonObj, TAG_BIND_LEVEL)) { - bindLevel = std::atoi(jsonObj[TAG_BIND_LEVEL].Get().c_str()); - return true; - } - if (IsInt32(jsonObj, TAG_BIND_LEVEL)) { - bindLevel = jsonObj[TAG_BIND_LEVEL].Get(); - return true; - } - return false; -} - -bool DmAuthManager::CheckHmlParamValid(JsonObject &jsonObject) -{ - if (!IsString(jsonObject, PARAM_KEY_HML_ACTIONID)) { - LOGE("PARAM_KEY_HML_ACTIONID is not string"); - return false; - } - std::string actionIdStr = jsonObject[PARAM_KEY_HML_ACTIONID].Get(); - if (!IsNumberString(actionIdStr)) { - LOGE("PARAM_KEY_HML_ACTIONID is not number"); - return false; - } - int32_t actionId = std::atoi(actionIdStr.c_str()); - if (actionId <= 0) { - LOGE("PARAM_KEY_HML_ACTIONID is <= 0"); - return false; - } - return true; -} - -void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, - const std::string &deviceId, const std::string &extra) -{ - LOGI("Get auth param."); - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - std::string localUdid = static_cast(localDeviceId); - authRequestContext_->hostPkgName = pkgName; - authRequestContext_->authType = authType; - authRequestContext_->localDeviceName = softbusConnector_->GetLocalDeviceName(); - authRequestContext_->localDeviceTypeId = softbusConnector_->GetLocalDeviceTypeId(); - authRequestContext_->localDeviceId = localUdid; - authRequestContext_->deviceId = deviceId; - authRequestContext_->addr = deviceId; - authRequestContext_->dmVersion = DM_VERSION_5_0_5; - authRequestContext_->localUserId = MultipleUserConnector::GetFirstForegroundUserId(); - authRequestContext_->localAccountId = MultipleUserConnector::GetFirstForegroundUserId(); - MultipleUserConnector::GetOhosAccountIdByUserId(authRequestContext_->localUserId); - authRequestContext_->isOnline = false; - authRequestContext_->authed = !authRequestContext_->bindType.empty(); - authRequestContext_->bindLevel = INVALIED_TYPE; - JsonObject jsonObject(extra); - if (jsonObject.IsDiscarded()) { - LOGE("extra string not a json type."); - return; - } - ParseJsonObject(jsonObject); - authRequestContext_->token = std::to_string(GenRandInt(MIN_PIN_TOKEN, MAX_PIN_TOKEN)); - authRequestContext_->bindLevel = GetBindLevel(authRequestContext_->bindLevel); -} - -void DmAuthManager::ParseJsonObject(JsonObject &jsonObject) -{ - if (!jsonObject.IsDiscarded()) { - if (IsString(jsonObject, TARGET_PKG_NAME_KEY)) { - authRequestContext_->targetPkgName = jsonObject[TARGET_PKG_NAME_KEY].Get(); - } - if (IsString(jsonObject, APP_OPERATION_KEY)) { - authRequestContext_->appOperation = jsonObject[APP_OPERATION_KEY].Get(); - } - if (IsString(jsonObject, CUSTOM_DESCRIPTION_KEY)) { - authRequestContext_->customDesc = DmLanguageManager::GetInstance(). - GetTextBySystemLanguage(jsonObject[CUSTOM_DESCRIPTION_KEY].Get()); - } - if (IsString(jsonObject, TAG_APP_THUMBNAIL2)) { - authRequestContext_->appThumbnail = jsonObject[TAG_APP_THUMBNAIL2].Get(); - } - CheckBindLevel(jsonObject, TAG_BIND_LEVEL, authRequestContext_->bindLevel); - authRequestContext_->closeSessionDelaySeconds = 0; - if (IsString(jsonObject, PARAM_CLOSE_SESSION_DELAY_SECONDS)) { - std::string delaySecondsStr = jsonObject[PARAM_CLOSE_SESSION_DELAY_SECONDS].Get(); - authRequestContext_->closeSessionDelaySeconds = GetCloseSessionDelaySeconds(delaySecondsStr); - } - if (IsString(jsonObject, TAG_PEER_BUNDLE_NAME)) { - authRequestContext_->peerBundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get(); - if (authRequestContext_->peerBundleName == "") { - authRequestContext_->peerBundleName = authRequestContext_->hostPkgName; - } - LOGI("ParseJsonObject peerBundleName = %{public}s", authRequestContext_->peerBundleName.c_str()); - } else { - authRequestContext_->peerBundleName = authRequestContext_->hostPkgName; - } - ParseHmlInfoInJsonObject(jsonObject); - } -} - -void DmAuthManager::ParseHmlInfoInJsonObject(JsonObject &jsonObject) -{ - CHECK_NULL_VOID(authRequestContext_); - if (IsString(jsonObject, PARAM_KEY_CONN_SESSIONTYPE)) { - authRequestContext_->connSessionType = jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get(); - LOGI("connSessionType %{public}s", authRequestContext_->connSessionType.c_str()); - } - if (!IsHmlSessionType()) { - return; - } - if (IsString(jsonObject, PARAM_KEY_HML_ACTIONID)) { - std::string actionIdStr = jsonObject[PARAM_KEY_HML_ACTIONID].Get(); - if (IsNumberString(actionIdStr)) { - authRequestContext_->hmlActionId = std::atoi(actionIdStr.c_str()); - } - if (authRequestContext_->hmlActionId <= 0) { - authRequestContext_->hmlActionId = 0; - } - LOGI("hmlActionId %{public}d", authRequestContext_->hmlActionId); - } -} - -int32_t DmAuthManager::GetCloseSessionDelaySeconds(std::string &delaySecondsStr) -{ - if (!IsNumberString(delaySecondsStr)) { - LOGE("Invalid parameter, param is not number."); - return 0; - } - const int32_t CLOSE_SESSION_DELAY_SECONDS_MAX = 10; - int32_t delaySeconds = std::atoi(delaySecondsStr.c_str()); - if (delaySeconds < 0 || delaySeconds > CLOSE_SESSION_DELAY_SECONDS_MAX) { - LOGE("Invalid parameter, param out of range."); - return 0; - } - return delaySeconds; -} - -void DmAuthManager::InitAuthState(const std::string &pkgName, int32_t authType, - const std::string &deviceId, const std::string &extra) -{ - auto iter = authenticationMap_.find(authType); - if (iter != authenticationMap_.end()) { - authPtr_ = iter->second; - } - - if (timer_ == nullptr) { - timer_ = std::make_shared(); - } - timer_->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), - GetTaskTimeout(AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT), [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); - authMessageProcessor_ = std::make_shared(shared_from_this()); - authResponseContext_ = std::make_shared(); - authRequestContext_ = std::make_shared(); - JsonObject jsonObject(extra); - if (jsonObject.IsDiscarded()) { - LOGE("extra string not a json type."); - return; - } - GetCallerInfo(pkgName, jsonObject); - GetAuthParam(pkgName, authType, deviceId, extra); - authMessageProcessor_->SetRequestContext(authRequestContext_); - authRequestState_ = std::make_shared(); - authRequestState_->SetAuthManager(shared_from_this()); - authRequestState_->SetAuthContext(authRequestContext_); - if (!DmRadarHelper::GetInstance().ReportAuthStart(peerTargetId_.deviceId, pkgName)) { - LOGE("ReportAuthStart failed"); - } - authRequestState_->Enter(); - LOGI("DmAuthManager::AuthenticateDevice complete"); -} - -int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t authType, - const std::string &deviceId, const std::string &extra) -{ - LOGI("DmAuthManager::AuthenticateDevice start auth type %{public}d.", authType); - SetAuthType(authType); - int32_t ret = CheckAuthParamVaild(pkgName, authType, deviceId, extra); - if (ret != DM_OK) { - LOGE("DmAuthManager::AuthenticateDevice failed, param is invaild."); - return ret; - } - ret = CheckAuthParamVaildExtra(extra, deviceId); - if (ret != DM_OK) { - LOGE("CheckAuthParamVaildExtra failed, param is invaild."); - return ret; - } - InitAuthState(pkgName, authType, deviceId, extra); - isAuthenticateDevice_ = true; - int32_t userId = -1; - MultipleUserConnector::GetCallerUserId(userId); - processInfo_.pkgName = pkgName; - processInfo_.userId = userId; - if (authType == AUTH_TYPE_CRE) { - LOGI("DmAuthManager::AuthenticateDevice for credential type, joinLNN directly."); - softbusConnector_->JoinLnn(deviceId, true); - listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, DM_OK); - listener_->OnBindResult(processInfo_, peerTargetId_, DM_OK, STATUS_DM_AUTH_DEFAULT, ""); - } - return DM_OK; -} - -int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) -{ - if (pkgName.empty()) { - LOGE("Invalid parameter, pkgName is empty."); - return ERR_DM_FAILED; - } - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - struct RadarInfo info = { - .funcName = "UnAuthenticateDevice", - .toCallPkg = HICHAINNAME, - .hostName = pkgName, - .peerUdid = udid, - }; - if (!DmRadarHelper::GetInstance().ReportDeleteTrustRelation(info)) { - LOGE("ReportDeleteTrustRelation failed"); - } - remoteDeviceId_ = udid; - if (static_cast(bindLevel) == USER) { - DeleteGroup(pkgName, udid); - } - std::string extra = ""; - return DeleteAcl(pkgName, std::string(localDeviceId), udid, bindLevel, extra); -} - -int32_t DmAuthManager::StopAuthenticateDevice(const std::string &pkgName) -{ - if (pkgName.empty() || authRequestContext_ == nullptr || authResponseContext_ == nullptr) { - LOGE("Invalid parameter, pkgName is empty."); - return ERR_DM_INPUT_PARA_INVALID; - } - if (((authRequestState_!= nullptr && authRequestContext_->hostPkgName == pkgName) || - (authResponseContext_ != nullptr && authResponseContext_->hostPkgName == pkgName)) && - isAuthenticateDevice_) { - LOGI("Stop previous AuthenticateDevice."); - authRequestContext_->reason = STOP_BIND; - authResponseContext_->state = authRequestState_->GetStateType(); - authResponseContext_->reply = STOP_BIND; - authRequestState_->TransitionTo(std::make_shared()); - } - return DM_OK; -} - -int32_t DmAuthManager::DeleteAcl(const std::string &pkgName, const std::string &localUdid, - const std::string &remoteUdid, int32_t bindLevel, const std::string &extra) -{ - LOGI("DeleteAcl pkgName %{public}s, localUdid %{public}s, remoteUdid %{public}s, bindLevel %{public}d.", - pkgName.c_str(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str(), bindLevel); - DmOfflineParam offlineParam = - DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localUdid, remoteUdid, bindLevel, extra); - if (offlineParam.bindType == INVALIED_TYPE) { - LOGE("Acl not contain the pkgname bind data."); - return ERR_DM_FAILED; - } - if (static_cast(bindLevel) == APP) { - ProcessInfo processInfo; - processInfo.pkgName = pkgName; - processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); - 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(), - offlineParam.peerUserId); - return DM_OK; - } - } - if (static_cast(bindLevel) == USER && offlineParam.leftAclNumber != 0) { - LOGI("Unbind deivce-level, retain identical account bind type."); - return DM_OK; - } - if (static_cast(bindLevel) == USER && offlineParam.leftAclNumber == 0) { - LOGI("Unbind deivce-level, retain null."); - hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(), - offlineParam.peerUserId); - return DM_OK; - } - return ERR_DM_FAILED; -} - -int32_t DmAuthManager::UnBindDevice(const std::string &pkgName, const std::string &udid, - int32_t bindLevel, const std::string &extra) -{ - if (pkgName.empty()) { - LOGE("Invalid parameter, pkgName is empty."); - return ERR_DM_FAILED; - } - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - if (static_cast(bindLevel) == USER) { - DeleteGroup(pkgName, udid); - } - return DeleteAcl(pkgName, std::string(localDeviceId), udid, bindLevel, extra); -} - -void DmAuthManager::GetPeerUdidHash(int32_t sessionId, std::string &peerUdidHash) -{ - std::string peerUdid = ""; - int32_t ret = softbusConnector_->GetSoftbusSession()->GetPeerDeviceId(sessionId, peerUdid); - if (ret != DM_OK) { - LOGE("DmAuthManager::GetPeerUdidHash failed."); - peerUdidHash = ""; - return; - } - char udidHashTmp[DM_MAX_DEVICE_ID_LEN] = {0}; - if (Crypto::GetUdidHash(peerUdid, reinterpret_cast(udidHashTmp)) != DM_OK) { - LOGE("get udidhash by udid: %{public}s failed.", GetAnonyString(peerUdid).c_str()); - peerUdidHash = ""; - return; - } - peerUdidHash = std::string(udidHashTmp); -} - -void DmAuthManager::DeleteOffLineTimer(int32_t sessionId) -{ - GetPeerUdidHash(sessionId, remoteUdidHash_); - if (remoteUdidHash_.empty()) { - LOGE("DeleteOffLineTimer remoteUdidHash is empty."); - return; - } - if (softbusConnector_ != nullptr) { - softbusConnector_->DeleteOffLineTimer(remoteUdidHash_); - } -} - -void DmAuthManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) -{ - LOGI("sessionId = %{public}d and sessionSide = %{public}d result = %{public}d", sessionId, sessionSide, result); - DeleteOffLineTimer(sessionId); - if (sessionSide == AUTH_SESSION_SIDE_SERVER) { - if (authResponseState_ == nullptr && authRequestState_ == nullptr) { - authMessageProcessor_ = std::make_shared(shared_from_this()); - authResponseState_ = std::make_shared(); - authResponseState_->SetAuthManager(shared_from_this()); - authResponseState_->Enter(); - authResponseContext_ = std::make_shared(); - authResponseContext_->sessionId = sessionId; - if (timer_ == nullptr) { - timer_ = std::make_shared(); - } - timer_->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), - GetTaskTimeout(AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT), [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); - timer_->StartTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), - GetTaskTimeout(WAIT_NEGOTIATE_TIMEOUT_TASK, WAIT_NEGOTIATE_TIMEOUT), [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); - } else { - std::shared_ptr authMessageProcessor = - std::make_shared(shared_from_this()); - std::shared_ptr authResponseContext = std::make_shared(); - authResponseContext->reply = ERR_DM_AUTH_BUSINESS_BUSY; - authMessageProcessor->SetResponseContext(authResponseContext); - std::string message = authMessageProcessor->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE); - softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); - softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId); - } - } else { - if (authResponseState_ == nullptr && authRequestState_ != nullptr && - authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT) { - authRequestContext_->sessionId = sessionId; - authResponseContext_->sessionId = sessionId; - authMessageProcessor_->SetRequestContext(authRequestContext_); - authRequestState_->SetAuthContext(authRequestContext_); - authRequestState_->TransitionTo(std::make_shared()); - struct RadarInfo info = { .funcName = "OnSessionOpened" }; - info.channelId = sessionId; - DmRadarHelper::GetInstance().ReportAuthSendRequest(info); - } else { - softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId); - LOGE("DmAuthManager::OnSessionOpened but request state is wrong"); - } - } -} - -void DmAuthManager::OnSessionClosed(const int32_t sessionId) -{ - LOGI("DmAuthManager::OnSessionClosed sessionId = %{public}d", sessionId); - if (authResponseState_ != nullptr && authResponseContext_ != nullptr) { - isFinishOfLocal_ = false; - authResponseContext_->state = authResponseState_->GetStateType(); - authResponseState_->TransitionTo(std::make_shared()); - } -} - -void DmAuthManager::ClearSoftbusSessionCallback() -{ - LOGI("DmAuthManager ClearSoftbusSessionCallback"); - if (softbusConnector_ != nullptr && softbusConnector_->GetSoftbusSession() != nullptr) { - softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback(); - } -} - -void DmAuthManager::PrepareSoftbusSessionCallback() -{ - LOGI("DmAuthManager PrepareSoftbusSessionCallback"); - if (softbusConnector_ != nullptr && softbusConnector_->GetSoftbusSession() != nullptr) { - softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(shared_from_this()); - } -} - -void DmAuthManager::ProcessSourceMsg() -{ - authRequestContext_ = authMessageProcessor_->GetRequestContext(); - authRequestState_->SetAuthContext(authRequestContext_); - LOGI("OnDataReceived for source device, authResponseContext msgType = %{public}d, authRequestState stateType =" - "%{public}d", authResponseContext_->msgType, authRequestState_->GetStateType()); - - switch (authResponseContext_->msgType) { - case MSG_TYPE_RESP_AUTH: - case MSG_TYPE_RESP_AUTH_EXT: - if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) { - authRequestState_->TransitionTo(std::make_shared()); - } - break; - case MSG_TYPE_RESP_NEGOTIATE: - if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE) { - authRequestState_->TransitionTo(std::make_shared()); - } - break; - case MSG_TYPE_REQ_AUTH_TERMINATE: - if (authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) { - isFinishOfLocal_ = false; - authResponseContext_->state = authRequestState_->GetStateType(); - authRequestState_->TransitionTo(std::make_shared()); - } - break; - case MSG_TYPE_RESP_PUBLICKEY: - if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_CREDENTIAL) { - authRequestState_->TransitionTo(std::make_shared()); - } - break; - case MSG_TYPE_RESP_RECHECK_MSG: - if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_RECHECK_MSG) { - authRequestState_->TransitionTo(std::make_shared()); - } - break; - default: - break; - } -} - -void DmAuthManager::ProcessSinkMsg() -{ - authResponseState_->SetAuthContext(authResponseContext_); - LOGI("OnDataReceived for sink device, authResponseContext msgType = %{public}d, authResponseState stateType =" - "%{public}d", authResponseContext_->msgType, authResponseState_->GetStateType()); - - switch (authResponseContext_->msgType) { - case MSG_TYPE_NEGOTIATE: - if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_INIT) { - if (timer_ != nullptr) { - timer_->DeleteTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK)); - } - authResponseState_->TransitionTo(std::make_shared()); - } - break; - case MSG_TYPE_REQ_AUTH: - if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_NEGOTIATE) { - if (timer_ != nullptr) { - timer_->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); - } - authResponseState_->TransitionTo(std::make_shared()); - } - break; - case MSG_TYPE_REQ_AUTH_TERMINATE: - if (authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) { - isFinishOfLocal_ = false; - authResponseContext_->state = authResponseState_->GetStateType(); - if (authResponseContext_->reply == DM_OK) { - authResponseContext_->state = AuthState::AUTH_RESPONSE_FINISH; - } - authResponseState_->TransitionTo(std::make_shared()); - } - break; - case MSG_TYPE_REQ_PUBLICKEY: - ProcessReqPublicKey(); - break; - case MSG_TYPE_REQ_RECHECK_MSG: - if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_AUTH_FINISH) { - authResponseState_->TransitionTo(std::make_shared()); - break; - } - if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW) { - std::lock_guard lock(srcReqMsgLock_); - isNeedProcCachedSrcReqMsg_ = true; - } - break; - default: - break; - } -} - -void DmAuthManager::OnDataReceived(const int32_t sessionId, const std::string message) -{ - if (authResponseContext_ == nullptr || authMessageProcessor_ == nullptr || - sessionId != authResponseContext_->sessionId) { - LOGE("OnDataReceived failed, authResponseContext or authMessageProcessor_ is nullptr."); - return; - } - - authResponseContext_->sessionId = sessionId; - authMessageProcessor_->SetResponseContext(authResponseContext_); - int32_t ret = authMessageProcessor_->ParseMessage(message); - if (ret != DM_OK) { - LOGE("OnDataReceived failed, parse input message error."); - return; - } - - if ((authRequestState_ != nullptr) && (authResponseState_ == nullptr)) { - // source device auth process - ProcessSourceMsg(); - } else if ((authResponseState_ != nullptr) && (authRequestState_ == nullptr)) { - // sink device auth process - { - std::lock_guard lock(srcReqMsgLock_); - srcReqMsg_ = message; - } - ProcessSinkMsg(); - } else { - LOGE("DmAuthManager::OnDataReceived failed, authRequestState_ or authResponseState_ is invalid."); - } -} - -void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId) -{ - if (authResponseContext_ == nullptr) { - LOGE("failed to OnGroupCreated because authResponseContext_ is nullptr"); - return; - } - if (authResponseState_ == nullptr) { - LOGE("DmAuthManager::AuthenticateDevice end"); - return; - } - LOGI("DmAuthManager::OnGroupCreated start group id %{public}s", GetAnonyString(groupId).c_str()); - if (groupId == "{}") { - authResponseContext_->reply = ERR_DM_CREATE_GROUP_FAILED; - authMessageProcessor_->SetResponseContext(authResponseContext_); - std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH); - softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); - return; - } - CompatiblePutAcl(); - std::string pinCode = ""; - if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && !importAuthCode_.empty()) { - GetAuthCode(authResponseContext_->hostPkgName, pinCode); - } else if (authResponseContext_->authType != AUTH_TYPE_IMPORT_AUTH_CODE) { - pinCode = GeneratePincode(); - } else { - LOGE("authType invalied."); - } - JsonObject jsonObj; - jsonObj[PIN_TOKEN] = authResponseContext_->token; - jsonObj[QR_CODE_KEY] = GenerateGroupName(); - jsonObj[NFC_CODE_KEY] = GenerateGroupName(); - authResponseContext_->authToken = SafetyDump(jsonObj); - LOGI("DmAuthManager::OnGroupCreated start group id %{public}s", GetAnonyString(groupId).c_str()); - authResponseContext_->groupId = groupId; - authResponseContext_->code = pinCode; - authMessageProcessor_->SetResponseContext(authResponseContext_); - std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH); - softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); - authResponseContext_->isFinish = true; - authResponseState_->TransitionTo(std::make_shared()); -} - -void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status) -{ - isAddingMember_ = false; - if (authResponseContext_ == nullptr || authUiStateMgr_ == nullptr) { - LOGE("failed to OnMemberJoin because authResponseContext_ or authUiStateMgr is nullptr"); - return; - } - LOGI("DmAuthManager OnMemberJoin start authTimes %{public}d", authTimes_); - if ((authRequestState_ != nullptr) && (authResponseState_ == nullptr)) { - MemberJoinAuthRequest(requestId, status); - } else if ((authResponseState_ != nullptr) && (authRequestState_ == nullptr)) { - if (status == DM_OK && authResponseContext_->requestId == requestId && - authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW) { - authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW); - } else { - if (++authTimes_ >= MAX_AUTH_TIMES) { - authResponseContext_->isFinish = false; - authResponseContext_->reply = ERR_DM_BIND_PIN_CODE_ERROR; - authResponseContext_->state = AuthState::AUTH_RESPONSE_SHOW; - isFinishOfLocal_ = false; - authResponseState_->TransitionTo(std::make_shared()); - } - } - } else { - LOGE("DmAuthManager::OnMemberJoin failed, authRequestState_ or authResponseState_ is invalid."); - } -} - -void DmAuthManager::MemberJoinAuthRequest(int64_t requestId, int32_t status) -{ - authTimes_++; - if (timer_ != nullptr) { - timer_->DeleteTimer(std::string(ADD_TIMEOUT_TASK)); - } - if (status == DM_OK) { - LOGI("join group success."); - CompatiblePutAcl(); - } - if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { - HandleMemberJoinImportAuthCode(requestId, status); - return; - } - if (status != DM_OK || authResponseContext_->requestId != requestId) { - if (authRequestState_ != nullptr && authTimes_ >= MAX_AUTH_TIMES) { - authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; - authResponseContext_->reply = ERR_DM_BIND_PIN_CODE_ERROR; - authRequestContext_->reason = ERR_DM_BIND_PIN_CODE_ERROR; - authRequestState_->TransitionTo(std::make_shared()); - return; - } - if (timer_ != nullptr) { - timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), - GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); - } - authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR); - } else { - authRequestState_->TransitionTo(std::make_shared()); - if (timer_ != nullptr) { - timer_->DeleteTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK)); - } - } -} - -void DmAuthManager::HandleMemberJoinImportAuthCode(const int64_t requestId, const int32_t status) -{ - if (status != DM_OK || authResponseContext_->requestId != requestId) { - authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; - authResponseContext_->reply = ERR_DM_AUTH_CODE_INCORRECT; - authRequestContext_->reason = ERR_DM_AUTH_CODE_INCORRECT; - authRequestState_->TransitionTo(std::make_shared()); - } else { - authRequestState_->TransitionTo(std::make_shared()); - } -} - -void DmAuthManager::HandleAuthenticateTimeout(std::string name) -{ - LOGI("DmAuthManager::HandleAuthenticateTimeout start timer name %{public}s", name.c_str()); - if (authRequestState_ != nullptr && authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) { - if (authResponseContext_ == nullptr) { - authResponseContext_ = std::make_shared(); - } - authResponseContext_->state = authRequestState_->GetStateType(); - authRequestContext_->reason = ERR_DM_TIME_OUT; - authResponseContext_->reply = ERR_DM_TIME_OUT; - authRequestState_->TransitionTo(std::make_shared()); - } - - if (authResponseState_ != nullptr && authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) { - authResponseContext_->state = authResponseState_->GetStateType(); - authResponseContext_->reply = ERR_DM_TIME_OUT; - authResponseState_->TransitionTo(std::make_shared()); - } - LOGI("DmAuthManager::HandleAuthenticateTimeout start complete"); -} - -int32_t DmAuthManager::EstablishAuthChannel(const std::string &deviceId) -{ - if (NeedInsensibleSwitching()) { - return DM_OK; - } - int32_t sessionId = 0; - if (IsHmlSessionType()) { - CHECK_NULL_RETURN(authRequestContext_, ERR_DM_FAILED); - LOGI("hmlActionId %{public}d, hmlReleaseTime %{public}d, hmlEnable160M %{public}d", - authRequestContext_->hmlActionId, authRequestContext_->closeSessionDelaySeconds, - authRequestContext_->hmlEnable160M); - sessionId = softbusConnector_->GetSoftbusSession()->OpenAuthSessionWithPara(deviceId, - authRequestContext_->hmlActionId, authRequestContext_->hmlEnable160M); - } else { - sessionId = softbusConnector_->GetSoftbusSession()->OpenAuthSession(deviceId); - } - struct RadarInfo info = { - .funcName = "EstablishAuthChannel", - .stageRes = (sessionId > 0) ? - static_cast(StageRes::STAGE_IDLE) : static_cast(StageRes::STAGE_FAIL), - .bizState = (sessionId > 0) ? - static_cast(BizState::BIZ_STATE_START) : static_cast(BizState::BIZ_STATE_END), - .localSessName = DM_SESSION_NAME, - .peerSessName = DM_SESSION_NAME, - .isTrust = static_cast(TrustStatus::NOT_TRUST), - .commServ = static_cast(CommServ::USE_SOFTBUS), - .peerUdid = peerTargetId_.deviceId, - .channelId = sessionId, - .errCode = sessionId, - }; - if (!DmRadarHelper::GetInstance().ReportAuthOpenSession(info)) { - LOGE("ReportAuthOpenSession failed"); - } - if (sessionId < 0) { - LOGE("OpenAuthSession failed, stop the authentication"); - if (authResponseContext_ == nullptr) { - authResponseContext_ = std::make_shared(); - } - authResponseContext_->state = AuthState::AUTH_REQUEST_NEGOTIATE; - authResponseContext_->reply = sessionId; - if (authRequestContext_ == nullptr) { - authRequestContext_ = std::make_shared(); - } - authRequestContext_->reason = sessionId; - if (authRequestState_ != nullptr) { - authRequestState_->TransitionTo(std::make_shared()); - } - } - return DM_OK; -} - -void DmAuthManager::StartNegotiate(const int32_t &sessionId) -{ - if (authResponseContext_ == nullptr) { - LOGE("DmAuthManager::StartNegotiate error, authResponseContext_ is nullptr"); - return; - } - LOGI("DmAuthManager::StartNegotiate sessionId %{public}d.", sessionId); - authResponseContext_->localDeviceId = authRequestContext_->localDeviceId; - authResponseContext_->reply = ERR_DM_AUTH_REJECT; - authResponseContext_->authType = authRequestContext_->authType; - authResponseContext_->deviceId = authRequestContext_->deviceId; - authResponseContext_->accountGroupIdHash = GetAccountGroupIdHash(); - authResponseContext_->hostPkgName = authRequestContext_->hostPkgName; - authResponseContext_->bundleName = authRequestContext_->bundleName; - authResponseContext_->peerBundleName = authRequestContext_->peerBundleName; - authResponseContext_->hostPkgLabel = authRequestContext_->hostPkgLabel; - authResponseContext_->tokenId = authRequestContext_->tokenId; - authResponseContext_->bindLevel = authRequestContext_->bindLevel; - authResponseContext_->bindType = authRequestContext_->bindType; - authResponseContext_->isOnline = authRequestContext_->isOnline; - authResponseContext_->authed = authRequestContext_->authed; - authResponseContext_->dmVersion = ""; - authResponseContext_->localAccountId = authRequestContext_->localAccountId; - authResponseContext_->localUserId = authRequestContext_->localUserId; - authResponseContext_->isIdenticalAccount = false; - authResponseContext_->edition = DM_VERSION_5_0_5; - authResponseContext_->remoteDeviceName = authRequestContext_->localDeviceName; - authMessageProcessor_->SetResponseContext(authResponseContext_); - std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_NEGOTIATE); - if (!NeedInsensibleSwitching()) { - softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); - } - if (timer_ != nullptr) { - timer_->StartTimer(std::string(NEGOTIATE_TIMEOUT_TASK), - GetTaskTimeout(NEGOTIATE_TIMEOUT_TASK, NEGOTIATE_TIMEOUT), [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); - } -} - -void DmAuthManager::AbilityNegotiate() -{ - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - authResponseContext_->remoteAccountId = authResponseContext_->localAccountId; - authResponseContext_->remoteUserId = authResponseContext_->localUserId; - GetBinderInfo(); - bool ret = hiChainConnector_->IsDevicesInP2PGroup(authResponseContext_->localDeviceId, localDeviceId); - if (ret) { - LOGE("DmAuthManager::EstablishAuthChannel device is in group"); - if (!DeviceProfileConnector::GetInstance().CheckSinkDevIdInAclForDevBind(authResponseContext_->hostPkgName, - authResponseContext_->localDeviceId)) { - CompatiblePutAcl(); - } - authResponseContext_->reply = ERR_DM_AUTH_PEER_REJECT; - } else { - authResponseContext_->reply = ERR_DM_AUTH_REJECT; - } - authResponseContext_->localDeviceId = localDeviceId; - - if (!IsAuthTypeSupported(authResponseContext_->authType)) { - LOGE("DmAuthManager::AuthenticateDevice authType %{public}d not support.", authResponseContext_->authType); - authResponseContext_->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; - } else { - authPtr_ = authenticationMap_[authResponseContext_->authType]; - } - - if (IsAuthCodeReady(authResponseContext_->hostPkgName)) { - authResponseContext_->isAuthCodeReady = true; - } else { - authResponseContext_->isAuthCodeReady = false; - } -} - -void DmAuthManager::RespNegotiate(const int32_t &sessionId) -{ - if (authResponseContext_ == nullptr || authRequestState_ != nullptr) { - LOGE("failed to RespNegotiate because authResponseContext_ is nullptr"); - return; - } - LOGI("DmAuthManager::RespNegotiate sessionid %{public}d", sessionId); - remoteDeviceId_ = authResponseContext_->localDeviceId; - authResponseContext_->networkId = softbusConnector_->GetLocalDeviceNetworkId(); - authResponseContext_->targetDeviceName = softbusConnector_->GetLocalDeviceName(); - remoteVersion_ = AuthManagerBase::ConvertSrcVersion(authResponseContext_->dmVersion, authResponseContext_->edition); - NegotiateRespMsg(remoteVersion_); - if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && - (static_cast(authResponseContext_->bindLevel) >= USER && - static_cast(authResponseContext_->bindLevel) <= APP)) { - ProcRespNegotiateExt(sessionId); - timer_->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), - GetTaskTimeout(WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); - } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || - static_cast(authResponseContext_->bindLevel) == INVALIED_TYPE) { - ProcRespNegotiate(sessionId); - timer_->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), - GetTaskTimeout(WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); - } else { - ProcIncompatible(sessionId); - } -} - -void DmAuthManager::NegotiateRespMsg(const std::string &version) -{ - if (version == DM_VERSION_5_0_1) { - authResponseContext_->dmVersion = DM_VERSION_5_0_1; - } else if (version < DM_VERSION_5_0_1) { - authResponseContext_->dmVersion = ""; - authResponseContext_->bindLevel = INVALIED_TYPE; - } else if (version > DM_VERSION_5_0_1) { - authResponseContext_->dmVersion = dmVersion_; - } -} - -void DmAuthManager::SendAuthRequest(const int32_t &sessionId) -{ - LOGI("DmAuthManager::SendAuthRequest sessionId %{public}d.", sessionId); - if (authResponseContext_ == nullptr) { - LOGE("failed to SendAuthRequest because authResponseContext_ is nullptr"); - return; - } - if (authResponseContext_->reply == ERR_DM_VERSION_INCOMPATIBLE) { - LOGE("The peer device version is not supported"); - authRequestContext_->reason = authResponseContext_->reply; - authRequestState_->TransitionTo(std::make_shared()); - return; - } - remoteDeviceId_ = authResponseContext_->localDeviceId; - authRequestContext_->remoteDeviceName = authResponseContext_->targetDeviceName; - remoteVersion_ = ConvertSinkVersion(authResponseContext_->dmVersion); - if (timer_ != nullptr) { - timer_->DeleteTimer(std::string(NEGOTIATE_TIMEOUT_TASK)); - } - if (authResponseContext_->cryptoSupport) { - isCryptoSupport_ = true; - } - LOGI("SendAuthRequest dmversion %{public}s, level %{public}d", - authResponseContext_->dmVersion.c_str(), authResponseContext_->bindLevel); - if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && - (static_cast(authResponseContext_->bindLevel) >= USER && - static_cast(authResponseContext_->bindLevel) <= APP)) { - ProcessAuthRequestExt(sessionId); - } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || - static_cast(authResponseContext_->bindLevel) == INVALIED_TYPE) { - ProcessAuthRequest(sessionId); - } else { - LOGE("Invalied bind mode."); - } -} - -void DmAuthManager::ProcessAuthRequest(const int32_t &sessionId) -{ - LOGI("ProcessAuthRequest start."); - if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && - !authResponseContext_->importAuthCode.empty() && !importAuthCode_.empty()) { - if (authResponseContext_->importAuthCode != Crypto::Sha256(importAuthCode_)) { - SetReasonAndFinish(ERR_DM_AUTH_CODE_INCORRECT, AuthState::AUTH_REQUEST_FINISH); - return; - } - } - - if (authResponseContext_->isOnline && softbusConnector_->CheckIsOnline(remoteDeviceId_)) { - authResponseContext_->isOnline = true; - } else { - authResponseContext_->isOnline = false; - } - if (CheckTrustState() != DM_OK) { - LOGI("CheckTrustState end."); - return; - } - - std::vector messageList = authMessageProcessor_->CreateAuthRequestMessage(); - for (auto msg : messageList) { - softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg); - } - - 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); - }); -} - -void DmAuthManager::GetAuthRequestContext() -{ - char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; - Crypto::GetUdidHash(authResponseContext_->localDeviceId, reinterpret_cast(deviceIdHash)); - authRequestContext_->deviceId = static_cast(deviceIdHash); - authResponseContext_->deviceId = authResponseContext_->localDeviceId; - authResponseContext_->localDeviceId = authRequestContext_->localDeviceId; - authRequestContext_->remoteAccountId = authResponseContext_->localAccountId; - authResponseContext_->remoteAccountId = authRequestContext_->remoteAccountId; - authResponseContext_->localAccountId = authRequestContext_->localAccountId; - authRequestContext_->remoteUserId = authResponseContext_->localUserId; - if (authResponseContext_->isOnline && softbusConnector_->CheckIsOnline(remoteDeviceId_)) { - authResponseContext_->isOnline = true; - } else { - authResponseContext_->isOnline = false; - } - authResponseContext_->haveCredential = false; -} - -void DmAuthManager::ProcessAuthRequestExt(const int32_t &sessionId) -{ - LOGI("ProcessAuthRequestExt start."); - if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_3)) && - authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && - !authResponseContext_->importAuthCode.empty() && !importAuthCode_.empty()) { - if (authResponseContext_->importAuthCode != Crypto::Sha256(importAuthCode_)) { - SetReasonAndFinish(ERR_DM_AUTH_CODE_INCORRECT, AuthState::AUTH_REQUEST_FINISH); - return; - } - } - - GetAuthRequestContext(); - std::vector bindType = - DeviceProfileConnector::GetInstance().SyncAclByBindType(authResponseContext_->hostPkgName, - authResponseContext_->bindType, authResponseContext_->localDeviceId, authResponseContext_->deviceId); - authResponseContext_->authed = !bindType.empty(); - if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_3)) && - authResponseContext_->isOnline && authResponseContext_->authed && - authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && - (authResponseContext_->importAuthCode.empty() || importAuthCode_.empty())) { - SetReasonAndFinish(ERR_DM_AUTH_CODE_INCORRECT, AuthState::AUTH_REQUEST_FINISH); - return; - } - authResponseContext_->bindType = bindType; - if (IsAuthFinish()) { - return; - } - - std::vector messageList = authMessageProcessor_->CreateAuthRequestMessage(); - for (auto msg : messageList) { - softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg); - } - 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); - }); -} - -bool DmAuthManager::IsAuthFinish() -{ - if (authResponseContext_->reply == ERR_DM_UNSUPPORTED_AUTH_TYPE) { - listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, - authRequestContext_->token, AuthState::AUTH_REQUEST_NEGOTIATE_DONE, ERR_DM_UNSUPPORTED_AUTH_TYPE); - authRequestState_->TransitionTo(std::make_shared()); - return true; - } - - if ((authResponseContext_->isIdenticalAccount && !authResponseContext_->authed) || - (authResponseContext_->authed && !authResponseContext_->isOnline)) { - JoinLnn(authRequestContext_->addr); - authRequestContext_->reason = DM_OK; - authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; - authResponseContext_->reply = DM_OK; - authRequestState_->TransitionTo(std::make_shared()); - return true; - } - - if (authResponseContext_->reply == ERR_DM_UNSUPPORTED_AUTH_TYPE || - (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && - authResponseContext_->isAuthCodeReady == false)) { - authRequestState_->TransitionTo(std::make_shared()); - return true; - } - return false; -} - -int32_t DmAuthManager::ConfirmProcess(const int32_t &action) -{ - LOGI("ConfirmProcess start."); - if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH || action_ == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { - authResponseContext_->reply = USER_OPERATION_TYPE_ALLOW_AUTH; - } else { - authResponseContext_->reply = action_; - } - - if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH && - authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_CONFIRM) { - authResponseState_->TransitionTo(std::make_shared()); - } else { - authMessageProcessor_->SetResponseContext(authResponseContext_); - std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH); - softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); - } - return DM_OK; -} - -int32_t DmAuthManager::ConfirmProcessExt(const int32_t &action) -{ - LOGI("ConfirmProcessExt start."); - authResponseContext_->confirmOperation = action; - if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH || action_ == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { - authResponseContext_->reply = USER_OPERATION_TYPE_ALLOW_AUTH; - } else { - authResponseContext_->reply = USER_OPERATION_TYPE_CANCEL_AUTH; - } - authMessageProcessor_->SetResponseContext(authResponseContext_); - if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH && - authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_CONFIRM) { - if (CanUsePincodeFromDp()) { - authResponseContext_->code = serviceInfoProfile_.GetPinCode(); - LOGI("import pincode from dp"); - } else if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && !importAuthCode_.empty()) { - GetAuthCode(authResponseContext_->hostPkgName, authResponseContext_->code); - } else { - authResponseContext_->code = GeneratePincode(); - } - authResponseContext_->requestId = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); - authResponseState_->TransitionTo(std::make_shared()); - } - authMessageProcessor_->SetResponseContext(authResponseContext_); - std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH_EXT); - softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); - return DM_OK; -} - -int32_t DmAuthManager::StartAuthProcess(const int32_t &action) -{ - if (authResponseContext_ == nullptr) { - LOGE("failed to StartAuthProcess because authResponseContext_ is nullptr"); - return ERR_DM_AUTH_NOT_START; - } - LOGI("DmAuthManager::StartAuthProcess"); - action_ = action; - struct RadarInfo info = { - .funcName = "StartAuthProcess", - .stageRes = (action_ == USER_OPERATION_TYPE_CANCEL_AUTH) ? - static_cast(StageRes::STAGE_CANCEL) : static_cast(StageRes::STAGE_SUCC), - .bizState = (action_ == USER_OPERATION_TYPE_CANCEL_AUTH) ? - static_cast(BizState::BIZ_STATE_END) : static_cast(BizState::BIZ_STATE_START), - .errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_AUTH_REJECT), - }; - if (!DmRadarHelper::GetInstance().ReportAuthConfirmBox(info)) { - LOGE("ReportAuthConfirmBox failed"); - } - if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && - (static_cast(authResponseContext_->bindLevel) >= USER && - static_cast(authResponseContext_->bindLevel) <= APP)) { - return ConfirmProcessExt(action); - } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || - static_cast(authResponseContext_->bindLevel) == INVALIED_TYPE) { - return ConfirmProcess(action); - } else { - LOGE("Invalied bind mode."); - } - return DM_OK; -} - -void DmAuthManager::StartRespAuthProcess() -{ - if (authResponseContext_ == nullptr) { - LOGE("failed to StartRespAuthProcess because authResponseContext_ is nullptr"); - return; - } - LOGI("DmAuthManager::StartRespAuthProcess sessionId = %{public}d", authResponseContext_->sessionId); - if (timer_ != nullptr) { - timer_->DeleteTimer(std::string(CONFIRM_TIMEOUT_TASK)); - } - if (authResponseContext_->groupName[CHECK_AUTH_ALWAYS_POS] == AUTH_ALWAYS) { - action_ = USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; - } else if (authResponseContext_->groupName[CHECK_AUTH_ALWAYS_POS] == AUTH_ONCE) { - action_ = USER_OPERATION_TYPE_ALLOW_AUTH; - } - if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH) { - timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), - GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); - timer_->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), - GetTaskTimeout(SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), [this] (std::string name) { - DmAuthManager::HandleSessionHeartbeat(name); - }); - listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, - authRequestContext_->token, STATUS_DM_SHOW_PIN_INPUT_UI, DM_OK); - listener_->OnBindResult(processInfo_, peerTargetId_, DM_OK, STATUS_DM_SHOW_PIN_INPUT_UI, ""); - authRequestState_->TransitionTo(std::make_shared()); - } else { - LOGE("do not accept"); - authResponseContext_->state = AuthState::AUTH_REQUEST_REPLY; - authRequestContext_->reason = ERR_DM_AUTH_PEER_REJECT; - authResponseContext_->reply = ERR_DM_AUTH_PEER_REJECT; - authRequestState_->TransitionTo(std::make_shared()); - } -} - -int32_t DmAuthManager::CreateGroup() -{ - if (authResponseContext_ == nullptr) { - LOGE("failed to CreateGroup because authResponseContext_ is nullptr"); - return ERR_DM_FAILED; - } - LOGI("DmAuthManager::CreateGroup start"); - authResponseContext_->groupName = GenerateGroupName(); - authResponseContext_->requestId = GenRandLongLong(MIN_REQUEST_ID, MAX_REQUEST_ID); - hiChainConnector_->CreateGroup(authResponseContext_->requestId, authResponseContext_->groupName); - return DM_OK; -} - -int32_t DmAuthManager::AddMember(const std::string &pinCode) -{ - if (authResponseContext_ == nullptr) { - LOGE("failed to AddMember because authResponseContext_ is nullptr"); - return ERR_DM_FAILED; - } - LOGI("DmAuthManager::AddMember start group id %{public}s", GetAnonyString(authResponseContext_->groupId).c_str()); - if (timer_ != nullptr) { - timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK)); - } - JsonObject jsonObject; - jsonObject[TAG_GROUP_ID] = authResponseContext_->groupId; - jsonObject[TAG_GROUP_NAME] = authResponseContext_->groupName; - jsonObject[PIN_CODE_KEY] = pinCode; - jsonObject[TAG_REQUEST_ID] = authResponseContext_->requestId; - jsonObject[TAG_DEVICE_ID] = authResponseContext_->deviceId; - std::string connectInfo = SafetyDump(jsonObject); - if (timer_ != nullptr) { - timer_->StartTimer(std::string(ADD_TIMEOUT_TASK), - GetTaskTimeout(ADD_TIMEOUT_TASK, ADD_TIMEOUT), [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); - } - if (authUiStateMgr_ == nullptr) { - LOGE("DmAuthManager::AddMember authUiStateMgr is null."); - return ERR_DM_FAILED; - } - if (isAddingMember_) { - LOGE("DmAuthManager::AddMember doing add member."); - authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_DOING_AUTH); - return ERR_DM_FAILED; - } - isAddingMember_ = true; - int32_t ret = hiChainConnector_->AddMember(authRequestContext_->addr, connectInfo); - struct RadarInfo info = { - .funcName = "AddMember", - .stageRes = (ret == 0) ? - static_cast(StageRes::STAGE_IDLE) : static_cast(StageRes::STAGE_FAIL), - .peerUdid = authResponseContext_ == nullptr ? "" : authResponseContext_->deviceId, - .errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_ADD_GROUP_FAILED), - }; - if (!DmRadarHelper::GetInstance().ReportAuthAddGroup(info)) { - LOGE("ReportAuthAddGroup failed"); - } - if (ret != 0) { - LOGE("DmAuthManager::AddMember failed, ret: %{public}d", ret); - isAddingMember_ = false; - return ERR_DM_ADD_GROUP_FAILED; - } - return DM_OK; -} - -std::string DmAuthManager::GetConnectAddr(std::string deviceId) -{ - std::string connectAddr; - if (softbusConnector_->GetConnectAddr(deviceId, connectAddr) == nullptr) { - LOGE("DmAuthManager::GetConnectAddr error"); - } - return connectAddr; -} - -int32_t DmAuthManager::JoinNetwork() -{ - if (authResponseContext_ == nullptr) { - LOGE("failed to JoinNeWork because authResponseContext_ is nullptr"); - return ERR_DM_FAILED; - } - LOGI("DmAuthManager JoinNetwork start"); - if (timer_ != nullptr) { - timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); - } - authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; - authResponseContext_->isFinish = true; - authRequestContext_->reason = DM_OK; - authResponseContext_->reply = DM_OK; - authRequestState_->TransitionTo(std::make_shared()); - return DM_OK; -} - -void DmAuthManager::SinkAuthenticateFinish() -{ - LOGI("DmAuthManager::SinkAuthenticateFinish, isFinishOfLocal: %{public}d", isFinishOfLocal_); - processInfo_.pkgName = authResponseContext_->peerBundleName; - listener_->OnSinkBindResult(processInfo_, peerTargetId_, authResponseContext_->reply, - authResponseContext_->state, GenerateBindResultContent()); - if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_FINISH && - (authResponseContext_->authType == AUTH_TYPE_NFC || authPtr_ != nullptr)) { - authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW); - authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_CONFIRM_SHOW); - } - if (isFinishOfLocal_) { - authMessageProcessor_->SetResponseContext(authResponseContext_); - std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE); - softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); - } - authResponseState_ = nullptr; - authTimes_ = 0; -} - -void DmAuthManager::SrcAuthenticateFinish() -{ - LOGI("DmAuthManager::SrcAuthenticateFinish, isFinishOfLocal: %{public}d", isFinishOfLocal_); - if (isFinishOfLocal_) { - authMessageProcessor_->SetResponseContext(authResponseContext_); - std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE); - softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); - } else { - authRequestContext_->reason = authResponseContext_->reply; - } - if ((authResponseContext_->state == AuthState::AUTH_REQUEST_JOIN || - authResponseContext_->state == AuthState::AUTH_REQUEST_FINISH) && - (authResponseContext_->authType == AUTH_TYPE_NFC || authPtr_ != nullptr)) { - authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); - } - if (timer_ == nullptr) { - timer_ = std::make_shared(); - } - int32_t closeSessionDelaySeconds = authRequestContext_->closeSessionDelaySeconds; - if (IsHmlSessionType() && closeSessionDelaySeconds == 0 && isWaitingJoinLnnCallback_) { - closeSessionDelaySeconds = SESSION_CLOSE_TIMEOUT; - } - timer_->StartTimer(std::string(WAIT_SESSION_CLOSE_TIMEOUT_TASK) + std::string(CLOSE_SESSION_TASK_SEPARATOR) + - std::to_string(authRequestContext_->sessionId), - closeSessionDelaySeconds, [this] (std::string name) { - int32_t sessionIdIndex = 1; - std::string sessionStr = GetSubStr(name, std::string(CLOSE_SESSION_TASK_SEPARATOR), sessionIdIndex); - if (!sessionStr.empty()) { - int32_t sessionId = std::atoi(sessionStr.c_str()); - DmAuthManager::CloseAuthSession(sessionId); - } - }); - listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, authRequestContext_->token, - authResponseContext_->state, authRequestContext_->reason); - listener_->OnBindResult(processInfo_, peerTargetId_, authRequestContext_->reason, - authResponseContext_->state, GenerateBindResultContent()); - - authRequestContext_ = nullptr; - authRequestState_ = nullptr; - authTimes_ = 0; - isWaitingJoinLnnCallback_ = false; -} - -void DmAuthManager::AuthenticateFinish() -{ - { - std::lock_guard lock(srcReqMsgLock_); - srcReqMsg_ = ""; - isNeedProcCachedSrcReqMsg_ = false; - std::lock_guard guard(sessionKeyIdMutex_); - sessionKeyIdAsyncResult_.clear(); - } - pincodeDialogEverShown_ = false; - serviceInfoProfile_ = {}; - authType_ = AUTH_TYPE_UNKNOW; - std::lock_guard autoLock(g_authFinishLock); - if (authResponseContext_ == nullptr || authUiStateMgr_ == nullptr) { - LOGE("failed to AuthenticateFinish because authResponseContext_ or authUiStateMgr is nullptr"); - return; - } - LOGI("DmAuthManager::AuthenticateFinish start"); - isAddingMember_ = false; - isAuthenticateDevice_ = false; - isAuthDevice_ = false; - ClearCallerInfo(); - if (DeviceProfileConnector::GetInstance().GetTrustNumber(remoteDeviceId_) >= 1 && - CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && - softbusConnector_->CheckIsOnline(remoteDeviceId_) && authResponseContext_->isFinish) { - softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); - } - - DeleteAuthCode(); - if (timer_ != nullptr) { - timer_->DeleteAll(); - } - if (authResponseState_ != nullptr) { - SinkAuthenticateFinish(); - } else if (authRequestState_ != nullptr) { - SrcAuthenticateFinish(); - } - isFinishOfLocal_ = true; - authResponseContext_ = nullptr; - authMessageProcessor_ = nullptr; - authPtr_ = nullptr; - authRequestStateTemp_ = nullptr; - authenticationType_ = USER_OPERATION_TYPE_ALLOW_AUTH; - bundleName_ = ""; - if (cleanNotifyCallback_ != nullptr) { - cleanNotifyCallback_(0); - } - LOGI("DmAuthManager::AuthenticateFinish complete"); -} - -int32_t DmAuthManager::RegisterUiStateCallback(const std::string pkgName) -{ - LOGI("DmAuthManager::RegisterUiStateCallback start"); - if (authUiStateMgr_ == nullptr) { - LOGE("DmAuthManager::RegisterUiStateCallback authUiStateMgr_ is null."); - return ERR_DM_FAILED; - } - authUiStateMgr_->RegisterUiStateCallback(pkgName); - return DM_OK; -} - -int32_t DmAuthManager::UnRegisterUiStateCallback(const std::string pkgName) -{ - LOGI("DmAuthManager::UnRegisterUiStateCallback start"); - if (authUiStateMgr_ == nullptr) { - LOGE("DmAuthManager::UnRegisterUiStateCallback authUiStateMgr_ is null."); - return ERR_DM_FAILED; - } - authUiStateMgr_->UnRegisterUiStateCallback(pkgName); - return DM_OK; -} - -std::string DmAuthManager::GeneratePincode() -{ - int32_t pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); - return std::to_string(pinCode); -} - -bool DmAuthManager::IsPinCodeValid(const std::string strpin) -{ - if (strpin.empty()) { - return false; - } - for (size_t i = 0; i < strpin.length(); i++) { - if (!isdigit(strpin[i])) { - return false; - } - } - int32_t pinnum = std::atoi(strpin.c_str()); - return IsPinCodeValid(pinnum); -} - -bool DmAuthManager::IsPinCodeValid(int32_t numpin) -{ - if (numpin < MIN_PIN_CODE || numpin > MAX_PIN_CODE) { - return false; - } - return true; -} - -bool DmAuthManager::CanUsePincodeFromDp() -{ - CHECK_NULL_RETURN(authResponseContext_, false); - return (IsPinCodeValid(serviceInfoProfile_.GetPinCode()) && - serviceInfoProfile_.GetPinExchangeType() == (int32_t)DMLocalServiceInfoPinExchangeType::FROMDP); -} - -bool DmAuthManager::IsServiceInfoAuthTypeValid(int32_t authType) -{ - if (authType != (int32_t)DMLocalServiceInfoAuthType::TRUST_ONETIME && - authType != (int32_t)DMLocalServiceInfoAuthType::TRUST_ALWAYS && - authType != (int32_t)DMLocalServiceInfoAuthType::CANCEL) { - return false; - } - return true; -} - -bool DmAuthManager::IsServiceInfoAuthBoxTypeValid(int32_t authBoxType) -{ - if (authBoxType != (int32_t)DMLocalServiceInfoAuthBoxType::STATE3 && - authBoxType != (int32_t)DMLocalServiceInfoAuthBoxType::SKIP_CONFIRM) { - return false; - } - return true; -} - -bool DmAuthManager::IsServiceInfoPinExchangeTypeValid(int32_t pinExchangeType) -{ - if (pinExchangeType != (int32_t)DMLocalServiceInfoPinExchangeType::PINBOX && - pinExchangeType != (int32_t)DMLocalServiceInfoPinExchangeType::FROMDP && - pinExchangeType != (int32_t)DMLocalServiceInfoPinExchangeType::ULTRASOUND) { - return false; - } - return true; -} - -bool DmAuthManager::IsLocalServiceInfoValid(const DistributedDeviceProfile::LocalServiceInfo &localServiceInfo) -{ - if (!IsServiceInfoAuthTypeValid(localServiceInfo.GetAuthType())) { - LOGE("AuthType not valid, %{public}d", localServiceInfo.GetAuthType()); - return false; - } - if (!IsServiceInfoAuthBoxTypeValid(localServiceInfo.GetAuthBoxType())) { - LOGE("AuthBoxType not valid, %{public}d", localServiceInfo.GetAuthBoxType()); - return false; - } - if (!IsServiceInfoPinExchangeTypeValid(localServiceInfo.GetPinExchangeType())) { - LOGE("PinExchangeType not valid, %{public}d", localServiceInfo.GetPinExchangeType()); - return false; - } - return true; -} - -std::string DmAuthManager::GenerateGroupName() -{ - if (authResponseContext_ == nullptr) { - LOGE("failed to GenerateGroupName because authResponseContext_ is nullptr."); - return ""; - } - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - std::string sLocalDeviceId = localDeviceId; - uint32_t interceptLength = sLocalDeviceId.size() / DEVICE_ID_HALF; - std::string groupName = ""; - if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { - groupName += AUTH_ALWAYS; - } else { - groupName += AUTH_ONCE; - } - groupName += authResponseContext_->targetPkgName + sLocalDeviceId.substr(0, interceptLength) - + authResponseContext_->localDeviceId.substr(0, interceptLength); - return groupName; -} - -bool DmAuthManager::GetIsCryptoSupport() -{ - if (authResponseState_ == nullptr) { - return false; - } - if (authRequestState_ == nullptr) { - if (authResponseState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) { - return false; - } - } else { - if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE || - authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) { - return false; - } - } - - return isCryptoSupport_; -} - -int32_t DmAuthManager::SetAuthRequestState(std::shared_ptr authRequestState) -{ - if (authRequestState == nullptr) { - LOGE("authRequestState is nullptr."); - return ERR_DM_INPUT_PARA_INVALID; - } - // Keep current state, avoid deconstructed during state transitions - authRequestStateTemp_ = authRequestState_; - authRequestState_ = authRequestState; - return DM_OK; -} - -int32_t DmAuthManager::SetAuthResponseState(std::shared_ptr authResponseState) -{ - if (authResponseState == nullptr) { - LOGE("authResponseState is nullptr."); - return ERR_DM_INPUT_PARA_INVALID; - } - authResponseState_ = authResponseState; - return DM_OK; -} - -int32_t DmAuthManager::GetPinCode(std::string &code) -{ - if (authResponseContext_ == nullptr) { - LOGE("failed to GetPinCode because authResponseContext_ is nullptr"); - return ERR_DM_FAILED; - } - LOGI("ShowConfigDialog start add member pin code."); - code = authResponseContext_->code; - return DM_OK; -} - -void DmAuthManager::CheckAndEndTvDream() -{ - NodeBasicInfo nodeBasicInfo; - int32_t result = GetLocalNodeDeviceInfo(DM_PKG_NAME, &nodeBasicInfo); - if (result != SOFTBUS_OK) { - LOGE("GetLocalNodeDeviceInfo from dsofbus fail, result=%{public}d", result); - return; - } - - if (nodeBasicInfo.deviceTypeId == TYPE_TV_ID) { - int32_t ret = AuthManagerBase::EndDream(); - if (ret != DM_OK) { - LOGE("fail to end dream, err:%{public}d", ret); - return; - } - } -} - -void DmAuthManager::ShowConfigDialog() -{ - if (authResponseContext_ == nullptr) { - LOGE("failed to ShowConfigDialog because authResponseContext_ is nullptr"); - return; - } - if (authResponseContext_->authType == AUTH_TYPE_NFC && - serviceInfoProfile_.GetAuthBoxType() == (int32_t)DMLocalServiceInfoAuthBoxType::SKIP_CONFIRM) { - LOGI("no need confirm dialog"); - StartAuthProcess(serviceInfoProfile_.GetAuthType()); - return; - } - if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && !importAuthCode_.empty()) { - LOGI("start auth process"); - StartAuthProcess(authenticationType_); - return; - } - CheckAndEndTvDream(); - LOGI("ShowConfigDialog start"); - JsonObject jsonObj; - jsonObj[TAG_AUTH_TYPE] = AUTH_TYPE_PIN; - jsonObj[TAG_TOKEN] = authResponseContext_->token; - jsonObj[TARGET_PKG_NAME_KEY] = authResponseContext_->targetPkgName; - jsonObj[TAG_CUSTOM_DESCRIPTION] = authResponseContext_->customDesc; - jsonObj[TAG_APP_OPERATION] = authResponseContext_->appOperation; - jsonObj[TAG_LOCAL_DEVICE_TYPE] = authResponseContext_->deviceTypeId; - jsonObj[TAG_REQUESTER] = authResponseContext_->deviceName; - jsonObj[TAG_HOST_PKGLABEL] = authResponseContext_->hostPkgLabel; - const std::string params = SafetyDump(jsonObj); - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - std::string localUdid = static_cast(localDeviceId); - DeviceProfileConnector::GetInstance().SyncAclByBindType(authResponseContext_->peerBundleName, - authResponseContext_->bindType, localUdid, remoteDeviceId_); - DmDialogManager::GetInstance().ShowConfirmDialog(params); - struct RadarInfo info = { - .funcName = "ShowConfigDialog", - .stageRes = static_cast(StageRes::STAGE_IDLE), - }; - if (!DmRadarHelper::GetInstance().ReportAuthPullAuthBox(info)) { - LOGE("ReportAuthPullAuthBox failed"); - } - LOGI("ShowConfigDialog end"); -} - -void DmAuthManager::ShowAuthInfoDialog(bool authDeviceError) -{ - if (authResponseContext_ == nullptr) { - LOGE("failed to ShowAuthInfoDialog because authResponseContext_ is nullptr"); - return; - } - LOGI("DmAuthManager::ShowAuthInfoDialog start"); - if (!authDeviceError && CanUsePincodeFromDp()) { - LOGI("pin import from dp, not show dialog"); - return; - } - if (pincodeDialogEverShown_) { - return; - } - if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && !importAuthCode_.empty()) { - LOGI("not show dialog."); - return; - } - struct RadarInfo info = { - .funcName = "ShowAuthInfoDialog", - .stageRes = static_cast(StageRes::STAGE_SUCC), - }; - if (!DmRadarHelper::GetInstance().ReportAuthPullPinBox(info)) { - LOGE("ReportAuthPullPinBox failed"); - } - pincodeDialogEverShown_ = true; - DmDialogManager::GetInstance().ShowPinDialog(authResponseContext_->code); -} - -void DmAuthManager::ShowStartAuthDialog() -{ - if (authResponseContext_ == nullptr) { - LOGE("failed to ShowStartAuthDialog because authResponseContext_ is nullptr"); - return; - } - if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { - LOGI("Add member start"); - std::string pinCode = ""; - if (GetAuthCode(authResponseContext_->hostPkgName, pinCode) != DM_OK) { - LOGE("failed to get auth code"); - return; - } - if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && - (static_cast(authResponseContext_->bindLevel) >= USER && - static_cast(authResponseContext_->bindLevel) <= APP)) { - AuthDevice(pinCode); - } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || - static_cast(authResponseContext_->bindLevel) == INVALIED_TYPE) { - AddMember(pinCode); - } else { - LOGE("Invalied bind mode."); - } - return; - } - if (IsScreenLocked()) { - LOGE("ShowStartAuthDialog screen is locked."); - SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL, STATUS_DM_AUTH_DEFAULT); - return; - } - LOGI("DmAuthManager::ShowStartAuthDialog start"); - std::string pincode = ""; - if (authResponseContext_->authType == AUTH_TYPE_NFC && - GetAuthCode(authResponseContext_->hostPkgName, pincode) == DM_OK) { - LOGI("already has pin code"); - ProcessPincode(pincode); - return; - } - - pincodeDialogEverShown_ = true; - DmDialogManager::GetInstance().ShowInputDialog(authResponseContext_->targetDeviceName); -} - -int32_t DmAuthManager::ProcessPincode(const std::string &pinCode) -{ - if (authResponseContext_ == nullptr) { - LOGE("failed to ProcessPincode because authResponseContext_ is nullptr"); - return ERR_DM_FAILED; - } - if (timer_ != nullptr) { - timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK)); - } - if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && - (static_cast(authResponseContext_->bindLevel) >= USER && - static_cast(authResponseContext_->bindLevel) <= APP)) { - return AuthDevice(pinCode); - } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || - static_cast(authResponseContext_->bindLevel) == INVALIED_TYPE) { - return AddMember(pinCode); - } else { - LOGE("Invalied bind mode."); - } - return ERR_DM_FAILED; -} - -int32_t DmAuthManager::AuthDevice(const std::string &pinCode) -{ - LOGI("DmAuthManager::AuthDevice start."); - if (isAuthDevice_) { - LOGE("DmAuthManager::AuthDevice doing auth device."); - authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_DOING_AUTH); - return ERR_DM_FAILED; - } - isAuthDevice_ = true; - int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); - if (timer_ != nullptr) { - timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK)); - timer_->StartTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK), AUTH_DEVICE_TIMEOUT, - [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); - } - if (hiChainAuthConnector_->AuthDevice(pinCode, osAccountId, remoteDeviceId_, - authResponseContext_->requestId) != DM_OK) { - LOGE("DmAuthManager::AuthDevice failed."); - isAuthDevice_ = false; - if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { - HandleMemberJoinImportAuthCode(authResponseContext_->requestId, ERR_DM_FAILED); - return ERR_DM_FAILED; - } - } - return DM_OK; -} - -int32_t DmAuthManager::OnUserOperation(int32_t action, const std::string ¶ms) -{ - if (authResponseContext_ == nullptr) { - LOGE("Authenticate is not start"); - return ERR_DM_AUTH_NOT_START; - } - struct RadarInfo info = { - .funcName = "OnUserOperation", - .stageRes = static_cast(StageRes::STAGE_CANCEL), - .bizState = static_cast(BizState::BIZ_STATE_END), - }; - switch (action) { - case USER_OPERATION_TYPE_ALLOW_AUTH: - case USER_OPERATION_TYPE_CANCEL_AUTH: - case USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS: - StartAuthProcess(action); - break; - case USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT: - SetReasonAndFinish(ERR_DM_TIME_OUT, STATUS_DM_AUTH_DEFAULT); - info.errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_TIME_OUT); - break; - case USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY: - SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY, STATUS_DM_AUTH_DEFAULT); - info.errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY); - break; - case USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT: - SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL_ERROR, STATUS_DM_AUTH_DEFAULT); - info.errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_BIND_USER_CANCEL_ERROR); - break; - case USER_OPERATION_TYPE_DONE_PINCODE_INPUT: - ProcessPincode(params); - info.stageRes = static_cast(StageRes::STAGE_SUCC); - break; - default: - LOGE("this action id not support"); - break; - } - if (!DmRadarHelper::GetInstance().ReportAuthConfirmBox(info)) { - LOGE("ReportAuthConfirmBox failed"); - } - return DM_OK; -} - -int32_t DmAuthManager::SetPageId(int32_t pageId) -{ - if (authResponseContext_ == nullptr) { - LOGE("Authenticate is not start"); - return ERR_DM_AUTH_NOT_START; - } - authResponseContext_->pageId = pageId; - return DM_OK; -} - -int32_t DmAuthManager::SetReasonAndFinish(int32_t reason, int32_t state) -{ - if (authResponseContext_ == nullptr) { - LOGE("Authenticate is not start"); - return ERR_DM_AUTH_NOT_START; - } - authResponseContext_->state = state; - authResponseContext_->reply = reason; - if (authRequestState_ != nullptr && authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) { - authRequestContext_->reason = reason; - authRequestState_->TransitionTo(std::make_shared()); - } else if (authResponseState_ != nullptr && authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) { - authResponseState_->TransitionTo(std::make_shared()); - } - return DM_OK; -} - -bool DmAuthManager::IsIdenticalAccount() -{ - JsonObject jsonObj; - jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP; - std::string queryParams = SafetyDump(jsonObj); - - int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); - if (osAccountUserId < 0) { - LOGE("get current process account user id failed"); - return false; - } - std::vector groupList; - if (!hiChainConnector_->GetGroupInfo(osAccountUserId, queryParams, groupList)) { - return false; - } - if (authResponseContext_ == nullptr) { - LOGE("authResponseContext_ is nullptr."); - return false; - } - if (authResponseContext_->accountGroupIdHash == OLD_VERSION_ACCOUNT) { - LOGI("The old version."); - return true; - } - JsonObject jsonPeerGroupIdObj(authResponseContext_->accountGroupIdHash); - if (jsonPeerGroupIdObj.IsDiscarded()) { - LOGE("accountGroupIdHash string not a json type."); - return false; - } - - std::vector items = jsonPeerGroupIdObj.Items(); - for (auto &groupInfo : groupList) { - for (auto it = items.begin(); it != items.end(); ++it) { - if (it->IsString() && it->Get() == Crypto::GetGroupIdHash(groupInfo.groupId)) { - LOGI("Is identical Account."); - return true; - } - } - } - return false; -} - -std::string DmAuthManager::GetAccountGroupIdHash() -{ - JsonObject jsonObj; - jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP; - std::string queryParams = SafetyDump(jsonObj); - - int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); - if (osAccountUserId < 0) { - LOGE("get current process account user id failed"); - return ""; - } - std::vector groupList; - if (!hiChainConnector_->GetGroupInfo(osAccountUserId, queryParams, groupList)) { - return ""; - } - JsonObject jsonAccountObj(JsonCreateType::JSON_CREATE_TYPE_ARRAY); - for (auto &groupInfo : groupList) { - jsonAccountObj.PushBack(Crypto::GetGroupIdHash(groupInfo.groupId)); - } - return SafetyDump(jsonAccountObj); -} - -int32_t DmAuthManager::ImportAuthCode(const std::string &pkgName, const std::string &authCode) -{ - if (authCode.empty() || pkgName.empty()) { - LOGE("ImportAuthCode failed, authCode or pkgName is empty"); - return ERR_DM_INPUT_PARA_INVALID; - } - importAuthCode_ = authCode; - importPkgName_ = pkgName; - return DM_OK; -} - -int32_t DmAuthManager::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, - const std::map &bindParam, int sessionId, uint64_t logicalSessionId) -{ - struct RadarInfo info = { - .funcName = "AuthenticateDevice", - .stageRes = static_cast(StageRes::STAGE_SUCC), - .bizState = static_cast(BizState::BIZ_STATE_END), - }; - if (!DmRadarHelper::GetInstance().ReportDiscoverUserRes(info)) { - LOGE("ReportDiscoverUserRes failed"); - } - if (pkgName.empty()) { - LOGE("DmAuthManager::BindTarget failed, pkgName is empty."); - return ERR_DM_INPUT_PARA_INVALID; - } - int32_t authType = -1; - if (ParseAuthType(bindParam, authType) != DM_OK) { - LOGE("DmAuthManager::BindTarget failed, key: %{public}s error.", PARAM_KEY_AUTH_TYPE); - return ERR_DM_INPUT_PARA_INVALID; - } - peerTargetId_ = targetId; - std::string deviceId = ""; - std::string addrType; - if (bindParam.count(PARAM_KEY_CONN_ADDR_TYPE) != 0) { - addrType = bindParam.at(PARAM_KEY_CONN_ADDR_TYPE); - } - if (ParseConnectAddr(targetId, deviceId, addrType) == DM_OK) { - return AuthenticateDevice(pkgName, authType, deviceId, ParseExtraFromMap(bindParam)); - } else if (!targetId.deviceId.empty()) { - return AuthenticateDevice(pkgName, authType, targetId.deviceId, ParseExtraFromMap(bindParam)); - } else { - LOGE("DmAuthManager::BindTarget failed, targetId is error."); - return ERR_DM_INPUT_PARA_INVALID; - } -} - -int32_t DmAuthManager::ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, std::string &addrType) -{ - int32_t index = 0; - std::shared_ptr deviceInfo = std::make_shared(); - ConnectionAddr addr; - if (!targetId.wifiIp.empty() && targetId.wifiIp.length() <= IP_STR_MAX_LEN) { - LOGI("DmAuthManager::ParseConnectAddr parse wifiIp: %{public}s.", GetAnonyString(targetId.wifiIp).c_str()); - if (!addrType.empty()) { - addr.type = static_cast(std::atoi(addrType.c_str())); - } else { - addr.type = ConnectionAddrType::CONNECTION_ADDR_WLAN; - } - memcpy_s(addr.info.ip.ip, IP_STR_MAX_LEN, targetId.wifiIp.c_str(), targetId.wifiIp.length()); - addr.info.ip.port = targetId.wifiPort; - deviceInfo->addr[index] = addr; - deviceId = targetId.wifiIp; - index++; - } else if (!targetId.brMac.empty() && targetId.brMac.length() <= BT_MAC_LEN) { - LOGI("DmAuthManager::ParseConnectAddr parse brMac: %{public}s.", GetAnonyString(targetId.brMac).c_str()); - addr.type = ConnectionAddrType::CONNECTION_ADDR_BR; - memcpy_s(addr.info.br.brMac, BT_MAC_LEN, targetId.brMac.c_str(), targetId.brMac.length()); - deviceInfo->addr[index] = addr; - deviceId = targetId.brMac; - index++; - } else if (!targetId.bleMac.empty() && targetId.bleMac.length() <= BT_MAC_LEN) { - LOGI("DmAuthManager::ParseConnectAddr parse bleMac: %{public}s.", GetAnonyString(targetId.bleMac).c_str()); - addr.type = ConnectionAddrType::CONNECTION_ADDR_BLE; - memcpy_s(addr.info.ble.bleMac, BT_MAC_LEN, targetId.bleMac.c_str(), targetId.bleMac.length()); - if (!targetId.deviceId.empty()) { - Crypto::ConvertHexStringToBytes(addr.info.ble.udidHash, UDID_HASH_LEN, - targetId.deviceId.c_str(), targetId.deviceId.length()); - } - deviceInfo->addr[index] = addr; - deviceId = targetId.bleMac; - index++; - } else { - LOGE("DmAuthManager::ParseConnectAddr failed, not addr."); - return ERR_DM_INPUT_PARA_INVALID; - } - - deviceInfo->addrNum = static_cast(index); - if (softbusConnector_->AddMemberToDiscoverMap(deviceId, deviceInfo) != DM_OK) { - LOGE("DmAuthManager::ParseConnectAddr failed, AddMemberToDiscoverMap failed."); - return ERR_DM_INPUT_PARA_INVALID; - } - deviceInfo = nullptr; - return DM_OK; -} - -std::string DmAuthManager::ParseExtraFromMap(const std::map &bindParam) -{ - auto iter = bindParam.find(PARAM_KEY_BIND_EXTRA_DATA); - if (iter != bindParam.end()) { - return iter->second; - } - return ConvertMapToJsonString(bindParam); -} - -bool DmAuthManager::IsAuthCodeReady(const std::string &pkgName) -{ - if (importAuthCode_.empty() || importPkgName_.empty()) { - LOGE("DmAuthManager::IsAuthCodeReady, auth code not ready."); - return false; - } - if (pkgName != importPkgName_) { - LOGE("IsAuthCodeReady failed, pkgName not supported."); - return false; - } - return true; -} - -int32_t DmAuthManager::DeleteAuthCode() -{ - importAuthCode_ = ""; - importPkgName_ = ""; - return DM_OK; -} - -int32_t DmAuthManager::GetAuthCode(const std::string &pkgName, std::string &pinCode) -{ - if (importAuthCode_.empty() || importPkgName_.empty()) { - LOGE("GetAuthCode failed, auth code not exist."); - return ERR_DM_FAILED; - } - if (pkgName != importPkgName_) { - LOGE("GetAuthCode failed, pkgName not supported."); - return ERR_DM_FAILED; - } - pinCode = std::to_string(std::atoi(importAuthCode_.c_str())); - return DM_OK; -} - -bool DmAuthManager::IsImportedAuthCodeValid() -{ - std::string pinCode = ""; - if (GetAuthCode(authRequestContext_->hostPkgName, pinCode) == DM_OK) { - return true; - } - return false; -} - -bool DmAuthManager::IsSrc() -{ - if (authRequestState_ != nullptr) { - return true; - } else { - return false; - } -} - -bool DmAuthManager::IsAuthTypeSupported(const int32_t &authType) -{ - if (authenticationMap_.find(authType) == authenticationMap_.end()) { - LOGE("IsAuthTypeSupported failed, authType is not supported."); - return false; - } - return true; -} - -std::string DmAuthManager::GenerateBindResultContent() -{ - JsonObject jsonObj; - jsonObj[DM_BIND_RESULT_NETWORK_ID] = authResponseContext_->networkId; - if (remoteDeviceId_.empty()) { - jsonObj[TAG_DEVICE_ID] = ""; - } else { - char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; - Crypto::GetUdidHash(remoteDeviceId_, reinterpret_cast(deviceIdHash)); - jsonObj[TAG_DEVICE_ID] = deviceIdHash; - } - jsonObj[TAG_CONFIRM_OPERATION] = authResponseContext_->confirmOperation; - std::string content = SafetyDump(jsonObj); - return content; -} - -void DmAuthManager::RequestCredential() -{ - LOGI("DmAuthManager::RequestCredential start."); - std::string publicKey = ""; - GenerateCredential(publicKey); - authResponseContext_->publicKey = publicKey; - std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_PUBLICKEY); - softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); -} - -void DmAuthManager::GenerateCredential(std::string &publicKey) -{ - LOGI("DmAuthManager::GenerateCredential start."); - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - std::string localUdid = localDeviceId; - int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); - hiChainAuthConnector_->GetCredential(localUdid, osAccountId, publicKey); - if (publicKey == "") { - hiChainAuthConnector_->GenerateCredential(localUdid, osAccountId, publicKey); - } -} - -void DmAuthManager::RequestCredentialDone() -{ - LOGI("DmAuthManager ExchangeCredentailDone start"); - CHECK_NULL_VOID(authResponseContext_); - if (authResponseContext_->publicKey == "" || - ImportCredential(remoteDeviceId_, authResponseContext_->publicKey) != DM_OK) { - LOGE("RequestCredentialDone import credential failed."); - } - if (timer_ != nullptr) { - timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); - } - if (softbusConnector_->CheckIsOnline(remoteDeviceId_) && !authResponseContext_->isOnline) { - JoinLnn(authRequestContext_->addr, true); - } else { - JoinLnn(authRequestContext_->addr, false); - } - authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; - authRequestContext_->reason = DM_OK; - authResponseContext_->reply = DM_OK; - authRequestState_->TransitionTo(std::make_shared()); -} - -int32_t DmAuthManager::ImportCredential(std::string &deviceId, std::string &publicKey) -{ - LOGI("DmAuthManager::ImportCredential, deviceId %{public}s", GetAnonyString(deviceId).c_str()); - int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); - if ((authRequestState_ != nullptr) && (authResponseState_ == nullptr)) { - // Source Import Credential - LOGI("Source Import Credential remoteUserId: %{public}d", authRequestContext_->remoteUserId); - CHECK_NULL_RETURN(authRequestContext_, ERR_DM_POINT_NULL); - CHECK_NULL_RETURN(hiChainAuthConnector_, ERR_DM_POINT_NULL); - return hiChainAuthConnector_->ImportCredential(osAccountId, authRequestContext_->remoteUserId, deviceId, - publicKey); - } else if ((authResponseState_ != nullptr) && (authRequestState_ == nullptr)) { - // Sink Import Credential - LOGI("Source Import Credential remoteUserId: %{public}d", authResponseContext_->remoteUserId); - CHECK_NULL_RETURN(authResponseContext_, ERR_DM_POINT_NULL); - CHECK_NULL_RETURN(hiChainAuthConnector_, ERR_DM_POINT_NULL); - return hiChainAuthConnector_->ImportCredential(osAccountId, authResponseContext_->remoteUserId, deviceId, - publicKey); - } else { - LOGE("DmAuthManager::ImportCredential failed, authRequestState_ or authResponseState_ is invalid."); - return ERR_DM_AUTH_FAILED; - } -} - -void DmAuthManager::ResponseCredential() -{ - LOGI("DmAuthManager::ResponseCredential start."); - CHECK_NULL_VOID(authResponseContext_); - if (authResponseContext_->publicKey == "") { - LOGE("authResponseContext_->publicKey is empty."); - authResponseContext_->isFinish = false; - isFinishOfLocal_ = false; - authMessageProcessor_->SetEncryptFlag(false); - authResponseContext_->state = authResponseState_->GetStateType(); - authResponseState_->TransitionTo(std::make_shared()); - return; - } - std::string publicKey = ""; - GenerateCredential(publicKey); - if (ImportCredential(remoteDeviceId_, authResponseContext_->publicKey) != DM_OK) { - LOGE("ResponseCredential import credential failed."); - authResponseContext_->state = authResponseState_->GetStateType(); - authResponseState_->TransitionTo(std::make_shared()); - return; - } - authResponseContext_->publicKey = publicKey; - std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_PUBLICKEY); - softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); -} - -bool DmAuthManager::AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) -{ - LOGI("DmAuthManager::onTransmit start."); - if (requestId != authResponseContext_->requestId) { - LOGE("DmAuthManager::onTransmit requestId %{public}" PRId64"is error.", requestId); - return false; - } - std::string message = ""; - if (authRequestState_ != nullptr && authResponseState_ == nullptr) { - LOGI("SoftbusSession send msgType %{public}d.", MSG_TYPE_REQ_AUTH_DEVICE_NEGOTIATE); - message = authMessageProcessor_->CreateDeviceAuthMessage(MSG_TYPE_REQ_AUTH_DEVICE_NEGOTIATE, data, dataLen); - } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) { - LOGI("SoftbusSession send msgType %{public}d.", MSG_TYPE_RESP_AUTH_DEVICE_NEGOTIATE); - message = authMessageProcessor_->CreateDeviceAuthMessage(MSG_TYPE_RESP_AUTH_DEVICE_NEGOTIATE, data, dataLen); - } - if (softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message) != DM_OK) { - LOGE("SoftbusSession send data failed."); - return false; - } - return true; -} - -void DmAuthManager::SrcAuthDeviceFinish() -{ - LOGI("DmAuthManager::SrcAuthDeviceFinish Start."); - CHECK_NULL_VOID(authRequestState_); - authRequestState_->TransitionTo(std::make_shared()); - if (authResponseContext_->confirmOperation != USER_OPERATION_TYPE_ALLOW_AUTH && - authResponseContext_->confirmOperation != USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { - LOGE("auth failed %{public}d.", authResponseContext_->confirmOperation); - return; - } - if (authResponseContext_->isOnline && authResponseContext_->haveCredential) { - if (!authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { - SetProcessInfo(); - } - softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); - if (timer_ != nullptr) { - timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); - } - ConverToFinish(); - return; - } - if (authResponseContext_->isOnline && !authResponseContext_->haveCredential) { - authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); - if (!authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { - SetProcessInfo(); - } - softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); - if (CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_2))) { - authRequestState_->TransitionTo(std::make_shared()); - } else { - authRequestState_->TransitionTo(std::make_shared()); - } - return; - } - if (!authResponseContext_->isOnline && authResponseContext_->haveCredential) { - JoinLnn(authRequestContext_->addr); - timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); - ConverToFinish(); - return; - } - if (!authResponseContext_->isOnline && !authResponseContext_->haveCredential) { - authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); - if (CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_2))) { - authRequestState_->TransitionTo(std::make_shared()); - } else { - authRequestState_->TransitionTo(std::make_shared()); - } - return; - } -} - -void DmAuthManager::SinkAuthDeviceFinish() -{ - LOGI("isNeedProcCachedSrcReqMsg %{public}d.", isNeedProcCachedSrcReqMsg_); - CHECK_NULL_VOID(authResponseState_); - authResponseState_->TransitionTo(std::make_shared()); - if (!authResponseContext_->haveCredential) { - authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW); - } - if (authResponseContext_->isOnline) { - LOGI("The device is online."); - SetProcessInfo(); - softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); - } - std::string srcReqMsg = ""; - bool isNeedProcCachedSrcReqMsg = false; - { - std::lock_guard lock(srcReqMsgLock_); - srcReqMsg = srcReqMsg_; - isNeedProcCachedSrcReqMsg = isNeedProcCachedSrcReqMsg_; - srcReqMsg_ = ""; - isNeedProcCachedSrcReqMsg_ = false; - } - if (!isNeedProcCachedSrcReqMsg || srcReqMsg.empty()) { - LOGI("please wait client request."); - return; - } - authMessageProcessor_->SetResponseContext(authResponseContext_); - if (authMessageProcessor_->ParseMessage(srcReqMsg) != DM_OK) { - LOGE("ParseMessage failed."); - return; - } - if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_2))) { - authResponseState_->TransitionTo(std::make_shared()); - } else { - authResponseState_->TransitionTo(std::make_shared()); - } -} - -void DmAuthManager::AuthDeviceFinish(int64_t requestId) -{ - LOGI("DmAuthManager::AuthDeviceFinish start."); - if (requestId != authResponseContext_->requestId) { - LOGE("DmAuthManager::onTransmit requestId %{public}" PRId64 "is error.", requestId); - return; - } - isAuthDevice_ = false; - if (timer_ != nullptr) { - timer_->DeleteTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK)); - } - if (CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_2))) { - LOGI("Set EncryptFlag true."); - authMessageProcessor_->SetEncryptFlag(true); - } else { - PutAccessControlList(); - } - if (authRequestState_ != nullptr && authResponseState_ == nullptr) { - SrcAuthDeviceFinish(); - } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) { - SinkAuthDeviceFinish(); - } -} - -void DmAuthManager::AuthDeviceError(int64_t requestId, int32_t errorCode) -{ - LOGI("AuthDeviceError start."); - isAuthDevice_ = false; - if (authRequestState_ == nullptr || authResponseState_ != nullptr) { - if (CheckNeedShowAuthInfoDialog(errorCode)) { - return; - } - authTimes_++; - if (authTimes_ >= MAX_AUTH_TIMES) { - authResponseContext_->isFinish = false; - authResponseContext_->reply = ERR_DM_AUTH_CODE_INCORRECT; - authResponseContext_->state = AuthState::AUTH_RESPONSE_SHOW; - isFinishOfLocal_ = false; - authResponseState_->TransitionTo(std::make_shared()); - } - return; - } - if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { - if (requestId != authResponseContext_->requestId) { - LOGE("DmAuthManager::AuthDeviceError requestId %{public}" PRId64 "is error.", requestId); - return; - } - authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; - authRequestContext_->reason = ERR_DM_AUTH_CODE_INCORRECT; - authResponseContext_->reply = ERR_DM_AUTH_CODE_INCORRECT; - authRequestState_->TransitionTo(std::make_shared()); - return; - } - authTimes_++; - if (timer_ != nullptr) { - timer_->DeleteTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK)); - } - if (errorCode != DM_OK || requestId != authResponseContext_->requestId) { - if (authRequestState_ != nullptr && authTimes_ >= MAX_AUTH_TIMES) { - authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; - authRequestContext_->reason = ERR_DM_INPUT_PARA_INVALID; - authResponseContext_->reply = ERR_DM_INPUT_PARA_INVALID; - authRequestState_->TransitionTo(std::make_shared()); - } else { - if (timer_ != nullptr) { - timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), - GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); - } - UpdateInputPincodeDialog(errorCode); - } - } -} - -void DmAuthManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) -{ - LOGI("DmAuthManager::AuthDeviceSessionKey start. keyLen: %{public}u", sessionKeyLen); - if (requestId != authResponseContext_->requestId) { - LOGE("DmAuthManager::onTransmit requestId %{public}" PRId64 "is error.", requestId); - return; - } - CHECK_NULL_VOID(authMessageProcessor_); - if (CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_4))) { - if (authMessageProcessor_->ProcessSessionKey(sessionKey, sessionKeyLen) != DM_OK) { - LOGE("Process session key err."); - return; - } - } else { - if (authMessageProcessor_->SaveSessionKey(sessionKey, sessionKeyLen) != DM_OK) { - LOGE("Save session key err."); - return; - } - } - authResponseContext_->localSessionKeyId = 0; - { - std::lock_guard guard(sessionKeyIdMutex_); - sessionKeyIdAsyncResult_.clear(); - sessionKeyIdAsyncResult_[requestId] = std::optional(); - } - unsigned char hash[SHA256_DIGEST_LENGTH] = { 0 }; - Crypto::DmGenerateStrHash(sessionKey, sessionKeyLen, hash, SHA256_DIGEST_LENGTH, 0); - std::vector hashVector(hash, hash + SHA256_DIGEST_LENGTH); - std::shared_ptr sharePtrThis = shared_from_this(); - auto asyncTaskFunc = [sharePtrThis, requestId, hashVector]() { - sharePtrThis->PutSessionKeyAsync(requestId, hashVector); - }; - ffrt::submit(asyncTaskFunc, ffrt::task_attr().delay(0)); -} - -void DmAuthManager::PutSessionKeyAsync(int64_t requestId, std::vector hash) -{ - { - std::lock_guard guard(sessionKeyIdMutex_); - int32_t sessionKeyId = 0; - int32_t ret = - DeviceProfileConnector::GetInstance().PutSessionKey(MultipleUserConnector::GetCurrentAccountUserID(), - hash, sessionKeyId); - if (ret != DM_OK) { - LOGI("PutSessionKey failed."); - sessionKeyId = 0; - } - sessionKeyIdAsyncResult_[requestId] = sessionKeyId; - } - sessionKeyIdCondition_.notify_one(); -} - -int32_t DmAuthManager::GetSessionKeyIdSync(int64_t requestId) -{ - std::unique_lock guard(sessionKeyIdMutex_); - if (sessionKeyIdAsyncResult_.find(requestId) == sessionKeyIdAsyncResult_.end()) { - LOGW("GetSessionKeyIdSync failed, not find by requestId"); - return 0; - } - if (sessionKeyIdAsyncResult_[requestId].has_value()) { - LOGI("GetSessionKeyIdSync, already ready"); - return sessionKeyIdAsyncResult_[requestId].value(); - } - LOGI("GetSessionKeyIdSync need wait"); - sessionKeyIdCondition_.wait_for(guard, std::chrono::milliseconds(MAX_PUT_SESSIONKEY_TIMEOUT)); - int32_t keyid = sessionKeyIdAsyncResult_[requestId].value_or(0); - LOGI("GetSessionKeyIdSync exit"); - return keyid; -} - -char *DmAuthManager::AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) -{ - LOGI("DmAuthManager::AuthDeviceRequest start."); - (void)requestId; - (void)reqParams; - JsonObject jsonObj; - std::string pinCode = ""; - if (GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == "") { - jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED; - } else { - jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; - jsonObj[FIELD_PIN_CODE] = pinCode; - } - std::string deviceId = ""; - GetRemoteDeviceId(deviceId); - jsonObj[FIELD_PEER_CONN_DEVICE_ID] = deviceId; - std::string jsonStr = SafetyDump(jsonObj); - char *buffer = strdup(jsonStr.c_str()); - return buffer; -} - -void DmAuthManager::GetRemoteDeviceId(std::string &deviceId) -{ - LOGI("GetRemoteDeviceId start."); - deviceId = remoteDeviceId_; -} - -void DmAuthManager::CompatiblePutAcl() -{ - LOGI("DmAuthManager::CompatiblePutAcl"); - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - std::string localUdid = static_cast(localDeviceId); - char mUdidHash[DM_MAX_DEVICE_ID_LEN] = {0}; - Crypto::GetUdidHash(localUdid, reinterpret_cast(mUdidHash)); - std::string localUdidHash = static_cast(mUdidHash); - DmAclInfo aclInfo; - aclInfo.bindLevel = USER; - aclInfo.bindType = DM_POINT_TO_POINT; - aclInfo.trustDeviceId = remoteDeviceId_; - if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { - aclInfo.authenticationType = ALLOW_AUTH_ALWAYS; - } else if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH) { - aclInfo.authenticationType = ALLOW_AUTH_ONCE; - } - aclInfo.deviceIdHash = localUdidHash; - - DmAccesser accesser; - DmAccessee accessee; - if (authRequestState_ != nullptr && authResponseState_ == nullptr) { - accesser.requestBundleName = authResponseContext_->hostPkgName; - accesser.requestDeviceId = localUdid; - accesser.requestUserId = MultipleUserConnector::GetCurrentAccountUserID(); - accesser.requestAccountId = MultipleUserConnector::GetAccountInfoByUserId(accesser.requestUserId).accountId; - accesser.requestTokenId = static_cast(authRequestContext_->tokenId); - accessee.trustBundleName = authResponseContext_->hostPkgName; - accessee.trustDeviceId = remoteDeviceId_; - accessee.trustUserId = -1; - } - if (authRequestState_ == nullptr && authResponseState_ != nullptr) { - accesser.requestBundleName = authResponseContext_->hostPkgName; - accesser.requestDeviceId = remoteDeviceId_; - accesser.requestUserId = authResponseContext_->remoteUserId; - accesser.requestAccountId = authResponseContext_->remoteAccountId; - accesser.requestTokenId = static_cast(authResponseContext_->remoteTokenId); - accessee.trustBundleName = authResponseContext_->hostPkgName; - accessee.trustDeviceId = localUdid; - accessee.trustUserId = MultipleUserConnector::GetCurrentAccountUserID(); - accessee.trustAccountId = MultipleUserConnector::GetAccountInfoByUserId(accessee.trustUserId).accountId; - accessee.trustTokenId = static_cast(authResponseContext_->tokenId); - } - DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, accesser, accessee); -} - -void DmAuthManager::ProcRespNegotiateExt(const int32_t &sessionId) -{ - LOGI("DmAuthManager::ProcRespNegotiateExt start."); - remoteDeviceId_ = authResponseContext_->localDeviceId; - authResponseContext_->remoteAccountId = authResponseContext_->localAccountId; - authResponseContext_->remoteUserId = authResponseContext_->localUserId; - GetBinderInfo(); - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - authResponseContext_->deviceId = authResponseContext_->localDeviceId; - authResponseContext_->localDeviceId = static_cast(localDeviceId); - authResponseContext_->bindType = - DeviceProfileConnector::GetInstance().GetBindTypeByPkgName(authResponseContext_->hostPkgName, - authResponseContext_->localDeviceId, authResponseContext_->deviceId); - authResponseContext_->authed = !authResponseContext_->bindType.empty(); - - authResponseContext_->isIdenticalAccount = false; - if (authResponseContext_->localAccountId == authResponseContext_->remoteAccountId && - authResponseContext_->localAccountId != "ohosAnonymousUid" && authResponseContext_->authed) { - authResponseContext_->isIdenticalAccount = true; - } - - authResponseContext_->isOnline = softbusConnector_->CheckIsOnline(remoteDeviceId_); - authResponseContext_->haveCredential = - hiChainAuthConnector_->QueryCredential(authResponseContext_->deviceId, - MultipleUserConnector::GetFirstForegroundUserId(), authResponseContext_->remoteUserId); - if (!IsAuthTypeSupported(authResponseContext_->authType)) { - LOGE("DmAuthManager::AuthenticateDevice authType %{public}d not support.", authResponseContext_->authType); - authResponseContext_->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; - } else { - authPtr_ = authenticationMap_[authResponseContext_->authType]; - } - if (IsAuthCodeReady(authResponseContext_->hostPkgName)) { - authResponseContext_->isAuthCodeReady = true; - } else { - authResponseContext_->isAuthCodeReady = false; - } - std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_NEGOTIATE); - softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); - - if (authResponseContext_->authType == AUTH_TYPE_NFC) { - GetLocalServiceInfoInDp(); - } -} - -void DmAuthManager::ProcRespNegotiate(const int32_t &sessionId) -{ - LOGI("DmAuthManager::ProcRespNegotiate session id"); - AbilityNegotiate(); - authResponseContext_->isOnline = softbusConnector_->CheckIsOnline(remoteDeviceId_); - std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_NEGOTIATE); - JsonObject jsonObject(message); - if (jsonObject.IsDiscarded()) { - softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); - return; - } - if (!IsBool(jsonObject, TAG_CRYPTO_SUPPORT)) { - LOGE("err json string."); - softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); - return; - } - jsonObject[TAG_ACCOUNT_GROUPID] = GetAccountGroupIdHash(); - authResponseContext_ = authResponseState_->GetAuthContext(); - if (jsonObject[TAG_CRYPTO_SUPPORT].Get() == true && authResponseContext_->cryptoSupport) { - if (IsString(jsonObject, TAG_CRYPTO_NAME) && IsString(jsonObject, TAG_CRYPTO_VERSION)) { - if (jsonObject[TAG_CRYPTO_NAME].Get() == authResponseContext_->cryptoName && - jsonObject[TAG_CRYPTO_VERSION].Get() == authResponseContext_->cryptoVer) { - isCryptoSupport_ = true; - softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); - return; - } - } - } - jsonObject[TAG_CRYPTO_SUPPORT] = false; - message = SafetyDump(jsonObject); - softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); -} - -void DmAuthManager::ProcIncompatible(const int32_t &sessionId) -{ - LOGI("DmAuthManager::ProcIncompatible sessionId %{public}d.", sessionId); - JsonObject respNegotiateMsg; - respNegotiateMsg[TAG_REPLY] = ERR_DM_VERSION_INCOMPATIBLE; - respNegotiateMsg[TAG_VER] = DM_ITF_VER; - respNegotiateMsg[TAG_MSG_TYPE] = MSG_TYPE_RESP_NEGOTIATE; - std::string message = SafetyDump(respNegotiateMsg); - softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); -} - -void DmAuthManager::OnAuthDeviceDataReceived(const int32_t sessionId, const std::string message) -{ - if (authResponseContext_ == nullptr || authMessageProcessor_ == nullptr || hiChainAuthConnector_ == nullptr || - authResponseContext_->sessionId != sessionId) { - LOGE("OnAuthDeviceDataReceived param is invalid"); - return; - } - authResponseContext_->sessionId = sessionId; - authMessageProcessor_->SetResponseContext(authResponseContext_); - JsonObject jsonObject(message); - if (jsonObject.IsDiscarded()) { - LOGE("DecodeRequestAuth jsonStr error"); - return; - } - if (!IsString(jsonObject, TAG_DATA) || !IsInt32(jsonObject, TAG_DATA_LEN) || !IsInt32(jsonObject, TAG_MSG_TYPE)) { - LOGE("Auth device data is error."); - return; - } - LOGI("OnAuthDeviceDataReceived start msgType %{public}d.", jsonObject[TAG_MSG_TYPE].Get()); - std::string authData = jsonObject[TAG_DATA].Get(); - int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); - hiChainAuthConnector_->ProcessAuthData(authResponseContext_->requestId, authData, osAccountId); -} - -int32_t DmAuthManager::DeleteGroup(const std::string &pkgName, const std::string &deviceId) -{ - LOGI("DmAuthManager::DeleteGroup"); - if (pkgName.empty()) { - LOGE("Invalid parameter, pkgName is empty."); - return ERR_DM_FAILED; - } - std::vector groupList; - CHECK_NULL_RETURN(hiChainConnector_, ERR_DM_POINT_NULL); - hiChainConnector_->GetRelatedGroups(deviceId, groupList); - for (const auto &item : groupList) { - std::string groupId = item.groupId; - hiChainConnector_->DeleteGroup(groupId); - } - return DM_OK; -} - -int32_t DmAuthManager::DeleteGroup(const std::string &pkgName, int32_t userId, const std::string &deviceId) -{ - LOGI("DmAuthManager::DeleteGroup"); - if (pkgName.empty()) { - LOGE("Invalid parameter, pkgName is empty."); - return ERR_DM_FAILED; - } - std::vector groupList; - hiChainConnector_->GetRelatedGroups(userId, deviceId, groupList); - if (groupList.size() > 0) { - std::string groupId = ""; - groupId = groupList.front().groupId; - hiChainConnector_->DeleteGroup(userId, groupId); - } else { - LOGE("DmAuthManager::UnAuthenticateDevice groupList.size = 0"); - return ERR_DM_FAILED; - } - if (softbusConnector_ != nullptr) { - softbusConnector_->EraseUdidFromMap(deviceId); - } - return DM_OK; -} - -void DmAuthManager::PutAccessControlList() -{ - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - std::string localUdid = static_cast(localDeviceId); - char mUdidHash[DM_MAX_DEVICE_ID_LEN] = {0}; - Crypto::GetUdidHash(localUdid, reinterpret_cast(mUdidHash)); - std::string localUdidHash = static_cast(mUdidHash); - DmAclInfo aclInfo; - aclInfo.bindType = DM_ACROSS_ACCOUNT; - if (authResponseContext_->localAccountId == "ohosAnonymousUid" || - authResponseContext_->remoteAccountId == "ohosAnonymousUid") { - aclInfo.bindType = DM_POINT_TO_POINT; - authForm_ = DmAuthForm::PEER_TO_PEER; - } - aclInfo.bindLevel = authResponseContext_->bindLevel; - aclInfo.trustDeviceId = remoteDeviceId_; - aclInfo.authenticationType = ALLOW_AUTH_ONCE; - if (authResponseContext_->confirmOperation == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { - aclInfo.authenticationType = ALLOW_AUTH_ALWAYS; - } - aclInfo.deviceIdHash = localUdidHash; - DmAccesser accesser; - accesser.requestBundleName = authResponseContext_->hostPkgName; - DmAccessee accessee; - accessee.trustBundleName = authResponseContext_->peerBundleName; - if (authRequestState_ != nullptr && authResponseState_ == nullptr) { - PutSrcAccessControlList(accesser, accessee, localUdid); - } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) { - PutSinkAccessControlList(accesser, accessee, localUdid); - } - DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, accesser, accessee); -} - -void DmAuthManager::PutSrcAccessControlList(DmAccesser &accesser, DmAccessee &accessee, - const std::string &localUdid) -{ - accesser.requestTokenId = static_cast(authRequestContext_->tokenId); - accesser.requestUserId = authRequestContext_->localUserId; - accesser.requestAccountId = authRequestContext_->localAccountId; - accesser.requestDeviceId = authRequestContext_->localDeviceId; - accesser.requestDeviceName = authRequestContext_->localDeviceName; - if (authResponseContext_->remoteTokenId == authRequestContext_->tokenId) { - accessee.trustTokenId = 0; - } else { - accessee.trustTokenId = static_cast(authResponseContext_->remoteTokenId); - } - accessee.trustUserId = authRequestContext_->remoteUserId; - accessee.trustAccountId = authRequestContext_->remoteAccountId; - accessee.trustDeviceId = remoteDeviceId_; - accessee.trustDeviceName = authRequestContext_->remoteDeviceName; -} - -void DmAuthManager::PutSinkAccessControlList(DmAccesser &accesser, DmAccessee &accessee, - const std::string &localUdid) -{ - accesser.requestTokenId = static_cast(authResponseContext_->remoteTokenId); - accesser.requestUserId = authResponseContext_->remoteUserId; - accesser.requestAccountId = authResponseContext_->remoteAccountId; - accesser.requestDeviceId = remoteDeviceId_; - accesser.requestDeviceName = authResponseContext_->remoteDeviceName; - if (authResponseContext_->remoteTokenId == authResponseContext_->tokenId) { - accessee.trustTokenId = 0; - } else { - accessee.trustTokenId = static_cast(authResponseContext_->tokenId); - } - accessee.trustUserId = authResponseContext_->localUserId; - accessee.trustAccountId = authResponseContext_->localAccountId; - accessee.trustDeviceId = localUdid; - accessee.trustDeviceName = authResponseContext_->targetDeviceName; -} - -void DmAuthManager::HandleSessionHeartbeat(std::string name) -{ - if (timer_ != nullptr) { - timer_->DeleteTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK)); - } - LOGI("DmAuthManager::HandleSessionHeartbeat name %{public}s", name.c_str()); - JsonObject jsonObj; - jsonObj[TAG_SESSION_HEARTBEAT] = TAG_SESSION_HEARTBEAT; - std::string message = SafetyDump(jsonObj); - softbusConnector_->GetSoftbusSession()->SendHeartbeatData(authResponseContext_->sessionId, message); - - if (authRequestState_ != nullptr) { - if (timer_ != nullptr) { - timer_->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), - GetTaskTimeout(SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), [this] (std::string name) { - DmAuthManager::HandleSessionHeartbeat(name); - }); - } - } - LOGI("DmAuthManager::HandleSessionHeartbeat complete"); -} - -int32_t DmAuthManager::CheckTrustState() -{ - bool isSameGroup = false; - if (authResponseContext_->reply == ERR_DM_AUTH_PEER_REJECT && - hiChainConnector_->IsDevicesInP2PGroup(authResponseContext_->localDeviceId, - authRequestContext_->localDeviceId)) { - isSameGroup = true; - } - if (isSameGroup && authResponseContext_->isOnline && authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { - authResponseContext_->isFinish = true; - SetReasonAndFinish(DM_OK, AuthState::AUTH_REQUEST_FINISH); - return ALREADY_BIND; - } - if (authResponseContext_->isIdenticalAccount) { - if (IsIdenticalAccount()) { - JoinLnn(authResponseContext_->deviceId); - authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; - authRequestContext_->reason = DM_OK; - authResponseContext_->reply = DM_OK; - authRequestState_->TransitionTo(std::make_shared()); - return ALREADY_BIND; - } - } - if (isSameGroup) { - if (!DeviceProfileConnector::GetInstance().CheckSrcDevIdInAclForDevBind(authResponseContext_->hostPkgName, - authResponseContext_->localDeviceId)) { - CompatiblePutAcl(); - } - JoinLnn(authResponseContext_->deviceId); - authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; - authRequestState_->TransitionTo(std::make_shared()); - return ALREADY_BIND; - } - if (authResponseContext_->reply == ERR_DM_UNSUPPORTED_AUTH_TYPE || - (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && - authResponseContext_->isAuthCodeReady == false)) { - authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; - authRequestContext_->reason = ERR_DM_BIND_PEER_UNSUPPORTED; - authRequestState_->TransitionTo(std::make_shared()); - return ERR_DM_BIND_PEER_UNSUPPORTED; - } - return DM_OK; -} - -std::string DmAuthManager::GetBundleLable(const std::string &bundleName) -{ - auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (samgr == nullptr) { - LOGE("Get ability manager failed"); - return bundleName; - } - - sptr object = samgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); - if (object == nullptr) { - LOGE("object is NULL."); - return bundleName; - } - - sptr bms = iface_cast(object); - if (bms == nullptr) { - LOGE("bundle manager service is NULL."); - return bundleName; - } - - auto bundleResourceProxy = bms->GetBundleResourceProxy(); - if (bundleResourceProxy == nullptr) { - LOGE("GetBundleResourceProxy fail"); - return bundleName; - } - AppExecFwk::BundleResourceInfo resourceInfo; - auto result = bundleResourceProxy->GetBundleResourceInfo(bundleName, - static_cast(OHOS::AppExecFwk::ResourceFlag::GET_RESOURCE_INFO_ALL), resourceInfo); - if (result != ERR_OK) { - LOGE("GetBundleResourceInfo failed"); - return bundleName; - } - LOGI("bundle resource label is %{public}s ", (resourceInfo.label).c_str()); - return resourceInfo.label; -} - -bool DmAuthManager::IsScreenLocked() -{ - bool isLocked = false; -#if defined(SUPPORT_SCREENLOCK) - isLocked = OHOS::ScreenLock::ScreenLockManager::GetInstance()->IsScreenLocked(); -#endif - LOGI("IsScreenLocked isLocked: %{public}d.", isLocked); - return isLocked; -} - -void DmAuthManager::OnScreenLocked() -{ - if (authResponseContext_ != nullptr && AUTH_TYPE_IMPORT_AUTH_CODE == authResponseContext_->authType) { - LOGI("OnScreenLocked authtype is: %{public}d, no need stop bind.", authResponseContext_->authType); - return; - } - if (authRequestState_ == nullptr) { - LOGE("OnScreenLocked authRequestState_ is nullptr."); - return; - } - if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE || - authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT) { - LOGI("OnScreenLocked stop bind."); - SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL, STATUS_DM_AUTH_DEFAULT); - return; - } - if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_JOIN) { - LOGI("OnScreenLocked stop user input."); - if (authUiStateMgr_ != nullptr) { - authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); - } - SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL, STATUS_DM_AUTH_DEFAULT); - return; - } - if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) { - LOGI("OnScreenLocked stop confirm."); - SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL, STATUS_DM_AUTH_DEFAULT); - } -} - -void DmAuthManager::HandleDeviceNotTrust(const std::string &udid) -{ - LOGI("DmAuthManager::HandleDeviceNotTrust udid: %{public}s.", GetAnonyString(udid).c_str()); - if (udid.empty()) { - LOGE("DmAuthManager::HandleDeviceNotTrust udid is empty."); - return; - } - DeviceProfileConnector::GetInstance().DeleteAccessControlList(udid); - CHECK_NULL_VOID(hiChainConnector_); - hiChainConnector_->DeleteAllGroupByUdid(udid); -} - -std::string DmAuthManager::ConvertSinkVersion(const std::string &version) -{ - std::string sinkVersion = ""; - if (version == "") { - sinkVersion = DM_VERSION_4_1_5_1; - } else { - sinkVersion = version; - } - LOGI("ConvertSinkVersion version %{public}s, sinkVersion is %{public}s.", version.c_str(), sinkVersion.c_str()); - return sinkVersion; -} - -void DmAuthManager::SetAuthType(int32_t authType) -{ - authType_ = authType; -} - -int32_t DmAuthManager::GetTaskTimeout(const char* taskName, int32_t taskTimeOut) -{ - LOGI("GetTaskTimeout, taskName: %{public}s, authType_: %{public}d", taskName, authType_.load()); - if (AUTH_TYPE_IMPORT_AUTH_CODE == authType_) { - auto timeout = TASK_TIME_OUT_MAP.find(std::string(taskName)); - if (timeout != TASK_TIME_OUT_MAP.end()) { - return timeout->second; - } - } - return taskTimeOut; -} - -bool DmAuthManager::IsAllowDeviceBind() -{ - if (AppManager::GetInstance().IsSystemSA()) { - return true; - } - return false; -} - -int32_t DmAuthManager::GetBindLevel(int32_t bindLevel) -{ -#ifdef DEVICE_MANAGER_COMMON_FLAG - LOGI("device_manager_common is true!"); - std::string processName = ""; - int32_t ret = AppManager::GetInstance().GetCallerProcessName(processName); - LOGI("GetBindLevel processName = %{public}s", GetAnonyString(processName).c_str()); - if (ret == DM_OK && CheckProcessNameInWhiteList(processName)) { - return USER; - } -#endif - if (IsAllowDeviceBind()) { - if (static_cast(bindLevel) == INVALIED_TYPE || static_cast(bindLevel) > APP || - static_cast(bindLevel) < USER) { - return USER; - } - return bindLevel; - } - if (static_cast(bindLevel) == INVALIED_TYPE || (static_cast(bindLevel) != APP && - static_cast(bindLevel) != SERVICE)) { - return APP; - } - return bindLevel; -} - -std::string DmAuthManager::GetBundleName(JsonObject &jsonObject) -{ - if (!jsonObject.IsDiscarded() && 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(); - return DM_OK; - } - authResponseContext_->localUserId = MultipleUserConnector::GetFirstForegroundUserId(); - authResponseContext_->localAccountId = - MultipleUserConnector::GetOhosAccountIdByUserId(authResponseContext_->localUserId); - if (authResponseContext_->peerBundleName == authResponseContext_->hostPkgName) { - bundleName_ = authResponseContext_->bundleName; - } else { - bundleName_ = authResponseContext_->peerBundleName; - } - 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_->peerBundleName, 0, authResponseContext_->tokenId); -#ifndef DEVICE_MANAGER_COMMON_FLAG - if (ret == DM_OK && static_cast(authResponseContext_->bindLevel) != APP) { - LOGI("get tokenId by bundleName failed %{public}s", GetAnonyString(authResponseContext_->bundleName).c_str()); - return ERR_DM_FAILED; - } -#endif - return ret; -} - -void DmAuthManager::SetProcessInfo() -{ - CHECK_NULL_VOID(authResponseContext_); - ProcessInfo processInfo; - if (static_cast(authResponseContext_->bindLevel) == APP) { - if ((authRequestState_ != nullptr) && (authResponseState_ == nullptr)) { - processInfo.pkgName = authResponseContext_->hostPkgName; - processInfo.userId = authRequestContext_->localUserId; - } else if ((authRequestState_ == nullptr) && (authResponseState_ != nullptr)) { - processInfo.pkgName = authResponseContext_->peerBundleName; - processInfo.userId = authResponseContext_->localUserId; - } else { - LOGE("DMAuthManager::SetProcessInfo failed, state is invalid."); - } - } else if (static_cast(authResponseContext_->bindLevel) == USER || - static_cast(authResponseContext_->bindLevel) == INVALIED_TYPE) { - processInfo.pkgName = std::string(DM_PKG_NAME); - processInfo.userId = authResponseContext_->localUserId; - } else { - LOGE("bindlevel error %{public}d.", authResponseContext_->bindLevel); - return; - } - softbusConnector_->SetProcessInfo(processInfo); -} - -void DmAuthManager::ConverToFinish() -{ - authRequestContext_->reason = DM_OK; - authResponseContext_->reply = DM_OK; - authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; - authRequestState_->TransitionTo(std::make_shared()); -} - -void DmAuthManager::RequestReCheckMsg() -{ - LOGI("dmVersion %{public}s.", DM_VERSION_5_0_5); - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - uint32_t tokenId = 0; - int32_t localUserId = 0; - MultipleUserConnector::GetTokenIdAndForegroundUserId(tokenId, localUserId); - std::string localAccountId = MultipleUserConnector::GetOhosAccountIdByUserId(localUserId); - authResponseContext_->edition = DM_VERSION_5_0_5; - authResponseContext_->localDeviceId = static_cast(localDeviceId); - authResponseContext_->localUserId = localUserId; - authResponseContext_->bundleName = authRequestContext_->hostPkgName; - authResponseContext_->bindLevel = authRequestContext_->bindLevel; - authResponseContext_->localAccountId = localAccountId; - authResponseContext_->tokenId = authRequestContext_->tokenId; - authMessageProcessor_->SetResponseContext(authResponseContext_); - std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_RECHECK_MSG); - softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); -} - -void DmAuthManager::ResponseReCheckMsg() -{ - LOGI("remoteVersion %{public}s, authResponseContext_->edition %{public}s.", - remoteVersion_.c_str(), authResponseContext_->edition.c_str()); - if (!IsSinkMsgValid()) { - LOGE("peer deviceId not trust."); - authResponseContext_->isFinish = false; - isFinishOfLocal_ = false; - authMessageProcessor_->SetEncryptFlag(false); - int32_t sessionId = authResponseContext_->sessionId; - authResponseContext_->state = authResponseState_->GetStateType(); - authResponseState_->TransitionTo(std::make_shared()); - return; - } - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - authResponseContext_->edition = DM_VERSION_5_0_5; - authResponseContext_->localDeviceId = std::string(localDeviceId); - authResponseContext_->localUserId = MultipleUserConnector::GetFirstForegroundUserId(); - authResponseContext_->localAccountId = - MultipleUserConnector::GetOhosAccountIdByUserId(authResponseContext_->localUserId); - if (AppManager::GetInstance().GetNativeTokenIdByName(bundleName_, authResponseContext_->tokenId) != DM_OK) { - LOGE("BundleName %{public}s, GetNativeTokenIdByName failed.", GetAnonyString(bundleName_).c_str()); - if (AppManager::GetInstance().GetHapTokenIdByName(authResponseContext_->localUserId, - bundleName_, 0, authResponseContext_->tokenId) != DM_OK) { - LOGE("get tokenId by bundleName failed %{public}s", GetAnonyString(bundleName_).c_str()); - authResponseContext_->tokenId = 0; - } - } - authResponseContext_->bundleName = authResponseContext_->peerBundleName; - authMessageProcessor_->SetEncryptFlag(true); - std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_RECHECK_MSG); - softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); - PutAccessControlList(); -} - -void DmAuthManager::RequestReCheckMsgDone() -{ - LOGI("remoteVersion %{public}s, authResponseContext_->edition %{public}s.", - remoteVersion_.c_str(), authResponseContext_->edition.c_str()); - if (!IsSourceMsgValid()) { - LOGE("peer deviceId not trust."); - authResponseContext_->isFinish = false; - isFinishOfLocal_ = false; - authMessageProcessor_->SetEncryptFlag(false); - authRequestState_->TransitionTo(std::make_shared()); - return; - } - authRequestState_->TransitionTo(std::make_shared()); - PutAccessControlList(); -} - -bool DmAuthManager::IsSinkMsgValid() -{ - if (authResponseContext_->edition != remoteVersion_ || - authResponseContext_->localDeviceId != remoteDeviceId_ || - authResponseContext_->localUserId != authResponseContext_->remoteUserId || - authResponseContext_->bundleName != authResponseContext_->hostPkgName || - authResponseContext_->localBindLevel != authResponseContext_->bindLevel) { - return false; - } - return true; -} - -bool DmAuthManager::IsSourceMsgValid() -{ - if (authResponseContext_->edition != remoteVersion_ || - authResponseContext_->localDeviceId != remoteDeviceId_ || - authResponseContext_->localUserId != authRequestContext_->remoteUserId || - authResponseContext_->bundleName != authResponseContext_->peerBundleName || - authResponseContext_->localBindLevel != authResponseContext_->bindLevel) { - return false; - } - authResponseContext_->localAccountId = authRequestContext_->localAccountId; - return true; -} - -int32_t DmAuthManager::RegisterAuthenticationType(int32_t authenticationType) -{ - authenticationType_ = authenticationType; - return DM_OK; -} - -void DmAuthManager::ProcessReqPublicKey() -{ - if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_AUTH_FINISH || - authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_RECHECK_MSG) { - authResponseState_->TransitionTo(std::make_shared()); - return; - } - if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW) { - std::lock_guard lock(srcReqMsgLock_); - isNeedProcCachedSrcReqMsg_ = true; - } -} - -void DmAuthManager::GetLocalServiceInfoInDp() -{ - DistributedDeviceProfile::LocalServiceInfo localServiceInfo; - int32_t result = DeviceProfileConnector::GetInstance().GetLocalServiceInfoByBundleNameAndPinExchangeType( - authResponseContext_->hostPkgName, (int32_t)DMLocalServiceInfoPinExchangeType::FROMDP, localServiceInfo); - if (result != DM_OK) { - return; - } - if (IsLocalServiceInfoValid(localServiceInfo)) { - serviceInfoProfile_ = localServiceInfo; - LOGI("authBoxType %{public}d, authType %{public}d, pinExchangeType %{public}d", - serviceInfoProfile_.GetAuthBoxType(), serviceInfoProfile_.GetAuthType(), - serviceInfoProfile_.GetPinExchangeType()); - auto updateProfile = serviceInfoProfile_; - updateProfile.SetPinCode("******"); - DeviceProfileConnector::GetInstance().UpdateLocalServiceInfo(updateProfile); - } -} - -bool DmAuthManager::CheckNeedShowAuthInfoDialog(int32_t errorCode) -{ - CHECK_NULL_RETURN(authResponseContext_, false); - if (errorCode == ERR_DM_HICHAIN_PROOFMISMATCH && !pincodeDialogEverShown_ && CanUsePincodeFromDp()) { - authResponseContext_->code = GeneratePincode(); - LOGI("AuthDeviceError, GeneratePincode, ShowAuthInfoDialog"); - authTimes_ = 0; - ShowAuthInfoDialog(true); - return true; - } - return false; -} - -void DmAuthManager::UpdateInputPincodeDialog(int32_t errorCode) -{ - CHECK_NULL_VOID(authResponseContext_); - CHECK_NULL_VOID(authUiStateMgr_); - if (authResponseContext_->authType == AUTH_TYPE_NFC && !pincodeDialogEverShown_ && - IsImportedAuthCodeValid() && errorCode == ERR_DM_HICHAIN_PROOFMISMATCH) { - LOGI("AuthDeviceError, ShowStartAuthDialog"); - authTimes_ = 0; - DeleteAuthCode(); - ShowStartAuthDialog(); - } else { - authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR); - } -} - -void DmAuthManager::JoinLnn(const std::string &deviceId, bool isForceJoin) -{ - CHECK_NULL_VOID(authRequestContext_); - CHECK_NULL_VOID(authResponseContext_); - CHECK_NULL_VOID(softbusConnector_); - if (IsHmlSessionType()) { - if (authRequestContext_->closeSessionDelaySeconds == 0) { - isWaitingJoinLnnCallback_ = true; - } - authResponseContext_->localSessionKeyId = GetSessionKeyIdSync(authResponseContext_->requestId); - softbusConnector_->JoinLnnByHml(authRequestContext_->sessionId, authResponseContext_->localSessionKeyId, - authResponseContext_->remoteSessionKeyId); - return; - } - softbusConnector_->JoinLnn(deviceId, isForceJoin); -} - -int32_t DmAuthManager::GetTokenIdByBundleName(int32_t userId, std::string &bundleName, int64_t &tokenId) -{ - int32_t ret = AppManager::GetInstance().GetNativeTokenIdByName(bundleName, tokenId); - if (ret == DM_OK) { - return DM_OK; - } - ret = AppManager::GetInstance().GetHapTokenIdByName(userId, bundleName, 0, tokenId); - if (ret != DM_OK) { - LOGE("get tokenId by bundleName failed %{public}s", GetAnonyString(bundleName).c_str()); - } - return ret; -} - -void DmAuthManager::OnSoftbusJoinLNNResult(const int32_t sessionId, const char *networkId, int32_t result) -{ - (void)sessionId; - (void)networkId; - (void)result; -} - -void DmAuthManager::CloseAuthSession(const int32_t sessionId) -{ - if (timer_ != nullptr) { - timer_->DeleteTimer(std::string(WAIT_SESSION_CLOSE_TIMEOUT_TASK) + std::string(CLOSE_SESSION_TASK_SEPARATOR) + - std::to_string(sessionId)); - } - CHECK_NULL_VOID(softbusConnector_); - CHECK_NULL_VOID(softbusConnector_->GetSoftbusSession()); - softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId); -} - -void DmAuthManager::RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback) -{ - cleanNotifyCallback_ = cleanNotifyCallback; - return; -} - -void DmAuthManager::GetCallerInfo(DmBindCallerInfo &callerInfo) -{ - (void)callerInfo; -} - -void DmAuthManager::SetCallerInfo(const DmBindCallerInfo &callerInfo) -{ - std::lock_guard lock(callerInfoMutex_); - callerInfo_.userId = callerInfo.userId; - callerInfo_.tokenId = callerInfo.tokenId; - callerInfo_.bundleName = callerInfo.bundleName; - callerInfo_.hostPkgLabel = callerInfo.hostPkgLabel; - callerInfoReady_ = true; -} - -void DmAuthManager::GetCallerInfo(const std::string &pkgName, JsonObject &jsonObject) -{ - CHECK_NULL_VOID(authRequestContext_); - std::lock_guard lock(callerInfoMutex_); - if (callerInfoReady_) { - authRequestContext_->localUserId = callerInfo_.userId; - authRequestContext_->tokenId = static_cast(callerInfo_.tokenId); - authRequestContext_->bundleName = callerInfo_.bundleName; - authRequestContext_->hostPkgLabel = callerInfo_.hostPkgLabel; - } else { - authRequestContext_->hostPkgLabel = GetBundleLable(pkgName); - uint32_t tokenId = 0 ; - MultipleUserConnector::GetTokenIdAndForegroundUserId(tokenId, authRequestContext_->localUserId); - authRequestContext_->tokenId = static_cast(tokenId); - authRequestContext_->bundleName = GetBundleName(jsonObject); - } -} - -void DmAuthManager::ClearCallerInfo() -{ - std::lock_guard lock(callerInfoMutex_); - callerInfo_.userId = -1; - callerInfo_.tokenId = -1; - callerInfo_.bundleName = ""; - callerInfo_.hostPkgLabel = ""; - callerInfoReady_ = false; -} -} // namespace DistributedHardware -} // namespace OHOS diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp.bak b/services/implementation/src/authentication_v2/auth_manager.cpp.bak deleted file mode 100644 index 662df9c97..000000000 --- a/services/implementation/src/authentication_v2/auth_manager.cpp.bak +++ /dev/null @@ -1,1051 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -#include "app_manager.h" -#include "softbus_common.h" -#include "system_ability_definition.h" -#include "iservice_registry.h" -#include "parameter.h" -#include "deviceprofile_connector.h" -#include "multiple_user_connector.h" - -#include "auth_manager.h" -#include "dm_constants.h" -#include "dm_crypto.h" -#include "dm_random.h" -#include "dm_log.h" -#include "dm_timer.h" -#include "dm_radar_helper.h" -#include "dm_device_info.h" -#include "dm_anonymous.h" -#include "dm_auth_state_machine.h" -#include "dm_auth_context.h" -#include "dm_auth_message_processor.h" -#include "dm_auth_state.h" - -namespace OHOS { -namespace DistributedHardware { -namespace { - -constexpr int32_t MIN_PIN_CODE = 100000; -constexpr int32_t MAX_PIN_CODE = 999999; -constexpr int32_t DM_ULTRASONIC_FORWARD = 0; -constexpr int32_t DM_ULTRASONIC_REVERSE = 1; - -int32_t GetCloseSessionDelaySeconds(std::string &delaySecondsStr) -{ - if (!IsNumberString(delaySecondsStr)) { - LOGE("Invalid parameter, param is not number."); - return 0; - } - const int32_t closeSessionDelaySecondsMax = 10; - int32_t delaySeconds = std::atoi(delaySecondsStr.c_str()); - if (delaySeconds < 0 || delaySeconds > closeSessionDelaySecondsMax) { - LOGE("Invalid parameter, param out of range."); - return 0; - } - return delaySeconds; -} - -std::string GetBundleLabel(const std::string &bundleName) -{ - auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (samgr == nullptr) { - LOGE("Get ability manager failed"); - return bundleName; - } - - sptr object = samgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); - if (object == nullptr) { - LOGE("object is NULL."); - return bundleName; - } - - sptr bms = iface_cast(object); - if (bms == nullptr) { - LOGE("bundle manager service is NULL."); - return bundleName; - } - - auto bundleResourceProxy = bms->GetBundleResourceProxy(); - if (bundleResourceProxy == nullptr) { - LOGE("GetBundleResourceProxy fail"); - return bundleName; - } - AppExecFwk::BundleResourceInfo resourceInfo; - auto result = bundleResourceProxy->GetBundleResourceInfo(bundleName, - static_cast(OHOS::AppExecFwk::ResourceFlag::GET_RESOURCE_INFO_ALL), resourceInfo); - if (result != ERR_OK) { - LOGE("GetBundleResourceInfo failed"); - return bundleName; - } - LOGI("bundle resource label is %{public}s ", (resourceInfo.label).c_str()); - return resourceInfo.label; -} - -std::string ParseExtraFromMap(const std::map &bindParam) -{ - auto iter = bindParam.find(PARAM_KEY_BIND_EXTRA_DATA); - if (iter != bindParam.end()) { - return iter->second; - } - return ConvertMapToJsonString(bindParam); -} - -bool IsAllowDeviceBind() -{ - if (AppManager::GetInstance().IsSystemSA()) { - return true; - } - return false; -} - -} // namespace - -bool AuthManager::IsHmlSessionType(const std::string &sessionType) -{ - return sessionType == CONN_SESSION_TYPE_HML; -} - -AuthManager::AuthManager(std::shared_ptr softbusConnector, - std::shared_ptr hiChainConnector, - std::shared_ptr listener, - std::shared_ptr hiChainAuthConnector) -{ - LOGI("DmAuthManager constructor"); - context_ = std::make_shared(); - context_->softbusConnector = softbusConnector; - context_->listener = listener; - context_->hiChainConnector = hiChainConnector; - context_->hiChainAuthConnector = hiChainAuthConnector; - context_->authUiStateMgr = std::make_shared(context_->listener); - context_->authenticationMap[AUTH_TYPE_PIN] = nullptr; - context_->authenticationMap[AUTH_TYPE_IMPORT_AUTH_CODE] = nullptr; - context_->authenticationMap[AUTH_TYPE_PIN_ULTRASONIC] = nullptr; - context_->authenticationMap[AUTH_TYPE_NFC] = nullptr; - context_->accesser.dmVersion = DM_VERSION_5_1_0; - context_->accessee.dmVersion = DM_VERSION_5_1_0; - context_->timer = std::make_shared(); - context_->authMessageProcessor = std::make_shared(); -} - -AuthManager::~AuthManager() -{ - if (context_ != nullptr) { - context_->successFinished = true; - context_->authStateMachine->Stop(); // Stop statemMachine thread - context_->timer->DeleteAll(); - LOGI("AuthManager context variables destroy successful."); - } - bindParam_.clear(); - LOGI("DmAuthManager destructor"); -} - -void AuthManager::RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback) -{ - context_->cleanNotifyCallback = cleanNotifyCallback; - return; -} - -void AuthManager::SetAuthContext(std::shared_ptr context) -{ - this->context_ = context; -} - -std::shared_ptr AuthManager::GetAuthContext() -{ - return this->context_; -} - -std::string AuthManager::GeneratePincode() -{ - LOGI("AuthManager::GeneratePincode start"); - int32_t pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); - context_->pinCode = std::to_string(pinCode); - return context_->pinCode; -} - -int32_t AuthManager::RegisterUiStateCallback(const std::string pkgName) -{ - LOGI("AuthManager::RegisterUiStateCallback start"); - if (context_->authUiStateMgr == nullptr) { - LOGE("AuthManager::RegisterUiStateCallback context_->authUiStateMgr is null."); - return ERR_DM_FAILED; - } - context_->authUiStateMgr->RegisterUiStateCallback(pkgName); - return DM_OK; -} - -int32_t AuthManager::UnRegisterUiStateCallback(const std::string pkgName) -{ - LOGI("AuthManager::UnRegisterUiStateCallback start"); - if (context_->authUiStateMgr == nullptr) { - LOGE("AuthManager::UnRegisterUiStateCallback context_->authUiStateMgr is null."); - return ERR_DM_FAILED; - } - context_->authUiStateMgr->UnRegisterUiStateCallback(pkgName); - return DM_OK; -} - -int32_t AuthManager::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) -{ - LOGI("AuthManager::UnAuthenticateDevice start"); - return ERR_DM_FAILED; -} - -int32_t AuthManager::ImportAuthCode(const std::string &pkgName, const std::string &authCode) -{ - if (authCode.empty() || pkgName.empty()) { - LOGE("ImportAuthCode failed, authCode or pkgName is empty"); - return ERR_DM_INPUT_PARA_INVALID; - } - context_->importAuthCode = authCode; - context_->importPkgName = pkgName; - context_->pinCode = authCode; - LOGI("AuthManager::ImportAuthCode ok"); - return DM_OK; -} - -int32_t AuthManager::UnBindDevice(const std::string &pkgName, const std::string &udid, - int32_t bindLevel, const std::string &extra) -{ - LOGI("AuthManager::UnBindDevice start"); - return ERR_DM_FAILED; -} - -int32_t AuthManager::StopAuthenticateDevice(const std::string &pkgName) -{ - (void)pkgName; - LOGI("AuthManager::StopAuthenticateDevice start"); - - context_->reason = STOP_BIND; - if (context_->direction == DM_AUTH_SOURCE) { - context_->authStateMachine->TransitionTo(std::make_shared()); - } else { - context_->authStateMachine->TransitionTo(std::make_shared()); - } - return DM_OK; -} - -void AuthManager::OnScreenLocked() -{ - LOGI("AuthManager::OnScreenLocked start"); - if (DmAuthState::IsImportAuthCodeCompatibility(context_->authType)) { - LOGI("OnScreenLocked authtype is: %{public}d, no need stop bind.", context_->authType); - return; - } - context_->reason = ERR_DM_BIND_USER_CANCEL; - context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); -} - -void AuthManager::HandleDeviceNotTrust(const std::string &udid) -{ - LOGI("AuthManager::HandleDeviceNotTrust start"); -} - -int32_t AuthManager::RegisterAuthenticationType(int32_t authenticationType) -{ - context_->confirmOperation = static_cast(authenticationType); - return DM_OK; -} - -int32_t AuthManager::GetReason() -{ - return context_->reason; -} - -// Save the key -void AuthSrcManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) -{ - LOGI("AuthSrcManager::AuthDeviceSessionKey start. keyLen: %{public}u", sessionKeyLen); - if (context_ == nullptr || context_->authMessageProcessor == nullptr || context_->authStateMachine == nullptr) { - LOGE("AuthSrcManager::AuthDeviceSessionKey failed, auth context not initial."); - return; - } - if (requestId != context_->requestId) { - LOGE("AuthSrcManager::onTransmit requestId %{public}" PRId64 "is error.", requestId); - return; - } - int32_t ret = context_->authMessageProcessor->SaveSessionKey(sessionKey, sessionKeyLen); - if (ret != DM_OK) { - LOGE("AuthSrcManager::AuthDeviceSessionKey, save session key error, ret: %{public}d", ret); - } - - context_->authStateMachine->NotifyEventFinish(ON_SESSION_KEY_RETURNED); - LOGI("AuthSrcManager::AuthDeviceSessionKey leave."); -} - -char *AuthSrcManager::AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) -{ - LOGI("AuthSrcManager::AuthDeviceRequest start"); - return nullptr; -} - -void AuthManager::SetAuthType(int32_t authType) -{ - context_->authType = (DmAuthType)authType; -} - -bool AuthManager::IsAuthTypeSupported(const int32_t &authType) -{ - if (context_->authenticationMap.find(authType) == context_->authenticationMap.end()) { - LOGE("IsAuthTypeSupported failed, authType is not supported."); - return false; - } - return true; -} - -bool AuthManager::IsAuthCodeReady(const std::string &pkgName) -{ - if (context_->importAuthCode.empty() || context_->importPkgName.empty()) { - LOGE("AuthManager::IsAuthCodeReady, auth code not ready with authCode %{public}s and pkgName %{public}s.", - GetAnonyString(context_->importAuthCode).c_str(), context_->importPkgName.c_str()); - return false; - } - if (pkgName != context_->importPkgName) { - LOGE("AuthManager::IsAuthCodeReady pkgName %{public}s not supported with import pkgName %{public}s.", - pkgName.c_str(), context_->importPkgName.c_str()); - return false; - } - return true; -} - -int32_t AuthManager::CheckAuthParamVaild(const std::string &pkgName, int32_t authType, - const std::string &deviceId, const std::string &extra) -{ - LOGI("AuthManager::CheckAuthParamVaild start."); - if (authType < DM_AUTH_TYPE_MIN || authType > DM_AUTH_TYPE_MAX) { - LOGE("CheckAuthParamVaild failed, authType is illegal."); - return ERR_DM_AUTH_FAILED; - } - if (pkgName.empty() || deviceId.empty()) { - LOGE("AuthManager::CheckAuthParamVaild failed, pkgName is %{public}s, deviceId is %{public}s, extra is" - "%{public}s.", pkgName.c_str(), GetAnonyString(deviceId).c_str(), extra.c_str()); - return ERR_DM_INPUT_PARA_INVALID; - } - if (context_->listener == nullptr || context_->authUiStateMgr == nullptr) { - LOGE("AuthManager::CheckAuthParamVaild listener or authUiStateMgr is nullptr."); - return ERR_DM_INPUT_PARA_INVALID; - } - - if (!IsAuthTypeSupported(authType)) { - LOGE("AuthManager::CheckAuthParamVaild authType %{public}d not support.", authType); - context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", - STATUS_DM_AUTH_DEFAULT, - ERR_DM_UNSUPPORTED_AUTH_TYPE); - context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, - ERR_DM_UNSUPPORTED_AUTH_TYPE, STATUS_DM_AUTH_DEFAULT, ""); - return ERR_DM_UNSUPPORTED_AUTH_TYPE; - } - JsonObject jsonObject(extra); - if ((jsonObject.IsDiscarded() || !IsString(jsonObject, PARAM_KEY_CONN_SESSIONTYPE) || - jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get() != CONN_SESSION_TYPE_HML) && - !context_->softbusConnector->HaveDeviceInMap(deviceId)) { - LOGE("CheckAuthParamVaild failed, the discoveryDeviceInfoMap_ not have this device."); - context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", - STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID); - context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, - ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, ""); - return ERR_DM_INPUT_PARA_INVALID; - } - - if (DmAuthState::IsImportAuthCodeCompatibility(static_cast(authType)) && - (!IsAuthCodeReady(pkgName))) { - LOGE("Auth code not exist."); - context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", - STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID); - context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, - ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, ""); - return ERR_DM_INPUT_PARA_INVALID; - } - return DM_OK; -} - -void AuthManager::ParseHmlInfoInJsonObject(const JsonObject &jsonObject) -{ - if (jsonObject[PARAM_KEY_CONN_SESSIONTYPE].IsString()) { - context_->connSessionType = jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get(); - LOGI("connSessionType %{public}s", context_->connSessionType.c_str()); - } - if (!IsHmlSessionType(context_->connSessionType)) { - return; - } - if (context_->connDelayCloseTime == 0) { - context_->connDelayCloseTime = HML_SESSION_TIMEOUT; - } - if (jsonObject[PARAM_KEY_HML_ENABLE_160M].IsBoolean()) { - context_->hmlEnable160M = jsonObject[PARAM_KEY_HML_ENABLE_160M].Get(); - LOGI("hmlEnable160M %{public}d", context_->hmlEnable160M); - } - if (jsonObject[PARAM_KEY_HML_ACTIONID].IsString()) { - std::string actionIdStr = jsonObject[PARAM_KEY_HML_ACTIONID].Get(); - if (IsNumberString(actionIdStr)) { - context_->hmlActionId = std::atoi(actionIdStr.c_str()); - } - if (context_->hmlActionId <= 0) { - context_->hmlActionId = 0; - } - LOGI("hmlActionId %{public}d", context_->hmlActionId); - } - - return; -} - -std::string AuthManager::GetBundleName(const JsonObject &jsonObject) -{ - if (!jsonObject.IsDiscarded() && jsonObject[BUNDLE_NAME_KEY].IsString()) { - return jsonObject[BUNDLE_NAME_KEY].Get(); - } - bool isSystemSA = false; - std::string bundleName; - AppManager::GetInstance().GetCallerName(isSystemSA, bundleName); - return bundleName; -} - -void AuthManager::ParseJsonObject(const JsonObject &jsonObject) -{ - if (jsonObject.IsDiscarded()) { - return; - } - - if (jsonObject[APP_OPERATION_KEY].IsString()) { - context_->appOperation = jsonObject[APP_OPERATION_KEY].Get(); - } - if (jsonObject[CUSTOM_DESCRIPTION_KEY].IsString()) { - context_->customData = jsonObject[CUSTOM_DESCRIPTION_KEY].Get(); - } - if (jsonObject[TAG_APP_THUMBNAIL2].IsString()) { - context_->appThumbnail = jsonObject[TAG_APP_THUMBNAIL2].Get(); - } - context_->connDelayCloseTime = 0; - if (jsonObject[PARAM_CLOSE_SESSION_DELAY_SECONDS].IsString()) { - std::string delaySecondsStr = jsonObject[PARAM_CLOSE_SESSION_DELAY_SECONDS].Get(); - context_->connDelayCloseTime = GetCloseSessionDelaySeconds(delaySecondsStr); - } - - context_->accesser.bundleName = GetBundleName(jsonObject); - bindParam_[BUNDLE_NAME_KEY] = context_->accesser.bundleName; - context_->accessee.bundleName = context_->accesser.bundleName; - - if (jsonObject[TAG_PEER_BUNDLE_NAME].IsString() && !jsonObject[TAG_PEER_BUNDLE_NAME].Get().empty()) { - context_->accessee.bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get(); - context_->accessee.oldBundleName = context_->accessee.bundleName; - } else { - context_->accessee.oldBundleName = context_->pkgName; - } - - context_->accesser.pkgName = context_->pkgName; - context_->accessee.pkgName = context_->accesser.pkgName; - - if (jsonObject[TAG_PEER_PKG_NAME].IsString()) { - context_->accessee.pkgName = jsonObject[TAG_PEER_PKG_NAME].Get(); - } - - if (jsonObject[TAG_PEER_DISPLAY_ID].IsNumberInteger()) { - context_->accessee.displayId = jsonObject[TAG_PEER_DISPLAY_ID].Get(); - } - if (jsonObject[TAG_LOCAL_USERID].IsNumberInteger()) { - context_->accesser.userId = jsonObject[TAG_LOCAL_USERID].Get(); - } else { - context_->accesser.userId = MultipleUserConnector::GetFirstForegroundUserId(); - } - - if (context_->authType == AUTH_TYPE_PIN_ULTRASONIC) { - ParseUltrasonicSide(jsonObject); - } - - ParseHmlInfoInJsonObject(jsonObject); - return; -} - -void AuthManager::ParseUltrasonicSide(const JsonObject &jsonObject) -{ - if (jsonObject[TAG_ULTRASONIC_SIDE].IsString()) { - std::string tempInfo = jsonObject[TAG_ULTRASONIC_SIDE].Get(); - if (tempInfo.length() > 0 && isdigit(tempInfo[0])) { - int32_t intTempInfo = std::atoi(tempInfo.c_str()); - if (intTempInfo == DM_ULTRASONIC_REVERSE) { - context_->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Reverse; - } else if (intTempInfo == DM_ULTRASONIC_FORWARD) { - context_->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Forward; - } else { - context_->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Invalid; - } - } - } -} - -int32_t AuthManager::GetTokenIdByBundleName(int32_t userId, std::string &bundleName, int64_t &tokenId) -{ - int32_t ret = AppManager::GetInstance().GetNativeTokenIdByName(bundleName, tokenId); - if (ret == DM_OK) { - return DM_OK; - } - ret = AppManager::GetInstance().GetHapTokenIdByName(userId, bundleName, 0, tokenId); - if (ret != DM_OK) { - LOGE("get tokenId by bundleName failed %{public}s", GetAnonyString(bundleName).c_str()); - } - return ret; -} - -bool CheckBindLevel(const JsonItemObject &jsonObj, const std::string &key, int32_t &bindLevel) -{ - if (IsJsonValIntegerString(jsonObj, TAG_BIND_LEVEL)) { - bindLevel = std::atoi(jsonObj[TAG_BIND_LEVEL].Get().c_str()); - return true; - } - if (IsInt32(jsonObj, TAG_BIND_LEVEL)) { - bindLevel = jsonObj[TAG_BIND_LEVEL].Get(); - return true; - } - return false; -} - -int32_t GetBindLevel(int32_t bindLevel) -{ -#ifdef DEVICE_MANAGER_COMMON_FLAG - LOGI("device_manager_common is true!"); - std::string processName = ""; - int32_t ret = AppManager::GetInstance().GetCallerProcessName(processName); - LOGI("GetBindLevel processName = %{public}s", GetAnonyString(processName).c_str()); - if (ret == DM_OK && DmAuthState::CheckProcessNameInWhiteList(processName)) { - return USER; - } -#endif - if (IsAllowDeviceBind()) { - if (static_cast(bindLevel) == INVALIED_TYPE || static_cast(bindLevel) > APP || - static_cast(bindLevel) < USER) { - return USER; - } - return bindLevel; - } - if (static_cast(bindLevel) == INVALIED_TYPE || (static_cast(bindLevel) != APP && - static_cast(bindLevel) != SERVICE)) { - return APP; - } - return bindLevel; -} - -void AuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, - const std::string &deviceId, const std::string &extra) -{ - LOGI("Get auth param with pkgName %{public}s and extra %{public}s.", pkgName.c_str(), extra.c_str()); - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - context_->accesser.deviceId = std::string(localDeviceId); - context_->pkgName = pkgName; - context_->pkgLabel = GetBundleLabel(pkgName); - context_->authType = (DmAuthType)authType; - context_->accesser.deviceName = context_->listener->GetLocalDisplayDeviceNameForPrivacy(); - context_->accesser.deviceType = context_->softbusConnector->GetLocalDeviceTypeId(); - context_->accesser.isOnline = false; - uint32_t callingTokenId = 0; - MultipleUserConnector::GetCallingTokenId(callingTokenId); - context_->accesser.tokenId = static_cast(callingTokenId); - - context_->accessee.deviceId = deviceId; - context_->accessee.addr = deviceId; - JsonObject jsonObject(extra); - if (jsonObject.IsDiscarded()) { - LOGE("extra string not a json type."); - return; - } - ParseJsonObject(jsonObject); - context_->accesser.accountId = MultipleUserConnector::GetOhosAccountIdByUserId(context_->accesser.userId); - - // compatible for old version - context_->accesser.oldBindLevel = INVALIED_TYPE; - CheckBindLevel(jsonObject, TAG_BIND_LEVEL, context_->accesser.oldBindLevel); - context_->accesser.oldBindLevel = GetBindLevel(context_->accesser.oldBindLevel); - - context_->accesser.bindLevel = DmRole::DM_ROLE_FA; - if (AppManager::GetInstance().IsSystemApp()) { - context_->accesser.bindLevel = DmRole::DM_ROLE_FA; - } - if (AppManager::GetInstance().IsSystemSA()) { - context_->accesser.bindLevel = DmRole::DM_ROLE_SA; - } - if (DmAuthState::CheckProcessNameInWhiteList(context_->accesser.bundleName)) { - context_->accesser.bindLevel = DmRole::DM_ROLE_USER; - } -} - -void AuthManager::InitAuthState(const std::string &pkgName, int32_t authType, - const std::string &deviceId, const std::string &extra) -{ - auto iter = context_->authenticationMap.find(authType); - if (iter != context_->authenticationMap.end()) { - context_->authPtr = iter->second; - } - - context_->timer->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), - AUTHENTICATE_TIMEOUT, - [this] (std::string name) { - DmAuthState::HandleAuthenticateTimeout(context_, name); - }); - GetAuthParam(pkgName, authType, deviceId, extra); - context_->authStateMachine->TransitionTo(std::make_shared()); - LOGI("AuthManager::AuthenticateDevice complete"); - - return; -} - -int32_t AuthManager::AuthenticateDevice(const std::string &pkgName, int32_t authType, - const std::string &deviceId, const std::string &extra) -{ - LOGI("AuthManager::AuthenticateDevice start auth type %{public}d.", authType); - SetAuthType(authType); - int32_t userId = -1; - MultipleUserConnector::GetCallerUserId(userId); - context_->processInfo.pkgName = pkgName; - context_->processInfo.userId = userId; - int32_t ret = CheckAuthParamVaild(pkgName, authType, deviceId, extra); - if (ret != DM_OK) { - LOGE("AuthManager::AuthenticateDevice failed, param is invaild."); - return ret; - } - context_->isAuthenticateDevice = true; - if (authType == AUTH_TYPE_CRE) { - LOGI("AuthManager::AuthenticateDevice for credential type, joinLNN directly."); - context_->softbusConnector->JoinLnn(deviceId, true); - context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, - "", STATUS_DM_AUTH_DEFAULT, DM_OK); - context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, - DM_OK, STATUS_DM_AUTH_DEFAULT, ""); - return DM_OK; - } - InitAuthState(pkgName, authType, deviceId, extra); - if (context_->ultrasonicInfo == DmUltrasonicInfo::DM_Ultrasonic_Invalid) { - return ERR_DM_INPUT_PARA_INVALID; - } - return DM_OK; -} - -int32_t AuthManager::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, - const std::map &bindParam, int sessionId, uint64_t logicalSessionId) -{ - int ret = DM_OK; - LOGI("AuthManager::BindTarget start. pkgName: %{public}s", pkgName.c_str()); - for (auto iter = bindParam.begin(); iter != bindParam.end(); iter++) { - LOGI("AuthManager::BindTarget para: %{public}s : %{public}s ", iter->first.c_str(), iter->second.c_str()); - } - - struct RadarInfo info = { - .funcName = "AuthenticateDevice", - .stageRes = static_cast(StageRes::STAGE_SUCC), - .bizState = static_cast(BizState::BIZ_STATE_END), - }; - if (!DmRadarHelper::GetInstance().ReportDiscoverUserRes(info)) { - LOGE("ReportDiscoverUserRes failed"); - } - if (pkgName.empty()) { - LOGE("AuthManager::BindTarget failed, pkgName is empty."); - return ERR_DM_INPUT_PARA_INVALID; - } - int32_t authType = -1; - if (ParseAuthType(bindParam, authType) != DM_OK) { - LOGE("AuthManager::BindTarget failed, key: %{public}s error.", PARAM_KEY_AUTH_TYPE); - return ERR_DM_INPUT_PARA_INVALID; - } - context_->peerTargetId = targetId_; - bindParam_ = bindParam; - if (!targetId.deviceId.empty()) { - ret = AuthenticateDevice(pkgName, authType, targetId.deviceId, ParseExtraFromMap(bindParam)); - if (ret != DM_OK) { - return ret; - } - } else { - LOGE("AuthManager::BindTarget failed, targetId is error."); - return ERR_DM_INPUT_PARA_INVALID; - } - - context_->sessionId = sessionId; - context_->logicalSessionId = logicalSessionId; - context_->requestId = static_cast(logicalSessionId); - context_->authStateMachine->TransitionTo(std::make_shared()); - info = { .funcName = "BindTarget" }; - info.channelId = sessionId; - DmRadarHelper::GetInstance().ReportAuthSendRequest(info); - return ret; -} - -AuthSinkManager::AuthSinkManager(std::shared_ptr softbusConnector, - std::shared_ptr hiChainConnector, - std::shared_ptr listener, - std::shared_ptr hiChainAuthConnector) - : AuthManager(softbusConnector, hiChainConnector, listener, hiChainAuthConnector) -{ - context_->direction = DM_AUTH_SINK; - context_->authStateMachine = std::make_shared(context_); -} - -void AuthSinkManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) -{ - LOGI("sessionId = %{public}d and sessionSide = %{public}d result = %{public}d", sessionId, sessionSide, result); -} - -void AuthSinkManager::OnSessionClosed(int32_t sessionId) -{ - LOGI("AuthSrcManager::OnSessionClosed sessionId = %{public}d", sessionId); - context_->reason = ERR_DM_SESSION_CLOSED; - context_->authStateMachine->TransitionTo(std::make_shared()); -} - -void AuthSinkManager::OnDataReceived(int32_t sessionId, std::string message) -{ - context_->sessionId = sessionId; - int32_t ret = context_->authMessageProcessor->ParseMessage(context_, message); - if (ret != DM_OK) { - LOGE("OnDataReceived failed, parse input message error."); - context_->reason = ERR_DM_PARSE_MESSAGE_FAILED; - context_->authStateMachine->TransitionTo(std::make_shared()); - } - - return; -} - -bool AuthSinkManager::GetIsCryptoSupport() -{ - return false; -} - -void AuthManager::GetRemoteDeviceId(std::string &deviceId) -{ - deviceId = (context_->direction == DM_AUTH_SOURCE) ? context_->accessee.deviceId : context_->accesser.deviceId; - return; -} - -int32_t AuthSinkManager::OnUserOperation(int32_t action, const std::string ¶ms) -{ - LOGI("AuthSinkManager::OnUserOperation start."); - if (context_ == nullptr || context_->authStateMachine == nullptr) { - LOGE("OnUserOperation: Authenticate is not start"); - return ERR_DM_AUTH_NOT_START; - } - - switch (action) { - case USER_OPERATION_TYPE_CANCEL_AUTH: - case USER_OPERATION_TYPE_ALLOW_AUTH: - case USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS: - context_->confirmOperation = static_cast(action); - context_->reply = USER_OPERATION_TYPE_ALLOW_AUTH; - if (action == USER_OPERATION_TYPE_CANCEL_AUTH) { - LOGI("AuthSinkManager::OnUserOperation USER_OPERATION_TYPE_CANCEL_AUTH."); - context_->reply = USER_OPERATION_TYPE_CANCEL_AUTH; - } - context_->authStateMachine->NotifyEventFinish(DmEventType::ON_USER_OPERATION); - break; - case USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT: - LOGI("AuthSinkManager::OnUserOperation USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT."); - context_->confirmOperation = USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT; - context_->reason = ERR_DM_TIME_OUT; - context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); - break; - case USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY: - LOGI("AuthSinkManager::OnUserOperation USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY."); - context_->confirmOperation = USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY; - context_->reason = ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY; - context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); - break; - default: - LOGE("this action id not support"); - break; - } - LOGI("AuthSinkManager::OnUserOperation leave."); - return DM_OK; -} - -AuthSrcManager::AuthSrcManager(std::shared_ptr softbusConnector, - std::shared_ptr hiChainConnector, - std::shared_ptr listener, - std::shared_ptr hiChainAuthConnector) - : AuthManager(softbusConnector, hiChainConnector, listener, hiChainAuthConnector) -{ - context_->direction = DM_AUTH_SOURCE; - context_->authStateMachine = std::make_shared(context_); -} - -void AuthSrcManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) -{ - LOGI("sessionId = %{public}d and sessionSide = %{public}d result = %{public}d", sessionId, sessionSide, result); -} - -void AuthSrcManager::OnSessionClosed(int32_t sessionId) -{ - LOGI("AuthSrcManager::OnSessionClosed sessionId = %{public}d", sessionId); - context_->reason = ERR_DM_SESSION_CLOSED; - context_->authStateMachine->TransitionTo(std::make_shared()); -} - -void AuthSrcManager::OnSessionDisable() -{ - context_->sessionId = -1; -} - -void AuthSrcManager::OnDataReceived(int32_t sessionId, std::string message) -{ - context_->sessionId = sessionId; - int32_t ret = context_->authMessageProcessor->ParseMessage(context_, message); - if (ret != DM_OK) { - LOGE("OnDataReceived failed, parse input message error."); - context_->reason = ERR_DM_PARSE_MESSAGE_FAILED; - context_->authStateMachine->TransitionTo(std::make_shared()); - } - - return; -} - -bool AuthSrcManager::GetIsCryptoSupport() -{ - return false; -} - -int32_t AuthSrcManager::OnUserOperation(int32_t action, const std::string ¶ms) -{ - LOGI("AuthSrcManager::OnUserOperation start."); - if (context_ == nullptr || context_->authStateMachine == nullptr) { - LOGE("OnUserOperation: Authenticate is not start"); - return ERR_DM_AUTH_NOT_START; - } - - switch (action) { - case USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT: - LOGE("AuthSrcManager OnUserOperation user cancel"); - context_->pinInputResult = USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT; - context_->reason = ERR_DM_BIND_USER_CANCEL_ERROR; - context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); - break; - case USER_OPERATION_TYPE_DONE_PINCODE_INPUT: - LOGE("AuthSrcManager OnUserOperation user input done"); - context_->pinInputResult = USER_OPERATION_TYPE_DONE_PINCODE_INPUT; - { - if (!IsNumberString(params)) { - LOGE("OnUserOperation jsonStr error"); - return ERR_DM_INPUT_PARA_INVALID; - } - context_->pinCode = params; - } - context_->authStateMachine->NotifyEventFinish(DmEventType::ON_USER_OPERATION); - break; - default: - LOGE("this action id not support"); - break; - } - LOGI("AuthSrcManager::OnUserOperation leave."); - return DM_OK; -} - -void AuthSrcManager::AuthDeviceError(int64_t requestId, int32_t errorCode) -{ - LOGI("AuthSrcManager::AuthDeviceError start."); - auto curState = context_->authStateMachine->GetCurState(); - if (curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE || - curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE || - curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE) { - LOGI("AuthSrcManager::AuthDeviceError Auth pin err."); - if (context_->authType == DmAuthType::AUTH_TYPE_PIN) { - context_->inputPinAuthFailTimes++; - } - context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ERROR); - context_->authStateMachine->TransitionTo(std::make_shared()); - } else { - LOGI("AuthSrcManager::AuthDeviceError unexpected err."); - context_->reason = errorCode; - context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); - } - LOGI("AuthSrcManager::AuthDeviceError leave."); -} - -void AuthSinkManager::AuthDeviceError(int64_t requestId, int32_t errorCode) -{ - LOGI("AuthSinkManager::AuthDeviceError start."); - auto curState = context_->authStateMachine->GetCurState(); - if (curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE || - curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE) { - LOGI("AuthSrcManager::AuthDeviceError Auth pin err."); - if (context_->authType == DmAuthType::AUTH_TYPE_PIN) { - context_->inputPinAuthFailTimes++; - } - context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ERROR); - context_->authStateMachine->TransitionTo(std::make_shared()); - } else { - LOGI("AuthSinkManager::AuthDeviceError unexpected err."); - context_->reason = errorCode; - context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); - } - LOGI("AuthSinkManager::AuthDeviceError leave."); -} - -bool AuthSrcManager::AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) -{ - LOGI("AuthSrcManager::AuthDeviceTransmit start."); - // check request id first - if (requestId != context_->requestId) { - LOGE("AuthSrcManager::onTransmit requestId %{public}" PRId64"is error.", requestId); - return false; - } - - context_->transmitData = std::string(reinterpret_cast(data), dataLen); - context_->authStateMachine->NotifyEventFinish(ON_TRANSMIT); - LOGI("AuthSrcManager::AuthDeviceTransmit leave."); - return true; -} - -bool AuthSinkManager::AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) -{ - LOGI("AuthSinkManager::AuthDeviceTransmit start."); - // check request id first - if (requestId != context_->requestId) { - LOGE("AuthSinkManager::onTransmit requestId %{public}" PRId64"is error.", requestId); - return false; - } - - context_->transmitData = std::string(reinterpret_cast(data), dataLen); - context_->authStateMachine->NotifyEventFinish(ON_TRANSMIT); - LOGI("AuthSinkManager::AuthDeviceTransmit leave."); - return true; -} - -void AuthSrcManager::AuthDeviceFinish(int64_t requestId) -{ - LOGI("AuthSrcManager::AuthDeviceFinish start."); - context_->authStateMachine->NotifyEventFinish(ON_FINISH); - // Perform business processing based on the current state - DmAuthStateType curState = context_->authStateMachine->GetCurState(); - switch (curState) { - case DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE: - // ON_FINISH event occurs, start credential exchange - context_->authStateMachine->TransitionTo(std::make_shared()); - break; - default: - break; - } - LOGI("AuthSrcManager::AuthDeviceFinish leave."); -} - -void AuthSinkManager::AuthDeviceFinish(int64_t requestId) -{ - LOGI("AuthSinkManager::AuthDeviceFinish start."); - context_->authStateMachine->NotifyEventFinish(ON_FINISH); - LOGI("AuthSinkManager::AuthDeviceFinish leave."); -} - -void AuthSinkManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) -{ - LOGI("AuthSrcManager::AuthDeviceSessionKey start. keyLen: %{public}u", sessionKeyLen); - if (context_ == nullptr || context_->authMessageProcessor == nullptr || context_->authStateMachine == nullptr) { - LOGE("AuthSrcManager::AuthDeviceSessionKey failed, auth context not initial."); - return; - } - if (requestId != context_->requestId) { - LOGE("AuthSrcManager::onTransmit requestId %{public}" PRId64 "is error.", requestId); - return; - } - int32_t ret = context_->authMessageProcessor->SaveSessionKey(sessionKey, sessionKeyLen); - if (ret != DM_OK) { - LOGE("AuthSrcManager::AuthDeviceSessionKey, save session key error, ret: %{public}d", ret); - } - - context_->authStateMachine->NotifyEventFinish(ON_SESSION_KEY_RETURNED); -} - -char *AuthSinkManager::AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) -{ - LOGI("AuthSinkManager::AuthDeviceRequest start"); - (void)requestId; - (void)reqParams; - JsonObject jsonObj; - - DmAuthStateType curState = context_->authStateMachine->GetCurState(); - if (curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE || - curState == DmAuthStateType::AUTH_SINK_REVERSE_ULTRASONIC_DONE_STATE|| - curState == DmAuthStateType::AUTH_SINK_FORWARD_ULTRASONIC_DONE_STATE) { - std::string pinCode = ""; - if (GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == "") { - jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED; - } else { - jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; - jsonObj[FIELD_PIN_CODE] = pinCode; - } - } else if (curState == DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE) { - if (context_->isOnline) { // Non-first time certification - jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; - jsonObj[FIELD_CRED_ID] = context_->accessee.transmitCredentialId; - } else if (!context_->isAppCredentialVerified) { // First-time authentication && appCred auth - jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; - jsonObj[FIELD_CRED_ID] = context_->accessee.transmitCredentialId; - } else { // First-time authentication && User credential authentication - jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; - jsonObj[FIELD_CRED_ID] = context_->accessee.lnnCredentialId; - } - } - jsonObj[FIELD_SERVICE_PKG_NAME] = std::string(DM_PKG_NAME); - std::string jsonStr = jsonObj.Dump(); - char *buffer = strdup(jsonStr.c_str()); - return buffer; -} - -int32_t AuthManager::GetPinCode(std::string &code) -{ - if (context_ == nullptr) { - LOGE("AuthManager failed to GetPinCode because context_ is nullptr"); - return ERR_DM_FAILED; - } - LOGI("GetPinCode called."); - code = context_->pinCode; - return DM_OK; -} - -// Reacquire BindParams to rebuild the link, generally used when switching between old and new protocol objects -void AuthManager::GetBindTargetParams(std::string &pkgName, PeerTargetId &targetId, - std::map &bindParam) -{ - pkgName = context_->pkgName; - targetId = targetId_; - bindParam = bindParam_; - - LOGI("AuthManager::GetBindTargetParams get pkgName %{public}s to reuse", pkgName.c_str()); - return; -} - -void AuthManager::SetBindTargetParams(const PeerTargetId &targetId) -{ - targetId_ = targetId; - LOGI("AuthManager::SetBindTargetParams set targetId to reuse"); - return; -} - -void AuthManager::ClearSoftbusSessionCallback() -{} - -void AuthManager::PrepareSoftbusSessionCallback() -{} - -void AuthManager::GetCallerInfo(DmBindCallerInfo &callerInfo) -{ - callerInfo.userId = context_->accesser.userId; - callerInfo.tokenId = context_->accesser.tokenId; - callerInfo.bundleName = context_->accesser.bundleName; - callerInfo.hostPkgLabel = context_->pkgLabel; -} - -void AuthManager::SetCallerInfo(const DmBindCallerInfo &callerInfo) -{ - (void)callerInfo; -} -} // namespace DistributedHardware -} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp.bak b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp.bak deleted file mode 100644 index fa963619f..000000000 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp.bak +++ /dev/null @@ -1,534 +0,0 @@ -/* - * Copyright (c) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include "accesstoken_kit.h" -#include "access_control_profile.h" -#include "accesser.h" -#include "accessee.h" -#include "auth_manager.h" -#include "app_manager.h" -#include "dm_crypto.h" -#include "dm_log.h" -#include "dm_timer.h" -#include "dm_radar_helper.h" -#include "dm_language_manager.h" -#include "dm_constants.h" -#include "dm_anonymous.h" -#include "dm_random.h" -#include "dm_auth_context.h" -#include "dm_auth_state.h" -#include "deviceprofile_connector.h" -#include "distributed_device_profile_errors.h" -#include "device_auth.h" -#include "hap_token_info.h" -#include "json_object.h" -#include "multiple_user_connector.h" -#include "os_account_manager.h" -#include "parameter.h" - -using namespace OHOS::Security::AccessToken; - -namespace OHOS { -namespace DistributedHardware { - -DmAuthStateType AuthSrcStartState::GetStateType() -{ - return DmAuthStateType::AUTH_SRC_START_STATE; -} - -int32_t AuthSrcStartState::Action(std::shared_ptr context) -{ - return DM_OK; -} - -DmAuthStateType AuthSrcNegotiateStateMachine::GetStateType() -{ - return DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE; -} - -std::string AuthSrcNegotiateStateMachine::GetAccountGroupIdHash(std::shared_ptr context) -{ - JsonObject jsonObj; - jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP; - std::string queryParams = SafetyDump(jsonObj); - - int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); - if (osAccountUserId < 0) { - LOGE("get current process account user id failed"); - return ""; - } - std::vector groupList; - if (!context->hiChainConnector->GetGroupInfo(osAccountUserId, queryParams, groupList)) { - return ""; - } - JsonObject jsonAccountObj(JsonCreateType::JSON_CREATE_TYPE_ARRAY); - for (auto &groupInfo : groupList) { - jsonAccountObj.PushBack(Crypto::GetGroupIdHash(groupInfo.groupId)); - } - return SafetyDump(jsonAccountObj); -} - -int32_t AuthSrcNegotiateStateMachine::Action(std::shared_ptr context) -{ - LOGI("AuthSrcNegotiateStateMachine::Action sessionId %{public}d.", context->sessionId); - - context->reply = ERR_DM_AUTH_REJECT; - context->accessee.dmVersion = ""; - - // Calculate the hash value - context->accesser.deviceIdHash = Crypto::GetUdidHash(context->accesser.deviceId); - context->accesser.accountIdHash = Crypto::GetAccountIdHash16(context->accesser.accountId); - context->accesser.tokenIdHash = Crypto::GetTokenIdHash(std::to_string(context->accesser.tokenId)); - - // Create old message for compatible - context->accesser.accountGroupIdHash = GetAccountGroupIdHash(context); - - std::string message = context->authMessageProcessor->CreateMessage(MSG_TYPE_REQ_ACL_NEGOTIATE, context); - context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); - if (context->timer != nullptr) { - context->timer->StartTimer(std::string(NEGOTIATE_TIMEOUT_TASK), - DmAuthState::GetTaskTimeout(context, NEGOTIATE_TIMEOUT_TASK, NEGOTIATE_TIMEOUT), - [this, context] (std::string name) { - DmAuthState::HandleAuthenticateTimeout(context, name); - }); - } - - return DM_OK; -} - -DmAuthStateType AuthSinkNegotiateStateMachine::GetStateType() -{ - return DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE; -} - -int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptr context) -{ - CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); - // 1. Get deviceId - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - context->accessee.deviceId = std::string(localDeviceId); - context->accessee.deviceIdHash = Crypto::GetUdidHash(context->accessee.deviceId); - - // 2. Get userId - context->accessee.userId = MultipleUserConnector::GetUserIdByDisplayId( - static_cast(context->accessee.displayId)); - if (context->accessee.userId < 0) { - LOGE("get userId failed."); - return ERR_DM_GET_LOCAL_USERID_FAILED; - } - - // 3. Get accountId - context->accessee.accountId = MultipleUserConnector::GetOhosAccountIdByUserId(context->accessee.userId); - context->accessee.accountIdHash = Crypto::GetAccountIdHash16(context->accessee.accountId); - - // 4. Get tokenId - if (AppManager::GetInstance().GetNativeTokenIdByName(context->accessee.bundleName, - context->accessee.tokenId) == DM_OK) { - context->accessee.bindLevel = DmRole::DM_ROLE_SA; - } else if (AppManager::GetInstance().GetHapTokenIdByName(context->accessee.userId, context->accessee.bundleName, 0, - context->accessee.tokenId) == DM_OK) { - context->accessee.bindLevel = DmRole::DM_ROLE_FA; - } else { - LOGE("sink not contain the bundlename %{public}s.", context->accessee.bundleName.c_str()); - return ERR_DM_GET_TOKENID_FAILED; - } - if (DmAuthState::CheckProcessNameInWhiteList(context->accessee.bundleName)) { - context->accessee.bindLevel = DmRole::DM_ROLE_USER; - } - context->accessee.tokenIdHash = Crypto::GetTokenIdHash(std::to_string(context->accessee.tokenId)); - context->accesser.isOnline = context->softbusConnector->CheckIsOnline(context->accesser.deviceIdHash, true); - context->accessee.language = DmLanguageManager::GetInstance().GetSystemLanguage(); - context->accessee.deviceName = context->listener->GetLocalDisplayDeviceNameForPrivacy(); - context->accessee.networkId = context->softbusConnector->GetLocalDeviceNetworkId(); - return DM_OK; -} - -int32_t AuthSinkNegotiateStateMachine::ProcRespNegotiate5_1_0(std::shared_ptr context) -{ - CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); - int32_t ret = RespQueryAcceseeIds(context); - if (ret != DM_OK) { - LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to get all id."); - return ret; - } - JsonObject credInfo; - GetSinkCredentialInfo(context, credInfo); - JsonObject aclTypeJson; - GetSinkAclInfo(context, credInfo, aclTypeJson); - context->accessee.aclTypeList = aclTypeJson.Dump(); - JsonObject credTypeJson; - GetSinkCredType(context, credInfo, aclTypeJson, credTypeJson); - context->accessee.credTypeList = credTypeJson.Dump(); - return DM_OK; -} - -int32_t AuthSinkNegotiateStateMachine::Action(std::shared_ptr context) -{ - LOGI("AuthSinkNegotiateStateMachine::Action sessionid %{public}d", context->sessionId); - - // 1. Create an authorization timer - if (context->timer != nullptr) { - context->timer->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), - AUTHENTICATE_TIMEOUT, - [this, context] (std::string name) { - DmAuthState::HandleAuthenticateTimeout(context, name); - }); - } - - // To be compatible with historical versions, use ConvertSrcVersion to get the actual version on the source side. - std::string preVersion = std::string(DM_VERSION_5_0_OLD_MAX); - LOGI("AuthSinkNegotiateStateMachine::Action start version compare %{public}s to %{public}s", - context->accesser.dmVersion.c_str(), preVersion.c_str()); - if (CompareVersion(context->accesser.dmVersion, preVersion) == false) { - LOGE("AuthSinkNegotiateStateMachine::Action incompatible version"); - context->reason = ERR_DM_VERSION_INCOMPATIBLE; - return ERR_DM_VERSION_INCOMPATIBLE; - } - - int32_t ret = ProcRespNegotiate5_1_0(context); - if (ret != DM_OK) { - LOGE("AuthSinkNegotiateStateMachine::Action proc response negotiate failed"); - context->reason = ret; - return ret; - } - context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_ACL_NEGOTIATE, context); - context->timer->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), - DmAuthState::GetTaskTimeout(context, WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), - [this, context] (std::string name) { - DmAuthState::HandleAuthenticateTimeout(context, name); - }); - return DM_OK; -} - -void AuthSinkNegotiateStateMachine::GetSinkCredType(std::shared_ptr context, - JsonObject &credInfo, JsonObject &aclInfo, JsonObject &credTypeJson) -{ - CHECK_NULL_VOID(context); - std::vector deleteCredInfo; - for (const auto &item : credInfo.Items()) { - if (!item.Contains(FILED_CRED_TYPE) || !item[FILED_CRED_TYPE].IsNumberInteger() || - !item.Contains(FILED_CRED_ID) || !item[FILED_CRED_ID].IsString()) { - deleteCredInfo.push_back(item[FILED_CRED_ID].Get()); - continue; - } - int32_t credType = item[FILED_CRED_TYPE].Get(); - LOGI("credType %{public}d.", credType); - switch (credType) { - case DM_IDENTICAL_ACCOUNT: - credTypeJson["identicalCredType"] = credType; - context->accessee.credentialInfos[credType] = item.Dump(); - break; - case DM_SHARE: - credTypeJson["shareCredType"] = credType; - context->accessee.credentialInfos[credType] = item.Dump(); - break; - case DM_POINT_TO_POINT: - GetSinkCredTypeForP2P(context, item, aclInfo, credTypeJson, credType, deleteCredInfo); - break; - case DM_LNN: - if (!aclInfo.Contains("lnnAcl") || - (context->accessee.aclProfiles[DM_LNN].GetAccessee().GetAccesseeCredentialIdStr() != - item[FILED_CRED_ID].Get() && - context->accessee.aclProfiles[DM_LNN].GetAccesser().GetAccesserCredentialIdStr() != - item[FILED_CRED_ID].Get())) { - deleteCredInfo.push_back(item[FILED_CRED_ID].Get()); - } else { - credTypeJson["lnnCredType"] = credType; - context->accessee.credentialInfos[credType] = item.Dump(); - } - break; - default: - LOGE("invalid credType %{public}d.", credType); - break; - } - } - for (const auto &item : deleteCredInfo) { - credInfo.Erase(item); - context->hiChainAuthConnector->DeleteCredential(context->accessee.userId, item); - } -} - -void AuthSinkNegotiateStateMachine::GetSinkCredTypeForP2P(std::shared_ptr context, - const JsonItemObject &credObj, JsonObject &aclInfo, JsonObject &credTypeJson, - int32_t credType, std::vector &deleteCredInfo) -{ - CHECK_NULL_VOID(context); - if (!aclInfo.Contains("pointTopointAcl") || - (context->accessee.aclProfiles[DM_POINT_TO_POINT].GetAccessee().GetAccesseeCredentialIdStr() != - credObj[FILED_CRED_ID].Get() && - context->accessee.aclProfiles[DM_POINT_TO_POINT].GetAccesser().GetAccesserCredentialIdStr() != - credObj[FILED_CRED_ID].Get())) { - deleteCredInfo.push_back(credObj[FILED_CRED_ID].Get()); - } else { - credTypeJson["pointTopointCredType"] = credType; - context->accessee.credentialInfos[credType] = credObj.Dump(); - } -} - -void AuthSinkNegotiateStateMachine::GetSinkAclInfo(std::shared_ptr context, - JsonObject &credInfo, JsonObject &aclInfo) -{ - CHECK_NULL_VOID(context); - std::vector profiles = - DeviceProfileConnector::GetInstance().GetAllAclIncludeLnnAcl(); - int32_t bindLevel = DM_INVALIED_TYPE; - for (const auto &item : profiles) { - std::string trustDeviceId = item.GetTrustDeviceId(); - std::string trustDeviceIdHash = Crypto::GetUdidHash(trustDeviceId); - if (trustDeviceIdHash != context->accesser.deviceIdHash && - trustDeviceIdHash != context->accessee.deviceIdHash) { - LOGE("devId %{public}s hash %{public}s, er devId %{public}s.", GetAnonyString(trustDeviceId).c_str(), - GetAnonyString(trustDeviceIdHash).c_str(), GetAnonyString(context->accesser.deviceIdHash).c_str()); - continue; - } - bindLevel = item.GetBindLevel(); - switch (item.GetBindType()) { - case DM_IDENTICAL_ACCOUNT: - if (IdenticalAccountAclCompare(context, item.GetAccesser(), item.GetAccessee())) { - aclInfo["identicalAcl"] = DM_IDENTICAL_ACCOUNT; - context->accessee.aclProfiles[DM_IDENTICAL_ACCOUNT] = item; - } - break; - case DM_SHARE: - if (ShareAclCompare(context, item.GetAccesser(), item.GetAccessee()) && - CheckCredIdInAcl(context, item, credInfo, DM_SHARE)) { - aclInfo["shareAcl"] = DM_SHARE; - context->accessee.aclProfiles[DM_SHARE] = item; - } - break; - case DM_POINT_TO_POINT: - GetSinkAclInfoForP2P(context, item, credInfo, aclInfo); - break; - default: - LOGE("invalid bindType %{public}d.", item.GetBindType()); - break; - } - } - if (aclInfo.Contains("pointTopointAcl") && !aclInfo.Contains("lnnAcl") && bindLevel != USER) { - aclInfo.Erase("pointTopointAcl"); - DeleteAcl(context, context->accessee.aclProfiles[DM_POINT_TO_POINT]); - } -} - -void AuthSinkNegotiateStateMachine::GetSinkAclInfoForP2P(std::shared_ptr context, - const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, JsonObject &aclInfo) -{ - CHECK_NULL_VOID(context); - if (Point2PointAclCompare(context, profile.GetAccesser(), profile.GetAccessee()) && - CheckCredIdInAcl(context, profile, credInfo, DM_POINT_TO_POINT)) { - aclInfo["pointTopointAcl"] = DM_POINT_TO_POINT; - context->accessee.aclProfiles[DM_POINT_TO_POINT] = profile; - } - if (LnnAclCompare(context, profile.GetAccesser(), profile.GetAccessee()) && - CheckCredIdInAcl(context, profile, credInfo, DM_LNN) && profile.GetBindLevel() == USER) { - aclInfo["lnnAcl"] = DM_LNN; - context->accessee.aclProfiles[DM_LNN] = profile; - } -} - -bool AuthSinkNegotiateStateMachine::CheckCredIdInAcl(std::shared_ptr context, - const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, uint32_t bindType) -{ - std::string credId = profile.GetAccessee().GetAccesseeCredentialIdStr(); - if (!credInfo.Contains(credId)) { - credId = profile.GetAccesser().GetAccesserCredentialIdStr(); - if (!credInfo.Contains(credId)) { - LOGE("credInfoJson not contain credId %{public}s.", credId.c_str()); - DeleteAcl(context, profile); - return false; - } - } - if (credInfo.Contains(credId) && (!credInfo[credId].IsObject() || !credInfo[credId].Contains(FILED_CRED_TYPE) || - !credInfo[credId][FILED_CRED_TYPE].IsNumberInteger())) { - LOGE("credId %{public}s contain credInfoJson invalid.", credId.c_str()); - credInfo.Erase(credId); - DeleteAcl(context, profile); - return false; - } - bool checkResult = false; - switch (bindType) { - LOGI("bindType %{public}d.", bindType); - case DM_IDENTICAL_ACCOUNT: - case DM_SHARE: - case DM_LNN: - if (credInfo[credId][FILED_CRED_TYPE].Get() == bindType) { - checkResult = true; - } else { - DeleteAcl(context, profile); - } - break; - case DM_POINT_TO_POINT: - CheckCredIdInAclForP2P(context, credId, profile, credInfo, bindType, checkResult); - break; - default: - break; - } - return checkResult; -} - -void AuthSinkNegotiateStateMachine::CheckCredIdInAclForP2P(std::shared_ptr context, - std::string &credId, const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, - uint32_t bindType, bool &checkResult) -{ - if (credInfo[credId][FILED_CRED_TYPE].Get() == bindType) { - std::vector appList; - credInfo[credId][FILED_AUTHORIZED_APP_LIST].Get(appList); - const size_t APP_LIST_SIZE = 2; - if (appList.size() >= APP_LIST_SIZE && - ((std::to_string(profile.GetAccesser().GetAccesserTokenId()) == appList[0] && - std::to_string(profile.GetAccessee().GetAccesseeTokenId()) == appList[1]) || - (std::to_string(profile.GetAccessee().GetAccesseeTokenId()) == appList[0] && - std::to_string(profile.GetAccesser().GetAccesserTokenId()) == appList[1]))) { - checkResult = true; - } else { - DeleteAcl(context, profile); - } - } else { - DeleteAcl(context, profile); - } -} - -bool AuthSinkNegotiateStateMachine::IdenticalAccountAclCompare(std::shared_ptr context, - const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) -{ - LOGI("start"); - return accesser.GetAccesserDeviceId() == context->accessee.deviceId && - accesser.GetAccesserUserId() == context->accessee.userId && - Crypto::GetUdidHash(accessee.GetAccesseeDeviceId()) == context->accesser.deviceIdHash; -} - -bool AuthSinkNegotiateStateMachine::ShareAclCompare(std::shared_ptr context, - const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) -{ - LOGI("start"); - return accessee.GetAccesseeDeviceId() == context->accessee.deviceId && - accessee.GetAccesseeUserId() == context->accessee.userId && - Crypto::GetUdidHash(accesser.GetAccesserDeviceId()) == context->accesser.deviceIdHash; -} - -bool AuthSinkNegotiateStateMachine::Point2PointAclCompare(std::shared_ptr context, - const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) -{ - LOGI("start"); - return (accessee.GetAccesseeDeviceId() == context->accessee.deviceId && - accessee.GetAccesseeUserId() == context->accessee.userId && - accessee.GetAccesseeTokenId() == context->accessee.tokenId && - Crypto::GetUdidHash(accesser.GetAccesserDeviceId()) == context->accesser.deviceIdHash && - Crypto::GetTokenIdHash(std::to_string(accesser.GetAccesserTokenId())) == context->accesser.tokenIdHash) || - (accesser.GetAccesserDeviceId() == context->accessee.deviceId && - accesser.GetAccesserUserId() == context->accessee.userId && - accesser.GetAccesserTokenId() == context->accessee.tokenId && - Crypto::GetUdidHash(accessee.GetAccesseeDeviceId()) == context->accesser.deviceIdHash && - Crypto::GetTokenIdHash(std::to_string(accessee.GetAccesseeTokenId())) == context->accesser.tokenIdHash); -} - -bool AuthSinkNegotiateStateMachine::LnnAclCompare(std::shared_ptr context, - const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) -{ - LOGI("start"); - return ((accessee.GetAccesseeDeviceId() == context->accessee.deviceId && - accessee.GetAccesseeUserId() == context->accessee.userId) || - (accesser.GetAccesserDeviceId() == context->accessee.deviceId && - accesser.GetAccesserUserId() == context->accessee.userId)) && - accessee.GetAccesseeTokenId() == 0 && accessee.GetAccesseeBundleName() == "" && - (Crypto::GetUdidHash(accesser.GetAccesserDeviceId()) == context->accesser.deviceIdHash || - Crypto::GetUdidHash(accessee.GetAccesseeDeviceId()) == context->accesser.deviceIdHash) && - accesser.GetAccesserTokenId() == 0 && accesser.GetAccesserBundleName() == ""; -} - -void AuthSinkNegotiateStateMachine::GetSinkCredentialInfo(std::shared_ptr context, - JsonObject &credInfo) -{ - CHECK_NULL_VOID(context); - // get identical credential - if (context->accesser.accountIdHash == context->accessee.accountIdHash) { - GetIdenticalCredentialInfo(context, credInfo); - } - // get share credential - if (context->accesser.accountIdHash != context->accessee.accountIdHash && - context->accesser.accountIdHash != Crypto::GetAccountIdHash16("ohosAnonymousUid") && - context->accessee.accountIdHash != Crypto::GetAccountIdHash16("ohosAnonymousUid")) { - GetShareCredentialInfo(context, credInfo); - GetP2PCredentialInfo(context, credInfo); - } - // get point_to_point credential - if (context->accesser.accountIdHash == Crypto::GetAccountIdHash16("ohosAnonymousUid") || - context->accessee.accountIdHash == Crypto::GetAccountIdHash16("ohosAnonymousUid")) { - GetP2PCredentialInfo(context, credInfo); - } - std::vector deleteCredInfo; - for (auto& item : credInfo.Items()) { // id1:json1, id2:json2, id3:json3 - uint32_t credType = DmAuthState::GetCredentialType(context, item); - if (credType == DM_INVALIED_TYPE || !item.Contains(FILED_CRED_TYPE) || - !item[FILED_CRED_TYPE].IsNumberInteger() || !item.Contains(FILED_CRED_ID) || - !item[FILED_CRED_ID].IsString()) { - deleteCredInfo.push_back(item[FILED_CRED_ID].Get()); - continue; - } - item[FILED_CRED_TYPE] = credType; - } - for (const auto &item : deleteCredInfo) { - credInfo.Erase(item); - } -} - -void AuthSinkNegotiateStateMachine::GetIdenticalCredentialInfo(std::shared_ptr context, - JsonObject &credInfo) -{ - CHECK_NULL_VOID(context); - JsonObject queryParams; - queryParams[FILED_DEVICE_ID] = context->accessee.deviceId; - queryParams[FILED_USER_ID] = MultipleUserConnector::GetOhosAccountNameByUserId(context->accessee.userId); - queryParams[FILED_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_RELATED; - CHECK_NULL_VOID(context->hiChainAuthConnector); - if (context->hiChainAuthConnector->QueryCredentialInfo(context->accessee.userId, queryParams, credInfo) != DM_OK) { - LOGE("QueryCredentialInfo failed credInfo %{public}s.", credInfo.Dump().c_str()); - } -} - -void AuthSinkNegotiateStateMachine::GetShareCredentialInfo(std::shared_ptr context, - JsonObject &credInfo) -{ - CHECK_NULL_VOID(context); - JsonObject queryParams; - queryParams[FILED_DEVICE_ID_HASH] = context->accesser.deviceIdHash; - queryParams[FILED_PEER_USER_SPACE_ID] = std::to_string(context->accesser.userId); - queryParams[FILED_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS; - CHECK_NULL_VOID(context->hiChainAuthConnector); - if (context->hiChainAuthConnector->QueryCredentialInfo(context->accessee.userId, queryParams, credInfo) != DM_OK) { - LOGE("QueryCredentialInfo failed credInfo %{public}s.", credInfo.Dump().c_str()); - } -} - -void AuthSinkNegotiateStateMachine::GetP2PCredentialInfo(std::shared_ptr context, - JsonObject &credInfo) -{ - CHECK_NULL_VOID(context); - JsonObject queryParams; - queryParams[FILED_DEVICE_ID_HASH] = context->accesser.deviceIdHash; - queryParams[FILED_PEER_USER_SPACE_ID] = std::to_string(context->accesser.userId); - queryParams[FILED_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; - queryParams[FILED_CRED_OWNER] = "DM"; - CHECK_NULL_VOID(context->hiChainAuthConnector); - if (context->hiChainAuthConnector->QueryCredentialInfo(context->accessee.userId, queryParams, credInfo) != DM_OK) { - LOGE("QueryCredentialInfo failed credInfo %{public}s.", credInfo.Dump().c_str()); - } -} -} // namespace DistributedHardware -} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp.bak b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp.bak deleted file mode 100644 index 49eb28e17..000000000 --- a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp.bak +++ /dev/null @@ -1,514 +0,0 @@ -/* - * Copyright (c) 2025 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 "multiple_user_connector.h" -#include "os_account_manager.h" - -#include "dm_constants.h" -#include "dm_error_type.h" -#include "dm_auth_manager_base.h" -#include "power_mgr_client.h" -#if defined(SUPPORT_SCREENLOCK) -#include "screenlock_manager.h" -#endif - -#ifdef OS_ACCOUNT_PART_EXISTS -#include "os_account_manager.h" -using namespace OHOS::AccountSA; -#endif // OS_ACCOUNT_PART_EXISTS - -namespace OHOS { -namespace DistributedHardware { -const char* TAG_DMVERSION = "dmVersion"; -const char* TAG_DM_VERSION_V2 = "dmVersionV2"; -const char* TAG_EDITION = "edition"; -const char* TAG_DATA = "data"; -const char* TAG_DATA_LEN = "dataLen"; -const char* TAG_BUNDLE_NAME = "bundleName"; -const char* TAG_BUNDLE_NAME_V2 = "bundleNameV2"; -const char* TAG_PEER_BUNDLE_NAME = "PEER_BUNDLE_NAME"; -const char* TAG_PEER_BUNDLE_NAME_V2 = "PEER_BUNDLE_NAME_V2"; -const char* TAG_PEER_PKG_NAME = "PEER_PKG_NAME"; -const char* TAG_BIND_LEVEL = "bindLevel"; -const char* TAG_REPLY = "REPLY"; -const char* TAG_APP_THUMBNAIL2 = "appThumbnail"; // Naming Add 2 to resolve conflicts with TAG_APP_THUMBNAIL -const char* TAG_AUTH_FINISH = "isFinish"; -const char* TAG_LOCAL_USERID = "localUserId"; -const char* TAG_LOCAL_DEVICE_ID = "LOCALDEVICEID"; -const char* TAG_IDENTICAL_ACCOUNT = "IDENTICALACCOUNT"; -const char* TAG_ACCOUNT_GROUPID = "ACCOUNTGROUPID"; -const char* TAG_HAVE_CREDENTIAL = "haveCredential"; -const char* TAG_ISONLINE = "isOnline"; -const char* TAG_AUTHED = "authed"; -const char* TAG_LOCAL_ACCOUNTID = "localAccountId"; -const char* TAG_TOKENID = "tokenId"; -const char* TAG_HOST_PKGLABEL = "hostPkgLabel"; -const char* TAG_REMOTE_DEVICE_NAME = "REMOTE_DEVICE_NAME"; -const char* TAG_HOST = "HOST"; - -const char* APP_OPERATION_KEY = "appOperation"; -const char* TARGET_PKG_NAME_KEY = "targetPkgName"; -const char* CUSTOM_DESCRIPTION_KEY = "customDescription"; -const char* CANCEL_DISPLAY_KEY = "cancelPinCodeDisplay"; -const char* BUNDLE_NAME_KEY = "bundleName"; - -const char* AUTHENTICATE_TIMEOUT_TASK = "deviceManagerTimer:authenticate"; -const char* NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:negotiate"; -const char* CONFIRM_TIMEOUT_TASK = "deviceManagerTimer:confirm"; -const char* INPUT_TIMEOUT_TASK = "deviceManagerTimer:input"; -const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessionHeartbeat"; -const char* WAIT_REQUEST_TIMEOUT_TASK = "deviceManagerTimer:waitRequest"; -const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_"; -const char* WAIT_PIN_AUTH_TIMEOUT_TASK = "deviceManagerTimer:waitPinAuth"; -const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNegotiate"; -const char* GET_ULTRASONIC_PIN_TIMEOUT_TASK = "deviceManagerTimer:getUltrasonicPin"; -const char* ADD_TIMEOUT_TASK = "deviceManagerTimer:add"; -const char* WAIT_SESSION_CLOSE_TIMEOUT_TASK = "deviceManagerTimer:waitSessionClose"; -const char* CLOSE_SESSION_TASK_SEPARATOR = "#"; - -const int32_t AUTHENTICATE_TIMEOUT = 120; -const int32_t CONFIRM_TIMEOUT = 60; -const int32_t NEGOTIATE_TIMEOUT = 10; -const int32_t INPUT_TIMEOUT = 60; -const int32_t ADD_TIMEOUT = 10; -const int32_t WAIT_NEGOTIATE_TIMEOUT = 10; -const int32_t WAIT_REQUEST_TIMEOUT = 10; -const int32_t CLONE_AUTHENTICATE_TIMEOUT = 20; -const int32_t CLONE_CONFIRM_TIMEOUT = 10; -const int32_t CLONE_NEGOTIATE_TIMEOUT = 10; -const int32_t CLONE_ADD_TIMEOUT = 10; -const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT = 10; -const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 10; -const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT = 20; -const int32_t CLONE_PIN_AUTH_TIMEOUT = 10; -const int32_t HML_SESSION_TIMEOUT = 10; -const int32_t SESSION_HEARTBEAT_TIMEOUT = 50; -const int32_t PIN_AUTH_TIMEOUT = 60; -const int32_t EVENT_TIMEOUT = 5000; // 5000 ms - - -int32_t AuthManagerBase::AuthenticateDevice(const std::string &pkgName, int32_t authType, - const std::string &deviceId, const std::string &extra) -{ - LOGE("AuthenticateDevice is not implemented in the current version"); - return ERR_DM_FAILED; -} - -int32_t AuthManagerBase::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) -{ - LOGE("UnAuthenticateDevice is not implemented in the current version"); - return ERR_DM_FAILED; -} - -int32_t AuthManagerBase::UnBindDevice(const std::string &pkgName, const std::string &udid, - int32_t bindLevel, const std::string &extra) -{ - LOGE("UnBindDevice is not implemented in the current version"); - return ERR_DM_FAILED; -} - -void AuthManagerBase::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) -{ - LOGE("OnSessionOpened is not implemented in the current version"); -} - -void AuthManagerBase::OnSessionClosed(const int32_t sessionId) -{ - LOGE("OnSessionClosed is not implemented in the current version"); -} - -void AuthManagerBase::OnSessionDisable() -{ - LOGE("OnSessionDisable is not implemented in the current version"); -} - -void AuthManagerBase::OnDataReceived(const int32_t sessionId, const std::string message) -{ - LOGE("OnDataReceived is not implemented in the current version"); -} - -void AuthManagerBase::OnSoftbusJoinLNNResult(const int32_t sessionId, const char *networkId, int32_t result) -{ - LOGE("OnSoftbusJoinLNNResult is not implemented in the current version"); -} - -void AuthManagerBase::OnGroupCreated(int64_t requestId, const std::string &groupId) -{ - LOGE("OnGroupCreated is not implemented in the current version"); -} - -void AuthManagerBase::OnMemberJoin(int64_t requestId, int32_t status) -{ - LOGE("OnMemberJoin is not implemented in the current version"); -} - -int32_t AuthManagerBase::EstablishAuthChannel(const std::string &deviceId) -{ - LOGE("EstablishAuthChannel is not implemented in the current version"); - return ERR_DM_FAILED; -} - -void AuthManagerBase::StartNegotiate(const int32_t &sessionId) -{ - LOGE("StartNegotiate is not implemented in the current version"); -} - -void AuthManagerBase::RespNegotiate(const int32_t &sessionId) -{ - LOGE("RespNegotiate is not implemented in the current version"); -} - -void AuthManagerBase::SendAuthRequest(const int32_t &sessionId) -{ - LOGE("SendAuthRequest is not implemented in the current version"); -} - -int32_t AuthManagerBase::StartAuthProcess(const int32_t &action) -{ - LOGE("StartAuthProcess is not implemented in the current version"); - return ERR_DM_FAILED; -} - -void AuthManagerBase::StartRespAuthProcess() -{ - LOGE("StartRespAuthProcess is not implemented in the current version"); -} - -int32_t AuthManagerBase::CreateGroup() -{ - LOGE("CreateGroup is not implemented in the current version"); - return ERR_DM_FAILED; -} - -int32_t AuthManagerBase::ProcessPincode(const std::string &pinCode) -{ - LOGE("ProcessPincode is not implemented in the current version"); - return ERR_DM_FAILED; -} - -std::string AuthManagerBase::GetConnectAddr(std::string deviceId) -{ - LOGE("GetConnectAddr is not implemented in the current version"); - return ""; -} - -int32_t AuthManagerBase::JoinNetwork() -{ - LOGE("JoinNetwork is not implemented in the current version"); - return ERR_DM_FAILED; -} - -void AuthManagerBase::AuthenticateFinish() -{ - LOGE("AuthenticateFinish is not implemented in the current version"); -} - -bool AuthManagerBase::GetIsCryptoSupport() -{ - LOGE("GetIsCryptoSupport is not implemented in the current version"); - return false; -} - -int32_t AuthManagerBase::SetAuthRequestState(std::shared_ptr authRequestState) -{ - LOGE("SetAuthRequestState is not implemented in the current version"); - return ERR_DM_FAILED; -} - -int32_t AuthManagerBase::SetAuthResponseState(std::shared_ptr authResponseState) -{ - LOGE("SetAuthResponseState is not implemented in the current version"); - return ERR_DM_FAILED; -} - -int32_t AuthManagerBase::GetPinCode(std::string &code) -{ - LOGE("GetPinCode is not implemented in the current version"); - return ERR_DM_FAILED; -} - -std::string AuthManagerBase::GenerateGroupName() -{ - LOGE("GenerateGroupName is not implemented in the current version"); - return ""; -} - -void AuthManagerBase::HandleAuthenticateTimeout(std::string name) -{ - LOGE("HandleAuthenticateTimeout is not implemented in the current version"); -} - -std::string AuthManagerBase::GeneratePincode() -{ - LOGE("GeneratePincode is not implemented in the current version"); - return ""; -} - -void AuthManagerBase::ShowConfigDialog() -{ - LOGE("ShowConfigDialog is not implemented in the current version"); -} - -void AuthManagerBase::ShowAuthInfoDialog(bool authDeviceError) -{ - LOGE("ShowAuthInfoDialog is not implemented in the current version"); -} - -void AuthManagerBase::ShowStartAuthDialog() -{ - LOGE("ShowStartAuthDialog is not implemented in the current version"); -} - -int32_t AuthManagerBase::OnUserOperation(int32_t action, const std::string ¶ms) -{ - LOGE("OnUserOperation is not implemented in the current version"); - return ERR_DM_FAILED; -} - -int32_t AuthManagerBase::SetPageId(int32_t pageId) -{ - LOGE("SetPageId is not implemented in the current version"); - return ERR_DM_FAILED; -} - -int32_t AuthManagerBase::SetReasonAndFinish(int32_t reason, int32_t state) -{ - LOGE("SetReasonAndFinish is not implemented in the current version"); - return ERR_DM_FAILED; -} - -bool AuthManagerBase::IsIdenticalAccount() -{ - LOGE("IsIdenticalAccount is not implemented in the current version"); - return false; -} - -int32_t AuthManagerBase::RegisterUiStateCallback(const std::string pkgName) -{ - LOGE("RegisterUiStateCallback is not implemented in the current version"); - return ERR_DM_FAILED; -} - -int32_t AuthManagerBase::UnRegisterUiStateCallback(const std::string pkgName) -{ - LOGE("UnRegisterUiStateCallback is not implemented in the current version"); - return ERR_DM_FAILED; -} - -int32_t AuthManagerBase::ImportAuthCode(const std::string &pkgName, const std::string &authCode) -{ - LOGE("ImportAuthCode is not implemented in the current version"); - return ERR_DM_FAILED; -} - -int32_t AuthManagerBase::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, - const std::map &bindParam, int sessionId, uint64_t logicalSessionId) -{ - LOGE("BindTarget is not implemented in the current version"); - return ERR_DM_FAILED; -} - -int32_t AuthManagerBase::RegisterAuthenticationType(int32_t authenticationType) -{ - LOGE("RegisterAuthenticationType is not implemented in the current version"); - return ERR_DM_FAILED; -} - -int32_t AuthManagerBase::StopAuthenticateDevice(const std::string &pkgName) -{ - LOGE("StopAuthenticateDevice is not implemented in the current version"); - return ERR_DM_FAILED; -} - -int32_t AuthManagerBase::DeleteGroup(const std::string &pkgName, const std::string &deviceId) -{ - LOGE("DeleteGroup is not implemented in the current version"); - return ERR_DM_FAILED; -} - -int32_t AuthManagerBase::GetReason() -{ - LOGE("GetReason is not implemented in the current version"); - return ERR_DM_FAILED; -} - -void AuthManagerBase::GetBindTargetParams(std::string &pkgName, PeerTargetId &targetId, - std::map &bindParam) -{ - LOGE("GetBindTargetParams is not implemented in the current version"); - return; -} - -void AuthManagerBase::SetBindTargetParams(const PeerTargetId &targetId) -{ - LOGE("SetBindTargetParams is not implemented in the current version"); - return; -} - -void AuthManagerBase::RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback) -{ - LOGE("RegisterCleanNotifyCallback is not implemented in the current version"); - return; -} - -std::string AuthManagerBase::ConvertSrcVersion(const std::string &version, const std::string &edition) -{ - std::string srcVersion = ""; - if (version == "" && edition != "") { - srcVersion = edition; - } else if (version == "" && edition == "") { - srcVersion = DM_VERSION_5_1_0; - } else if (version != "" && edition == "") { - srcVersion = version; - } - LOGI("ConvertSrcVersion version %{public}s, edition %{public}s, srcVersion is %{public}s.", - version.c_str(), edition.c_str(), srcVersion.c_str()); - return srcVersion; -} - -// Scenario 1: The remote side specifies userId -> Verify if it is a front-end user -// Scenario 2: The remote side does not specify userId -// Scenario 2.1: Single user -> Use the current unique front-end user -// Scenario 2.2: Multiple users -> Use the current main screen user -int32_t AuthManagerBase::DmGetUserId(int32_t displayId) -{ - int32_t ret; - int32_t userId = -1; - - std::vector userIds; - ret = MultipleUserConnector::GetForegroundUserIds(userIds); - if (ret != DM_OK) { - LOGE("RespQueryTokenId: GetForegroundUserIds failed, ret: %{public}d", ret); - return -1; - } - // Scenario 1: The remote side specifies userId -> Verify if it is a front-end user - // Scenario 2: The remote side does not specify userId - // Scenario 2.1: Single user -> Use the current unique front-end user - // Scenario 2.2: Multiple users -> Use the current main screen user - if (userIds.size() == 0) { - LOGE("RespQueryTokenId: GetForegroundUserIds no foreground users"); - return -1; - } - - if (displayId != -1) { - ret = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(displayId, userId); - if (ret != DM_OK) { - LOGE("RespQueryTokenId: fail to get userId by displayId %{public}d", displayId); - return -1; - } - return userId; - } - if (userIds.size() == 1) { - return userIds[0]; - } else { - // If userIds.size() > 1, we need to find the main screen user -#ifdef OS_ACCOUNT_PART_EXISTS - ret = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId); - if (ret != DM_OK) { - LOGE("AuthManagerBase::DmGetUserId: get foreground user failed in multi users with error %{public}d", ret); - return -1; - } - return userId; -#else - LOGE("AuthManagerBase::DmGetUserId: get foreground user failed because no OsAcccountManager"); - return -1; -#endif - } -} - -bool AuthManagerBase::IsTransferReady() -{ - return isTransferReady_; -} - -void AuthManagerBase::SetTransferReady(bool version) -{ - isTransferReady_ = version; -} - -void AuthManagerBase::ClearSoftbusSessionCallback() -{} - -void AuthManagerBase::PrepareSoftbusSessionCallback() -{} - -void AuthManagerBase::EnableInsensibleSwitching() -{ - insensibleSwitching = true; -} - -void AuthManagerBase::DisableInsensibleSwitching() -{ - insensibleSwitching = false; -} - -bool AuthManagerBase::NeedInsensibleSwitching() -{ - return insensibleSwitching; -} - -int32_t AuthManagerBase::ParseAuthType(const std::map &bindParam, int32_t &authType) -{ - auto iter = bindParam.find(PARAM_KEY_AUTH_TYPE); - if (iter == bindParam.end()) { - LOGE("AuthManagerBase::ParseAuthType bind param key: %{public}s not exist.", PARAM_KEY_AUTH_TYPE); - return ERR_DM_INPUT_PARA_INVALID; - } - std::string authTypeStr = iter->second; - if (authTypeStr.empty()) { - LOGE("AuthManagerBase::ParseAuthType bind param %{public}s is empty.", PARAM_KEY_AUTH_TYPE); - return ERR_DM_INPUT_PARA_INVALID; - } - if (authTypeStr.length() > 1) { - LOGE("AuthManagerBase::ParseAuthType bind param %{public}s length is unsupported.", PARAM_KEY_AUTH_TYPE); - return ERR_DM_INPUT_PARA_INVALID; - } - if (!isdigit(authTypeStr[0])) { - LOGE("AuthManagerBase::ParseAuthType bind param %{public}s fromat is unsupported.", PARAM_KEY_AUTH_TYPE); - return ERR_DM_INPUT_PARA_INVALID; - } - authType = std::atoi(authTypeStr.c_str()); - return DM_OK; -} - -void AuthManagerBase::OnAuthDeviceDataReceived(int32_t sessionId, std::string message) -{ - LOGE("OnAuthDeviceDataReceived is not used in the new protocol"); -} - -int32_t AuthManagerBase::EndDream() -{ - auto &powerMgrClient = OHOS::PowerMgr::PowerMgrClient::GetInstance(); - if (!powerMgrClient.IsScreenOn()) { - LOGW("screen not on"); - return ERR_DM_FAILED; - } -#if defined(SUPPORT_SCREENLOCK) - if (!OHOS::ScreenLock::ScreenLockManager::GetInstance()->IsScreenLocked()) { - LOGI("screen not locked"); - return DM_OK; - } -#endif - PowerMgr::PowerErrors ret = - powerMgrClient.WakeupDevice(PowerMgr::WakeupDeviceType::WAKEUP_DEVICE_END_DREAM, "end_dream"); - if (ret != OHOS::PowerMgr::PowerErrors::ERR_OK) { - LOGE("fail to end dream, err:%{public}d", ret); - return ERR_DM_FAILED; - } - LOGI("end dream success"); - return DM_OK; -} -} // namespace DistributedHardware -} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp.bak b/services/implementation/src/authentication_v2/dm_auth_state.cpp.bak deleted file mode 100644 index e10b392e0..000000000 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp.bak +++ /dev/null @@ -1,461 +0,0 @@ -/* - * Copyright (c) 2025 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 "access_control_profile.h" -#include "hichain_auth_connector.h" -#include "multiple_user_connector.h" -#include "dm_crypto.h" -#include "dm_auth_state.h" -#include "dm_auth_context.h" -#include "dm_auth_manager_base.h" -#include "dm_auth_state_machine.h" -#include "dm_crypto.h" -#include "dm_softbus_cache.h" -#if defined(SUPPORT_SCREENLOCK) -#include "screenlock_manager.h" -#endif -#include "dm_log.h" -#include - -namespace OHOS { -namespace DistributedHardware { -// clone task timeout map -const std::map TASK_TIME_OUT_MAP = { - { std::string(AUTHENTICATE_TIMEOUT_TASK), CLONE_AUTHENTICATE_TIMEOUT }, - { std::string(NEGOTIATE_TIMEOUT_TASK), CLONE_NEGOTIATE_TIMEOUT }, - { std::string(CONFIRM_TIMEOUT_TASK), CLONE_CONFIRM_TIMEOUT }, - { std::string(ADD_TIMEOUT_TASK), CLONE_ADD_TIMEOUT }, - { std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), CLONE_WAIT_NEGOTIATE_TIMEOUT }, - { std::string(WAIT_REQUEST_TIMEOUT_TASK), CLONE_WAIT_REQUEST_TIMEOUT }, - { std::string(WAIT_PIN_AUTH_TIMEOUT_TASK), CLONE_PIN_AUTH_TIMEOUT }, - { std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), CLONE_SESSION_HEARTBEAT_TIMEOUT } -}; - -constexpr int32_t ONBINDRESULT_MAPPING_NUM = 2; -constexpr int32_t MS_PER_SECOND = 1000; -constexpr int32_t US_PER_MSECOND = 1000; -constexpr const static char* ONBINDRESULT_MAPPING_LIST[ONBINDRESULT_MAPPING_NUM] = { - "CollaborationFwk", - "cast_engine_service", -}; - -const std::map NEW_AND_OLD_STATE_MAPPING = { - { DmAuthStateType::AUTH_SRC_FINISH_STATE, DmAuthStatus::STATUS_DM_AUTH_FINISH }, - { DmAuthStateType::AUTH_SINK_FINISH_STATE, DmAuthStatus::STATUS_DM_SINK_AUTH_FINISH } -}; - -const std::map NEW_AND_OLD_REPLAY_MAPPING = { - { DM_ALREADY_AUTHED, SOFTBUS_OK }, - { SOFTBUS_OK, SOFTBUS_OK } -}; - -constexpr int32_t OPEN_PROCESS_NAME_WHITE_LIST_NUM = 1; -constexpr int32_t CLOSE_PROCESS_NAME_WHITE_LIST_NUM = 2; -constexpr const static char* OPEN_PROCESS_NAME_WHITE_LIST[OPEN_PROCESS_NAME_WHITE_LIST_NUM] = { - "com.example.myapplication" -}; -constexpr const static char* CLOSE_PROCESS_NAME_WHITE_LIST[CLOSE_PROCESS_NAME_WHITE_LIST_NUM] = { - "CollaborationFwk", - "gameservice_server" -}; - - -int32_t DmAuthState::GetTaskTimeout(std::shared_ptr context, const char* taskName, int32_t taskTimeOut) -{ - LOGI("GetTaskTimeout, taskName: %{public}s, authType_: %{public}d", taskName, context->authType); - if (DmAuthState::IsImportAuthCodeCompatibility(context->authType)) { - auto timeout = TASK_TIME_OUT_MAP.find(std::string(taskName)); - if (timeout != TASK_TIME_OUT_MAP.end()) { - return timeout->second; - } - } - return taskTimeOut; -} - -void DmAuthState::HandleAuthenticateTimeout(std::shared_ptr context, std::string name) -{ - LOGI("DmAuthContext::HandleAuthenticateTimeout start timer name %{public}s", name.c_str()); - context->timer->DeleteTimer(name); - context->reason = ERR_DM_TIME_OUT; - context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); - LOGI("DmAuthContext::HandleAuthenticateTimeout complete"); -} - -bool DmAuthState::IsScreenLocked() -{ - bool isLocked = false; -#if defined(SUPPORT_SCREENLOCK) - isLocked = OHOS::ScreenLock::ScreenLockManager::GetInstance()->IsScreenLocked(); -#endif - LOGI("IsScreenLocked isLocked: %{public}d.", isLocked); - return isLocked; -} - -void DmAuthState::SourceFinish(std::shared_ptr context) -{ - LOGI("SourceFinish reason:%{public}d", context->reason); - context->listener->OnAuthResult(context->processInfo, context->peerTargetId.deviceId, context->accessee.tokenIdHash, - GetOutputState(context->accesser.bundleName, context->state), context->reason); - context->listener->OnBindResult(context->processInfo, context->peerTargetId, - GetOutputReplay(context->accesser.bundleName, context->reason), - GetOutputState(context->accesser.bundleName, context->state), GenerateBindResultContent(context)); - context->successFinished = true; - - if (context->reason != DM_OK && context->reason != DM_ALREADY_AUTHED) { - // 根据凭据id 删除sink端多余的凭据 - context->hiChainAuthConnector->DeleteCredential(context->accesser.userId, - context->accesser.lnnCredentialId); - context->hiChainAuthConnector->DeleteCredential(context->accesser.userId, - context->accesser.transmitCredentialId); - // 根据skid删除sk,删除skid - DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accesser.userId, - context->accesser.lnnSessionKeyId); - DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accesser.userId, - context->accesser.transmitSessionKeyId); - } - LOGI("SourceFinish notify online"); - char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; - Crypto::GetUdidHash(context->accessee.deviceId, reinterpret_cast(deviceIdHash)); - if (SoftbusCache::GetInstance().CheckIsOnline(std::string(deviceIdHash))) { - SetProcessInfo(context); - int32_t authForm = context->accesser.transmitBindType == DM_POINT_TO_POINT_TYPE ? - DmAuthForm::PEER_TO_PEER : context->accesser.transmitBindType; - context->softbusConnector->HandleDeviceOnline(context->accessee.deviceId, authForm); - } - - context->authUiStateMgr->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); - context->timer->DeleteAll(); -} - -void DmAuthState::SinkFinish(std::shared_ptr context) -{ - LOGI("SinkFinish reason:%{public}d", context->reason); - context->processInfo.pkgName = context->accessee.pkgName; - context->listener->OnSinkBindResult(context->processInfo, context->peerTargetId, - GetOutputReplay(context->accessee.bundleName, context->reason), - GetOutputState(context->accessee.bundleName, context->state), GenerateBindResultContent(context)); - context->successFinished = true; - if (context->reason != DM_OK) { - // 根据凭据id 删除sink端多余的凭据 - context->hiChainAuthConnector->DeleteCredential(context->accessee.userId, - context->accessee.lnnCredentialId); - context->hiChainAuthConnector->DeleteCredential(context->accessee.userId, - context->accessee.transmitCredentialId); - // 根据skid删除sk,删除skid - DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accessee.userId, - context->accessee.lnnSessionKeyId); - DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accessee.userId, - context->accessee.transmitSessionKeyId); - } else { - SetAclInfo(context); - if (NeedAgreeAcl(context)) { - context->authMessageProcessor->PutAccessControlList(context, - context->accessee, context->accesser.deviceId); - } - LOGI("SinkFinish notify online"); - char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; - Crypto::GetUdidHash(context->accesser.deviceId, reinterpret_cast(deviceIdHash)); - if (SoftbusCache::GetInstance().CheckIsOnline(std::string(deviceIdHash))) { - SetProcessInfo(context); - int32_t authForm = context->accessee.transmitBindType == DM_POINT_TO_POINT_TYPE ? - DmAuthForm::PEER_TO_PEER : context->accessee.transmitBindType; - context->softbusConnector->HandleDeviceOnline(context->accesser.deviceId, authForm); - } - } - - context->authUiStateMgr->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW); - context->timer->DeleteAll(); - context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_RESP_FINISH, context); // 发送201给source侧 -} - -std::string DmAuthState::GenerateBindResultContent(std::shared_ptr context) -{ - CHECK_NULL_RETURN(context, ""); - DmAccess access = context->direction == DmAuthDirection::DM_AUTH_SOURCE ? - context->accessee : context->accesser; - JsonObject jsonObj; - jsonObj[DM_BIND_RESULT_NETWORK_ID] = access.networkId; - if (access.deviceId.empty()) { - jsonObj[TAG_DEVICE_ID] = ""; - } else { - char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; - Crypto::GetUdidHash(access.deviceId, reinterpret_cast(deviceIdHash)); - jsonObj[TAG_DEVICE_ID] = deviceIdHash; - } - jsonObj[TAG_CONFIRM_OPERATION_V2] = context->confirmOperation; - std::string content = jsonObj.Dump(); - return content; -} - -bool DmAuthState::NeedReqUserConfirm(std::shared_ptr context) -{ - // 不管是否有可信关系,都需要走pin码认证,主要指鸿蒙环PIN码导入场景 - if (DmAuthState::IsImportAuthCodeCompatibility(context->authType)) { - return true; - } - - // 有ACL,跳转到结束状态,发200报文,直接组网 - DmAccess access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; - if (access.isAuthed) { - return false; - } - - return true; -} - -bool DmAuthState::NeedAgreeCredential(std::shared_ptr context) -{ - return context->needAgreeCredential; -} - -bool DmAuthState::NeedAgreeAcl(std::shared_ptr context) -{ - return (context->direction == DM_AUTH_SOURCE) ? !context->accesser.isAuthed : !context->accessee.isAuthed; -} - -bool DmAuthState::IsImportAuthCodeCompatibility(DmAuthType authType) -{ - if (authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE || - authType == DmAuthType::AUTH_TYPE_NFC) { - return true; - } - return false; -} - -void DmAuthState::SetAclExtraInfo(std::shared_ptr context) -{ - DmAccess &access = (context->direction == DM_AUTH_SOURCE) ? context->accesser : context->accessee; - DmAccess &remoteAccess = (context->direction == DM_AUTH_SOURCE) ? context->accessee : context->accesser; - JsonObject jsonObj; - jsonObj[TAG_DMVERSION] = access.dmVersion; - access.extraInfo = jsonObj.Dump(); - remoteAccess.extraInfo = jsonObj.Dump(); -} - -void DmAuthState::SetAclInfo(std::shared_ptr context) -{ - DmAccess &access = (context->direction == DM_AUTH_SOURCE) ? context->accesser : context->accessee; - DmAccess &remoteAccess = (context->direction == DM_AUTH_SOURCE) ? context->accessee : context->accesser; - SetAclExtraInfo(context); - access.lnnBindType = GetAclBindType(context, access.lnnCredentialId); - remoteAccess.lnnBindType = GetAclBindType(context, remoteAccess.lnnCredentialId); - - access.transmitBindType = GetAclBindType(context, access.transmitCredentialId); - remoteAccess.transmitBindType = GetAclBindType(context, remoteAccess.transmitCredentialId); -} - -int32_t DmAuthState::GetAclBindType(std::shared_ptr context, std::string credId) -{ - DmAccess &access = (context->direction == DM_AUTH_SOURCE) ? context->accesser : context->accessee; - JsonObject result; - int32_t ret = context->hiChainAuthConnector->QueryCredInfoByCredId(access.userId, credId, result); - if (ret != DM_OK) { - LOGE("GetAclBindType QueryCredInfoByCredId failed, ret: %{public}d.", ret); - return DM_UNKNOWN_TYPE; - } - if (!result.Contains(credId)) { - LOGE("GetAclBindType result not contains credId."); - return DM_UNKNOWN_TYPE; - } - int32_t credType = result[credId][FILED_CRED_TYPE].Get(); - if (credType == DM_AUTH_CREDENTIAL_ACCOUNT_RELATED) { - return DM_SAME_ACCOUNT_TYPE; - } - if (credType == DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED) { - return DM_POINT_TO_POINT_TYPE; - } - if (credType == DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS) { - return DM_SHARE_TYPE; - } - return DM_UNKNOWN_TYPE; -} - -uint32_t DmAuthState::GetCredType(std::shared_ptr context, const JsonItemObject &credInfo) -{ - int32_t credType = credInfo[FILED_CRED_TYPE].Get(); - int32_t authorizedScope = credInfo[FILED_AUTHORIZED_SCOPE].Get(); - int32_t subject = credInfo[FILED_SUBJECT].Get(); - std::vector appList; - credInfo[FILED_AUTHORIZED_APP_LIST].Get(appList); - if (credType == ACCOUNT_RELATED && authorizedScope == SCOPE_USER) { - return DM_IDENTICAL_ACCOUNT; - } - if (credType == ACCOUNT_ACROSS && authorizedScope == SCOPE_USER && - context->direction == DM_AUTH_SOURCE && subject == SUBJECT_PRIMARY) { - return DM_SHARE; - } - if (credType == ACCOUNT_ACROSS && authorizedScope == SCOPE_USER && - context->direction == DM_AUTH_SINK && subject == SUBJECT_SECONDARY) { - return DM_SHARE; - } - if (credType == ACCOUNT_UNRELATED && authorizedScope == SCOPE_APP && HaveSameTokenId(context, appList)) { - return DM_POINT_TO_POINT; - } - if (credType == ACCOUNT_UNRELATED && authorizedScope == SCOPE_USER && appList.empty()) { - return DM_LNN; - } - return DM_INVALIED_TYPE; -} - -uint32_t DmAuthState::GetCredentialType(std::shared_ptr context, const JsonItemObject &credInfo) -{ - CHECK_NULL_RETURN(context, DM_INVALIED_TYPE); - if (!credInfo.Contains(FILED_CRED_TYPE) || !credInfo[FILED_CRED_TYPE].IsNumberInteger() || - !credInfo.Contains(FILED_AUTHORIZED_SCOPE) || !credInfo[FILED_AUTHORIZED_SCOPE].IsNumberInteger() || - !credInfo.Contains(FILED_SUBJECT) || !credInfo[FILED_SUBJECT].IsNumberInteger()) { - LOGE("credType or authorizedScope invalid."); - return DM_INVALIED_TYPE; - } - return GetCredType(context, credInfo); -} - -bool DmAuthState::HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList) -{ - // Store the token of src and sink. The size must be 2. - if (tokenList.size() != 2) { - LOGE("HaveSameTokenId invalid tokenList size."); - return false; - } - - // tokenIdList = [srcTokenId, sinkTokenId] - std::string srcTokenIdHash = Crypto::GetTokenIdHash(tokenList[0]); - std::string sinkTokenIdHash = Crypto::GetTokenIdHash(tokenList[1]); - - return ((srcTokenIdHash == context->accesser.tokenIdHash) && - (sinkTokenIdHash == context->accessee.tokenIdHash)) || - ((sinkTokenIdHash == context->accesser.tokenIdHash) && - (srcTokenIdHash == context->accessee.tokenIdHash)); -} - -bool DmAuthState::CheckProcessNameInWhiteList(const std::string &processName) -{ - LOGI("DmAuthState::CheckProcessNameInWhiteList start"); - if (processName.empty()) { - LOGE("processName is empty"); - return false; - } - uint16_t index = 0; -#ifdef DEVICE_MANAGER_COMMON_FLAG - for (; index < OPEN_PROCESS_NAME_WHITE_LIST_NUM; ++index) { - std::string whitePkgName(OPEN_PROCESS_NAME_WHITE_LIST[index]); - if (processName == whitePkgName) { - LOGI("processName = %{public}s in whiteList.", processName.c_str()); - return true; - } - } -#else - for (; index < CLOSE_PROCESS_NAME_WHITE_LIST_NUM; ++index) { - std::string whitePkgName(CLOSE_PROCESS_NAME_WHITE_LIST[index]); - if (processName == whitePkgName) { - LOGI("processName = %{public}s in whiteList.", processName.c_str()); - return true; - } - } -#endif - LOGI("CheckProcessNameInWhiteList: %{public}s invalid.", processName.c_str()); - return false; -} - -int32_t DmAuthState::GetOutputState(const std::string &processName, int32_t state) -{ - LOGI("state %{public}d.", state); - bool needMapFlag = false; - for (uint16_t index = 0; index < ONBINDRESULT_MAPPING_NUM; ++index) { - if (std::string(ONBINDRESULT_MAPPING_LIST[index]) == processName) { - LOGI("processName %{public}s new protocol param convert to old protocol param.", processName.c_str()); - needMapFlag = true; - break; - } - } - if (needMapFlag) { - auto it = NEW_AND_OLD_STATE_MAPPING.find(static_cast(state)); - if (it != NEW_AND_OLD_STATE_MAPPING.end()) { - return static_cast(it->second); - } - } - return state; -} - -int32_t DmAuthState::GetOutputReplay(const std::string &processName, int32_t replay) -{ - LOGI("replay %{public}d.", replay); - bool needMapFlag = false; - for (uint16_t index = 0; index < ONBINDRESULT_MAPPING_NUM; ++index) { - if (std::string(ONBINDRESULT_MAPPING_LIST[index]) == processName) { - LOGI("processName %{public}s new protocol param convert to old protocol param.", processName.c_str()); - needMapFlag = true; - break; - } - } - if (needMapFlag) { - auto it = NEW_AND_OLD_REPLAY_MAPPING.find(replay); - if (it != NEW_AND_OLD_REPLAY_MAPPING.end()) { - return static_cast(it->second); - } - } - return replay; -} - -uint64_t DmAuthState::GetSysTimeMs() -{ - struct timeval time; - time.tv_sec = 0; - time.tv_usec = 0; - if (gettimeofday(&time, nullptr) != 0) { - LOGE("GetSysTimeMs failed."); - return 0; - } - return (uint64_t) time.tv_sec * MS_PER_SECOND + (uint64_t)time.tv_usec / US_PER_MSECOND; -} - -void DmAuthState::DeleteAcl(std::shared_ptr context, - const DistributedDeviceProfile::AccessControlProfile &profile) -{ - CHECK_NULL_VOID(context); - LOGI("direction %{public}d.", static_cast(context->direction)); - CHECK_NULL_VOID(context->authMessageProcessor); - CHECK_NULL_VOID(context->hiChainAuthConnector); - int32_t userId = context->direction == DmAuthDirection::DM_AUTH_SOURCE ? - profile.GetAccesser().GetAccesserUserId() : profile.GetAccessee().GetAccesseeUserId(); - int32_t sessionKeyId = context->direction == DmAuthDirection::DM_AUTH_SOURCE ? - profile.GetAccesser().GetAccesserSessionKeyId() : profile.GetAccessee().GetAccesseeSessionKeyId(); - std::string credId = context->direction == DmAuthDirection::DM_AUTH_SOURCE ? - profile.GetAccesser().GetAccesserCredentialIdStr() : profile.GetAccessee().GetAccesseeCredentialIdStr(); - - context->authMessageProcessor->DeleteSessionKeyToDP(userId, sessionKeyId); - context->hiChainAuthConnector->DeleteCredential(userId, credId); - DeviceProfileConnector::GetInstance().DeleteAccessControlById(profile.GetAccessControlId()); -} - -void DmAuthState::SetProcessInfo(std::shared_ptr context) -{ - CHECK_NULL_VOID(context); - DmAccess localAccess = context->direction == DmAuthDirection::DM_AUTH_SOURCE ? - context->accesser : context->accessee; - ProcessInfo processInfo; - processInfo.userId = localAccess.userId; - uint32_t bindLevel = static_cast(localAccess.bindLevel); - if (bindLevel == APP || bindLevel == SERVICE) { - processInfo.pkgName = localAccess.pkgName; - } else if (bindLevel == USER) { - processInfo.pkgName = std::string(DM_PKG_NAME); - } else { - LOGE("bindlevel error %{public}d.", bindLevel); - return; - } - context->softbusConnector->SetProcessInfo(processInfo); -} -} // namespace DistributedHardware -} // namespace OHOS diff --git a/services/implementation/src/device_manager_service_impl.cpp.bak b/services/implementation/src/device_manager_service_impl.cpp.bak deleted file mode 100644 index 326615429..000000000 --- a/services/implementation/src/device_manager_service_impl.cpp.bak +++ /dev/null @@ -1,2438 +0,0 @@ -/* - * Copyright (c) 2022-2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "device_manager_service_impl.h" - -#include -#include -#include -#include - -#include "app_manager.h" -#include "dm_error_type.h" -#include "dm_anonymous.h" -#include "dm_constants.h" -#include "dm_crypto.h" -#include "dm_distributed_hardware_load.h" -#include "dm_log.h" -#include "dm_radar_helper.h" -#include "dm_softbus_cache.h" -#include "multiple_user_connector.h" -#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) -#include "dm_common_event_manager.h" -#include "parameter.h" -#include "dm_random.h" -#include "common_event_support.h" -using namespace OHOS::EventFwk; -#endif - -namespace OHOS { -namespace DistributedHardware { - -namespace { - -// One year 365 * 24 * 60 * 60 -constexpr int32_t MAX_ALWAYS_ALLOW_SECONDS = 31536000; -constexpr int32_t MIN_PIN_CODE = 100000; -constexpr int32_t MAX_PIN_CODE = 999999; -// New protocol field definition. To avoid dependency on the new protocol header file, -// do not directly depend on the new protocol header file. -constexpr int32_t MSG_TYPE_REQ_ACL_NEGOTIATE = 80; -constexpr int32_t MSG_TYPE_RESP_ACL_NEGOTIATE = 90; -constexpr int32_t MSG_TYPE_REQ_AUTH_TERMINATE = 104; -constexpr int32_t AUTH_SRC_FINISH_STATE = 12; -constexpr int32_t MAX_DATA_LEN = 65535; -constexpr int32_t ULTRASONIC_AUTHTYPE = 6; -constexpr const char* DM_TAG_LOGICAL_SESSION_ID = "logicalSessionId"; -constexpr const char* DM_TAG_PEER_DISPLAY_ID = "peerDisplayId"; -constexpr const char* DM_TAG_ACCESSEE_USER_ID = "accesseeUserId"; -constexpr const char* DM_TAG_EXTRA_INFO = "extraInfo"; -constexpr const char* CHANGE_PINTYPE = "1"; -// currently, we just support one bind session in one device at same time -constexpr size_t MAX_NEW_PROC_SESSION_COUNT_TEMP = 1; -const int32_t USLEEP_TIME_US_500000 = 500000; // 500ms - -const std::map BUNDLENAME_MAPPING = { - { "wear_link_service", "watch_system_service" } -}; - -static bool IsMessageOldVersion(const JsonObject &jsonObject, std::shared_ptr session) -{ - std::string dmVersion = ""; - std::string edition = ""; - if (jsonObject[TAG_DMVERSION].IsString()) { - dmVersion = jsonObject[TAG_DMVERSION].Get(); - } - if (jsonObject[TAG_EDITION].IsString()) { - edition = jsonObject[TAG_EDITION].Get(); - } - dmVersion = AuthManagerBase::ConvertSrcVersion(dmVersion, edition); - - // Assign the physical session version and release the semaphore. - session->version_ = dmVersion; - - // If the version number is higher than 5.0.4 (the highest version of the old protocol), - // there is no need to switch to the old protocol. - if (CompareVersion(dmVersion, DM_VERSION_5_0_OLD_MAX) == true) { - return false; - } - - return true; -} - -std::string CreateTerminateMessage(void) -{ - JsonObject jsonObject; - jsonObject[TAG_MSG_TYPE] = MSG_TYPE_REQ_AUTH_TERMINATE; - jsonObject[TAG_REPLY] = ERR_DM_VERSION_INCOMPATIBLE; - jsonObject[TAG_AUTH_FINISH] = false; - - return jsonObject.Dump(); -} - -} - -std::condition_variable DeviceManagerServiceImpl::cleanEventCv_; -std::mutex DeviceManagerServiceImpl::cleanEventMutex_; -std::queue DeviceManagerServiceImpl::cleanEventQueue_; - -Session::Session(int sessionId, std::string deviceId) -{ - sessionId_ = sessionId; - deviceId_ = deviceId; -} - -DeviceManagerServiceImpl::DeviceManagerServiceImpl() -{ - running_ = true; - thread_ = std::thread(&DeviceManagerServiceImpl::CleanWorker, this); - LOGI("DeviceManagerServiceImpl constructor"); -} - -DeviceManagerServiceImpl::~DeviceManagerServiceImpl() -{ - Stop(); - thread_.join(); - LOGI("DeviceManagerServiceImpl destructor"); -} - -static uint64_t StringToUint64(const std::string& str) -{ - // Calculate the length of the substring, taking the minimum of the string length and 8 - size_t subStrLength = std::min(str.length(), static_cast(8U)); - - // Extract substring - std::string substr = str.substr(str.length() - subStrLength); - - // Convert substring to uint64_t - uint64_t result = 0; - for (size_t i = 0; i < subStrLength; ++i) { - result <<= 8; // Shift left 8 bits - result |= static_cast(substr[i]); - } - - return result; -} - - -static uint64_t GetTokenId(bool isSrcSide, int32_t displayId, std::string &bundleName) -{ - uint64_t tokenId = 0; - if (isSrcSide) { - // src end - tokenId = IPCSkeleton::GetCallingTokenID(); - } else { - // sink end - int64_t tmpTokenId; - // get userId - int32_t targetUserId = AuthManagerBase::DmGetUserId(displayId); - if (targetUserId == -1) { - return tokenId; - } - if (AppManager::GetInstance().GetHapTokenIdByName(targetUserId, bundleName, 0, tmpTokenId) == DM_OK) { - tokenId = static_cast(tmpTokenId); - } else if (AppManager::GetInstance().GetNativeTokenIdByName(bundleName, tmpTokenId) == DM_OK) { - tokenId = static_cast(tmpTokenId); - } else { - // get deviceId, take the 8 character value as tokenId - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - std::string deviceId = std::string(localDeviceId); - if (deviceId.length() != 0) { - tokenId = StringToUint64(deviceId); - } - } - } - return tokenId; -} - -uint64_t DeviceManagerServiceImpl::FetchCleanEvent() -{ - std::unique_lock lock(cleanEventMutex_); - cleanEventCv_.wait(lock, [&] { - return !running_.load() || !cleanEventQueue_.empty(); - }); - - if (!running_.load()) return 0; - - uint64_t logicalSessionId = cleanEventQueue_.front(); - cleanEventQueue_.pop(); - return logicalSessionId; -} - -void DeviceManagerServiceImpl::CleanWorker() -{ - while (running_.load()) { - auto logicalSessionId = FetchCleanEvent(); - LOGI("DeviceManagerServiceImpl::CleanWorker clean auth_mgr, its logicalSessionId: %{public}" PRIu64 "", - logicalSessionId); - CleanAuthMgrByLogicalSessionId(logicalSessionId); - } - while (!cleanEventQueue_.empty()) { - uint64_t logicalSessionId = cleanEventQueue_.front(); - cleanEventQueue_.pop(); - CleanAuthMgrByLogicalSessionId(logicalSessionId); - } - LOGI("DeviceManagerServiceImpl::CleanWorker end"); -} - -void DeviceManagerServiceImpl::Stop() -{ - std::lock_guard lock(cleanEventMutex_); - running_.store(false); - cleanEventCv_.notify_all(); -} - -void DeviceManagerServiceImpl::NotifyCleanEvent(uint64_t logicalSessionId) -{ - LOGI("DeviceManagerServiceImpl::NotifyCleanEvent logicalSessionId: %{public}" PRIu64 ".", logicalSessionId); - std::lock_guard lock(cleanEventMutex_); - // Store into the queue - cleanEventQueue_.push(logicalSessionId); - cleanEventCv_.notify_one(); -} - -void DeviceManagerServiceImpl::ImportConfig(std::shared_ptr authMgr, uint64_t tokenId) -{ - // Import configuration - if (configsMap_.find(tokenId) != configsMap_.end()) { - authMgr->ImportAuthCode(configsMap_[tokenId]->pkgName, configsMap_[tokenId]->authCode); - authMgr->RegisterAuthenticationType(configsMap_[tokenId]->authenticationType); - LOGI("DeviceManagerServiceImpl::ImportConfig import authCode Successful."); - } - return; -} - -int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide, uint64_t tokenId, - std::shared_ptr session, uint64_t logicalSessionId) -{ - if (session == nullptr) { - LOGE("InitAndRegisterAuthMgr, The physical link is not created."); - return ERR_DM_AUTH_OPEN_SESSION_FAILED; - } - // If version is empty, allow creation for the first time, create a new protocol auth_mgr to negotiate version; - // subsequent creations wait, and directly use version to create the corresponding auth_mgr after release. - if (session->version_ == "") { - bool expected = false; - if (session->flag_.compare_exchange_strong(expected, true)) { - LOGI("The physical link is being created and the dual-end device version is aligned."); - } else { - // Do not allow simultaneous version negotiation, return error directly - LOGE("Version negotiation is not allowed at the same time."); - return ERR_DM_AUTH_BUSINESS_BUSY; - } - } - - std::lock_guard lock(authMgrMtx_); - if (authMgrMap_.find(tokenId) == authMgrMap_.end()) { - if (session->version_ == "" || CompareVersion(session->version_, DM_VERSION_5_0_OLD_MAX)) { - if (authMgrMap_.size() > MAX_NEW_PROC_SESSION_COUNT_TEMP) { - LOGE("Other bind session exist, can not start new one."); - return ERR_DM_AUTH_BUSINESS_BUSY; - } - // Create a new auth_mgr, create authMgrMap_[tokenId] - if (isSrcSide) { - // src end - authMgrMap_[tokenId] = std::make_shared(softbusConnector_, hiChainConnector_, - listener_, hiChainAuthConnector_); - } else { - // sink end - authMgrMap_[tokenId] = std::make_shared(softbusConnector_, hiChainConnector_, - listener_, hiChainAuthConnector_); - } - // Register resource destruction notification function - authMgrMap_[tokenId]->RegisterCleanNotifyCallback(&DeviceManagerServiceImpl::NotifyCleanEvent); - hiChainAuthConnector_->RegisterHiChainAuthCallbackById(logicalSessionId, authMgrMap_[tokenId]); - LOGI("DeviceManagerServiceImpl::Initialize authMgrMap_ token: %{public}" PRId64 ".", tokenId); - ImportConfig(authMgrMap_[tokenId], tokenId); - return DM_OK; - } else { - LOGI("DeviceManagerServiceImpl::InitAndRegisterAuthMgr old authMgr."); - if (authMgr_ == nullptr) { - CreateGlobalClassicalAuthMgr(); - } - authMgr_->PrepareSoftbusSessionCallback(); - authMgrMap_[tokenId] = authMgr_; - ImportConfig(authMgr_, tokenId); - // The value of logicalSessionId in the old protocol is always 0. - logicalSessionId2TokenIdMap_[0] = tokenId; - return DM_OK; - } - } - // authMgr_ has been created, indicating that a binding event already exists. - // Other requests are rejected, and an error code is returned. - LOGE("BindTarget failed, this device is being bound. Please try again later."); - return ERR_DM_AUTH_BUSINESS_BUSY; -} - -void DeviceManagerServiceImpl::CleanSessionMap(int sessionId, std::shared_ptr session) -{ - session->logicalSessionCnt_.fetch_sub(1); - if (session->logicalSessionCnt_.load(std::memory_order_relaxed) == 0) { - usleep(USLEEP_TIME_US_500000); - softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId); - std::lock_guard lock(mapMutex_); - if (sessionsMap_.find(sessionId) != sessionsMap_.end()) { - sessionsMap_[sessionId] = nullptr; - sessionsMap_.erase(sessionId); - } - if (deviceId2SessionIdMap_.find(session->deviceId_) != deviceId2SessionIdMap_.end()) { - deviceId2SessionIdMap_.erase(session->deviceId_); - } - } - return; -} - -void DeviceManagerServiceImpl::CleanSessionMapByLogicalSessionId(uint64_t logicalSessionId) -{ - if (logicalSessionId2SessionIdMap_.find(logicalSessionId) != logicalSessionId2SessionIdMap_.end()) { - auto sessionId = logicalSessionId2SessionIdMap_[logicalSessionId]; - auto session = GetCurSession(sessionId); - if (session != nullptr) { - CleanSessionMap(sessionId, session); - } - logicalSessionId2SessionIdMap_.erase(logicalSessionId); - } - logicalSessionId2TokenIdMap_.erase(logicalSessionId); - return; -} - -void DeviceManagerServiceImpl::CleanAuthMgrByLogicalSessionId(uint64_t logicalSessionId) -{ - uint64_t tokenId = 0; - if (logicalSessionId2TokenIdMap_.find(logicalSessionId) != logicalSessionId2TokenIdMap_.end()) { - tokenId = logicalSessionId2TokenIdMap_[logicalSessionId]; - } else { - LOGE("logicalSessionId(%{public}" PRIu64 ") can not find the tokenId.", logicalSessionId); - return; - } - - if (configsMap_.find(tokenId) != configsMap_.end()) { - configsMap_[tokenId] = nullptr; - configsMap_.erase(tokenId); - } - - CleanSessionMapByLogicalSessionId(logicalSessionId); - if (logicalSessionId == 0 && authMgr_ != nullptr) { - authMgr_->SetTransferReady(true); - authMgr_->ClearSoftbusSessionCallback(); - } - hiChainAuthConnector_->UnRegisterHiChainAuthCallbackById(logicalSessionId); - if (authMgrMap_.find(tokenId) != authMgrMap_.end()) { - authMgrMap_[tokenId] = nullptr; - authMgrMap_.erase(tokenId); - } - return; -} - -std::shared_ptr DeviceManagerServiceImpl::GetAuthMgr() -{ - uint64_t tokenId = IPCSkeleton::GetCallingTokenID(); - if (authMgrMap_.find(tokenId) != authMgrMap_.end()) { - LOGI("DeviceManagerServiceImpl::GetAuthMgr authMgrMap_ token: %{public}" PRId64 ".", tokenId); - return authMgrMap_[tokenId]; - } - LOGE("DeviceManagerServiceImpl::GetAuthMgr authMgrMap_ not found, token: %{public}" PRId64 ".", tokenId); - return nullptr; -} - -// Needed in the callback function -std::shared_ptr DeviceManagerServiceImpl::GetAuthMgrByTokenId(uint64_t tokenId) -{ - if (authMgrMap_.find(tokenId) != authMgrMap_.end()) { - LOGI("DeviceManagerServiceImpl::GetAuthMgrByTokenId authMgrMap_ token: %{public}" PRId64 ".", tokenId); - return authMgrMap_[tokenId]; - } - LOGE("DeviceManagerServiceImpl::GetAuthMgrByTokenId authMgrMap_ not found, token: %{public}" PRId64 ".", tokenId); - return nullptr; -} - -std::shared_ptr DeviceManagerServiceImpl::GetCurrentAuthMgr() -{ - uint64_t tokenId = 0; - if (logicalSessionId2TokenIdMap_.find(0) != logicalSessionId2TokenIdMap_.end()) { - tokenId = logicalSessionId2TokenIdMap_[0]; - } - for (auto &pair : authMgrMap_) { - if (pair.first != tokenId) { - return pair.second; - } - } - return authMgr_; -} - -static uint64_t GenerateRandNum(int sessionId) -{ - // Get the current timestamp - auto timestamp = std::chrono::duration_cast(std::chrono::high_resolution_clock::now(). - time_since_epoch()).count(); - - // Generate random numbers - std::random_device rd; - std::mt19937 gen(rd()); - std::uniform_int_distribution<> rand_dis(1, 0xFFFFFFFF); - uint32_t randomNumber = rand_dis(gen); - - // Combination of random numbers - uint64_t randNum = (static_cast(timestamp) << 32) | - (static_cast(sessionId) << 16) | - static_cast(randomNumber); - - return randNum; -} - -int32_t DeviceManagerServiceImpl::Initialize(const std::shared_ptr &listener) -{ - LOGI("DeviceManagerServiceImpl Initialize"); - if (softbusConnector_ == nullptr) { - softbusConnector_ = std::make_shared(); - } - if (hiChainConnector_ == nullptr) { - hiChainConnector_ = std::make_shared(); - } - if (mineHiChainConnector_ == nullptr) { - mineHiChainConnector_ = std::make_shared(); - } - if (hiChainAuthConnector_ == nullptr) { - hiChainAuthConnector_ = std::make_shared(); - } - if (deviceStateMgr_ == nullptr) { - deviceStateMgr_ = std::make_shared(softbusConnector_, listener, - hiChainConnector_, hiChainAuthConnector_); - deviceStateMgr_->RegisterSoftbusStateCallback(); - } - if (credentialMgr_ == nullptr) { - credentialMgr_ = std::make_shared(hiChainConnector_, listener); - } - if (dpInitedCallback_ == nullptr) { - dpInitedCallback_ = sptr(new DpInitedCallback()); - DeviceProfileConnector::GetInstance().SubscribeDeviceProfileInited(dpInitedCallback_); - } - listener_ = listener; - CreateGlobalClassicalAuthMgr(); - if (authMgr_ != nullptr) { - authMgr_->ClearSoftbusSessionCallback(); - } - LOGI("Init success, singleton initialized"); - return DM_OK; -} - -void DeviceManagerServiceImpl::Release() -{ - LOGI("DeviceManagerServiceImpl Release"); -#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - commonEventManager_ = nullptr; -#endif - softbusConnector_->UnRegisterConnectorCallback(); - softbusConnector_->UnRegisterSoftbusStateCallback(); - softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback(); - hiChainConnector_->UnRegisterHiChainCallback(); - hiChainAuthConnector_->UnRegisterHiChainAuthCallback(); - authMgr_ = nullptr; - for (auto& pair : authMgrMap_) { - pair.second = nullptr; - } - authMgrMap_.clear(); - for (auto& pair : sessionsMap_) { - pair.second = nullptr; - } - sessionsMap_.clear(); - for (auto& pair : configsMap_) { - pair.second = nullptr; - } - configsMap_.clear(); - deviceId2SessionIdMap_.clear(); - deviceIdMutexMap_.clear(); - sessionEnableMutexMap_.clear(); - sessionEnableCvMap_.clear(); - logicalSessionId2TokenIdMap_.clear(); - logicalSessionId2SessionIdMap_.clear(); - deviceStateMgr_ = nullptr; - softbusConnector_ = nullptr; - abilityMgr_ = nullptr; - hiChainConnector_ = nullptr; - DeviceProfileConnector::GetInstance().UnSubscribeDeviceProfileInited(); - dpInitedCallback_ = nullptr; -} - -int32_t DeviceManagerServiceImpl::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, - int32_t bindLevel) -{ - if (pkgName.empty() || udid.empty()) { - LOGE("DeviceManagerServiceImpl::UnAuthenticateDevice failed, pkgName is %{public}s, udid is %{public}s", - pkgName.c_str(), GetAnonyString(udid).c_str()); - return ERR_DM_INPUT_PARA_INVALID; - } - auto authMgr = GetAuthMgr(); - if (authMgr == nullptr) { - LOGE("authMgr is nullptr, invoke the old protocal."); - if (authMgr_ == nullptr) { - LOGE("classical authMgr_ is nullptr"); - return ERR_DM_POINT_NULL; - } - return authMgr_->UnAuthenticateDevice(pkgName, udid, bindLevel); - } - return authMgr->UnAuthenticateDevice(pkgName, udid, bindLevel); -} - -int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgName) -{ - if (pkgName.empty()) { - LOGE("DeviceManagerServiceImpl::StopAuthenticateDevice failed"); - return ERR_DM_INPUT_PARA_INVALID; - } - auto authMgr = GetAuthMgr(); - if (authMgr == nullptr) { - LOGE("authMgr is nullptr"); - return ERR_DM_POINT_NULL; - } - return authMgr->StopAuthenticateDevice(pkgName); -} - -int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string &udid, - int32_t bindLevel) -{ - if (pkgName.empty() || udid.empty()) { - LOGE("DeviceManagerServiceImpl::UnBindDevice failed, pkgName is %{public}s, udid is %{public}s", - pkgName.c_str(), GetAnonyString(udid).c_str()); - return ERR_DM_INPUT_PARA_INVALID; - } - std::string extra = ""; - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - return DeleteAclV2(pkgName, std::string(localDeviceId), udid, bindLevel, extra); -} - -int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string &udid, - int32_t bindLevel, const std::string &extra) -{ - if (pkgName.empty() || udid.empty()) { - LOGE("DeviceManagerServiceImpl::UnBindDevice failed, pkgName is %{public}s, udid is %{public}s", - pkgName.c_str(), GetAnonyString(udid).c_str()); - return ERR_DM_INPUT_PARA_INVALID; - } - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - return DeleteAclV2(pkgName, std::string(localDeviceId), udid, bindLevel, extra); -} - -int32_t DeviceManagerServiceImpl::SetUserOperation(std::string &pkgName, int32_t action, - const std::string ¶ms) -{ - if (pkgName.empty() || params.empty()) { - LOGE("DeviceManagerServiceImpl::SetUserOperation error: Invalid parameter, pkgName: %{public}s, extra:" - "%{public}s", pkgName.c_str(), params.c_str()); - return ERR_DM_INPUT_PARA_INVALID; - } - auto authMgr = GetCurrentAuthMgr(); - if (authMgr != nullptr) { - authMgr->OnUserOperation(action, params); - } - return DM_OK; -} - -void DeviceManagerServiceImpl::CreateGlobalClassicalAuthMgr() -{ - LOGI("global classical authMgr_ not exit, create one"); - // Create old auth_mar, only create an independent one - authMgr_ = std::make_shared(softbusConnector_, hiChainConnector_, listener_, - hiChainAuthConnector_); - authMgr_->RegisterCleanNotifyCallback(&DeviceManagerServiceImpl::NotifyCleanEvent); - softbusConnector_->RegisterConnectorCallback(authMgr_); - softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); - hiChainConnector_->RegisterHiChainCallback(authMgr_); - hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_); -} - -void DeviceManagerServiceImpl::HandleOffline(DmDeviceState devState, DmDeviceInfo &devInfo) -{ - LOGI("DeviceManagerServiceImpl::HandleOffline"); - std::string trustDeviceId = deviceStateMgr_->GetUdidByNetWorkId(std::string(devInfo.networkId)); - LOGI("deviceStateMgr Udid: %{public}s", GetAnonyString(trustDeviceId).c_str()); - if (trustDeviceId == "") { - LOGE("HandleOffline not get udid in deviceStateMgr."); - return; - } - std::string udisHash = softbusConnector_->GetDeviceUdidHashByUdid(trustDeviceId); - if (memcpy_s(devInfo.deviceId, DM_MAX_DEVICE_ID_LEN, udisHash.c_str(), udisHash.length()) != 0) { - LOGE("get deviceId: %{public}s failed", GetAnonyString(udisHash).c_str()); - return; - } - char localUdid[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localUdid, DEVICE_UUID_LENGTH); - std::string requestDeviceId = std::string(localUdid); - std::map userIdAndBindLevel = - DeviceProfileConnector::GetInstance().GetUserIdAndBindLevel(requestDeviceId, trustDeviceId); - ProcessInfo processInfo; - processInfo.pkgName = std::string(DM_PKG_NAME); - processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); - if (userIdAndBindLevel.empty() || userIdAndBindLevel.find(processInfo.userId) == userIdAndBindLevel.end()) { - userIdAndBindLevel[processInfo.userId] = INVALIED_TYPE; - } - for (const auto &item : userIdAndBindLevel) { - if (static_cast(item.second) == INVALIED_TYPE) { - LOGI("The offline device is identical account bind type."); - devInfo.authForm = DmAuthForm::IDENTICAL_ACCOUNT; - processInfo.userId = item.first; - softbusConnector_->SetProcessInfo(processInfo); - } else if (static_cast(item.second) == USER) { - LOGI("The offline device is device bind type."); - devInfo.authForm = DmAuthForm::PEER_TO_PEER; - processInfo.userId = item.first; - softbusConnector_->SetProcessInfo(processInfo); - } else if (static_cast(item.second) == SERVICE || static_cast(item.second) == APP) { - LOGI("The offline device is PEER_TO_PEER_TYPE bind type, %{public}" PRIu32, item.second); - std::vector processInfoVec = - DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, - item.first); - softbusConnector_->SetProcessInfoVec(processInfoVec); - } - deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); - } -} - -void DeviceManagerServiceImpl::HandleOnline(DmDeviceState devState, DmDeviceInfo &devInfo) -{ - LOGI("DeviceManagerServiceImpl::HandleOnline networkId: %{public}s.", - GetAnonyString(devInfo.networkId).c_str()); - std::string trustDeviceId = ""; - if (softbusConnector_->GetUdidByNetworkId(devInfo.networkId, trustDeviceId) != DM_OK) { - LOGE("HandleOnline get udid failed."); - return; - } - std::string udisHash = softbusConnector_->GetDeviceUdidHashByUdid(trustDeviceId); - if (memcpy_s(devInfo.deviceId, DM_MAX_DEVICE_ID_LEN, udisHash.c_str(), udisHash.length()) != 0) { - LOGE("get deviceId: %{public}s failed", GetAnonyString(udisHash).c_str()); - return; - } - char localUdid[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localUdid, DEVICE_UUID_LENGTH); - std::string requestDeviceId = std::string(localUdid); - uint32_t bindType = DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); - LOGI("The online device bind type is %{public}" PRIu32, bindType); - ProcessInfo processInfo; - processInfo.pkgName = std::string(DM_PKG_NAME); - processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); - 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 || bindType == SERVICE_PEER_TO_PEER_TYPE) { - std::vector processInfoVec = - DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, - MultipleUserConnector::GetFirstForegroundUserId()); - softbusConnector_->SetProcessInfoVec(processInfoVec); - devInfo.authForm = DmAuthForm::PEER_TO_PEER; - } else if (bindType == APP_ACROSS_ACCOUNT_TYPE || bindType == SERVICE_ACROSS_ACCOUNT_TYPE) { - std::vector processInfoVec = - DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, - MultipleUserConnector::GetFirstForegroundUserId()); - softbusConnector_->SetProcessInfoVec(processInfoVec); - devInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; - } - LOGI("DeviceManagerServiceImpl::HandleOnline success devInfo auform %{public}d.", devInfo.authForm); - deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); -} - -void DeviceManagerServiceImpl::HandleDeviceStatusChange(DmDeviceState devState, DmDeviceInfo &devInfo) -{ - LOGI("DeviceManagerServiceImpl::HandleDeviceStatusChange start, devState = %{public}d, networkId: %{public}s.", - devState, GetAnonyString(devInfo.networkId).c_str()); - if (deviceStateMgr_ == nullptr) { - LOGE("deviceStateMgr_ is nullpter!"); - return; - } - if (devState == DEVICE_STATE_ONLINE) { - HandleOnline(devState, devInfo); - } else if (devState == DEVICE_STATE_OFFLINE) { - HandleOffline(devState, devInfo); - } else { - std::string udiddHash = GetUdidHashByNetworkId(devInfo.networkId); - if (memcpy_s(devInfo.deviceId, DM_MAX_DEVICE_ID_LEN, udiddHash.c_str(), udiddHash.length()) != 0) { - LOGE("get deviceId: %{public}s failed", GetAnonyString(udiddHash).c_str()); - return; - } - ProcessInfo processInfo; - processInfo.pkgName = std::string(DM_PKG_NAME); - processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); - softbusConnector_->SetProcessInfo(processInfo); - deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); - } -} - -std::string DeviceManagerServiceImpl::GetUdidHashByNetworkId(const std::string &networkId) -{ - if (softbusConnector_ == nullptr) { - LOGE("softbusConnector_ is nullpter!"); - return ""; - } - std::string udid = ""; - int32_t ret = softbusConnector_->GetUdidByNetworkId(networkId.c_str(), udid); - if (ret != DM_OK) { - LOGE("GetUdidByNetworkId failed ret: %{public}d", ret); - return ""; - } - return softbusConnector_->GetDeviceUdidHashByUdid(udid); -} - -int DeviceManagerServiceImpl::OnSessionOpened(int sessionId, int result) -{ - { - std::lock_guard lock(sessionEnableMutexMap_[sessionId]); - if (result == 0) { - LOGE("OnSessionOpened successful, sessionId: %{public}d", sessionId); - } else { - LOGE("OnSessionOpened failed, sessionId: %{public}d, res: %{public}d", sessionId, result); - } - sessionEnableCvReadyMap_[sessionId] = true; - sessionEnableCvMap_[sessionId].notify_all(); - } - std::string peerUdid = ""; - softbusConnector_->GetSoftbusSession()->GetPeerDeviceId(sessionId, peerUdid); - struct RadarInfo info = { - .funcName = "OnSessionOpened", - .stageRes = static_cast(StageRes::STAGE_SUCC), - .isTrust = static_cast(TrustStatus::NOT_TRUST), - .peerUdid = peerUdid, - .channelId = sessionId, - }; - if (!DmRadarHelper::GetInstance().ReportAuthSessionOpenCb(info)) { - LOGE("ReportAuthSessionOpenCb failed"); - } - - // Get the remote deviceId, sink end gives sessionsMap[deviceId] = session; - { - std::lock_guard lock(mapMutex_); - if (sessionsMap_.find(sessionId) == sessionsMap_.end()) { - sessionsMap_[sessionId] = std::make_shared(sessionId, peerUdid); - } - } - - return SoftbusSession::OnSessionOpened(sessionId, result); -} - -void DeviceManagerServiceImpl::OnSessionClosed(int sessionId) -{ - SoftbusSession::OnSessionClosed(sessionId); -} - -static JsonObject GetJsonObjectFromData(const void *data, unsigned int dataLen) -{ - std::string message = std::string(reinterpret_cast(data), dataLen); - return JsonObject(message); -} - -// When downgrading the version, determine whether it is src or sink based on the message. -// src: Received 90 message. -// sink: Received 80 message. -static bool IsAuthManagerSourceByMessage(int32_t msgType) -{ - return msgType == MSG_TYPE_RESP_ACL_NEGOTIATE; -} - -// Get the current session object -std::shared_ptr DeviceManagerServiceImpl::GetCurSession(int sessionId) -{ - std::shared_ptr curSession = nullptr; - // Get the remote deviceId, sink end gives sessionsMap[deviceId] = session; - { - std::lock_guard lock(mapMutex_); - if (sessionsMap_.find(sessionId) != sessionsMap_.end()) { - curSession = sessionsMap_[sessionId]; - } else { - LOGE("OnBytesReceived, The local session cannot be found."); - } - } - return curSession; -} - -std::shared_ptr DeviceManagerServiceImpl::GetAuthMgrByMessage(int32_t msgType, - uint64_t logicalSessionId, const JsonObject &jsonObject, std::shared_ptr curSession) -{ - uint64_t tokenId = 0; - if (msgType == MSG_TYPE_REQ_ACL_NEGOTIATE) { - std::string bundleName; - int32_t displayId = 0; - if (jsonObject[TAG_PEER_BUNDLE_NAME_V2].IsString()) { - bundleName = jsonObject[TAG_PEER_BUNDLE_NAME_V2].Get(); - } - if (jsonObject[DM_TAG_PEER_DISPLAY_ID].IsNumberInteger()) { - displayId = jsonObject[DM_TAG_PEER_DISPLAY_ID].Get(); - } - tokenId = GetTokenId(false, displayId, bundleName); - if (tokenId == 0) { - LOGE("GetAuthMgrByMessage, Get tokenId failed."); - return nullptr; - } - if (InitAndRegisterAuthMgr(false, tokenId, curSession, logicalSessionId) != DM_OK) { - return nullptr; - } - curSession->logicalSessionSet_.insert(logicalSessionId); - if (logicalSessionId2TokenIdMap_.find(logicalSessionId) != logicalSessionId2TokenIdMap_.end()) { - LOGE("GetAuthMgrByMessage, logicalSessionId exists in logicalSessionId2TokenIdMap_."); - return nullptr; - } - logicalSessionId2TokenIdMap_[logicalSessionId] = tokenId; - } else { - if (curSession->logicalSessionSet_.find(logicalSessionId) == curSession->logicalSessionSet_.end()) { - LOGE("GetAuthMgrByMessage, The logical session ID does not exist in the physical session."); - return nullptr; - } - tokenId = logicalSessionId2TokenIdMap_[logicalSessionId]; - } - - return GetAuthMgrByTokenId(tokenId); -} - -int32_t DeviceManagerServiceImpl::TransferSrcOldAuthMgr(std::shared_ptr curSession) -{ - // New Old Receive 90, destroy new authMgr, create old authMgr, source side - // The old protocol has only one session, reverse lookup logicalSessionId and tokenId - int sessionId = curSession->sessionId_; - uint64_t logicalSessionId = 0; - uint64_t tokenId = 0; - for (auto& pair : logicalSessionId2SessionIdMap_) { - if (pair.second == sessionId) { - logicalSessionId = pair.first; - tokenId = logicalSessionId2TokenIdMap_[logicalSessionId]; - } - } - if (logicalSessionId == 0 || tokenId == 0) { - LOGE("DeviceManagerServiceImpl::TransferSrcOldAuthMgr can not find logicalSessionId and tokenId."); - return ERR_DM_AUTH_FAILED; - } - std::string pkgName; - PeerTargetId peerTargetId; - std::map bindParam; - auto authMgr = GetAuthMgrByTokenId(tokenId); - authMgr->GetBindTargetParams(pkgName, peerTargetId, bindParam); - DmBindCallerInfo callerInfo; - authMgr->GetCallerInfo(callerInfo); - int32_t authType = -1; - authMgr->ParseAuthType(bindParam, authType); - authMgrMap_.erase(tokenId); - if (InitAndRegisterAuthMgr(true, tokenId, curSession, logicalSessionId) != DM_OK) { - return ERR_DM_AUTH_FAILED; - } - - int ret = TransferByAuthType(authType, curSession, authMgr, bindParam, logicalSessionId); - if (ret != DM_OK) { - LOGE("DeviceManagerServiceImpl::TransferByAuthType TransferByAuthType failed."); - return ret; - } - authMgr = nullptr; - authMgr_->SetCallerInfo(callerInfo); - if (authMgr_->BindTarget(pkgName, peerTargetId, bindParam, sessionId, 0) != DM_OK) { - LOGE("DeviceManagerServiceImpl::TransferSrcOldAuthMgr authManager BindTarget failed"); - return ERR_DM_AUTH_FAILED; - } - - if (authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { - int32_t sessionSide = GetSessionSide(curSession->sessionId_); - authMgr_->OnSessionOpened(curSession->sessionId_, sessionSide, 0); - } - - LOGI("DeviceManagerServiceImpl::TransferSrcOldAuthMgr src transfer to old version success"); - authMgr_->SetTransferReady(false); - return DM_OK; -} - -int32_t DeviceManagerServiceImpl::TransferByAuthType(int32_t authType, - std::shared_ptr curSession, std::shared_ptr authMgr, - std::map &bindParam, uint64_t logicalSessionId) -{ - int sessionId = curSession->sessionId_; - if (authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { - authMgr_->EnableInsensibleSwitching(); - curSession->logicalSessionSet_.insert(0); - curSession->logicalSessionCnt_.fetch_add(1); - logicalSessionId2SessionIdMap_[0] = sessionId; - authMgr->OnSessionDisable(); - } else { - authMgr_->DisableInsensibleSwitching(); - // send stop message - // Cannot stop using the new protocol. The new protocol is a signal mechanism and cannot be stopped serially. - // There will be a delay, causing new objects to be created before the stop is complete. - // Then the timeout mechanism of the new protocol will stop SoftBus again. - std::string endMessage = CreateTerminateMessage(); - (void)softbusConnector_->GetSoftbusSession()->SendData(sessionId, endMessage); - // Close new protocol session - CleanAuthMgrByLogicalSessionId(logicalSessionId); - } - if (authType == ULTRASONIC_AUTHTYPE) { - int32_t ret = ChangeUltrasonicTypeToPin(bindParam); - if (ret != DM_OK) { - LOGE("DeviceManagerServiceImpl::TransferSrcOldAuthMgr ChangeUltrasonicTypeToPin failed."); - return ret; - } - } - return DM_OK; -} - -int32_t DeviceManagerServiceImpl::ChangeUltrasonicTypeToPin(std::map &bindParam) -{ - auto iter = bindParam.find(PARAM_KEY_AUTH_TYPE); - if (iter == bindParam.end()) { - LOGE("DeviceManagerServiceImpl::ChangeUltrasonicTypeToPin bindParam:%{public}s not exist.", - PARAM_KEY_AUTH_TYPE); - return ERR_DM_AUTH_FAILED; - } - iter->second = CHANGE_PINTYPE; - LOGI("DeviceManagerServiceImpl::ChangeUltrasonicTypeToPin bindParam:%{public}s PINTYPE.", PARAM_KEY_AUTH_TYPE); - return DM_OK; -} - -int32_t DeviceManagerServiceImpl::TransferSinkOldAuthMgr(const JsonObject &jsonObject, - std::shared_ptr curSession) -{ - // Old New Received 80, New Old authMgr, Sink End - std::string bundleName; - if (jsonObject[TAG_BUNDLE_NAME].IsString()) { - bundleName = jsonObject[TAG_BUNDLE_NAME].Get(); - } else if (jsonObject[TAG_PEER_BUNDLE_NAME].IsString()) { - bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get(); - } else if (jsonObject[TAG_HOST_PKGLABEL].IsString()) { - bundleName = jsonObject[TAG_HOST_PKGLABEL].Get(); - } else { - LOGE("DeviceManagerServiceImpl::TransferSinkOldAuthMgr can not find bundleName."); - return ERR_DM_AUTH_FAILED; - } - if (softbusConnector_ == nullptr) { - LOGE("softbusConnector_ is nullpter!"); - return ERR_DM_AUTH_FAILED; - } - int32_t deviceType = softbusConnector_->GetLocalDeviceTypeId(); - if (deviceType == DmDeviceType::DEVICE_TYPE_WATCH && - BUNDLENAME_MAPPING.find(bundleName) != BUNDLENAME_MAPPING.end()) { - bundleName = BUNDLENAME_MAPPING.find(bundleName)->second; - } - uint64_t tokenId = GetTokenId(false, -1, bundleName); - if (InitAndRegisterAuthMgr(false, tokenId, curSession, 0) != DM_OK) { - // Internal error log printing completed - return ERR_DM_AUTH_FAILED; - } - - // Parameter 2 sessionSide is 0, authMgr_ is empty, it must be the sink end. - // The src end will create the protocol object when BindTarget. - authMgr_->OnSessionOpened(curSession->sessionId_, 0, 0); - LOGI("DeviceManagerServiceImpl::TransferSinkOldAuthMgr sink transfer to old version success"); - authMgr_->SetTransferReady(false); - return DM_OK; -} - -int32_t DeviceManagerServiceImpl::TransferOldAuthMgr(int32_t msgType, const JsonObject &jsonObject, - std::shared_ptr curSession) -{ - int ret = DM_OK; - if ((authMgr_ == nullptr || authMgr_->IsTransferReady()) && - (msgType == MSG_TYPE_REQ_ACL_NEGOTIATE || msgType == MSG_TYPE_RESP_ACL_NEGOTIATE)) { - if (IsMessageOldVersion(jsonObject, curSession)) { - if (IsAuthManagerSourceByMessage(msgType)) { - ret = TransferSrcOldAuthMgr(curSession); - } else { - ret = TransferSinkOldAuthMgr(jsonObject, curSession); - } - } - } - - return ret; -} - - -void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, unsigned int dataLen) -{ - if (sessionId < 0 || data == nullptr || dataLen <= 0 || dataLen > MAX_DATA_LEN) { - LOGE("[OnBytesReceived] Fail to receive data from softbus with sessionId: %{public}d, dataLen: %{public}d.", - sessionId, dataLen); - return; - } - - LOGI("start, sessionId: %{public}d, dataLen: %{public}d.", sessionId, dataLen); - - JsonObject jsonObject = GetJsonObjectFromData(data, dataLen); - if (jsonObject.IsDiscarded() || !IsInt32(jsonObject, TAG_MSG_TYPE)) { - LOGE("OnBytesReceived, MSG_TYPE parse failed."); - return; - } - int32_t msgType = jsonObject[TAG_MSG_TYPE].Get(); - uint64_t logicalSessionId = 0; - if (IsUint64(jsonObject, DM_TAG_LOGICAL_SESSION_ID)) { - logicalSessionId = jsonObject[DM_TAG_LOGICAL_SESSION_ID].Get(); - } - - std::shared_ptr curSession = GetCurSession(sessionId); - if (curSession == nullptr) { - LOGE("InitAndRegisterAuthMgr, The physical link is not created."); - return; - } - - std::shared_ptr authMgr = nullptr; - if (logicalSessionId != 0) { - authMgr = GetAuthMgrByMessage(msgType, logicalSessionId, jsonObject, curSession); - if (authMgr == nullptr) { - return; - } - if (msgType == MSG_TYPE_REQ_ACL_NEGOTIATE || msgType == MSG_TYPE_RESP_ACL_NEGOTIATE) { - curSession->version_ = DM_CURRENT_VERSION; - } - } else { - /** -        Monitor old messages on ports 80/90 -        1. New-to-old: When the src side receives a 90 message and detects a version mismatch, it receives - the 90 message, destroys the current new authMgr, creates a new old protocol authMgr, and re-BindTarget. -        2. Old-to-new: When the sink side receives an 80 message and detects a version mismatch, it receives the 80 - message, directly creates a new old protocol authMgr, and re-OnSessionOpened and OnBytesReceived. -        */ - if (curSession->version_ == "") { - if (TransferOldAuthMgr(msgType, jsonObject, curSession) != DM_OK) { - LOGE("DeviceManagerServiceImpl::OnBytesReceived TransferOldAuthMgr failed"); - return; - } - } else { - LOGI("DeviceManagerServiceImpl::OnBytesReceived Reuse Old AuthMgr, sessionId: %{public}d.", sessionId); - } - authMgr = authMgr_; - } - - std::string message = std::string(reinterpret_cast(data), dataLen); - if (msgType == AUTH_DEVICE_REQ_NEGOTIATE || msgType == AUTH_DEVICE_RESP_NEGOTIATE) { - authMgr->OnAuthDeviceDataReceived(sessionId, message); - } else { - authMgr->OnDataReceived(sessionId, message); - } - return; -} - -int32_t DeviceManagerServiceImpl::RequestCredential(const std::string &reqJsonStr, std::string &returnJsonStr) -{ - if (reqJsonStr.empty()) { - LOGE("reqJsonStr is empty"); - return ERR_DM_INPUT_PARA_INVALID; - } - if (credentialMgr_== nullptr) { - LOGE("credentialMgr_ is nullptr"); - return ERR_DM_POINT_NULL; - } - return credentialMgr_->RequestCredential(reqJsonStr, returnJsonStr); -} - -int32_t DeviceManagerServiceImpl::ImportCredential(const std::string &pkgName, const std::string &credentialInfo) -{ - if (pkgName.empty() || credentialInfo.empty()) { - LOGE("DeviceManagerServiceImpl::ImportCredential failed, pkgName is %{public}s, credentialInfo is %{public}s", - pkgName.c_str(), GetAnonyString(credentialInfo).c_str()); - return ERR_DM_INPUT_PARA_INVALID; - } - if (credentialMgr_== nullptr) { - LOGE("credentialMgr_ is nullptr"); - return ERR_DM_POINT_NULL; - } - isCredentialType_.store(true); - return credentialMgr_->ImportCredential(pkgName, credentialInfo); -} - -int32_t DeviceManagerServiceImpl::DeleteCredential(const std::string &pkgName, const std::string &deleteInfo) -{ - if (pkgName.empty() || deleteInfo.empty()) { - LOGE("DeviceManagerServiceImpl::DeleteCredential failed, pkgName is %{public}s, deleteInfo is %{public}s", - pkgName.c_str(), GetAnonyString(deleteInfo).c_str()); - return ERR_DM_INPUT_PARA_INVALID; - } - if (credentialMgr_== nullptr) { - LOGE("credentialMgr_ is nullptr"); - return ERR_DM_POINT_NULL; - } - isCredentialType_.store(false); - return credentialMgr_->DeleteCredential(pkgName, deleteInfo); -} - -int32_t DeviceManagerServiceImpl::MineRequestCredential(const std::string &pkgName, std::string &returnJsonStr) -{ - (void)pkgName; - if (mineHiChainConnector_->RequestCredential(returnJsonStr) != DM_OK) { - LOGE("failed to get device credential from hichain"); - return ERR_DM_HICHAIN_CREDENTIAL_REQUEST_FAILED; - } - return DM_OK; -} - -int32_t DeviceManagerServiceImpl::CheckCredential(const std::string &pkgName, const std::string &reqJsonStr, - std::string &returnJsonStr) -{ - (void)pkgName; - if (reqJsonStr.empty()) { - LOGE("reqJsonStr is empty"); - return ERR_DM_INPUT_PARA_INVALID; - } - if (mineHiChainConnector_->CheckCredential(reqJsonStr, returnJsonStr) != DM_OK) { - LOGE("failed to check devices credential status"); - return ERR_DM_HICHAIN_CREDENTIAL_CHECK_FAILED; - } - return DM_OK; -} - -int32_t DeviceManagerServiceImpl::ImportCredential(const std::string &pkgName, const std::string &reqJsonStr, - std::string &returnJsonStr) -{ - (void)pkgName; - if (reqJsonStr.empty()) { - LOGE("reqJsonStr is empty"); - return ERR_DM_INPUT_PARA_INVALID; - } - if (mineHiChainConnector_->ImportCredential(reqJsonStr, returnJsonStr) != DM_OK) { - LOGE("failed to import devices credential"); - return ERR_DM_HICHAIN_CREDENTIAL_IMPORT_FAILED; - } - isCredentialType_.store(true); - return DM_OK; -} - -int32_t DeviceManagerServiceImpl::DeleteCredential(const std::string &pkgName, const std::string &reqJsonStr, - std::string &returnJsonStr) -{ - (void)pkgName; - if (reqJsonStr.empty()) { - LOGE("reqJsonStr is empty"); - return ERR_DM_INPUT_PARA_INVALID; - } - if (mineHiChainConnector_->DeleteCredential(reqJsonStr, returnJsonStr) != DM_OK) { - LOGE("failed to delete devices credential"); - return ERR_DM_HICHAIN_CREDENTIAL_DELETE_FAILED; - } - isCredentialType_.store(false); - return DM_OK; -} - -int32_t DeviceManagerServiceImpl::RegisterCredentialCallback(const std::string &pkgName) -{ - if (pkgName.empty()) { - LOGE("RegisterCredentialCallback failed, pkgName is empty"); - return ERR_DM_INPUT_PARA_INVALID; - } - if (credentialMgr_ == nullptr) { - LOGE("credentialMgr_ is nullptr"); - return ERR_DM_POINT_NULL; - } - return credentialMgr_->RegisterCredentialCallback(pkgName); -} - -int32_t DeviceManagerServiceImpl::UnRegisterCredentialCallback(const std::string &pkgName) -{ - if (pkgName.empty()) { - LOGE("UnRegisterCredentialCallback failed, pkgName is empty"); - return ERR_DM_INPUT_PARA_INVALID; - } - if (credentialMgr_== nullptr) { - LOGE("credentialMgr_ is nullptr"); - return ERR_DM_POINT_NULL; - } - return credentialMgr_->UnRegisterCredentialCallback(pkgName); -} - -int32_t DeviceManagerServiceImpl::RegisterUiStateCallback(const std::string &pkgName) -{ - if (pkgName.empty()) { - LOGE("RegisterUiStateCallback failed, pkgName is empty"); - return ERR_DM_INPUT_PARA_INVALID; - } - auto authMgr = GetCurrentAuthMgr(); - if (authMgr == nullptr) { - LOGE("authMgr is nullptr"); - return ERR_DM_POINT_NULL; - } - return authMgr->RegisterUiStateCallback(pkgName); -} - -int32_t DeviceManagerServiceImpl::UnRegisterUiStateCallback(const std::string &pkgName) -{ - if (pkgName.empty()) { - LOGE("UnRegisterUiStateCallback failed, pkgName is empty"); - return ERR_DM_INPUT_PARA_INVALID; - } - auto authMgr = GetCurrentAuthMgr(); - if (authMgr == nullptr) { - LOGE("authMgr is nullptr"); - return ERR_DM_POINT_NULL; - } - return authMgr->UnRegisterUiStateCallback(pkgName); -} - -int32_t DeviceManagerServiceImpl::PraseNotifyEventJson(const std::string &event, JsonObject &jsonObject) -{ - jsonObject.Parse(event); - if (jsonObject.IsDiscarded()) { - LOGE("event prase error."); - return ERR_DM_FAILED; - } - if ((!jsonObject.Contains("extra")) || (!jsonObject["extra"].IsObject())) { - LOGE("extra error"); - return ERR_DM_FAILED; - } - if ((!jsonObject["extra"].Contains("deviceId")) || (!jsonObject["extra"]["deviceId"].IsString())) { - LOGE("NotifyEvent deviceId invalid"); - return ERR_DM_FAILED; - } - return DM_OK; -} - -int32_t DeviceManagerServiceImpl::NotifyEvent(const std::string &pkgName, const int32_t eventId, - const std::string &event) -{ - LOGI("NotifyEvent begin, pkgName : %{public}s, eventId : %{public}d", pkgName.c_str(), eventId); - if ((eventId <= DM_NOTIFY_EVENT_START) || (eventId >= DM_NOTIFY_EVENT_BUTT)) { - LOGE("NotifyEvent eventId invalid"); - return ERR_DM_INPUT_PARA_INVALID; - } - if (eventId == DM_NOTIFY_EVENT_ONDEVICEREADY) { - JsonObject jsonObject; - if (PraseNotifyEventJson(event, jsonObject) != DM_OK) { - LOGE("NotifyEvent json invalid"); - return ERR_DM_INPUT_PARA_INVALID; - } - std::string deviceId; - jsonObject["extra"]["deviceId"].GetTo(deviceId); - if (deviceStateMgr_== nullptr) { - LOGE("deviceStateMgr_ is nullptr"); - return ERR_DM_POINT_NULL; - } - if (deviceStateMgr_->ProcNotifyEvent(eventId, deviceId) != DM_OK) { - LOGE("NotifyEvent failed"); - return ERR_DM_INPUT_PARA_INVALID; - }; - } - return DM_OK; -} - -int32_t DeviceManagerServiceImpl::GetGroupType(std::vector &deviceList) -{ - LOGI("GetGroupType begin"); - if (softbusConnector_ == nullptr || hiChainConnector_ == nullptr) { - LOGE("softbusConnector_ or hiChainConnector_ is nullptr"); - return ERR_DM_POINT_NULL; - } - - for (auto it = deviceList.begin(); it != deviceList.end(); ++it) { - std::string udid = ""; - int32_t ret = softbusConnector_->GetUdidByNetworkId(it->networkId, udid); - if (ret != DM_OK) { - LOGE("GetUdidByNetworkId failed ret: %{public}d", ret); - return ret; - } - std::string deviceId = softbusConnector_->GetDeviceUdidHashByUdid(udid); - if (memcpy_s(it->deviceId, DM_MAX_DEVICE_ID_LEN, deviceId.c_str(), deviceId.length()) != 0) { - LOGE("get deviceId: %{public}s failed", GetAnonyString(deviceId).c_str()); - return ERR_DM_SECURITY_FUNC_FAILED; - } - it->authForm = hiChainConnector_->GetGroupType(udid); - } - return DM_OK; -} - -int32_t DeviceManagerServiceImpl::GetUdidHashByNetWorkId(const char *networkId, std::string &deviceId) -{ - if (softbusConnector_ == nullptr || hiChainConnector_ == nullptr) { - LOGE("softbusConnector_ or hiChainConnector_ is nullptr"); - return ERR_DM_POINT_NULL; - } - std::string udid = ""; - int32_t ret = softbusConnector_->GetUdidByNetworkId(networkId, udid); - if (ret != DM_OK) { - LOGE("GetUdidByNetworkId failed ret: %{public}d", ret); - return ret; - } - deviceId = softbusConnector_->GetDeviceUdidHashByUdid(udid); - return DM_OK; -} - -std::shared_ptr DeviceManagerServiceImpl::GetConfigByTokenId() -{ - uint64_t tokenId = IPCSkeleton::GetCallingTokenID(); - if (configsMap_.find(tokenId) == configsMap_.end()) { - configsMap_[tokenId] = std::make_shared(); - } - return configsMap_[tokenId]; -} - -int32_t DeviceManagerServiceImpl::ImportAuthCode(const std::string &pkgName, const std::string &authCode) -{ - if (pkgName.empty() || authCode.empty()) { - LOGE("ImportAuthCode failed, pkgName or authCode is empty"); - return ERR_DM_INPUT_PARA_INVALID; - } - - LOGI("DeviceManagerServiceImpl::ImportAuthCode pkgName is %{public}s, authCode is %{public}s", - pkgName.c_str(), GetAnonyString(authCode).c_str()); - auto authMgr = GetAuthMgr(); - if (authMgr == nullptr) { - auto config = GetConfigByTokenId(); - config->pkgName = pkgName; - config->authCode = authCode; // If registered multiple times, only the last one is kept - return DM_OK; - } - - return authMgr->ImportAuthCode(pkgName, authCode); -} - -int32_t DeviceManagerServiceImpl::ExportAuthCode(std::string &authCode) -{ - int32_t ret = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); - authCode = std::to_string(ret); - LOGI("ExportAuthCode success, authCode: %{public}s.", GetAnonyString(authCode).c_str()); - return DM_OK; -} - -static JsonObject GetExtraJsonObject(const std::map &bindParam) -{ - std::string extra; - auto iter = bindParam.find(PARAM_KEY_BIND_EXTRA_DATA); - if (iter != bindParam.end()) { - extra = iter->second; - } else { - extra = ConvertMapToJsonString(bindParam); - } - - return JsonObject(extra); -} - -static int32_t GetHmlInfo(const JsonObject &jsonObject, bool &hmlEnable160M, int32_t &hmlActionId) -{ - if (jsonObject[PARAM_KEY_HML_ENABLE_160M].IsBoolean()) { - hmlEnable160M = jsonObject[PARAM_KEY_HML_ENABLE_160M].Get(); - LOGI("hmlEnable160M %{public}d", hmlEnable160M); - } - if (!IsString(jsonObject, PARAM_KEY_HML_ACTIONID)) { - LOGE("PARAM_KEY_HML_ACTIONID is not string"); - return ERR_DM_INPUT_PARA_INVALID; - } - std::string actionIdStr = jsonObject[PARAM_KEY_HML_ACTIONID].Get(); - if (!IsNumberString(actionIdStr)) { - LOGE("PARAM_KEY_HML_ACTIONID is not number"); - return ERR_DM_INPUT_PARA_INVALID; - } - int32_t actionId = std::atoi(actionIdStr.c_str()); - if (actionId <= 0) { - LOGE("PARAM_KEY_HML_ACTIONID is <= 0"); - return ERR_DM_INPUT_PARA_INVALID; - } - hmlActionId = actionId; - return DM_OK; -} - -static bool IsHmlSessionType(const JsonObject &jsonObject) -{ - std::string connSessionType; - if (jsonObject[PARAM_KEY_CONN_SESSIONTYPE].IsString()) { - connSessionType = jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get(); - LOGI("connSessionType %{public}s", connSessionType.c_str()); - } - return connSessionType == CONN_SESSION_TYPE_HML; -} - -int DeviceManagerServiceImpl::OpenAuthSession(const std::string& deviceId, - const std::map &bindParam) -{ - bool hmlEnable160M = false; - int32_t hmlActionId = 0; - JsonObject jsonObject = GetExtraJsonObject(bindParam); - if (jsonObject.IsDiscarded()) { - LOGE("extra string not a json type."); - return -1; - } - if (IsHmlSessionType(jsonObject)) { - auto ret = GetHmlInfo(jsonObject, hmlEnable160M, hmlActionId); - if (ret != DM_OK) { - LOGE("OpenAuthSession failed, GetHmlInfo failed."); - return ret; - } - LOGI("hmlActionId %{public}d, hmlEnable160M %{public}d", hmlActionId, hmlEnable160M); - return softbusConnector_->GetSoftbusSession()->OpenAuthSessionWithPara(deviceId, - hmlActionId, hmlEnable160M); - } else { - return softbusConnector_->GetSoftbusSession()->OpenAuthSession(deviceId); - } -} - -std::shared_ptr DeviceManagerServiceImpl::GetOrCreateSession(const std::string& deviceId, - const std::map &bindParam) -{ - std::shared_ptr instance; - int sessionId = -1; - // Acquire global lock to ensure thread safety for maps - { - std::lock_guard lock(mapMutex_); - if (deviceId2SessionIdMap_.find(deviceId) != deviceId2SessionIdMap_.end()) { - sessionId = deviceId2SessionIdMap_[deviceId]; - } - if (sessionsMap_.find(sessionId) != sessionsMap_.end()) { - return sessionsMap_[sessionId]; - } - } - - // Get the lock corresponding to deviceId - std::mutex& device_mutex = deviceIdMutexMap_[deviceId]; - std::lock_guard lock(device_mutex); - - // Check again whether the corresponding object already exists (because other threads may have created it during - // the lock acquisition in the previous step) - { - std::lock_guard lock(mapMutex_); - if (deviceId2SessionIdMap_.find(deviceId) != deviceId2SessionIdMap_.end()) { - sessionId = deviceId2SessionIdMap_[deviceId]; - } - if (sessionsMap_.find(sessionId) != sessionsMap_.end()) { - return sessionsMap_[sessionId]; - } - - sessionId = OpenAuthSession(deviceId, bindParam); - if (sessionId < 0) { - LOGE("OpenAuthSession failed, stop the authentication"); - return nullptr; - } - - std::unique_lock cvLock(sessionEnableMutexMap_[sessionId]); - if (sessionEnableCvMap_[sessionId].wait_for(cvLock, std::chrono::milliseconds(EVENT_TIMEOUT), - [&] { return sessionEnableCvReadyMap_[sessionId]; })) { - LOGI("session enable, sessionId: %{public}d.", sessionId); - } else { - LOGE("wait session enable timeout or enable fail, sessionId: %{public}d.", sessionId); - return nullptr; - } - sessionEnableCvReadyMap_.erase(sessionId); - instance = std::make_shared(sessionId, deviceId); - deviceId2SessionIdMap_[deviceId] = sessionId; - sessionsMap_[sessionId] = instance; - } - return instance; -} - -int32_t DeviceManagerServiceImpl::GetDeviceInfo(const PeerTargetId &targetId, std::string &addrType, - std::string &deviceId, std::shared_ptr deviceInfo, int32_t &index) -{ - ConnectionAddr addr; - if (!targetId.wifiIp.empty() && targetId.wifiIp.length() <= IP_STR_MAX_LEN) { - LOGI("parse wifiIp: %{public}s.", GetAnonyString(targetId.wifiIp).c_str()); - if (!addrType.empty()) { - addr.type = static_cast(std::atoi(addrType.c_str())); - } else { - addr.type = ConnectionAddrType::CONNECTION_ADDR_WLAN; - } - if (memcpy_s(addr.info.ip.ip, IP_STR_MAX_LEN, targetId.wifiIp.c_str(), targetId.wifiIp.length()) != 0) { - LOGE("get ip addr: %{public}s failed", GetAnonyString(targetId.wifiIp).c_str()); - return ERR_DM_SECURITY_FUNC_FAILED; - } - addr.info.ip.port = targetId.wifiPort; - deviceInfo->addr[index] = addr; - deviceId = targetId.wifiIp; - index++; - } else if (!targetId.brMac.empty() && targetId.brMac.length() <= BT_MAC_LEN) { - LOGI("parse brMac: %{public}s.", GetAnonyString(targetId.brMac).c_str()); - addr.type = ConnectionAddrType::CONNECTION_ADDR_BR; - if (memcpy_s(addr.info.br.brMac, BT_MAC_LEN, targetId.brMac.c_str(), targetId.brMac.length()) != 0) { - LOGE("get brMac addr: %{public}s failed", GetAnonyString(targetId.brMac).c_str()); - return ERR_DM_SECURITY_FUNC_FAILED; - } - deviceInfo->addr[index] = addr; - deviceId = targetId.brMac; - index++; - } else if (!targetId.bleMac.empty() && targetId.bleMac.length() <= BT_MAC_LEN) { - LOGI("parse bleMac: %{public}s.", GetAnonyString(targetId.bleMac).c_str()); - addr.type = ConnectionAddrType::CONNECTION_ADDR_BLE; - if (memcpy_s(addr.info.ble.bleMac, BT_MAC_LEN, targetId.bleMac.c_str(), targetId.bleMac.length()) != 0) { - LOGE("get bleMac addr: %{public}s failed", GetAnonyString(targetId.bleMac).c_str()); - return ERR_DM_SECURITY_FUNC_FAILED; - } - if (!targetId.deviceId.empty()) { - Crypto::ConvertHexStringToBytes(addr.info.ble.udidHash, UDID_HASH_LEN, - targetId.deviceId.c_str(), targetId.deviceId.length()); - } - deviceInfo->addr[index] = addr; - deviceId = targetId.bleMac; - index++; - } else { - LOGE("DeviceManagerServiceImpl::GetDeviceInfo failed, not addr."); - return ERR_DM_INPUT_PARA_INVALID; - } - return DM_OK; -} - -bool DeviceManagerServiceImpl::IsAuthNewVersion(int32_t bindLevel, std::string localUdid, std::string remoteUdid, - int32_t tokenId, int32_t userId) -{ - std::string extraInfo = DeviceProfileConnector::GetInstance().IsAuthNewVersion( - bindLevel, localUdid, remoteUdid, tokenId, userId); - JsonObject extraInfoJson(extraInfo); - if (extraInfoJson.IsDiscarded()) { - LOGE("IsAuthNewVersion extraInfoJson error"); - return false; - } - if (!extraInfoJson[TAG_DMVERSION].IsString()) { - LOGE("IsAuthNewVersion PARAM_KEY_OS_VERSION error"); - return false; - } - std::string dmVersion = extraInfoJson[TAG_DMVERSION].Get(); - if (CompareVersion(dmVersion, std::string(DM_VERSION_5_1_0)) || dmVersion == std::string(DM_VERSION_5_1_0)) { - return true; - } - return false; -} - -int32_t DeviceManagerServiceImpl::ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, - const std::map &bindParam) -{ - std::string addrType; - if (bindParam.count(PARAM_KEY_CONN_ADDR_TYPE) != 0) { - addrType = bindParam.at(PARAM_KEY_CONN_ADDR_TYPE); - } - - std::shared_ptr deviceInfo = std::make_shared(); - int32_t index = 0; - int32_t ret = GetDeviceInfo(targetId, addrType, deviceId, deviceInfo, index); - if (ret != DM_OK) { - LOGE("GetDeviceInfo failed, ret: %{public}d", ret); - } - deviceInfo->addrNum = static_cast(index); - if (softbusConnector_->AddMemberToDiscoverMap(deviceId, deviceInfo) != DM_OK) { - LOGE("DeviceManagerServiceImpl::ParseConnectAddr failed, AddMemberToDiscoverMap failed."); - return ERR_DM_INPUT_PARA_INVALID; - } - deviceInfo = nullptr; - return DM_OK; -} - -int32_t DeviceManagerServiceImpl::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, - const std::map &bindParam) -{ - if (pkgName.empty()) { - LOGE("BindTarget failed, pkgName is empty."); - return ERR_DM_INPUT_PARA_INVALID; - } - - std::string deviceId = ""; - PeerTargetId targetIdTmp = const_cast(targetId); - if (ParseConnectAddr(targetId, deviceId, bindParam) == DM_OK) { - targetIdTmp.deviceId = deviceId; - } else { - if (targetId.deviceId.empty()) { - LOGE("DeviceManagerServiceImpl::BindTarget failed, ParseConnectAddr failed."); - return ERR_DM_INPUT_PARA_INVALID; - } - } - // Created only at the source end. The same target device will not be created repeatedly with the new protocol. - std::shared_ptr curSession = GetOrCreateSession(targetIdTmp.deviceId, bindParam); - if (curSession == nullptr) { - LOGE("Failed to create the session. Target deviceId: %{public}s.", targetIdTmp.deviceId.c_str()); - return ERR_DM_AUTH_OPEN_SESSION_FAILED; - } - - // Logical session random number - int sessionId = curSession->sessionId_; - uint64_t logicalSessionId = 0; - if (curSession->version_ == "" || CompareVersion(curSession->version_, DM_VERSION_5_0_OLD_MAX)) { - logicalSessionId = GenerateRandNum(sessionId); - if (curSession->logicalSessionSet_.find(logicalSessionId) != curSession->logicalSessionSet_.end()) { - LOGE("Failed to create the logical session."); - return ERR_DM_LOGIC_SESSION_CREATE_FAILED; - } - } - - // Create on the src end. - uint64_t tokenId = IPCSkeleton::GetCallingTokenID(); - int32_t ret = InitAndRegisterAuthMgr(true, tokenId, curSession, logicalSessionId); - if (ret != DM_OK) { - LOGE("InitAndRegisterAuthMgr failed, ret %{public}d.", ret); - return ret; - } - curSession->logicalSessionSet_.insert(logicalSessionId); - curSession->logicalSessionCnt_.fetch_add(1); - logicalSessionId2TokenIdMap_[logicalSessionId] = tokenId; - logicalSessionId2SessionIdMap_[logicalSessionId] = sessionId; - - auto authMgr = GetAuthMgrByTokenId(tokenId); - if (authMgr == nullptr) { - return ERR_DM_POINT_NULL; - } - authMgr->SetBindTargetParams(targetId); - if ((ret = authMgr->BindTarget(pkgName, targetIdTmp, bindParam, sessionId, logicalSessionId)) != DM_OK) { - LOGE("authMgr BindTarget failed, ret %{public}d.", ret); - CleanAuthMgrByLogicalSessionId(logicalSessionId); - } - return ret; -} - -int32_t DeviceManagerServiceImpl::DpAclAdd(const std::string &udid) -{ - LOGI("DeviceManagerServiceImpl DpAclAdd start."); - MultipleUserConnector::SetSwitchOldUserId(MultipleUserConnector::GetCurrentAccountUserID()); - 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::GetFirstForegroundUserId(); - softbusConnector_->SetProcessInfo(processInfo); - deviceStateMgr_->OnDeviceOnline(udid, DmAuthForm::IDENTICAL_ACCOUNT); - } - LOGI("DeviceManagerServiceImpl::DpAclAdd completed"); - return DM_OK; -} - -int32_t DeviceManagerServiceImpl::IsSameAccount(const std::string &udid) -{ - if (udid.empty()) { - LOGE("DeviceManagerServiceImpl::IsSameAccount error: udid: %{public}s", GetAnonyString(udid).c_str()); - return ERR_DM_INPUT_PARA_INVALID; - } - - return DeviceProfileConnector::GetInstance().IsSameAccount(udid); -} - -uint64_t DeviceManagerServiceImpl::GetTokenIdByNameAndDeviceId(std::string pkgName, - std::string requestDeviceId) -{ - if (pkgName.empty()) { - LOGE("DeviceManagerServiceImpl::GetTokenIdByNameAndDeviceId error: pkgName."); - return ERR_DM_INPUT_PARA_INVALID; - } - - if (requestDeviceId.empty()) { - LOGE("DeviceManagerServiceImpl::GetTokenIdByNameAndDeviceId error: requestDeviceId."); - return ERR_DM_INPUT_PARA_INVALID; - } - - return DeviceProfileConnector::GetInstance().GetTokenIdByNameAndDeviceId(pkgName, requestDeviceId); -} - -std::unordered_map DeviceManagerServiceImpl::GetAppTrustDeviceIdList( - std::string pkgname) -{ - char localDeviceId[DEVICE_UUID_LENGTH]; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - std::string deviceId = reinterpret_cast(localDeviceId); - return DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgname, deviceId); -} - -void DeviceManagerServiceImpl::LoadHardwareFwkService() -{ - DmDistributedHardwareLoad::GetInstance().LoadDistributedHardwareFwk(); -} - -void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, - const std::string &peerUdid, int32_t peerUserId) -{ - LOGI("localUdid %{public}s, localUserId %{public}d, peerUdid %{public}s, peerUserId %{public}d.", - GetAnonyString(localUdid).c_str(), localUserId, GetAnonyString(peerUdid).c_str(), peerUserId); - DmOfflineParam offlineParam; - bool notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, - peerUdid, peerUserId, offlineParam); - if (notifyOffline) { - ProcessInfo processInfo; - processInfo.pkgName = std::string(DM_PKG_NAME); - processInfo.userId = localUserId; - CHECK_NULL_VOID(softbusConnector_); - softbusConnector_->SetProcessInfo(processInfo); - CHECK_NULL_VOID(deviceStateMgr_); - deviceStateMgr_->OnDeviceOffline(peerUdid); - } - CHECK_NULL_VOID(hiChainConnector_); - hiChainConnector_->DeleteAllGroup(localUserId); - CHECK_NULL_VOID(hiChainAuthConnector_); - hiChainAuthConnector_->DeleteCredential(peerUdid, localUserId, peerUserId); - LOGE("DeleteSkCredAndAcl start"); - DeleteSkCredAndAcl(offlineParam.needDelAclInfos); -} - -void DeviceManagerServiceImpl::HandleUserRemoved(std::vector peerUdids, int32_t preUserId) -{ - LOGI("PreUserId %{public}d.", preUserId); - char localDeviceId[DEVICE_UUID_LENGTH]; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - std::string localUdid = reinterpret_cast(localDeviceId); - std::multimap peerUserIdMap; // key: peerUdid value: peerUserId - DmOfflineParam offlineParam; - DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(localUdid, preUserId, peerUdids, peerUserIdMap, - offlineParam); - CHECK_NULL_VOID(hiChainConnector_); - hiChainConnector_->DeleteAllGroup(preUserId); - - if (peerUserIdMap.empty()) { - LOGE("peerUserIdMap is empty"); - return; - } - CHECK_NULL_VOID(hiChainAuthConnector_); - for (const auto &item : peerUserIdMap) { - hiChainAuthConnector_->DeleteCredential(item.first, preUserId, item.second); - } - LOGE("DeleteSkCredAndAcl start"); - DeleteSkCredAndAcl(offlineParam.needDelAclInfos); -} - -void DeviceManagerServiceImpl::HandleRemoteUserRemoved(int32_t userId, const std::string &remoteUdid) -{ - LOGI("remoteUdid %{public}s, userId %{public}d", GetAnonyString(remoteUdid).c_str(), userId); - std::vector localUserIds; - DmOfflineParam offlineParam; - DeviceProfileConnector::GetInstance().DeleteAclForRemoteUserRemoved(remoteUdid, userId, localUserIds, offlineParam); - if (localUserIds.empty()) { - return; - } - CHECK_NULL_VOID(hiChainAuthConnector_); - std::vector> delInfoVec; - for (int32_t localUserId : localUserIds) { - delInfoVec.push_back(std::pair(localUserId, remoteUdid)); - hiChainAuthConnector_->DeleteCredential(remoteUdid, localUserId, userId); - } - CHECK_NULL_VOID(hiChainConnector_); - hiChainConnector_->DeleteGroupByACL(delInfoVec, localUserIds); - LOGE("DeleteSkCredAndAcl start"); - DeleteSkCredAndAcl(offlineParam.needDelAclInfos); -} - -void DeviceManagerServiceImpl::HandleUserSwitched(const std::vector &deviceVec, - 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); - DeviceProfileConnector::GetInstance().HandleUserSwitched(localUdid, deviceVec, currentUserId, beforeUserId); -} - -void DeviceManagerServiceImpl::ScreenCommonEventCallback(std::string commonEventType) -{ - if (commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED) { - LOGI("DeviceManagerServiceImpl::ScreenCommonEventCallback on screen locked."); - for (auto& pair : authMgrMap_) { - if (pair.second != nullptr) { - LOGI("DeviceManagerServiceImpl::ScreenCommonEventCallback tokenId: %{public}" PRId64 ".", pair.first); - pair.second->OnScreenLocked(); - } - } - return; - } - LOGI("DeviceManagerServiceImpl::ScreenCommonEventCallback error."); -} - -int32_t DeviceManagerServiceImpl::CheckIsSameAccount(const DmAccessCaller &caller, const std::string &srcUdid, - const DmAccessCallee &callee, const std::string &sinkUdid) -{ - return DeviceProfileConnector::GetInstance().CheckIsSameAccount(caller, srcUdid, callee, sinkUdid); -} - -int32_t DeviceManagerServiceImpl::CheckAccessControl(const DmAccessCaller &caller, const std::string &srcUdid, - const DmAccessCallee &callee, const std::string &sinkUdid) -{ - CHECK_NULL_RETURN(hiChainConnector_, ERR_DM_POINT_NULL); - bool ret = hiChainConnector_->IsDevicesInP2PGroup(srcUdid, sinkUdid); - if (!ret) { - int32_t checkRet = DeviceProfileConnector::GetInstance().CheckAccessControl(caller, - srcUdid, callee, sinkUdid); - return checkRet; - } else { - return DM_OK; - } -} - -void DeviceManagerServiceImpl::HandleDeviceNotTrust(const std::string &udid) -{ - LOGI("DeviceManagerServiceImpl::HandleDeviceNotTrust udid: %{public}s.", GetAnonyString(udid).c_str()); - if (udid.empty()) { - LOGE("HandleDeviceNotTrust udid is empty."); - return; - } - DeviceProfileConnector::GetInstance().DeleteAccessControlList(udid); - CHECK_NULL_VOID(hiChainConnector_); - hiChainConnector_->DeleteAllGroupByUdid(udid); -} - -int32_t DeviceManagerServiceImpl::GetBindLevel(const std::string &pkgName, const std::string &localUdid, - const std::string &udid, uint64_t &tokenId) -{ - 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::multimap DeviceManagerServiceImpl::GetDeviceIdAndUserId(int32_t userId, - const std::string &accountId) -{ - char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); - std::string localUdid = std::string(localUdidTemp); - return DeviceProfileConnector::GetInstance().GetDeviceIdAndUserId(userId, accountId, localUdid); -} - -void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, - const std::string &remoteUdid) -{ - char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); - std::string localUdid = std::string(localUdidTemp); - std::multimap devIdAndUserMap = - DeviceProfileConnector::GetInstance().GetDevIdAndUserIdByActHash(localUdid, remoteUdid, - remoteUserId, remoteAccountHash); - CHECK_NULL_VOID(listener_); - std::string uuid = ""; - SoftbusCache::GetInstance().GetUuidByUdid(remoteUdid, uuid); - listener_->OnDeviceTrustChange(remoteUdid, uuid, DmAuthForm::IDENTICAL_ACCOUNT); - for (const auto &item : devIdAndUserMap) { - DmOfflineParam offlineParam; - LOGI("remoteUdid %{public}s.", GetAnonyString(remoteUdid).c_str()); - bool notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(item.first, item.second, - remoteUdid, remoteUserId, offlineParam); - if (notifyOffline) { - ProcessInfo processInfo; - processInfo.pkgName = std::string(DM_PKG_NAME); - processInfo.userId = item.second; - CHECK_NULL_VOID(softbusConnector_); - softbusConnector_->SetProcessInfo(processInfo); - CHECK_NULL_VOID(deviceStateMgr_); - deviceStateMgr_->OnDeviceOffline(remoteUdid); - } - CHECK_NULL_VOID(hiChainConnector_); - hiChainConnector_->DeleteAllGroup(item.second); - CHECK_NULL_VOID(hiChainAuthConnector_); - hiChainAuthConnector_->DeleteCredential(remoteUdid, item.second, remoteUserId); - LOGE("DeleteSkCredAndAcl start"); - DeleteSkCredAndAcl(offlineParam.needDelAclInfos); - } -} - -DmAuthForm DeviceManagerServiceImpl::ConvertBindTypeToAuthForm(int32_t bindType) -{ - LOGI("BindType %{public}d.", bindType); - DmAuthForm authForm = DmAuthForm::INVALID_TYPE; - if (static_cast(bindType) == DM_IDENTICAL_ACCOUNT) { - authForm = IDENTICAL_ACCOUNT; - } else if (static_cast(bindType) == DM_POINT_TO_POINT) { - authForm = PEER_TO_PEER; - } else if (static_cast(bindType) == DM_ACROSS_ACCOUNT) { - authForm = ACROSS_ACCOUNT; - } else { - LOGE("Invalied bindType."); - } - return authForm; -} - -int32_t DeviceManagerServiceImpl::DeleteGroup(const std::string &pkgName, const std::string &deviceId) -{ - LOGI("DeviceManagerServiceImpl::DeleteGroup"); - if (pkgName.empty()) { - LOGE("Invalid parameter, pkgName is empty."); - return ERR_DM_FAILED; - } - std::vector groupList; - CHECK_NULL_RETURN(hiChainConnector_, ERR_DM_POINT_NULL); - hiChainConnector_->GetRelatedGroups(deviceId, groupList); - for (const auto &item : groupList) { - std::string groupId = item.groupId; - hiChainConnector_->DeleteGroup(groupId); - } - return DM_OK; -} - -void DeviceManagerServiceImpl::HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid) -{ - char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); - std::string localUdid = std::string(localUdidTemp); - DmOfflineParam offlineParam; - int32_t bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent( - remoteUserId, remoteUdid, localUdid, offlineParam); - if (static_cast(bindType) == DM_INVALIED_TYPE) { - LOGE("Invalied bindtype."); - return; - } - int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); - DeleteGroup(DM_PKG_NAME, remoteUdid); - DeleteSkCredAndAcl(offlineParam.needDelAclInfos); -} - -void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, - int32_t tokenId) -{ - LOGI("HandleAppUnBindEvent tokenId = %{public}d.", tokenId); - char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); - std::string localUdid = std::string(localUdidTemp); - int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); - DmOfflineParam offlineParam = - DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); - if (offlineParam.leftAclNumber != 0) { - LOGI("HandleAppUnBindEvent app-level type leftAclNumber not zero."); - CHECK_NULL_VOID(softbusConnector_); - softbusConnector_->SetProcessInfoVec(offlineParam.processVec); - softbusConnector_->HandleDeviceOffline(remoteUdid); - DeleteSkCredAndAcl(offlineParam.needDelAclInfos); - return; - } - if (offlineParam.leftAclNumber == 0) { - LOGI("HandleAppUnBindEvent app-level type leftAclNumber is zero."); - CHECK_NULL_VOID(softbusConnector_); - softbusConnector_->SetProcessInfoVec(offlineParam.processVec); - if (!offlineParam.hasLnnAcl) { - CHECK_NULL_VOID(hiChainAuthConnector_); - hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(), - remoteUserId); - } else { - DeleteSkCredAndAcl(offlineParam.needDelAclInfos); - } - return; - } -} - -void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, - int32_t tokenId, int32_t peerTokenId) -{ - LOGI("HandleAppUnBindEvent peerTokenId = %{public}d.", peerTokenId); - char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); - std::string localUdid = std::string(localUdidTemp); - int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); - DmOfflineParam offlineParam = - DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, - tokenId, localUdid, peerTokenId); - if (offlineParam.leftAclNumber != 0) { - LOGI("HandleAppUnBindEvent app-level type leftAclNumber not zero."); - CHECK_NULL_VOID(softbusConnector_); - softbusConnector_->SetProcessInfoVec(offlineParam.processVec); - softbusConnector_->HandleDeviceOffline(remoteUdid); - DeleteSkCredAndAcl(offlineParam.needDelAclInfos); - return; - } - if (offlineParam.leftAclNumber == 0) { - LOGI("HandleAppUnBindEvent app-level type leftAclNumber is zero."); - CHECK_NULL_VOID(softbusConnector_); - softbusConnector_->SetProcessInfoVec(offlineParam.processVec); - if (!offlineParam.hasLnnAcl) { - CHECK_NULL_VOID(hiChainAuthConnector_); - hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(), - remoteUserId); - } else { - DeleteSkCredAndAcl(offlineParam.needDelAclInfos); - } - return; - } -} - -void DeviceManagerServiceImpl::HandleServiceUnBindEvent(int32_t userId, const std::string &remoteUdid, - int32_t remoteTokenId) -{ - LOGI("HandleServiceUnBindEvent remoteTokenId = %{public}d, userId: %{public}d, remoteUdid: %{public}s.", - remoteTokenId, userId, GetAnonyString(remoteUdid).c_str()); - char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); - std::string localUdid = std::string(localUdidTemp); - int32_t localUserId = MultipleUserConnector::GetCurrentAccountUserID(); - DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().HandleServiceUnBindEvent( - userId, remoteUdid, localUdid, remoteTokenId); - - CHECK_NULL_VOID(softbusConnector_); - if (offlineParam.hasLnnAcl) { - softbusConnector_->SetProcessInfoVec(offlineParam.processVec); - } else { - softbusConnector_->SetProcessInfoVec(offlineParam.processVec); - softbusConnector_->HandleDeviceOffline(remoteUdid); - } - DeleteSkCredAndAcl(offlineParam.needDelAclInfos); -} - -void DeviceManagerServiceImpl::HandleSyncUserIdEvent(const std::vector &foregroundUserIds, - const std::vector &backgroundUserIds, const std::string &remoteUdid, bool isCheckUserStatus) -{ - LOGI("remote udid: %{public}s, foregroundUserIds: %{public}s, backgroundUserIds: %{public}s", - GetAnonyString(remoteUdid).c_str(), GetIntegerList(foregroundUserIds).c_str(), - GetIntegerList(backgroundUserIds).c_str()); - char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); - std::string localUdid = std::string(localUdidTemp); - std::vector rmtFrontUserIdsTemp(foregroundUserIds.begin(), foregroundUserIds.end()); - std::vector rmtBackUserIdsTemp(backgroundUserIds.begin(), backgroundUserIds.end()); - std::vector localUserIds; - int32_t ret = MultipleUserConnector::GetForegroundUserIds(localUserIds); - if (ret != DM_OK) { - LOGE("Get foreground userids failed, ret: %{public}d", ret); - return; - } - if (isCheckUserStatus) { - MultipleUserConnector::ClearLockedUser(localUserIds); - } - DmOfflineParam offlineParam; - DeviceProfileConnector::GetInstance().UpdateACL(localUdid, localUserIds, remoteUdid, - rmtFrontUserIdsTemp, rmtBackUserIdsTemp, offlineParam); - DeleteSkCredAndAcl(offlineParam.needDelAclInfos); - DeviceProfileConnector::GetInstance().HandleSyncBackgroundUserIdEvent(rmtBackUserIdsTemp, remoteUdid, - localUserIds, localUdid); - DeviceProfileConnector::GetInstance().HandleSyncForegroundUserIdEvent(rmtFrontUserIdsTemp, remoteUdid, - localUserIds, localUdid); -} - -void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) -{ - LOGI("In"); - CHECK_NULL_VOID(deviceStateMgr_); - CHECK_NULL_VOID(softbusConnector_); - std::string trustDeviceId = ""; - if (softbusConnector_->GetUdidByNetworkId(devInfo.networkId, trustDeviceId) != DM_OK) { - LOGE("get udid failed."); - return; - } - std::string udidHash = softbusConnector_->GetDeviceUdidHashByUdid(trustDeviceId); - if (memcpy_s(devInfo.deviceId, DM_MAX_DEVICE_ID_LEN, udidHash.c_str(), udidHash.length()) != 0) { - LOGE("get deviceId: %{public}s failed", GetAnonyString(udidHash).c_str()); - return; - } - char localUdid[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localUdid, DEVICE_UUID_LENGTH); - std::string requestDeviceId = static_cast(localUdid); - uint32_t bindType = DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); - LOGI("bind type is %{public}d.", bindType); - if (bindType == INVALIED_TYPE) { - return; - } else if (bindType == IDENTICAL_ACCOUNT_TYPE || bindType == DEVICE_PEER_TO_PEER_TYPE || - bindType == DEVICE_ACROSS_ACCOUNT_TYPE) { - ProcessInfo processInfo; - processInfo.pkgName = std::string(DM_PKG_NAME); - processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); - softbusConnector_->SetProcessInfo(processInfo); - } else if (bindType == APP_PEER_TO_PEER_TYPE || bindType == APP_ACROSS_ACCOUNT_TYPE) { - std::vector processInfoVec = - DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, - MultipleUserConnector::GetFirstForegroundUserId()); - softbusConnector_->SetProcessInfoVec(processInfoVec); - } - deviceStateMgr_->HandleDeviceScreenStatusChange(devInfo); -} - -int32_t DeviceManagerServiceImpl::SyncLocalAclListProcess(const DevUserInfo &localDevUserInfo, - const DevUserInfo &remoteDevUserInfo, std::string remoteAclList) -{ - CHECK_NULL_RETURN(softbusConnector_, ERR_DM_POINT_NULL); - return softbusConnector_->SyncLocalAclListProcess(localDevUserInfo, remoteDevUserInfo, remoteAclList); -} - -int32_t DeviceManagerServiceImpl::GetAclListHash(const DevUserInfo &localDevUserInfo, - const DevUserInfo &remoteDevUserInfo, std::string &aclList) -{ - CHECK_NULL_RETURN(softbusConnector_, ERR_DM_POINT_NULL); - return softbusConnector_->GetAclListHash(localDevUserInfo, remoteDevUserInfo, aclList); -} - -void DeviceManagerServiceImpl::HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, - int32_t errcode) -{ - CHECK_NULL_VOID(credentialMgr_); - credentialMgr_->HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode); -} - -int32_t DeviceManagerServiceImpl::ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) -{ - CHECK_NULL_RETURN(listener_, ERR_DM_POINT_NULL); - std::vector profiles = - DeviceProfileConnector::GetInstance().GetAllAclIncludeLnnAcl(); - LOGI("delete ACL size is %{public}zu, appId %{public}s", profiles.size(), GetAnonyString(appId).c_str()); - if (profiles.size() == 0) { - return DM_OK; - } - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - std::string localUdid = std::string(localDeviceId); - std::vector> delACLInfoVec; - std::vector userIdVec; - std::map delProfileMap; - DeleteAclByTokenId(accessTokenId, profiles, delProfileMap, delACLInfoVec, userIdVec); - for (auto item : delProfileMap) { - DmOfflineParam lnnAclParam; - bool isLastLnnAcl = false; - for (auto it : profiles) { - CheckIsLastLnnAcl(it, item.second, lnnAclParam, isLastLnnAcl, localUdid); - } - if (!isLastLnnAcl) { - DeleteSkCredAndAcl(lnnAclParam.needDelAclInfos); - } - } - - if (delACLInfoVec.size() == 0) { - return DM_OK; - } - if (userIdVec.size() == 0) { - return DM_OK; - } - CHECK_NULL_RETURN(hiChainConnector_, ERR_DM_POINT_NULL); - hiChainConnector_->DeleteGroupByACL(delACLInfoVec, userIdVec); - return DM_OK; -} - -void DeviceManagerServiceImpl::CheckIsLastLnnAcl(DistributedDeviceProfile::AccessControlProfile profile, - DistributedDeviceProfile::AccessControlProfile delProfile, DmOfflineParam &lnnAclParam, bool &isLastLnnAcl, - const std::string &localUdid) -{ - if (DeviceProfileConnector::GetInstance().IsLnnAcl(profile) && CheckLnnAcl(delProfile, profile)) { - if (profile.GetAccesser().GetAccesserDeviceId() == localUdid) { - DeviceProfileConnector::GetInstance().CacheAcerAclId(profile, lnnAclParam.needDelAclInfos); - } - if (profile.GetAccessee().GetAccesseeDeviceId() == localUdid) { - DeviceProfileConnector::GetInstance().CacheAceeAclId(profile, lnnAclParam.needDelAclInfos); - } - } - if (!DeviceProfileConnector::GetInstance().IsLnnAcl(profile) && CheckLnnAcl(delProfile, profile)) { - isLastLnnAcl = true; - } -} - -void DeviceManagerServiceImpl::DeleteAclByTokenId(const int32_t accessTokenId, - std::vector &profiles, - std::map &delProfileMap, - std::vector> &delACLInfoVec, std::vector &userIdVec) -{ - for (auto &item : profiles) { - int64_t accesssertokenId = item.GetAccesser().GetAccesserTokenId(); - int64_t accessseetokenId = item.GetAccessee().GetAccesseeTokenId(); - if (accessTokenId != static_cast(accesssertokenId) && - accessTokenId != static_cast(accessseetokenId)) { - continue; - } - if (accessTokenId == static_cast(accesssertokenId)) { - DmOfflineParam offlineParam; - delProfileMap[item.GetAccessControlId()] = item; - DeviceProfileConnector::GetInstance().CacheAcerAclId(item, offlineParam.needDelAclInfos); - DeleteSkCredAndAcl(offlineParam.needDelAclInfos); - listener_->OnAppUnintall(item.GetAccesser().GetAccesserBundleName()); - if (item.GetBindLevel() == USER) { - userIdVec.push_back(item.GetAccesser().GetAccesserUserId()); - delACLInfoVec.push_back(std::pair(item.GetAccesser().GetAccesserUserId(), - item.GetAccessee().GetAccesseeDeviceId())); - } - } - if (accessTokenId == static_cast(accessseetokenId)) { - DmOfflineParam offlineParam; - DeviceProfileConnector::GetInstance().CacheAceeAclId(item, offlineParam.needDelAclInfos); - delProfileMap[item.GetAccessControlId()] = item; - DeleteSkCredAndAcl(offlineParam.needDelAclInfos); - listener_->OnAppUnintall(item.GetAccessee().GetAccesseeBundleName()); - if (item.GetBindLevel() == USER) { - userIdVec.push_back(item.GetAccessee().GetAccesseeUserId()); - delACLInfoVec.push_back(std::pair(item.GetAccessee().GetAccesseeUserId(), - item.GetAccesser().GetAccesserDeviceId())); - } - } - } - for (auto item : delProfileMap) { - for (auto it = profiles.begin(); it != profiles.end();) { - if (item.first == it->GetAccessControlId()) { - it = profiles.erase(it); - } else { - it++; - } - } - } -} - -bool DeviceManagerServiceImpl::CheckLnnAcl(DistributedDeviceProfile::AccessControlProfile delProfile, - DistributedDeviceProfile::AccessControlProfile lastprofile) -{ - if ((delProfile.GetAccesser().GetAccesserDeviceId() == lastprofile.GetAccesser().GetAccesserDeviceId() && - delProfile.GetAccesser().GetAccesserUserId() == lastprofile.GetAccesser().GetAccesserUserId() && - delProfile.GetAccessee().GetAccesseeDeviceId() == lastprofile.GetAccessee().GetAccesseeDeviceId() && - delProfile.GetAccessee().GetAccesseeUserId() == lastprofile.GetAccessee().GetAccesseeUserId()) || - (delProfile.GetAccesser().GetAccesserDeviceId() == lastprofile.GetAccessee().GetAccesseeDeviceId() && - delProfile.GetAccesser().GetAccesserUserId() == lastprofile.GetAccessee().GetAccesseeUserId() && - delProfile.GetAccessee().GetAccesseeDeviceId() == lastprofile.GetAccesser().GetAccesserDeviceId() && - delProfile.GetAccessee().GetAccesseeUserId() == lastprofile.GetAccesser().GetAccesserUserId())) { - return true; - } - return false; -} - -std::multimap DeviceManagerServiceImpl::GetDeviceIdAndUserId(int32_t localUserId) -{ - LOGI("localUserId %{public}d.", localUserId); - char localdeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localdeviceId, DEVICE_UUID_LENGTH); - std::string localUdid = std::string(localdeviceId); - return DeviceProfileConnector::GetInstance().GetDeviceIdAndUserId(localUdid, localUserId); -} - -int32_t DeviceManagerServiceImpl::SaveOnlineDeviceInfo(const std::vector &deviceList) -{ - CHECK_NULL_RETURN(deviceStateMgr_, ERR_DM_POINT_NULL); - for (auto item : deviceList) { - deviceStateMgr_->SaveOnlineDeviceInfo(item); - } - return DM_OK; -} - -void DeviceManagerServiceImpl::HandleDeviceUnBind(int32_t bindType, const std::string &peerUdid, - const std::string &localUdid, int32_t localUserId, const std::string &localAccountId) -{ - return DeviceProfileConnector::GetInstance().HandleDeviceUnBind(bindType, peerUdid, - localUdid, localUserId, localAccountId); -} - -int32_t DeviceManagerServiceImpl::RegisterAuthenticationType(int32_t authenticationType) -{ - if (authenticationType != USER_OPERATION_TYPE_ALLOW_AUTH && - authenticationType != USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { - LOGE("Invalid parameter."); - return ERR_DM_INPUT_PARA_INVALID; - } - auto authMgr = GetAuthMgr(); - if (authMgr == nullptr) { - auto config = GetConfigByTokenId(); - config->authenticationType = authenticationType; // only the last registration is retained - return DM_OK; - } - return authMgr->RegisterAuthenticationType(authenticationType); -} - -void DeviceManagerServiceImpl::DeleteAlwaysAllowTimeOut() -{ - LOGI("Start DeleteAlwaysAllowTimeOut"); - std::vector profiles = - DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); - std::string remoteUdid = ""; - int32_t remoteUserId = -1; - int64_t currentTime = - std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); - int32_t currentUserId = MultipleUserConnector::GetCurrentAccountUserID(); - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - std::string localUdid = std::string(localDeviceId); - for (auto &item : profiles) { - if (item.GetBindType() == DM_IDENTICAL_ACCOUNT) { - continue; - } - if ((currentTime - item.GetLastAuthTime()) > MAX_ALWAYS_ALLOW_SECONDS && item.GetLastAuthTime() > 0) { - DeviceProfileConnector::GetInstance().DeleteAccessControlById(item.GetAccessControlId()); - if (item.GetAccesser().GetAccesserUserId() == currentUserId && - item.GetAccesser().GetAccesserDeviceId() == localUdid) { - remoteUserId = item.GetAccessee().GetAccesseeUserId(); - } - if (item.GetAccessee().GetAccesseeUserId() == currentUserId && - item.GetAccessee().GetAccesseeDeviceId() == localUdid) { - remoteUserId = item.GetAccesser().GetAccesserUserId(); - } - remoteUdid = item.GetTrustDeviceId(); - CheckDeleteCredential(remoteUdid, remoteUserId); - } - } -} - -void DeviceManagerServiceImpl::CheckDeleteCredential(const std::string &remoteUdid, int32_t remoteUserId) -{ - std::vector profiles = - DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); - bool leftAcl = false; - for (auto &item : profiles) { - if (item.GetTrustDeviceId() == remoteUdid) { - leftAcl = true; - } - } - if (!leftAcl) { - LOGI("CheckDeleteCredential delete credential"); - hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(), - remoteUserId); - } -} - -int32_t DeviceManagerServiceImpl::CheckDeviceInfoPermission(const std::string &localUdid, - const std::string &peerDeviceId) -{ - int32_t ret = DeviceProfileConnector::GetInstance().CheckDeviceInfoPermission(localUdid, peerDeviceId); - if (ret != DM_OK) { - LOGE("CheckDeviceInfoPermission failed, ret: %{public}d", ret); - return ret; - } - return DM_OK; -} - -int32_t DeviceManagerServiceImpl::DeleteAcl(const std::string &pkgName, const std::string &localUdid, - const std::string &remoteUdid, int32_t bindLevel, const std::string &extra) -{ - LOGI("DeleteAcl pkgName %{public}s, localUdid %{public}s, remoteUdid %{public}s, bindLevel %{public}d.", - pkgName.c_str(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str(), bindLevel); - if (static_cast(bindLevel) == USER) { - DeleteGroup(pkgName, remoteUdid); - } - DmOfflineParam offlineParam = - DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localUdid, remoteUdid, bindLevel, extra); - if (offlineParam.bindType == INVALIED_TYPE) { - LOGE("Acl not contain the pkgname bind data."); - return ERR_DM_FAILED; - } - CHECK_NULL_RETURN(softbusConnector_, ERR_DM_POINT_NULL); - CHECK_NULL_RETURN(hiChainAuthConnector_, ERR_DM_POINT_NULL); - if (static_cast(bindLevel) == APP) { - ProcessInfo processInfo; - processInfo.pkgName = pkgName; - processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); - 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(), - offlineParam.peerUserId); - return DM_OK; - } - } - if (static_cast(bindLevel) == USER && offlineParam.leftAclNumber != 0) { - LOGI("Unbind deivce-level, retain identical account bind type."); - return DM_OK; - } - if (static_cast(bindLevel) == USER && offlineParam.leftAclNumber == 0) { - LOGI("Unbind deivce-level, retain null."); - hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(), - offlineParam.peerUserId); - return DM_OK; - } - return ERR_DM_FAILED; -} - -int32_t DeviceManagerServiceImpl::DeleteSkCredAndAcl(const std::vector &acls) -{ - LOGI("DeleteSkCredAndAcl start."); - int32_t ret = DM_OK; - if (acls.empty()) { - return ret; - } - CHECK_NULL_RETURN(hiChainAuthConnector_, ERR_DM_POINT_NULL); - for (auto item : acls) { - ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(item.userId, item.skId); - if (ret != DM_OK) { - LOGE("DeleteSessionKey err, userId:%{public}d, skId:%{public}d, ret:%{public}d", item.userId, item.skId, - ret); - } - ret = hiChainAuthConnector_->DeleteCredential(item.userId, item.credId); - if (ret != DM_OK) { - LOGE("DeletecredId err, userId:%{public}d, credId:%{public}s, ret:%{public}d", item.userId, - item.credId.c_str(), ret); - } - DeviceProfileConnector::GetInstance().DeleteAccessControlById(item.accessControlId); - } - return ret; -} - -int32_t DeviceManagerServiceImpl::DeleteAclForProcV2(const std::string &localUdid, uint32_t localTokenId, - const std::string &remoteUdid, int32_t bindLevel, const std::string &extra, int32_t userId) -{ - DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().FilterNeedDeleteACL( - localUdid, localTokenId, remoteUdid, extra); - - // first, clear the unbind sk/cred/acl - DeleteSkCredAndAcl(offlineParam.needDelAclInfos); - - // second, determin if need clear lnn acl - if (offlineParam.allLeftAppOrSvrAclInfos.empty()) { - LOGI("No app or service acl exist, clear lnn acl"); - DeleteSkCredAndAcl(offlineParam.allLnnAclInfos); - } - - // third, determin if need report offline to unbind bundle - if (offlineParam.allUserAclInfos.empty()) { - LOGI("after clear target acl, No user acl exist, report offline"); - softbusConnector_->SetProcessInfoVec(offlineParam.processVec); - softbusConnector_->HandleDeviceOffline(remoteUdid); - } - - return DM_OK; -} - -int32_t DeviceManagerServiceImpl::DeleteAclV2(const std::string &pkgName, const std::string &localUdid, - const std::string &remoteUdid, int32_t bindLevel, const std::string &extra) -{ - LOGI("DeleteAclV2 pkgName %{public}s, localUdid %{public}s, remoteUdid %{public}s, bindLevel %{public}d.", - pkgName.c_str(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str(), bindLevel); - uint32_t tokenId = 0; - MultipleUserConnector::GetTokenId(tokenId); - int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); - bool isNewVersion = IsAuthNewVersion(bindLevel, localUdid, remoteUdid, tokenId, userId); - if (!isNewVersion) { - return DeleteAcl(pkgName, localUdid, remoteUdid, bindLevel, extra); - } - return DeleteAclForProcV2(localUdid, tokenId, remoteUdid, bindLevel, extra, userId); -} - -void DeviceManagerServiceImpl::HandleCommonEventBroadCast(const std::vector &foregroundUserIds, - const std::vector &backgroundUserIds, const std::string &remoteUdid) -{ - LOGI("remote udid: %{public}s, foregroundUserIds: %{public}s, backgroundUserIds: %{public}s", - GetAnonyString(remoteUdid).c_str(), GetIntegerList(foregroundUserIds).c_str(), - GetIntegerList(backgroundUserIds).c_str()); - std::vector rmtFrontUserIdsTemp(foregroundUserIds.begin(), foregroundUserIds.end()); - std::vector rmtBackUserIdsTemp(backgroundUserIds.begin(), backgroundUserIds.end()); - std::vector localUserIds; - int32_t ret = MultipleUserConnector::GetForegroundUserIds(localUserIds); - if (ret != DM_OK) { - LOGE("Get foreground userids failed, ret: %{public}d", ret); - return; - } - char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); - std::string localUdid = std::string(localUdidTemp); - MultipleUserConnector::ClearLockedUser(localUserIds); - DmOfflineParam offlineParam; - DeviceProfileConnector::GetInstance().UpdateACL(localUdid, localUserIds, remoteUdid, - rmtFrontUserIdsTemp, rmtBackUserIdsTemp, offlineParam); - DeleteSkCredAndAcl(offlineParam.needDelAclInfos); - DeviceProfileConnector::GetInstance().HandleSyncBackgroundUserIdEvent(rmtBackUserIdsTemp, remoteUdid, - localUserIds, localUdid); - DeviceProfileConnector::GetInstance().HandleSyncForegroundUserIdEvent(rmtFrontUserIdsTemp, remoteUdid, - localUserIds, localUdid); -} - -extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) -{ - return new DeviceManagerServiceImpl; -} -} // namespace DistributedHardware -} // namespace OHOS -- Gitee From c22b451fd16cd4cfc41c8c5b164f9f05027a333c Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Tue, 6 May 2025 14:03:20 +0800 Subject: [PATCH 3/4] =?UTF-8?q?=E5=90=8C=E6=AD=A5=E9=BB=84=E5=8C=BA?= =?UTF-8?q?=E4=B8=BB=E5=B9=B2=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- .../include/device_manager_service_impl.h.bak | 284 ------------------ 1 file changed, 284 deletions(-) delete mode 100644 services/implementation/include/device_manager_service_impl.h.bak diff --git a/services/implementation/include/device_manager_service_impl.h.bak b/services/implementation/include/device_manager_service_impl.h.bak deleted file mode 100644 index ada8d9966..000000000 --- a/services/implementation/include/device_manager_service_impl.h.bak +++ /dev/null @@ -1,284 +0,0 @@ -/* - * Copyright (c) 2022-2025 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_SERVICE_IMPL_H -#define OHOS_DM_SERVICE_IMPL_H - -#include -#include -#include -#include -#include -#include - -#include "access_control_profile.h" -#include "auth_manager.h" -#include "dm_ability_manager.h" -#include "dm_auth_manager.h" -#include "dm_auth_manager_base.h" -#include "dm_common_event_manager.h" -#include "dm_credential_manager.h" -#include "dm_device_info.h" -#include "dm_device_state_manager.h" -#include "dm_single_instance.h" -#include "dp_inited_callback.h" -#include "idevice_manager_service_impl.h" -#include "ipc_skeleton.h" -#include "mine_hichain_connector.h" -#include "softbus_connector.h" -#include "deviceprofile_connector.h" - -namespace OHOS { -namespace DistributedHardware { - -class Session { -public: - Session(int sessionId, std::string deviceId); - int sessionId_; - std::string deviceId_; - std::string version_{""}; - std::atomic flag_{false}; // Only one session is allowed - std::set logicalSessionSet_; // Logical Session Set - std::atomic logicalSessionCnt_{0}; -}; - -struct Config { - std::string pkgName; - std::string authCode; - int32_t authenticationType{0}; -}; - -class DeviceManagerServiceImpl : public IDeviceManagerServiceImpl { -public: - DeviceManagerServiceImpl(); - virtual ~DeviceManagerServiceImpl(); - - int32_t Initialize(const std::shared_ptr &listener); - - void Release(); - - int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel); - - int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel); - - int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, - int32_t bindLevel, const std::string &extra); - - int32_t SetUserOperation(std::string &pkgName, int32_t action, const std::string ¶ms); - - void HandleDeviceStatusChange(DmDeviceState devState, DmDeviceInfo &devInfo); - - int OnSessionOpened(int sessionId, int result); - - void OnSessionClosed(int sessionId); - - void OnBytesReceived(int sessionId, const void *data, unsigned int dataLen); - - int OnPinHolderSessionOpened(int sessionId, int result); - - void OnPinHolderSessionClosed(int sessionId); - - void OnPinHolderBytesReceived(int sessionId, const void *data, unsigned int dataLen); - - int32_t RequestCredential(const std::string &reqJsonStr, std::string &returnJsonStr); - - int32_t ImportCredential(const std::string &pkgName, const std::string &credentialInfo); - - int32_t DeleteCredential(const std::string &pkgName, const std::string &deleteInfo); - - int32_t MineRequestCredential(const std::string &pkgName, std::string &returnJsonStr); - - int32_t CheckCredential(const std::string &pkgName, const std::string &reqJsonStr, - std::string &returnJsonStr); - - int32_t ImportCredential(const std::string &pkgName, const std::string &reqJsonStr, - std::string &returnJsonStr); - - int32_t DeleteCredential(const std::string &pkgName, const std::string &reqJsonStr, - std::string &returnJsonStr); - - int32_t RegisterCredentialCallback(const std::string &pkgName); - - int32_t UnRegisterCredentialCallback(const std::string &pkgName); - - int32_t NotifyEvent(const std::string &pkgName, const int32_t eventId, const std::string &event); - - int32_t GetGroupType(std::vector &deviceList); - - int32_t GetUdidHashByNetWorkId(const char *networkId, std::string &deviceId); - - void LoadHardwareFwkService(); - - int32_t RegisterUiStateCallback(const std::string &pkgName); - - int32_t UnRegisterUiStateCallback(const std::string &pkgName); - - int32_t ImportAuthCode(const std::string &pkgName, const std::string &authCode); - - int32_t ExportAuthCode(std::string &authCode); - - int32_t BindTarget(const std::string &pkgName, const PeerTargetId &targetId, - const std::map &bindParam); - - std::unordered_map GetAppTrustDeviceIdList(std::string pkgname); - - int32_t DpAclAdd(const std::string &udid); - int32_t IsSameAccount(const std::string &udid); - uint64_t GetTokenIdByNameAndDeviceId(std::string pkgName, std::string requestDeviceId); - void ScreenCommonEventCallback(std::string commonEventType); - int32_t CheckIsSameAccount(const DmAccessCaller &caller, const std::string &srcUdid, - const DmAccessCallee &callee, const std::string &sinkUdid); - int32_t CheckAccessControl(const DmAccessCaller &caller, const std::string &srcUdid, - const DmAccessCallee &callee, const std::string &sinkUdid); - void HandleDeviceNotTrust(const std::string &udid); - int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, - const std::string &udid, uint64_t &tokenId); - void HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, - int32_t peerUserId); - void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); - int32_t StopAuthenticateDevice(const std::string &pkgName); - void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); - int32_t SyncLocalAclListProcess(const DevUserInfo &localDevUserInfo, - const DevUserInfo &remoteDevUserInfo, std::string remoteAclList); - int32_t GetAclListHash(const DevUserInfo &localDevUserInfo, - const DevUserInfo &remoteDevUserInfo, std::string &aclList); - int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId); - void HandleSyncUserIdEvent(const std::vector &foregroundUserIds, - const std::vector &backgroundUserIds, const std::string &remoteUdid, bool isCheckUserStatus); - void HandleUserSwitched(const std::vector &deviceVec, int32_t currentUserId, - int32_t beforeUserId); - std::multimap GetDeviceIdAndUserId(int32_t localUserId); - int32_t SaveOnlineDeviceInfo(const std::vector &deviceList); - void HandleDeviceUnBind(int32_t bindType, const std::string &peerUdid, - const std::string &localUdid, int32_t localUserId, const std::string &localAccountId); - int32_t RegisterAuthenticationType(int32_t authenticationType); - void DeleteAlwaysAllowTimeOut(); - void CheckDeleteCredential(const std::string &remoteUdid, int32_t remoteUserId); - int32_t CheckDeviceInfoPermission(const std::string &localUdid, const std::string &peerDeviceId); - int32_t DeleteAcl(const std::string &sessionName, const std::string &localUdid, const std::string &remoteUdid, - int32_t bindLevel, const std::string &extra); - int32_t DeleteAclV2(const std::string &sessionName, const std::string &localUdid, const std::string &remoteUdid, - int32_t bindLevel, const std::string &extra); - static void NotifyCleanEvent(uint64_t logicalSessionId); - void HandleServiceUnBindEvent(int32_t userId, const std::string &remoteUdid, - int32_t remoteTokenId); - int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); - int32_t InitAndRegisterAuthMgr(bool isSrcSide, uint64_t tokenId, std::shared_ptr session, - uint64_t logicalSessionId); - void HandleCommonEventBroadCast(const std::vector &foregroundUserIds, - const std::vector &backgroundUserIds, const std::string &remoteUdid); -private: - int32_t PraseNotifyEventJson(const std::string &event, JsonObject &jsonObject); - std::string GetUdidHashByNetworkId(const std::string &networkId); - void HandleOffline(DmDeviceState devState, DmDeviceInfo &devInfo); - void HandleOnline(DmDeviceState devState, DmDeviceInfo &devInfo); - std::map GetDeviceIdAndBindLevel(int32_t userId); - std::multimap GetDeviceIdAndUserId(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 HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, - int32_t tokenId, int32_t peerTokenId); - void HandleUserRemoved(std::vector peerUdids, int32_t preUserId); - void HandleRemoteUserRemoved(int32_t preUserId, const std::string &remoteUdid); - DmAuthForm ConvertBindTypeToAuthForm(int32_t bindType); - std::shared_ptr GetAuthMgr(); - std::shared_ptr GetAuthMgrByTokenId(uint64_t tokenId); - std::shared_ptr GetCurrentAuthMgr(); - void CreateGlobalClassicalAuthMgr(); - std::shared_ptr GetCurSession(int sessionId); - std::shared_ptr GetOrCreateSession(const std::string& deviceId, - const std::map &bindParam); - int32_t ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, - const std::map &bindParam); - std::shared_ptr GetConfigByTokenId(); - int OpenAuthSession(const std::string& deviceId, const std::map &bindParam); - int32_t ChangeUltrasonicTypeToPin(std::map &bindParam); - int32_t TransferByAuthType(int32_t authType, - std::shared_ptr curSession, std::shared_ptr authMgr, - std::map &bindParam, uint64_t logicalSessionId); - - std::shared_ptr GetAuthMgrByMessage(int32_t msgType, uint64_t logicalSessionId, - const JsonObject &jsonObject, std::shared_ptr curSession); - int32_t TransferOldAuthMgr(int32_t msgType, const JsonObject &jsonObject, - std::shared_ptr curSession); - int32_t TransferSrcOldAuthMgr(std::shared_ptr curSession); - int32_t TransferSinkOldAuthMgr(const JsonObject &jsonObject, std::shared_ptr curSession); - int32_t GetDeviceInfo(const PeerTargetId &targetId, std::string &addrType, std::string &deviceId, - std::shared_ptr deviceInfo, int32_t &index); - bool IsAuthNewVersion(int32_t bindLevel, std::string localUdid, std::string remoteUdid, - int32_t tokenId, int32_t userId); - void ImportConfig(std::shared_ptr authMgr, uint64_t tokenId); - - // Resource cleanup thread - void CleanWorker(); - // Stop the thread - void Stop(); - uint64_t FetchCleanEvent(); - void CleanAuthMgrByLogicalSessionId(uint64_t logicalSessionId); - void CleanSessionMap(int sessionId, std::shared_ptr session); - void CleanSessionMapByLogicalSessionId(uint64_t logicalSessionId); - int32_t DeleteAclForProcV2(const std::string &localUdid, uint32_t localTokenId, const std::string &remoteUdid, - int32_t bindLevel, const std::string &extra, int32_t userId); - int32_t DeleteSkCredAndAcl(const std::vector &acls); - void DeleteAclByTokenId(const int32_t accessTokenId, - std::vector &profiles, - std::map &delProfileMap, - std::vector> &delACLInfoVec, std::vector &userIdVec); - bool CheckLnnAcl(DistributedDeviceProfile::AccessControlProfile delProfile, - DistributedDeviceProfile::AccessControlProfile lastprofile); - void CheckIsLastLnnAcl(DistributedDeviceProfile::AccessControlProfile profile, - DistributedDeviceProfile::AccessControlProfile delProfile, DmOfflineParam &lnnAclParam, - bool &isLastLnnAcl, const std::string &localUdid); -private: - std::shared_ptr authMgr_; // Old protocol only - std::mutex authMgrMtx_; - std::map> authMgrMap_; // New protocol sharing - std::shared_ptr hiChainConnector_; - std::shared_ptr hiChainAuthConnector_; - std::shared_ptr deviceStateMgr_; - std::shared_ptr softbusConnector_; - std::shared_ptr abilityMgr_; - std::shared_ptr mineHiChainConnector_; - std::shared_ptr credentialMgr_; - std::shared_ptr commonEventManager_; - std::shared_ptr listener_; - std::atomic isCredentialType_ = false; - sptr dpInitedCallback_ = nullptr; - - // The session ID corresponding to the device ID, used only on the src side - std::map deviceId2SessionIdMap_; - std::map> sessionsMap_; // sessionId corresponds to the session object - std::map deviceIdMutexMap_; // Lock corresponding to the device ID - std::mutex mapMutex_; // sessionsMap_ lock - std::map sessionEnableCvMap_; // Condition variable corresponding to the session - std::map sessionEnableMutexMap_; // Lock corresponding to the session - std::map sessionEnableCvReadyMap_; // Condition variable ready flag - std::map logicalSessionId2TokenIdMap_; // The relationship between logicalSessionId and tokenId - std::map logicalSessionId2SessionIdMap_; // The relationship logicalSessionId and physical sessionId - std::map> configsMap_; // Import when authMgr is not initialized - - std::thread thread_; - std::atomic running_; - static std::condition_variable cleanEventCv_; - static std::mutex cleanEventMutex_; - static std::queue cleanEventQueue_; -}; - -using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_SERVICE_IMPL_H -- Gitee From a1eb2a0e1f6d9c18c1ee91bb3d4a6863ed4f5a72 Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Wed, 7 May 2025 16:36:01 +0800 Subject: [PATCH 4/4] =?UTF-8?q?=E5=90=8C=E6=AD=A5=E9=BB=84=E5=8C=BA?= =?UTF-8?q?=E4=B8=BB=E5=B9=B2=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- .../include/authentication/dm_auth_manager.h | 2 - .../include/authentication_v2/auth_manager.h | 1 + .../include/device_manager_service_impl.h | 2 + .../src/authentication/dm_auth_manager.cpp | 46 ++++--------------- .../src/authentication_v2/auth_manager.cpp | 38 +++++++-------- .../dm_auth_manager_base.cpp | 6 ++- .../src/device_manager_service_impl.cpp | 27 +++++++---- 7 files changed, 52 insertions(+), 70 deletions(-) diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index 5a9e031b8..0e07eb948 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -585,7 +585,6 @@ private: int32_t GetTaskTimeout(const char* taskName, int32_t taskTimeOut); void GetPeerUdidHash(int32_t sessionId, std::string &peerUdidHash); void DeleteOffLineTimer(int32_t sessionId); - bool IsAllowDeviceBind(); int32_t GetBinderInfo(); void SetProcessInfo(); int32_t GetCloseSessionDelaySeconds(std::string &delaySecondsStr); @@ -594,7 +593,6 @@ private: bool IsSourceMsgValid(); void ProcessReqPublicKey(); int32_t GetTokenIdByBundleName(int32_t userId, std::string &bundleName, int64_t &tokenId); - bool CheckBindLevel(const JsonItemObject &jsonObj, const std::string &key, int32_t &bindLevel); void RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback); void GetBindCallerInfo(); diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index e9928b6c2..c11839419 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -146,6 +146,7 @@ private: const std::string &deviceId, const std::string &extra); void ParseUltrasonicSide(const JsonObject &jsonObject); void GetBindCallerInfo(); + int32_t GetBindLevel(int32_t bindLevel); }; class AuthSrcManager : public AuthManager { diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 8371ea709..2767fc1b0 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -64,8 +64,10 @@ typedef struct DmBindCallerInfo { int32_t userId = -1; int32_t tokenId = -1; int32_t bindLevel = -1; + bool isSystemSA = false; std::string bundleName = ""; std::string hostPkgLabel = ""; + std::string processName = ""; } DmBindCallerInfo; class DeviceManagerServiceImpl : public IDeviceManagerServiceImpl { diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 78592272e..046ff0ac2 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -179,36 +179,9 @@ int32_t DmAuthManager::CheckAuthParamVaildExtra(const std::string &extra, const if (jsonObject.IsDiscarded() || !jsonObject.Contains(TAG_BIND_LEVEL)) { return DM_OK; } - int32_t bindLevel = INVALID_TYPE; - if (!CheckBindLevel(jsonObject, TAG_BIND_LEVEL, bindLevel)) { - LOGE("TAG_BIND_LEVEL is not integer string or int32."); - return ERR_DM_INPUT_PARA_INVALID; - } - if (static_cast(bindLevel) > APP || bindLevel < INVALID_TYPE) { - LOGE("bindlevel error %{public}d.", bindLevel); - return ERR_DM_INPUT_PARA_INVALID; - } - - if (static_cast(bindLevel) == USER && !IsAllowDeviceBind()) { - LOGE("not allowd user level bind bindlevel: %{public}d.", bindLevel); - return ERR_DM_INPUT_PARA_INVALID; - } return DM_OK; } -bool DmAuthManager::CheckBindLevel(const JsonItemObject &jsonObj, const std::string &key, int32_t &bindLevel) -{ - if (IsJsonValIntegerString(jsonObj, TAG_BIND_LEVEL)) { - bindLevel = std::atoi(jsonObj[TAG_BIND_LEVEL].Get().c_str()); - return true; - } - if (IsInt32(jsonObj, TAG_BIND_LEVEL)) { - bindLevel = jsonObj[TAG_BIND_LEVEL].Get(); - return true; - } - return false; -} - bool DmAuthManager::CheckHmlParamValid(JsonObject &jsonObject) { if (!IsString(jsonObject, PARAM_KEY_HML_ACTIONID)) { @@ -244,7 +217,7 @@ void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, authRequestContext_->addr = deviceId; authRequestContext_->dmVersion = DM_VERSION_5_0_5; authRequestContext_->localUserId = MultipleUserConnector::GetFirstForegroundUserId(); - authRequestContext_->localAccountId = MultipleUserConnector::GetFirstForegroundUserId(); + authRequestContext_->localAccountId = MultipleUserConnector::GetOhosAccountIdByUserId(authRequestContext_->localUserId); authRequestContext_->isOnline = false; authRequestContext_->authed = !authRequestContext_->bindType.empty(); @@ -274,7 +247,6 @@ void DmAuthManager::ParseJsonObject(JsonObject &jsonObject) if (IsString(jsonObject, TAG_APP_THUMBNAIL2)) { authRequestContext_->appThumbnail = jsonObject[TAG_APP_THUMBNAIL2].Get(); } - CheckBindLevel(jsonObject, TAG_BIND_LEVEL, authRequestContext_->bindLevel); authRequestContext_->closeSessionDelaySeconds = 0; if (IsString(jsonObject, PARAM_CLOSE_SESSION_DELAY_SECONDS)) { std::string delaySecondsStr = jsonObject[PARAM_CLOSE_SESSION_DELAY_SECONDS].Get(); @@ -2993,14 +2965,6 @@ int32_t DmAuthManager::GetTaskTimeout(const char* taskName, int32_t taskTimeOut) return taskTimeOut; } -bool DmAuthManager::IsAllowDeviceBind() -{ - if (AppManager::GetInstance().IsSystemSA()) { - return true; - } - return false; -} - int32_t DmAuthManager::GetBinderInfo() { CHECK_NULL_RETURN(authResponseContext_, ERR_DM_POINT_NULL); @@ -3143,6 +3107,14 @@ void DmAuthManager::RequestReCheckMsgDone() bool DmAuthManager::IsSinkMsgValid() { + LOGI("sink remoteVersion %{public}s, remoteDeviceId %{public}s, remoteUserId %{public}d, + remoteHostPkgName %{public}s, remoteBindLevel %{public}d", remoteVersion_.c_str(), + GetAnonyString(remoteDeviceId_).c_str(), authResponseContext_->remoteUserId, + authResponseContext_->hostPkgName.c_str(), authResponseContext_->bindLevel); + LOGI("src version %{public}s, deviceId %{public}s, userId %{public}d, hostPkgName %{public}s, bindLevel %{public}d", + authResponseContext_->edition.c_str(), GetAnonyString(authResponseContext_->localDeviceId).c_str(), + authResponseContext_->localUserId, authResponseContext_->bundleName.c_str(), + authResponseContext_->localBindLevel); if (authResponseContext_->edition != remoteVersion_ || authResponseContext_->localDeviceId != remoteDeviceId_ || authResponseContext_->localUserId != authResponseContext_->remoteUserId || diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 9f34cbfaf..e2799af27 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -106,14 +106,6 @@ std::string ParseExtraFromMap(const std::map &bindPara return ConvertMapToJsonString(bindParam); } -bool IsAllowDeviceBind() -{ - if (AppManager::GetInstance().IsSystemSA()) { - return true; - } - return false; -} - } // namespace bool AuthManager::IsHmlSessionType(const std::string &sessionType) @@ -511,18 +503,25 @@ bool CheckBindLevel(const JsonItemObject &jsonObj, const std::string &key, int32 return false; } -int32_t GetBindLevel(int32_t bindLevel) +int32_t AuthManager::GetBindLevel(int32_t bindLevel) { -#ifdef DEVICE_MANAGER_COMMON_FLAG - LOGI("device_manager_common is true!"); + LOGI("start."); std::string processName = ""; - int32_t ret = AppManager::GetInstance().GetCallerProcessName(processName); - LOGI("GetBindLevel processName = %{public}s", GetAnonyString(processName).c_str()); - if (ret == DM_OK && AuthManagerBase::CheckProcessNameInWhiteList(processName)) { + bool isSystemSA = false; + { + std::lock_guard lock(bindParamMutex_); + if (bindParam_.find("bindCallerProcessName") != bindParam_.end()) { + processName = bindParam_["bindCallerProcessName"]; + } + if (bindParam_.find("bindCallerIsSystemSA") != bindParam_.end()) { + isSystemSA = static_cast(std::atoi(bindParam_["bindCallerIsSystemSA"].c_str())); + } + } + LOGI("processName = %{public}s, isSystemSA %{public}d.", GetAnonyString(processName).c_str(), isSystemSA); + if (processName != "" && AuthManagerBase::CheckProcessNameInWhiteList(processName)) { return USER; } -#endif - if (IsAllowDeviceBind()) { + if (isSystemSA) { if (static_cast(bindLevel) == INVALIED_TYPE || static_cast(bindLevel) > APP || static_cast(bindLevel) < USER) { return USER; @@ -548,9 +547,6 @@ void AuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, context_->accesser.deviceName = context_->listener->GetLocalDisplayDeviceNameForPrivacy(); context_->accesser.deviceType = context_->softbusConnector->GetLocalDeviceTypeId(); context_->accesser.isOnline = false; - uint32_t callingTokenId = 0; - MultipleUserConnector::GetCallingTokenId(callingTokenId); - context_->accesser.tokenId = static_cast(callingTokenId); context_->accessee.deviceId = deviceId; context_->accessee.addr = deviceId; @@ -566,11 +562,11 @@ void AuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, context_->accesser.oldBindLevel = INVALIED_TYPE; CheckBindLevel(jsonObject, TAG_BIND_LEVEL, context_->accesser.oldBindLevel); context_->accesser.oldBindLevel = GetBindLevel(context_->accesser.oldBindLevel); - { std::lock_guard lock(bindParamMutex_); bindParam_["bindCallerOldBindLevel"] = std::to_string(context_->accesser.oldBindLevel); } + LOGI("bindCallerOldBindLevel %{public}d.", context_->accesser.oldBindLevel); } void AuthManager::InitAuthState(const std::string &pkgName, int32_t authType, @@ -1043,7 +1039,7 @@ void AuthManager::GetBindCallerInfo() context_->accesser.bindLevel = std::atoi(bindParam_["bindCallerBindLevel"].c_str()); } if (bindParam_.find("bindCallerBundleName") != bindParam_.end()) { - context_->accesser.bindLevel = bindParam_["bindCallerBundleName"]; + context_->accesser.bundleName = bindParam_["bindCallerBundleName"]; } if (bindParam_.find("bindCallerHostPkgLabel") != bindParam_.end()) { context_->pkgLabel = bindParam_["bindCallerHostPkgLabel"]; diff --git a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp index 6eb16828c..0c8e5cbc8 100644 --- a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp @@ -99,13 +99,15 @@ const int32_t PIN_AUTH_TIMEOUT = 60; const int32_t EVENT_TIMEOUT = 5000; // 5000 ms constexpr int32_t OPEN_PROCESS_NAME_WHITE_LIST_NUM = 1; -constexpr int32_t CLOSE_PROCESS_NAME_WHITE_LIST_NUM = 2; +constexpr int32_t CLOSE_PROCESS_NAME_WHITE_LIST_NUM = 4; constexpr const static char* OPEN_PROCESS_NAME_WHITE_LIST[OPEN_PROCESS_NAME_WHITE_LIST_NUM] = { "com.example.myapplication" }; constexpr const static char* CLOSE_PROCESS_NAME_WHITE_LIST[CLOSE_PROCESS_NAME_WHITE_LIST_NUM] = { "CollaborationFwk", - "gameservice_server" + "gameservice_server", + "wear_link_service", + "watch_system_service" }; int32_t AuthManagerBase::AuthenticateDevice(const std::string &pkgName, int32_t authType, diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index af1fa73ed..4c0ecebc4 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -1547,14 +1547,14 @@ void DeviceManagerServiceImpl::BindTargetImpl(uint64_t tokenId, const std::strin } else { if (targetId.deviceId.empty()) { LOGE("DeviceManagerServiceImpl::BindTarget failed, ParseConnectAddr failed."); - return ERR_DM_INPUT_PARA_INVALID; + return; } } // Created only at the source end. The same target device will not be created repeatedly with the new protocol. std::shared_ptr curSession = GetOrCreateSession(targetIdTmp.deviceId, bindParam); if (curSession == nullptr) { LOGE("Failed to create the session. Target deviceId: %{public}s.", targetIdTmp.deviceId.c_str()); - return ERR_DM_AUTH_OPEN_SESSION_FAILED; + return; } // Logical session random number @@ -1564,7 +1564,8 @@ void DeviceManagerServiceImpl::BindTargetImpl(uint64_t tokenId, const std::strin logicalSessionId = GenerateRandNum(sessionId); if (curSession->logicalSessionSet_.find(logicalSessionId) != curSession->logicalSessionSet_.end()) { LOGE("Failed to create the logical session."); - return ERR_DM_LOGIC_SESSION_CREATE_FAILED; + softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId); + return; } } @@ -1573,7 +1574,8 @@ void DeviceManagerServiceImpl::BindTargetImpl(uint64_t tokenId, const std::strin int32_t ret = InitAndRegisterAuthMgr(true, tokenId, curSession, logicalSessionId); if (ret != DM_OK) { LOGE("InitAndRegisterAuthMgr failed, ret %{public}d.", ret); - return ret; + softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId); + return; } curSession->logicalSessionSet_.insert(logicalSessionId); curSession->logicalSessionCnt_.fetch_add(1); @@ -1582,14 +1584,15 @@ void DeviceManagerServiceImpl::BindTargetImpl(uint64_t tokenId, const std::strin auto authMgr = GetAuthMgrByTokenId(tokenId); if (authMgr == nullptr) { - return ERR_DM_POINT_NULL; + CleanAuthMgrByLogicalSessionId(logicalSessionId); + return; } authMgr->SetBindTargetParams(targetId); if ((ret = authMgr->BindTarget(pkgName, targetIdTmp, bindParam, sessionId, logicalSessionId)) != DM_OK) { LOGE("authMgr BindTarget failed, ret %{public}d.", ret); CleanAuthMgrByLogicalSessionId(logicalSessionId); } - LOGI("DeviceManagerServiceImpl BindTargetImpl thread end, tokenId %{public}" PRID64".", tokenId); + LOGI("DeviceManagerServiceImpl BindTargetImpl thread end, tokenId %{public}" PRId64".", tokenId); return; } @@ -2460,6 +2463,8 @@ void DeviceManagerServiceImpl::GetBindCallerInfo(DmBindCallerInfo &bindCallerInf bool isSystemSA = false; std::string bundleName = ""; AppManager::GetInstance().GetCallerName(isSystemSA, bundleName); + std::string processName = ""; + AppManager::GetInstance().GetCallerProcessName(processName); int32_t bindLevel = static_cast(DmRole::DM_ROLE_FA); if (AppManager::GetInstance().IsSystemApp()) { bindLevel = static_cast(DmRole::DM_ROLE_FA); @@ -2476,8 +2481,12 @@ void DeviceManagerServiceImpl::GetBindCallerInfo(DmBindCallerInfo &bindCallerInf bindCallerInfo.bindLevel = bindLevel; bindCallerInfo.bundleName = bundleName; bindCallerInfo.hostPkgLabel = hostPkgLabel; - LOGI("userId %{public}d, tokenId %{public}d, bindLevel %{public}d, bundleName %{public}s, hostPkgLabel %{public}s", - userId, callingTokenId, bindLevel, GetAnonyString(bundleName).c_str(), GetAnonyString(hostPkgLabel).c_str()); + bindCallerInfo.processName = processName; + bindCallerInfo.isSystemSA = isSystemSA; + LOGI("userId %{public}d, tokenId %{public}d, bindLevel %{public}d, bundleName %{public}s, hostPkgLabel %{public}s, + processName %{public}s, isSystemSA %{public}d", userId, callingTokenId, bindLevel, + GetAnonyString(bundleName).c_str(), GetAnonyString(hostPkgLabel).c_str(), GetAnonyString(processName).c_str(), + isSystemSA); } std::string DeviceManagerServiceImpl::GetBundleLable(const std::string &bundleName) @@ -2526,6 +2535,8 @@ void DeviceManagerServiceImpl::SetBindCallerInfoToBindParam(const std::map