1 /*
2  * Copyright (c) 2022-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "dm_auth_manager.h"
17 
18 #include <mutex>
19 #include <string>
20 #include <unistd.h>
21 
22 #include "bundle_mgr_interface.h"
23 #include "iservice_registry.h"
24 #if defined(SUPPORT_SCREENLOCK)
25 #include "screenlock_manager.h"
26 #endif
27 #include "system_ability_definition.h"
28 
29 #include "auth_message_processor.h"
30 #include "common_event_support.h"
31 #include "dm_ability_manager.h"
32 #include "dm_anonymous.h"
33 #include "dm_config_manager.h"
34 #include "dm_constants.h"
35 #include "dm_crypto.h"
36 #include "dm_dialog_manager.h"
37 #include "dm_log.h"
38 #include "dm_radar_helper.h"
39 #include "dm_random.h"
40 #include "multiple_user_connector.h"
41 #include "nlohmann/json.hpp"
42 #include "parameter.h"
43 #include "show_confirm.h"
44 
45 namespace OHOS {
46 namespace DistributedHardware {
47 const int32_t AUTHENTICATE_TIMEOUT = 120;
48 const int32_t CONFIRM_TIMEOUT = 60;
49 const int32_t NEGOTIATE_TIMEOUT = 10;
50 const int32_t INPUT_TIMEOUT = 60;
51 const int32_t ADD_TIMEOUT = 10;
52 const int32_t WAIT_NEGOTIATE_TIMEOUT = 10;
53 const int32_t WAIT_REQUEST_TIMEOUT = 10;
54 const int32_t CLONE_AUTHENTICATE_TIMEOUT = 20;
55 const int32_t CLONE_CONFIRM_TIMEOUT = 10;
56 const int32_t CLONE_NEGOTIATE_TIMEOUT = 10;
57 const int32_t CLONE_ADD_TIMEOUT = 10;
58 const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT = 10;
59 const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 10;
60 const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT = 20;
61 const int32_t CANCEL_PIN_CODE_DISPLAY = 1;
62 const int32_t DEVICE_ID_HALF = 2;
63 const int32_t MAX_AUTH_TIMES = 3;
64 const int32_t MIN_PIN_TOKEN = 10000000;
65 const int32_t MAX_PIN_TOKEN = 90000000;
66 const int32_t MIN_PIN_CODE = 100000;
67 const int32_t MAX_PIN_CODE = 999999;
68 const int32_t DM_AUTH_TYPE_MAX = 5;
69 const int32_t DM_AUTH_TYPE_MIN = 0;
70 const int32_t AUTH_SESSION_SIDE_SERVER = 0;
71 const int32_t USLEEP_TIME_MS = 500000; // 500ms
72 const int32_t SYNC_DELETE_TIMEOUT = 60;
73 const int32_t AUTH_DEVICE_TIMEOUT = 10;
74 const int32_t SESSION_HEARTBEAT_TIMEOUT = 50;
75 const int32_t ALREADY_BIND = 1;
76 
77 // clone task timeout map
78 const std::map<std::string, int32_t> TASK_TIME_OUT_MAP = {
79     { std::string(AUTHENTICATE_TIMEOUT_TASK), CLONE_AUTHENTICATE_TIMEOUT },
80     { std::string(NEGOTIATE_TIMEOUT_TASK), CLONE_NEGOTIATE_TIMEOUT },
81     { std::string(CONFIRM_TIMEOUT_TASK), CLONE_CONFIRM_TIMEOUT },
82     { std::string(ADD_TIMEOUT_TASK), CLONE_ADD_TIMEOUT },
83     { std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), CLONE_WAIT_NEGOTIATE_TIMEOUT },
84     { std::string(WAIT_REQUEST_TIMEOUT_TASK), CLONE_WAIT_REQUEST_TIMEOUT },
85     { std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), CLONE_SESSION_HEARTBEAT_TIMEOUT }
86 };
87 
88 constexpr const char* APP_OPERATION_KEY = "appOperation";
89 constexpr const char* TARGET_PKG_NAME_KEY = "targetPkgName";
90 constexpr const char* CUSTOM_DESCRIPTION_KEY = "customDescription";
91 constexpr const char* CANCEL_DISPLAY_KEY = "cancelPinCodeDisplay";
92 constexpr const char* DM_VERSION_4_1_5_1 = "4.1.5.1";
93 constexpr const char* DM_VERSION_5_0_1 = "5.0.1";
94 constexpr const char* DM_VERSION_5_0_2 = "5.0.2";
95 std::mutex g_authFinishLock;
96 
DmAuthManager(std::shared_ptr<SoftbusConnector> softbusConnector,std::shared_ptr<HiChainConnector> hiChainConnector,std::shared_ptr<IDeviceManagerServiceListener> listener,std::shared_ptr<HiChainAuthConnector> hiChainAuthConnector)97 DmAuthManager::DmAuthManager(std::shared_ptr<SoftbusConnector> softbusConnector,
98                              std::shared_ptr<HiChainConnector> hiChainConnector,
99                              std::shared_ptr<IDeviceManagerServiceListener> listener,
100                              std::shared_ptr<HiChainAuthConnector> hiChainAuthConnector)
101     : softbusConnector_(softbusConnector), hiChainConnector_(hiChainConnector), listener_(listener),
102       hiChainAuthConnector_(hiChainAuthConnector)
103 {
104     LOGI("DmAuthManager constructor");
105     DmConfigManager &dmConfigManager = DmConfigManager::GetInstance();
106     dmConfigManager.GetAuthAdapter(authenticationMap_);
107     authUiStateMgr_ = std::make_shared<AuthUiStateManager>(listener_);
108     authenticationMap_[AUTH_TYPE_IMPORT_AUTH_CODE] = nullptr;
109     authenticationMap_[AUTH_TYPE_CRE] = nullptr;
110     dmVersion_ = DM_VERSION_5_0_2;
111 }
112 
~DmAuthManager()113 DmAuthManager::~DmAuthManager()
114 {
115     LOGI("DmAuthManager destructor");
116 }
117 
CheckAuthParamVaild(const std::string & pkgName,int32_t authType,const std::string & deviceId,const std::string & extra)118 int32_t DmAuthManager::CheckAuthParamVaild(const std::string &pkgName, int32_t authType,
119     const std::string &deviceId, const std::string &extra)
120 {
121     LOGI("DmAuthManager::CheckAuthParamVaild start.");
122     if (authType < DM_AUTH_TYPE_MIN || authType > DM_AUTH_TYPE_MAX) {
123         LOGE("CheckAuthParamVaild failed, authType is illegal.");
124         return ERR_DM_AUTH_FAILED;
125     }
126     if (pkgName.empty() || deviceId.empty()) {
127         LOGE("DmAuthManager::CheckAuthParamVaild failed, pkgName is %{public}s, deviceId is %{public}s, extra is"
128             "%{public}s.", pkgName.c_str(), GetAnonyString(deviceId).c_str(), extra.c_str());
129         return ERR_DM_INPUT_PARA_INVALID;
130     }
131     if (listener_ == nullptr || authUiStateMgr_ == nullptr) {
132         LOGE("DmAuthManager::CheckAuthParamVaild listener or authUiStateMgr is nullptr.");
133         return ERR_DM_INPUT_PARA_INVALID;
134     }
135 
136     if (!IsAuthTypeSupported(authType)) {
137         LOGE("DmAuthManager::CheckAuthParamVaild authType %{public}d not support.", authType);
138         listener_->OnAuthResult(pkgName, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT,
139             ERR_DM_UNSUPPORTED_AUTH_TYPE);
140         listener_->OnBindResult(pkgName, peerTargetId_, ERR_DM_UNSUPPORTED_AUTH_TYPE, STATUS_DM_AUTH_DEFAULT, "");
141         return ERR_DM_UNSUPPORTED_AUTH_TYPE;
142     }
143 
144     if (authRequestState_ != nullptr || authResponseState_ != nullptr) {
145         LOGE("DmAuthManager::CheckAuthParamVaild %{public}s is request authentication.", pkgName.c_str());
146         return ERR_DM_AUTH_BUSINESS_BUSY;
147     }
148 
149     if (!softbusConnector_->HaveDeviceInMap(deviceId)) {
150         LOGE("CheckAuthParamVaild failed, the discoveryDeviceInfoMap_ not have this device.");
151         listener_->OnAuthResult(pkgName, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID);
152         listener_->OnBindResult(pkgName, peerTargetId_, ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, "");
153         return ERR_DM_INPUT_PARA_INVALID;
154     }
155 
156     if ((authType == AUTH_TYPE_IMPORT_AUTH_CODE) && (!IsAuthCodeReady(pkgName))) {
157         LOGE("Auth code not exist.");
158         listener_->OnAuthResult(pkgName, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID);
159         listener_->OnBindResult(pkgName, peerTargetId_, ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, "");
160         return ERR_DM_INPUT_PARA_INVALID;
161     }
162     return DM_OK;
163 }
164 
GetAuthParam(const std::string & pkgName,int32_t authType,const std::string & deviceId,const std::string & extra)165 void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType,
166     const std::string &deviceId, const std::string &extra)
167 {
168     LOGI("Get auth param.");
169     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
170     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
171     std::string localUdid = static_cast<std::string>(localDeviceId);
172     authRequestContext_->hostPkgName = pkgName;
173     authRequestContext_->hostPkgLabel = GetBundleLable(pkgName);
174     authRequestContext_->authType = authType;
175     authRequestContext_->localDeviceName = softbusConnector_->GetLocalDeviceName();
176     authRequestContext_->localDeviceTypeId = softbusConnector_->GetLocalDeviceTypeId();
177     authRequestContext_->localDeviceId = localUdid;
178     authRequestContext_->deviceId = deviceId;
179     authRequestContext_->ip = deviceId;
180     authRequestContext_->dmVersion = DM_VERSION_5_0_2;
181     authRequestContext_->localAccountId = MultipleUserConnector::GetOhosAccountId();
182     MultipleUserConnector::SetSwitchOldAccountId(authRequestContext_->localAccountId);
183     authRequestContext_->localUserId = MultipleUserConnector::GetCurrentAccountUserID();
184     MultipleUserConnector::SetSwitchOldUserId(authRequestContext_->localUserId);
185     authRequestContext_->isOnline = false;
186     authRequestContext_->authed = !authRequestContext_->bindType.empty();
187     authRequestContext_->bindLevel = INVALIED_TYPE;
188     nlohmann::json jsonObject = nlohmann::json::parse(extra, nullptr, false);
189     if (!jsonObject.is_discarded()) {
190         if (IsString(jsonObject, TARGET_PKG_NAME_KEY)) {
191             authRequestContext_->targetPkgName = jsonObject[TARGET_PKG_NAME_KEY].get<std::string>();
192         }
193         if (IsString(jsonObject, APP_OPERATION_KEY)) {
194             authRequestContext_->appOperation = jsonObject[APP_OPERATION_KEY].get<std::string>();
195         }
196         if (IsString(jsonObject, CUSTOM_DESCRIPTION_KEY)) {
197             authRequestContext_->customDesc = jsonObject[CUSTOM_DESCRIPTION_KEY].get<std::string>();
198         }
199         if (IsString(jsonObject, APP_THUMBNAIL)) {
200             authRequestContext_->appThumbnail = jsonObject[APP_THUMBNAIL].get<std::string>();
201         }
202         if (IsInt64(jsonObject, TAG_TOKENID)) {
203             authRequestContext_->tokenId = jsonObject[TAG_TOKENID].get<int64_t>();
204         }
205         if (IsInt32(jsonObject, TAG_BIND_LEVEL)) {
206             authRequestContext_->bindLevel = jsonObject[TAG_BIND_LEVEL].get<int32_t>();
207         }
208     }
209     authRequestContext_->token = std::to_string(GenRandInt(MIN_PIN_TOKEN, MAX_PIN_TOKEN));
210 }
211 
InitAuthState(const std::string & pkgName,int32_t authType,const std::string & deviceId,const std::string & extra)212 void DmAuthManager::InitAuthState(const std::string &pkgName, int32_t authType,
213     const std::string &deviceId, const std::string &extra)
214 {
215     authPtr_ = authenticationMap_[authType];
216     if (timer_ == nullptr) {
217         timer_ = std::make_shared<DmTimer>();
218     }
219     timer_->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK),
220         GetTaskTimeout(AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT), [this] (std::string name) {
221             DmAuthManager::HandleAuthenticateTimeout(name);
222         });
223     authMessageProcessor_ = std::make_shared<AuthMessageProcessor>(shared_from_this());
224     authResponseContext_ = std::make_shared<DmAuthResponseContext>();
225     authRequestContext_ = std::make_shared<DmAuthRequestContext>();
226     GetAuthParam(pkgName, authType, deviceId, extra);
227     authMessageProcessor_->SetRequestContext(authRequestContext_);
228     authRequestState_ = std::make_shared<AuthRequestInitState>();
229     authRequestState_->SetAuthManager(shared_from_this());
230     authRequestState_->SetAuthContext(authRequestContext_);
231     if (!DmRadarHelper::GetInstance().ReportAuthStart(peerTargetId_.deviceId, pkgName)) {
232         LOGE("ReportAuthStart failed");
233     }
234     authRequestState_->Enter();
235     LOGI("DmAuthManager::AuthenticateDevice complete");
236 }
237 
AuthenticateDevice(const std::string & pkgName,int32_t authType,const std::string & deviceId,const std::string & extra)238 int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t authType,
239     const std::string &deviceId, const std::string &extra)
240 {
241     LOGI("DmAuthManager::AuthenticateDevice start auth type %{public}d.", authType);
242     SetAuthType(authType);
243     int32_t ret = CheckAuthParamVaild(pkgName, authType, deviceId, extra);
244     if (ret != DM_OK) {
245         LOGE("DmAuthManager::AuthenticateDevice failed, param is invaild.");
246         return ret;
247     }
248     isAuthenticateDevice_ = true;
249     if (authType == AUTH_TYPE_CRE) {
250         LOGI("DmAuthManager::AuthenticateDevice for credential type, joinLNN directly.");
251         softbusConnector_->JoinLnn(deviceId);
252         listener_->OnAuthResult(pkgName, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, DM_OK);
253         listener_->OnBindResult(pkgName, peerTargetId_, DM_OK, STATUS_DM_AUTH_DEFAULT, "");
254         return DM_OK;
255     }
256     InitAuthState(pkgName, authType, deviceId, extra);
257     return DM_OK;
258 }
259 
UnAuthenticateDevice(const std::string & pkgName,const std::string & networkId)260 int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const std::string &networkId)
261 {
262     if (pkgName.empty()) {
263         LOGE("Invalid parameter, pkgName is empty.");
264         return ERR_DM_FAILED;
265     }
266     std::string deviceUdid = "";
267     int32_t ret = SoftbusConnector::GetUdidByNetworkId(networkId.c_str(), deviceUdid);
268     if (ret != DM_OK) {
269         LOGE("UnAuthenticateDevice GetNodeKeyInfo failed");
270         return ret;
271     }
272     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
273     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
274     struct RadarInfo info = {
275         .funcName = "UnAuthenticateDevice",
276         .toCallPkg = HICHAINNAME,
277         .hostName = pkgName,
278         .peerUdid = deviceUdid,
279     };
280     if (!DmRadarHelper::GetInstance().ReportDeleteTrustRelation(info)) {
281         LOGE("ReportDeleteTrustRelation failed");
282     }
283     if (!DeviceProfileConnector::GetInstance().CheckPkgnameInAcl(pkgName, localDeviceId, deviceUdid)) {
284         LOGE("The pkgName %{public}s cannot unbind.", pkgName.c_str());
285         return ERR_DM_FAILED;
286     }
287     remoteDeviceId_ = deviceUdid;
288     SyncDeleteAcl(pkgName, deviceUdid);
289     return DM_OK;
290 }
291 
StopAuthenticateDevice(const std::string & pkgName)292 int32_t DmAuthManager::StopAuthenticateDevice(const std::string &pkgName)
293 {
294     if (pkgName.empty()) {
295         LOGE("Invalid parameter, pkgName is empty.");
296         return ERR_DM_FAILED;
297     }
298     if (((authRequestState_!= nullptr && authRequestContext_->hostPkgName == pkgName) ||
299         (authResponseContext_ != nullptr && authResponseContext_->hostPkgName == pkgName)) &&
300         isAuthenticateDevice_) {
301         LOGI("Stop previous AuthenticateDevice.");
302         authRequestContext_->reason = STOP_BIND;
303         authResponseContext_->state = authRequestState_->GetStateType();
304         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
305     }
306     return DM_OK;
307 }
308 
UnBindDevice(const std::string & pkgName,const std::string & udidHash)309 int32_t DmAuthManager::UnBindDevice(const std::string &pkgName, const std::string &udidHash)
310 {
311     if (pkgName.empty()) {
312         LOGE("Invalid parameter, pkgName is empty.");
313         return ERR_DM_FAILED;
314     }
315     remoteDeviceId_ = SoftbusConnector::GetDeviceUdidByUdidHash(udidHash);
316     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
317     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
318     if (!DeviceProfileConnector::GetInstance().CheckPkgnameInAcl(pkgName, localDeviceId, remoteDeviceId_)) {
319         LOGE("The pkgname %{public}s cannot unbind.", pkgName.c_str());
320         return ERR_DM_FAILED;
321     }
322     SyncDeleteAcl(pkgName, remoteDeviceId_);
323     return DM_OK;
324 }
325 
SyncDeleteAcl(const std::string & pkgName,const std::string & deviceId)326 void DmAuthManager::SyncDeleteAcl(const std::string &pkgName, const std::string &deviceId)
327 {
328     LOGI("SyncDeleteAcl start.");
329     authMessageProcessor_ = std::make_shared<AuthMessageProcessor>(shared_from_this());
330     authResponseContext_ = std::make_shared<DmAuthResponseContext>();
331     authRequestContext_ = std::make_shared<DmAuthRequestContext>();
332 
333     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
334     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
335     std::string localUdid = static_cast<std::string>(localDeviceId);
336     authRequestContext_->localDeviceId = localUdid;
337     authRequestContext_->hostPkgName = pkgName;
338     authRequestContext_->deviceId = deviceId;
339     authMessageProcessor_->SetRequestContext(authRequestContext_);
340     authRequestState_ = std::make_shared<AuthRequestDeleteInit>();
341     authRequestState_->SetAuthManager(shared_from_this());
342     authRequestState_->SetAuthContext(authRequestContext_);
343     authRequestState_->Enter();
344 }
345 
GetPeerUdidHash(int32_t sessionId,std::string & peerUdidHash)346 void DmAuthManager::GetPeerUdidHash(int32_t sessionId, std::string &peerUdidHash)
347 {
348     std::string peerUdid = "";
349     int32_t ret = softbusConnector_->GetSoftbusSession()->GetPeerDeviceId(sessionId, peerUdid);
350     if (ret != DM_OK) {
351         LOGE("DmAuthManager::GetPeerUdidHash failed.");
352         peerUdidHash = "";
353         return;
354     }
355     char udidHashTmp[DM_MAX_DEVICE_ID_LEN] = {0};
356     if (Crypto::GetUdidHash(peerUdid, reinterpret_cast<uint8_t *>(udidHashTmp)) != DM_OK) {
357         LOGE("get udidhash by udid: %{public}s failed.", GetAnonyString(peerUdid).c_str());
358         peerUdidHash = "";
359         return;
360     }
361     peerUdidHash = std::string(udidHashTmp);
362 }
363 
DeleteOffLineTimer(int32_t sessionId)364 void DmAuthManager::DeleteOffLineTimer(int32_t sessionId)
365 {
366     GetPeerUdidHash(sessionId, remoteUdidHash_);
367     if (remoteUdidHash_.empty()) {
368         LOGE("DeleteOffLineTimer remoteUdidHash is empty.");
369         return;
370     }
371     if (softbusConnector_ != nullptr) {
372         softbusConnector_->DeleteOffLineTimer(remoteUdidHash_);
373     }
374 }
375 
OnSessionOpened(int32_t sessionId,int32_t sessionSide,int32_t result)376 void DmAuthManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result)
377 {
378     LOGI("DmAuthManager::OnSessionOpened, sessionId = %{public}d and sessionSide = %{public}d result = %{public}d",
379          sessionId, sessionSide, result);
380     DeleteOffLineTimer(sessionId);
381     if (sessionSide == AUTH_SESSION_SIDE_SERVER) {
382         if (authResponseState_ == nullptr && authRequestState_ == nullptr) {
383             authMessageProcessor_ = std::make_shared<AuthMessageProcessor>(shared_from_this());
384             authResponseState_ = std::make_shared<AuthResponseInitState>();
385             authResponseState_->SetAuthManager(shared_from_this());
386             authResponseState_->Enter();
387             authResponseContext_ = std::make_shared<DmAuthResponseContext>();
388             if (timer_ == nullptr) {
389                 timer_ = std::make_shared<DmTimer>();
390             }
391             timer_->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK),
392                 GetTaskTimeout(AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT), [this] (std::string name) {
393                     DmAuthManager::HandleAuthenticateTimeout(name);
394                 });
395             timer_->StartTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK),
396                 GetTaskTimeout(WAIT_NEGOTIATE_TIMEOUT_TASK, WAIT_NEGOTIATE_TIMEOUT), [this] (std::string name) {
397                     DmAuthManager::HandleAuthenticateTimeout(name);
398                 });
399         } else {
400             std::shared_ptr<AuthMessageProcessor> authMessageProcessor =
401                 std::make_shared<AuthMessageProcessor>(shared_from_this());
402             std::shared_ptr<DmAuthResponseContext> authResponseContext = std::make_shared<DmAuthResponseContext>();
403             authResponseContext->reply = ERR_DM_AUTH_BUSINESS_BUSY;
404             authMessageProcessor->SetResponseContext(authResponseContext);
405             std::string message = authMessageProcessor->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE);
406             softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
407         }
408     } else {
409         if (authResponseState_ == nullptr && authRequestState_ != nullptr &&
410             authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT) {
411             authRequestContext_->sessionId = sessionId;
412             authMessageProcessor_->SetRequestContext(authRequestContext_);
413             authRequestState_->SetAuthContext(authRequestContext_);
414             authRequestState_->TransitionTo(std::make_shared<AuthRequestNegotiateState>());
415             struct RadarInfo info = { .funcName = "OnSessionOpened" };
416             info.channelId = sessionId;
417             if (!DmRadarHelper::GetInstance().ReportAuthSendRequest(info)) {
418                 LOGE("ReportAuthSendRequest failed");
419             }
420         } else {
421             softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId);
422             LOGE("DmAuthManager::OnSessionOpened but request state is wrong");
423         }
424     }
425 }
426 
OnSessionClosed(const int32_t sessionId)427 void DmAuthManager::OnSessionClosed(const int32_t sessionId)
428 {
429     LOGI("DmAuthManager::OnSessionClosed sessionId = %{public}d", sessionId);
430 }
431 
ProcessSourceMsg()432 void DmAuthManager::ProcessSourceMsg()
433 {
434     authRequestContext_ = authMessageProcessor_->GetRequestContext();
435     authRequestState_->SetAuthContext(authRequestContext_);
436     LOGI("OnDataReceived for source device, authResponseContext msgType = %{public}d, authRequestState stateType ="
437         "%{public}d", authResponseContext_->msgType, authRequestState_->GetStateType());
438 
439     switch (authResponseContext_->msgType) {
440         case MSG_TYPE_RESP_AUTH:
441         case MSG_TYPE_RESP_AUTH_EXT:
442             if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) {
443                 authRequestState_->TransitionTo(std::make_shared<AuthRequestReplyState>());
444             }
445             break;
446         case MSG_TYPE_RESP_NEGOTIATE:
447             if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE) {
448                 authRequestState_->TransitionTo(std::make_shared<AuthRequestNegotiateDoneState>());
449             }
450             break;
451         case MSG_TYPE_REQ_AUTH_TERMINATE:
452             if (authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) {
453                 isFinishOfLocal_ = false;
454                 authResponseContext_->state = authRequestState_->GetStateType();
455                 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
456             }
457             break;
458         case MSG_TYPE_RESP_PUBLICKEY:
459             if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_CREDENTIAL) {
460                 authRequestState_->TransitionTo(std::make_shared<AuthRequestCredentialDone>());
461             }
462             break;
463         case MSG_TYPE_REQ_SYNC_DELETE_DONE:
464             if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_SYNCDELETE) {
465                 if (timer_ != nullptr) {
466                     timer_->DeleteTimer(std::string(SYNC_DELETE_TIMEOUT_TASK));
467                 }
468                 isFinishOfLocal_ = false;
469                 authRequestState_->TransitionTo(std::make_shared<AuthRequestSyncDeleteAclNone>());
470             }
471             break;
472         default:
473             break;
474     }
475 }
476 
ProcessSinkMsg()477 void DmAuthManager::ProcessSinkMsg()
478 {
479     authResponseState_->SetAuthContext(authResponseContext_);
480     LOGI("OnDataReceived for sink device, authResponseContext msgType = %{public}d, authResponseState stateType ="
481         "%{public}d", authResponseContext_->msgType, authResponseState_->GetStateType());
482 
483     switch (authResponseContext_->msgType) {
484         case MSG_TYPE_NEGOTIATE:
485             if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_INIT) {
486                 if (timer_ != nullptr) {
487                     timer_->DeleteTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK));
488                 }
489                 authResponseState_->TransitionTo(std::make_shared<AuthResponseNegotiateState>());
490             }
491             break;
492         case MSG_TYPE_REQ_AUTH:
493             if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_NEGOTIATE) {
494                 if (timer_ != nullptr) {
495                     timer_->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK));
496                 }
497                 authResponseState_->TransitionTo(std::make_shared<AuthResponseConfirmState>());
498             }
499             break;
500         case MSG_TYPE_REQ_AUTH_TERMINATE:
501             if (authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) {
502                 isFinishOfLocal_ = false;
503                 authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
504             }
505             break;
506         case MSG_TYPE_REQ_PUBLICKEY:
507             if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW) {
508                 authResponseState_->TransitionTo(std::make_shared<AuthResponseCredential>());
509             }
510             break;
511         case MSG_TYPE_REQ_SYNC_DELETE:
512             if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_INIT) {
513                 authResponseState_->TransitionTo(std::make_shared<AuthResponseSyncDeleteAcl>());
514             }
515             break;
516         case MSG_TYPE_REQ_SYNC_DELETE_DONE:
517             if (authResponseState_->GetStateType() == AuthState::AUTH_REQUEST_SYNCDELETE) {
518                 if (timer_ != nullptr) {
519                     timer_->DeleteTimer(std::string(SYNC_DELETE_TIMEOUT_TASK));
520                 }
521                 isFinishOfLocal_ = false;
522                 authResponseState_->TransitionTo(std::make_shared<AuthResponseSyncDeleteAclNone>());
523             }
524             break;
525         default:
526             break;
527     }
528 }
529 
OnDataReceived(const int32_t sessionId,const std::string message)530 void DmAuthManager::OnDataReceived(const int32_t sessionId, const std::string message)
531 {
532     if (authResponseContext_ == nullptr || authMessageProcessor_ == nullptr) {
533         LOGE("OnDataReceived failed, authResponseContext or authMessageProcessor_ is nullptr.");
534         return;
535     }
536 
537     authResponseContext_->sessionId = sessionId;
538     authMessageProcessor_->SetResponseContext(authResponseContext_);
539     int32_t ret = authMessageProcessor_->ParseMessage(message);
540     if (ret != DM_OK) {
541         LOGE("OnDataReceived failed, parse input message error.");
542         return;
543     }
544 
545     if ((authRequestState_ != nullptr) && (authResponseState_ == nullptr)) {
546         // source device auth process
547         ProcessSourceMsg();
548     } else if ((authResponseState_ != nullptr) && (authRequestState_ == nullptr)) {
549         // sink device auth process
550         ProcessSinkMsg();
551     } else {
552         LOGE("DmAuthManager::OnDataReceived failed, authRequestState_ or authResponseState_ is invalid.");
553     }
554 }
555 
OnGroupCreated(int64_t requestId,const std::string & groupId)556 void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId)
557 {
558     if (authResponseContext_ == nullptr) {
559         LOGE("failed to OnGroupCreated because authResponseContext_ is nullptr");
560         return;
561     }
562     if (authResponseState_ == nullptr) {
563         LOGE("DmAuthManager::AuthenticateDevice end");
564         return;
565     }
566     LOGI("DmAuthManager::OnGroupCreated start group id %{public}s", GetAnonyString(groupId).c_str());
567     if (groupId == "{}") {
568         authResponseContext_->reply = ERR_DM_CREATE_GROUP_FAILED;
569         authMessageProcessor_->SetResponseContext(authResponseContext_);
570         std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH);
571         softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
572         return;
573     }
574 
575     int32_t pinCode = -1;
576     if (authResponseContext_->isShowDialog) {
577         pinCode = GeneratePincode();
578     } else {
579         GetAuthCode(authResponseContext_->hostPkgName, pinCode);
580     }
581     nlohmann::json jsonObj;
582     jsonObj[PIN_TOKEN] = authResponseContext_->token;
583     jsonObj[QR_CODE_KEY] = GenerateGroupName();
584     jsonObj[NFC_CODE_KEY] = GenerateGroupName();
585     authResponseContext_->authToken = jsonObj.dump();
586     LOGI("DmAuthManager::OnGroupCreated start group id %{public}s", GetAnonyString(groupId).c_str());
587     authResponseContext_->groupId = groupId;
588     authResponseContext_->code = pinCode;
589     authMessageProcessor_->SetResponseContext(authResponseContext_);
590     std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH);
591     softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
592     authResponseContext_->isFinish = true;
593     authResponseState_->TransitionTo(std::make_shared<AuthResponseShowState>());
594 }
595 
OnMemberJoin(int64_t requestId,int32_t status)596 void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status)
597 {
598     isAddingMember_ = false;
599     if (authResponseContext_ == nullptr || authUiStateMgr_ == nullptr) {
600         LOGE("failed to OnMemberJoin because authResponseContext_ or authUiStateMgr is nullptr");
601         return;
602     }
603     LOGI("DmAuthManager OnMemberJoin start authTimes %{public}d", authTimes_);
604     if ((authRequestState_ != nullptr) && (authResponseState_ == nullptr)) {
605         authTimes_++;
606         timer_->DeleteTimer(std::string(ADD_TIMEOUT_TASK));
607         if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) {
608             HandleMemberJoinImportAuthCode(requestId, status);
609             return;
610         }
611         CHECK_NULL_VOID(timer_);
612         if (status != DM_OK || authResponseContext_->requestId != requestId) {
613             if (authRequestState_ != nullptr && authTimes_ >= MAX_AUTH_TIMES) {
614                 authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN;
615                 authRequestContext_->reason = ERR_DM_BIND_PIN_CODE_ERROR;
616                 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
617             } else {
618                 timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK),
619                     GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) {
620                         DmAuthManager::HandleAuthenticateTimeout(name);
621                     });
622                 authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR);
623             }
624         } else {
625             authRequestState_->TransitionTo(std::make_shared<AuthRequestNetworkState>());
626             timer_->DeleteTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK));
627         }
628     } else if ((authResponseState_ != nullptr) && (authRequestState_ == nullptr)) {
629         if (status == DM_OK && authResponseContext_->requestId == requestId &&
630             authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW) {
631             authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW);
632         } else {
633             if (++authTimes_ >= MAX_AUTH_TIMES) {
634                 authResponseContext_->isFinish = false;
635             }
636         }
637     } else {
638         LOGE("DmAuthManager::OnMemberJoin failed, authRequestState_ or authResponseState_ is invalid.");
639     }
640 }
641 
HandleMemberJoinImportAuthCode(const int64_t requestId,const int32_t status)642 void DmAuthManager::HandleMemberJoinImportAuthCode(const int64_t requestId, const int32_t status)
643 {
644     if (status != DM_OK || authResponseContext_->requestId != requestId) {
645         authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN;
646         authRequestContext_->reason = ERR_DM_AUTH_CODE_INCORRECT;
647         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
648     } else {
649         authRequestState_->TransitionTo(std::make_shared<AuthRequestNetworkState>());
650     }
651 }
652 
HandleAuthenticateTimeout(std::string name)653 void DmAuthManager::HandleAuthenticateTimeout(std::string name)
654 {
655     LOGI("DmAuthManager::HandleAuthenticateTimeout start timer name %{public}s", name.c_str());
656     if (authRequestState_ != nullptr && authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) {
657         if (authResponseContext_ == nullptr) {
658             authResponseContext_ = std::make_shared<DmAuthResponseContext>();
659         }
660         authResponseContext_->state = authRequestState_->GetStateType();
661         authRequestContext_->reason = ERR_DM_TIME_OUT;
662         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
663     }
664 
665     if (authResponseState_ != nullptr && authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) {
666         authResponseContext_->state = authResponseState_->GetStateType();
667         authResponseContext_->reply = ERR_DM_TIME_OUT;
668         authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
669     }
670     LOGI("DmAuthManager::HandleAuthenticateTimeout start complete");
671 }
672 
EstablishAuthChannel(const std::string & deviceId)673 int32_t DmAuthManager::EstablishAuthChannel(const std::string &deviceId)
674 {
675     int32_t sessionId = softbusConnector_->GetSoftbusSession()->OpenAuthSession(deviceId);
676     struct RadarInfo info = {
677         .funcName = "EstablishAuthChannel",
678         .stageRes = (sessionId > 0) ?
679             static_cast<int32_t>(StageRes::STAGE_IDLE) : static_cast<int32_t>(StageRes::STAGE_FAIL),
680         .bizState = (sessionId > 0) ?
681             static_cast<int32_t>(BizState::BIZ_STATE_START) : static_cast<int32_t>(BizState::BIZ_STATE_END),
682         .localSessName = DM_SESSION_NAME,
683         .peerSessName = DM_SESSION_NAME,
684         .isTrust = static_cast<int32_t>(TrustStatus::NOT_TRUST),
685         .commServ = static_cast<int32_t>(CommServ::USE_SOFTBUS),
686         .peerUdid = peerTargetId_.deviceId,
687         .channelId = sessionId,
688         .errCode = sessionId,
689     };
690     if (!DmRadarHelper::GetInstance().ReportAuthOpenSession(info)) {
691         LOGE("ReportAuthOpenSession failed");
692     }
693     if (sessionId < 0) {
694         LOGE("OpenAuthSession failed, stop the authentication");
695         if (authResponseContext_ == nullptr) {
696             authResponseContext_ = std::make_shared<DmAuthResponseContext>();
697         }
698         authResponseContext_->state = AuthState::AUTH_REQUEST_NEGOTIATE;
699         authRequestContext_->reason = sessionId;
700         if (authRequestState_ != nullptr) {
701             authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
702         }
703     }
704     return DM_OK;
705 }
706 
StartNegotiate(const int32_t & sessionId)707 void DmAuthManager::StartNegotiate(const int32_t &sessionId)
708 {
709     if (authResponseContext_ == nullptr) {
710         LOGE("DmAuthManager::StartNegotiate error, authResponseContext_ is nullptr");
711         return;
712     }
713     LOGI("DmAuthManager::StartNegotiate sessionId %{public}d.", sessionId);
714     authResponseContext_->localDeviceId = authRequestContext_->localDeviceId;
715     authResponseContext_->reply = ERR_DM_AUTH_REJECT;
716     authResponseContext_->authType = authRequestContext_->authType;
717     authResponseContext_->deviceId = authRequestContext_->deviceId;
718     authResponseContext_->accountGroupIdHash = GetAccountGroupIdHash();
719     authResponseContext_->hostPkgName = authRequestContext_->hostPkgName;
720     authResponseContext_->hostPkgLabel = authRequestContext_->hostPkgLabel;
721     authResponseContext_->tokenId = authRequestContext_->tokenId;
722     authResponseContext_->bindLevel = authRequestContext_->bindLevel;
723     authResponseContext_->bindType = authRequestContext_->bindType;
724     authResponseContext_->isOnline = authRequestContext_->isOnline;
725     authResponseContext_->authed = authRequestContext_->authed;
726     authResponseContext_->dmVersion = "";
727     authResponseContext_->localAccountId = authRequestContext_->localAccountId;
728     authResponseContext_->localUserId = authRequestContext_->localUserId;
729     authResponseContext_->isIdenticalAccount = false;
730     authResponseContext_->edition = DM_VERSION_5_0_2;
731     authMessageProcessor_->SetResponseContext(authResponseContext_);
732     std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_NEGOTIATE);
733     softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
734     if (timer_ != nullptr) {
735         timer_->StartTimer(std::string(NEGOTIATE_TIMEOUT_TASK),
736             GetTaskTimeout(NEGOTIATE_TIMEOUT_TASK, NEGOTIATE_TIMEOUT), [this] (std::string name) {
737                 DmAuthManager::HandleAuthenticateTimeout(name);
738             });
739     }
740 }
741 
AbilityNegotiate()742 void DmAuthManager::AbilityNegotiate()
743 {
744     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
745     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
746     bool ret = hiChainConnector_->IsDevicesInP2PGroup(authResponseContext_->localDeviceId, localDeviceId);
747     if (ret) {
748         LOGE("DmAuthManager::EstablishAuthChannel device is in group");
749         if (!DeviceProfileConnector::GetInstance().CheckSinkDevIdInAclForDevBind(authResponseContext_->hostPkgName,
750             authResponseContext_->localDeviceId)) {
751             CompatiblePutAcl();
752         }
753         authResponseContext_->reply = ERR_DM_AUTH_PEER_REJECT;
754         if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && !importAuthCode_.empty()) {
755             authResponseContext_->importAuthCode = Crypto::Sha256(importAuthCode_);
756         }
757     } else {
758         authResponseContext_->reply = ERR_DM_AUTH_REJECT;
759     }
760     authResponseContext_->localDeviceId = localDeviceId;
761 
762     if (!IsAuthTypeSupported(authResponseContext_->authType)) {
763         LOGE("DmAuthManager::AuthenticateDevice authType %{public}d not support.", authResponseContext_->authType);
764         authResponseContext_->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE;
765     } else {
766         authPtr_ = authenticationMap_[authResponseContext_->authType];
767     }
768 
769     if (IsAuthCodeReady(authResponseContext_->hostPkgName)) {
770         authResponseContext_->isAuthCodeReady = true;
771     } else {
772         authResponseContext_->isAuthCodeReady = false;
773     }
774 }
775 
RespNegotiate(const int32_t & sessionId)776 void DmAuthManager::RespNegotiate(const int32_t &sessionId)
777 {
778     if (authResponseContext_ == nullptr || authRequestState_ != nullptr) {
779         LOGE("failed to RespNegotiate because authResponseContext_ is nullptr");
780         return;
781     }
782     LOGI("DmAuthManager::RespNegotiate sessionid %{public}d", sessionId);
783     remoteDeviceId_ = authResponseContext_->localDeviceId;
784     authResponseContext_->networkId = softbusConnector_->GetLocalDeviceNetworkId();
785     authResponseContext_->targetDeviceName = softbusConnector_->GetLocalDeviceName();
786     remoteVersion_ = ConvertSrcVersion(authResponseContext_->dmVersion, authResponseContext_->edition);
787     NegotiateRespMsg(remoteVersion_);
788     if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) &&
789         (static_cast<uint32_t>(authResponseContext_->bindLevel) >= DEVICE &&
790         static_cast<uint32_t>(authResponseContext_->bindLevel) <= APP)) {
791         ProcRespNegotiateExt(sessionId);
792         timer_->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK),
793             GetTaskTimeout(WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), [this] (std::string name) {
794                 DmAuthManager::HandleAuthenticateTimeout(name);
795             });
796     } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) ||
797         authResponseContext_->bindLevel == INVALIED_TYPE) {
798         ProcRespNegotiate(sessionId);
799         timer_->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK),
800             GetTaskTimeout(WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), [this] (std::string name) {
801                 DmAuthManager::HandleAuthenticateTimeout(name);
802             });
803     } else {
804         ProcIncompatible(sessionId);
805     }
806 }
807 
NegotiateRespMsg(const std::string & version)808 void DmAuthManager::NegotiateRespMsg(const std::string &version)
809 {
810     if (version == DM_VERSION_5_0_1) {
811         authResponseContext_->dmVersion = DM_VERSION_5_0_1;
812     } else if (version < DM_VERSION_5_0_1) {
813         authResponseContext_->dmVersion = "";
814         authResponseContext_->bindLevel = INVALIED_TYPE;
815     } else if (version > DM_VERSION_5_0_1) {
816         authResponseContext_->dmVersion = dmVersion_;
817     }
818 }
819 
SendAuthRequest(const int32_t & sessionId)820 void DmAuthManager::SendAuthRequest(const int32_t &sessionId)
821 {
822     LOGI("DmAuthManager::SendAuthRequest sessionId %{public}d.", sessionId);
823     if (authResponseContext_ == nullptr) {
824         LOGE("failed to SendAuthRequest because authResponseContext_ is nullptr");
825         return;
826     }
827     if (authResponseContext_->reply == ERR_DM_VERSION_INCOMPATIBLE) {
828         LOGE("The peer device version is not supported");
829         authRequestContext_->reason = authResponseContext_->reply;
830         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
831         return;
832     }
833     remoteDeviceId_ = authResponseContext_->localDeviceId;
834     remoteVersion_ = ConvertSinkVersion(authResponseContext_->dmVersion);
835     if (timer_ != nullptr) {
836         timer_->DeleteTimer(std::string(NEGOTIATE_TIMEOUT_TASK));
837     }
838     if (authResponseContext_->cryptoSupport) {
839         isCryptoSupport_ = true;
840     }
841     LOGI("SendAuthRequest dmversion %{public}s, level %{public}d",
842         authResponseContext_->dmVersion.c_str(), authResponseContext_->bindLevel);
843     if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) &&
844         (static_cast<uint32_t>(authResponseContext_->bindLevel) >= DEVICE &&
845         static_cast<uint32_t>(authResponseContext_->bindLevel) <= APP)) {
846         ProcessAuthRequestExt(sessionId);
847     } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) ||
848         authResponseContext_->bindLevel == INVALIED_TYPE) {
849         ProcessAuthRequest(sessionId);
850     } else {
851         LOGE("Invalied bind mode.");
852     }
853 }
854 
ProcessAuthRequest(const int32_t & sessionId)855 void DmAuthManager::ProcessAuthRequest(const int32_t &sessionId)
856 {
857     LOGI("ProcessAuthRequest start.");
858     if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE &&
859         !authResponseContext_->importAuthCode.empty() && !importAuthCode_.empty()) {
860         if (authResponseContext_->importAuthCode != Crypto::Sha256(importAuthCode_)) {
861             SetReasonAndFinish(ERR_DM_AUTH_CODE_INCORRECT, AuthState::AUTH_REQUEST_FINISH);
862             return;
863         }
864     }
865 
866     if (authResponseContext_->isOnline && softbusConnector_->CheckIsOnline(remoteDeviceId_)) {
867         authResponseContext_->isOnline = true;
868     } else {
869         authResponseContext_->isOnline = false;
870     }
871     if (CheckTrustState() != DM_OK) {
872         LOGI("CheckTrustState end.");
873         return;
874     }
875 
876     std::vector<std::string> messageList = authMessageProcessor_->CreateAuthRequestMessage();
877     for (auto msg : messageList) {
878         softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg);
879     }
880 
881     listener_->OnAuthResult(authResponseContext_->hostPkgName, peerTargetId_.deviceId,
882         authRequestContext_->token, STATUS_DM_SHOW_AUTHORIZE_UI, DM_OK);
883     listener_->OnBindResult(authResponseContext_->hostPkgName, peerTargetId_, DM_OK, STATUS_DM_SHOW_AUTHORIZE_UI, "");
884     if (timer_ != nullptr) {
885         timer_->StartTimer(std::string(CONFIRM_TIMEOUT_TASK),
886             GetTaskTimeout(CONFIRM_TIMEOUT_TASK, CONFIRM_TIMEOUT), [this] (std::string name) {
887                 DmAuthManager::HandleAuthenticateTimeout(name);
888             });
889     }
890 }
891 
GetAuthRequestContext()892 void DmAuthManager::GetAuthRequestContext()
893 {
894     char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0};
895     Crypto::GetUdidHash(authResponseContext_->localDeviceId, reinterpret_cast<uint8_t *>(deviceIdHash));
896     authRequestContext_->deviceId = static_cast<std::string>(deviceIdHash);
897     authResponseContext_->deviceId = authResponseContext_->localDeviceId;
898     authResponseContext_->localDeviceId = authRequestContext_->localDeviceId;
899     authRequestContext_->remoteAccountId = authResponseContext_->localAccountId;
900     authResponseContext_->remoteAccountId = authRequestContext_->remoteAccountId;
901     authResponseContext_->localAccountId = authRequestContext_->localAccountId;
902     authRequestContext_->remoteUserId = authResponseContext_->localUserId;
903     if (authResponseContext_->isOnline && softbusConnector_->CheckIsOnline(remoteDeviceId_)) {
904         authResponseContext_->isOnline = true;
905     } else {
906         authResponseContext_->isOnline = false;
907     }
908     bool haveCredential = hiChainAuthConnector_->QueryCredential(remoteDeviceId_, authRequestContext_->localUserId);
909     if (authResponseContext_->haveCredential && haveCredential) {
910         authResponseContext_->haveCredential = true;
911     } else {
912         authResponseContext_->haveCredential = false;
913     }
914 }
915 
ProcessAuthRequestExt(const int32_t & sessionId)916 void DmAuthManager::ProcessAuthRequestExt(const int32_t &sessionId)
917 {
918     LOGI("ProcessAuthRequestExt start.");
919     if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE &&
920         !authResponseContext_->importAuthCode.empty() && !importAuthCode_.empty()) {
921         if (authResponseContext_->importAuthCode != Crypto::Sha256(importAuthCode_)) {
922             SetReasonAndFinish(ERR_DM_AUTH_CODE_INCORRECT, AuthState::AUTH_REQUEST_FINISH);
923             return;
924         }
925     }
926 
927     GetAuthRequestContext();
928     std::vector<int32_t> bindType =
929         DeviceProfileConnector::GetInstance().SyncAclByBindType(authResponseContext_->hostPkgName,
930         authResponseContext_->bindType, authResponseContext_->localDeviceId, authResponseContext_->deviceId);
931     authResponseContext_->authed = !bindType.empty();
932     if (authResponseContext_->isOnline && authResponseContext_->authed &&
933         authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE &&
934         (authResponseContext_->importAuthCode.empty() || importAuthCode_.empty())) {
935         SetReasonAndFinish(ERR_DM_AUTH_CODE_INCORRECT, AuthState::AUTH_REQUEST_FINISH);
936         return;
937     }
938     authResponseContext_->bindType = bindType;
939     if (IsAuthFinish()) {
940         return;
941     }
942 
943     std::vector<std::string> messageList = authMessageProcessor_->CreateAuthRequestMessage();
944     for (auto msg : messageList) {
945         softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg);
946     }
947     listener_->OnAuthResult(authResponseContext_->hostPkgName, peerTargetId_.deviceId,
948         authRequestContext_->token, STATUS_DM_SHOW_AUTHORIZE_UI, DM_OK);
949     listener_->OnBindResult(authResponseContext_->hostPkgName, peerTargetId_, DM_OK, STATUS_DM_SHOW_AUTHORIZE_UI, "");
950     if (timer_ != nullptr) {
951         timer_->StartTimer(std::string(CONFIRM_TIMEOUT_TASK),
952             GetTaskTimeout(CONFIRM_TIMEOUT_TASK, CONFIRM_TIMEOUT), [this] (std::string name) {
953                 DmAuthManager::HandleAuthenticateTimeout(name);
954             });
955     }
956 }
957 
IsAuthFinish()958 bool DmAuthManager::IsAuthFinish()
959 {
960     if (authResponseContext_->reply == ERR_DM_UNSUPPORTED_AUTH_TYPE) {
961         listener_->OnAuthResult(authResponseContext_->hostPkgName, peerTargetId_.deviceId,
962             authRequestContext_->token, AuthState::AUTH_REQUEST_NEGOTIATE_DONE, ERR_DM_UNSUPPORTED_AUTH_TYPE);
963         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
964         return true;
965     }
966 
967     if (authResponseContext_->isOnline && authResponseContext_->authed) {
968         authRequestContext_->reason = DM_OK;
969         authResponseContext_->reply = DM_OK;
970         authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
971         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
972         return true;
973     }
974 
975     if ((authResponseContext_->isIdenticalAccount && !authResponseContext_->authed) ||
976         (authResponseContext_->authed && !authResponseContext_->isOnline)) {
977         softbusConnector_->JoinLnn(authRequestContext_->deviceId);
978         authRequestContext_->reason = DM_OK;
979         authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
980         authResponseContext_->reply = DM_OK;
981         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
982         return true;
983     }
984 
985     if (authResponseContext_->reply == ERR_DM_UNSUPPORTED_AUTH_TYPE ||
986         (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE &&
987         authResponseContext_->isAuthCodeReady == false)) {
988         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
989         return true;
990     }
991     return false;
992 }
993 
ConfirmProcess(const int32_t & action)994 int32_t DmAuthManager::ConfirmProcess(const int32_t &action)
995 {
996     LOGI("ConfirmProcess start.");
997     if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH || action_ == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) {
998         authResponseContext_->reply = USER_OPERATION_TYPE_ALLOW_AUTH;
999     } else {
1000         authResponseContext_->reply = action_;
1001     }
1002 
1003     if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH &&
1004         authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_CONFIRM) {
1005         authResponseState_->TransitionTo(std::make_shared<AuthResponseGroupState>());
1006     } else {
1007         authMessageProcessor_->SetResponseContext(authResponseContext_);
1008         std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH);
1009         softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
1010     }
1011     return DM_OK;
1012 }
1013 
ConfirmProcessExt(const int32_t & action)1014 int32_t DmAuthManager::ConfirmProcessExt(const int32_t &action)
1015 {
1016     LOGI("ConfirmProcessExt start.");
1017     authResponseContext_->confirmOperation = action;
1018     if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH || action_ == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) {
1019         authResponseContext_->reply = USER_OPERATION_TYPE_ALLOW_AUTH;
1020     } else {
1021         authResponseContext_->reply = USER_OPERATION_TYPE_CANCEL_AUTH;
1022     }
1023     authMessageProcessor_->SetResponseContext(authResponseContext_);
1024     if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH &&
1025         authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_CONFIRM) {
1026         if (!authResponseContext_->isShowDialog) {
1027             GetAuthCode(authResponseContext_->hostPkgName, authResponseContext_->code);
1028         } else {
1029             authResponseContext_->code = GeneratePincode();
1030         }
1031         authResponseContext_->requestId = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE);
1032         authResponseState_->TransitionTo(std::make_shared<AuthResponseShowState>());
1033     }
1034     authMessageProcessor_->SetResponseContext(authResponseContext_);
1035     std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH_EXT);
1036     softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
1037     return DM_OK;
1038 }
1039 
StartAuthProcess(const int32_t & action)1040 int32_t DmAuthManager::StartAuthProcess(const int32_t &action)
1041 {
1042     if (authResponseContext_ == nullptr) {
1043         LOGE("failed to StartAuthProcess because authResponseContext_ is nullptr");
1044         return ERR_DM_AUTH_NOT_START;
1045     }
1046     LOGI("DmAuthManager::StartAuthProcess");
1047     action_ = action;
1048     struct RadarInfo info = {
1049         .funcName = "StartAuthProcess",
1050         .stageRes = (action_ == USER_OPERATION_TYPE_CANCEL_AUTH) ?
1051             static_cast<int32_t>(StageRes::STAGE_CANCEL) : static_cast<int32_t>(StageRes::STAGE_SUCC),
1052         .bizState = (action_ == USER_OPERATION_TYPE_CANCEL_AUTH) ?
1053             static_cast<int32_t>(BizState::BIZ_STATE_END) : static_cast<int32_t>(BizState::BIZ_STATE_START),
1054         .errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_AUTH_REJECT),
1055     };
1056     if (!DmRadarHelper::GetInstance().ReportAuthConfirmBox(info)) {
1057         LOGE("ReportAuthConfirmBox failed");
1058     }
1059     if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) &&
1060         (static_cast<uint32_t>(authResponseContext_->bindLevel) >= DEVICE &&
1061         static_cast<uint32_t>(authResponseContext_->bindLevel) <= APP)) {
1062         return ConfirmProcessExt(action);
1063     } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) ||
1064         authResponseContext_->bindLevel == INVALIED_TYPE) {
1065         return ConfirmProcess(action);
1066     } else {
1067         LOGE("Invalied bind mode.");
1068     }
1069     return DM_OK;
1070 }
1071 
StartRespAuthProcess()1072 void DmAuthManager::StartRespAuthProcess()
1073 {
1074     if (authResponseContext_ == nullptr) {
1075         LOGE("failed to StartRespAuthProcess because authResponseContext_ is nullptr");
1076         return;
1077     }
1078     LOGI("DmAuthManager::StartRespAuthProcess sessionId = %{public}d", authResponseContext_->sessionId);
1079     if (timer_ != nullptr) {
1080         timer_->DeleteTimer(std::string(CONFIRM_TIMEOUT_TASK));
1081     }
1082     if (authResponseContext_->groupName[CHECK_AUTH_ALWAYS_POS] == AUTH_ALWAYS) {
1083         action_ = USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS;
1084     } else if (authResponseContext_->groupName[CHECK_AUTH_ALWAYS_POS] == AUTH_ONCE) {
1085         action_ = USER_OPERATION_TYPE_ALLOW_AUTH;
1086     }
1087     if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH) {
1088         if (timer_ != nullptr) {
1089             timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK),
1090                 GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) {
1091                     DmAuthManager::HandleAuthenticateTimeout(name);
1092                 });
1093             timer_->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK),
1094                 GetTaskTimeout(SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), [this] (std::string name) {
1095                     DmAuthManager::HandleSessionHeartbeat(name);
1096                 });
1097         }
1098         listener_->OnAuthResult(authRequestContext_->hostPkgName, peerTargetId_.deviceId,
1099             authRequestContext_->token, STATUS_DM_SHOW_PIN_INPUT_UI, DM_OK);
1100         listener_->OnBindResult(authRequestContext_->hostPkgName, peerTargetId_, DM_OK,
1101             STATUS_DM_SHOW_PIN_INPUT_UI, "");
1102         authRequestState_->TransitionTo(std::make_shared<AuthRequestJoinState>());
1103     } else {
1104         LOGE("do not accept");
1105         authResponseContext_->state = AuthState::AUTH_REQUEST_REPLY;
1106         authRequestContext_->reason = ERR_DM_AUTH_PEER_REJECT;
1107         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
1108     }
1109 }
1110 
CreateGroup()1111 int32_t DmAuthManager::CreateGroup()
1112 {
1113     if (authResponseContext_ == nullptr) {
1114         LOGE("failed to CreateGroup because authResponseContext_ is nullptr");
1115         return ERR_DM_FAILED;
1116     }
1117     LOGI("DmAuthManager::CreateGroup start");
1118     authResponseContext_->groupName = GenerateGroupName();
1119     authResponseContext_->requestId = GenRandLongLong(MIN_REQUEST_ID, MAX_REQUEST_ID);
1120     hiChainConnector_->CreateGroup(authResponseContext_->requestId, authResponseContext_->groupName);
1121     return DM_OK;
1122 }
1123 
AddMember(int32_t pinCode)1124 int32_t DmAuthManager::AddMember(int32_t pinCode)
1125 {
1126     if (authResponseContext_ == nullptr) {
1127         LOGE("failed to AddMember because authResponseContext_ is nullptr");
1128         return ERR_DM_FAILED;
1129     }
1130     LOGI("DmAuthManager::AddMember start group id %{public}s", GetAnonyString(authResponseContext_->groupId).c_str());
1131     if (timer_ != nullptr) {
1132         timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK));
1133     }
1134     nlohmann::json jsonObject;
1135     jsonObject[TAG_GROUP_ID] = authResponseContext_->groupId;
1136     jsonObject[TAG_GROUP_NAME] = authResponseContext_->groupName;
1137     jsonObject[PIN_CODE_KEY] = pinCode;
1138     jsonObject[TAG_REQUEST_ID] = authResponseContext_->requestId;
1139     jsonObject[TAG_DEVICE_ID] = authResponseContext_->deviceId;
1140     std::string connectInfo = jsonObject.dump();
1141     if (timer_ != nullptr) {
1142         timer_->StartTimer(std::string(ADD_TIMEOUT_TASK),
1143             GetTaskTimeout(ADD_TIMEOUT_TASK, ADD_TIMEOUT), [this] (std::string name) {
1144                 DmAuthManager::HandleAuthenticateTimeout(name);
1145             });
1146     }
1147     if (authUiStateMgr_ == nullptr) {
1148         LOGE("DmAuthManager::AddMember authUiStateMgr is null.");
1149         return ERR_DM_FAILED;
1150     }
1151     if (isAddingMember_) {
1152         LOGE("DmAuthManager::AddMember doing add member.");
1153         authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_DOING_AUTH);
1154         return ERR_DM_FAILED;
1155     }
1156     isAddingMember_ = true;
1157     int32_t ret = hiChainConnector_->AddMember(authRequestContext_->ip, connectInfo);
1158     struct RadarInfo info = {
1159         .funcName = "AddMember",
1160         .stageRes = (ret == 0) ?
1161             static_cast<int32_t>(StageRes::STAGE_IDLE) : static_cast<int32_t>(StageRes::STAGE_FAIL),
1162         .peerUdid = authResponseContext_ == nullptr ? "" : authResponseContext_->deviceId,
1163         .errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_ADD_GROUP_FAILED),
1164     };
1165     if (!DmRadarHelper::GetInstance().ReportAuthAddGroup(info)) {
1166         LOGE("ReportAuthAddGroup failed");
1167     }
1168     if (ret != 0) {
1169         LOGE("DmAuthManager::AddMember failed, ret: %{public}d", ret);
1170         isAddingMember_ = false;
1171         return ERR_DM_ADD_GROUP_FAILED;
1172     }
1173     return DM_OK;
1174 }
1175 
GetConnectAddr(std::string deviceId)1176 std::string DmAuthManager::GetConnectAddr(std::string deviceId)
1177 {
1178     std::string connectAddr;
1179     if (softbusConnector_->GetConnectAddr(deviceId, connectAddr) == nullptr) {
1180         LOGE("DmAuthManager::GetConnectAddr error");
1181     }
1182     return connectAddr;
1183 }
1184 
JoinNetwork()1185 int32_t DmAuthManager::JoinNetwork()
1186 {
1187     if (authResponseContext_ == nullptr) {
1188         LOGE("failed to JoinNeWork because authResponseContext_ is nullptr");
1189         return ERR_DM_FAILED;
1190     }
1191     LOGI("DmAuthManager JoinNetwork start");
1192     if (timer_ != nullptr) {
1193         timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK));
1194     }
1195     authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
1196     authResponseContext_->isFinish = true;
1197     authRequestContext_->reason = DM_OK;
1198     authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
1199     return DM_OK;
1200 }
1201 
SinkAuthenticateFinish()1202 void DmAuthManager::SinkAuthenticateFinish()
1203 {
1204     LOGI("DmAuthManager::SinkAuthenticateFinish, isFinishOfLocal: %{public}d", isFinishOfLocal_);
1205     if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_FINISH && authPtr_ != nullptr) {
1206         authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW);
1207         authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_CONFIRM_SHOW);
1208     }
1209     if (isFinishOfLocal_) {
1210         authMessageProcessor_->SetResponseContext(authResponseContext_);
1211         std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE);
1212         softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
1213     }
1214     authResponseState_ = nullptr;
1215 }
1216 
SrcAuthenticateFinish()1217 void DmAuthManager::SrcAuthenticateFinish()
1218 {
1219     LOGI("DmAuthManager::SrcAuthenticateFinish, isFinishOfLocal: %{public}d", isFinishOfLocal_);
1220     if (isFinishOfLocal_) {
1221         authMessageProcessor_->SetResponseContext(authResponseContext_);
1222         std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE);
1223         softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
1224     } else {
1225         authRequestContext_->reason = authResponseContext_->reply;
1226     }
1227     if ((authResponseContext_->state == AuthState::AUTH_REQUEST_JOIN ||
1228         authResponseContext_->state == AuthState::AUTH_REQUEST_FINISH) && authPtr_ != nullptr) {
1229         authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT);
1230     }
1231     usleep(USLEEP_TIME_MS); // 500ms
1232     listener_->OnAuthResult(authRequestContext_->hostPkgName, peerTargetId_.deviceId,
1233         authRequestContext_->token, authResponseContext_->state, authRequestContext_->reason);
1234     listener_->OnBindResult(authRequestContext_->hostPkgName, peerTargetId_, authRequestContext_->reason,
1235         authResponseContext_->state, GenerateBindResultContent());
1236     softbusConnector_->GetSoftbusSession()->CloseAuthSession(authRequestContext_->sessionId);
1237     authRequestContext_ = nullptr;
1238     authRequestState_ = nullptr;
1239     authTimes_ = 0;
1240 }
1241 
AuthenticateFinish()1242 void DmAuthManager::AuthenticateFinish()
1243 {
1244     authType_ = AUTH_TYPE_UNKNOW;
1245     std::lock_guard<std::mutex> autoLock(g_authFinishLock);
1246     if (authResponseContext_ == nullptr || authUiStateMgr_ == nullptr) {
1247         LOGE("failed to AuthenticateFinish because authResponseContext_ or authUiStateMgr is nullptr");
1248         return;
1249     }
1250     LOGI("DmAuthManager::AuthenticateFinish start");
1251     isAddingMember_ = false;
1252     isAuthenticateDevice_ = false;
1253     isAuthDevice_ = false;
1254     if (authResponseContext_->isFinish) {
1255         CompatiblePutAcl();
1256     }
1257     if (DeviceProfileConnector::GetInstance().GetTrustNumber(remoteDeviceId_) >= 1 &&
1258         CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) &&
1259         authResponseContext_->bindLevel == INVALIED_TYPE && softbusConnector_->CheckIsOnline(remoteDeviceId_) &&
1260         authResponseContext_->isFinish) {
1261         softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_);
1262     }
1263 
1264     DeleteAuthCode();
1265     if (authResponseState_ != nullptr) {
1266         SinkAuthenticateFinish();
1267     } else if (authRequestState_ != nullptr) {
1268         SrcAuthenticateFinish();
1269     }
1270     if (timer_ != nullptr) {
1271         timer_->DeleteAll();
1272     }
1273     isFinishOfLocal_ = true;
1274     authResponseContext_ = nullptr;
1275     authMessageProcessor_ = nullptr;
1276     authPtr_ = nullptr;
1277     LOGI("DmAuthManager::AuthenticateFinish complete");
1278 }
1279 
CancelDisplay()1280 void DmAuthManager::CancelDisplay()
1281 {
1282     LOGI("DmAuthManager::CancelDisplay start");
1283     nlohmann::json jsonObj;
1284     jsonObj[CANCEL_DISPLAY_KEY] = CANCEL_PIN_CODE_DISPLAY;
1285     std::string paramJson = jsonObj.dump();
1286     std::string pkgName = "com.ohos.devicemanagerui";
1287     listener_->OnUiCall(pkgName, paramJson);
1288 }
1289 
RegisterUiStateCallback(const std::string pkgName)1290 int32_t DmAuthManager::RegisterUiStateCallback(const std::string pkgName)
1291 {
1292     LOGI("DmAuthManager::RegisterUiStateCallback start");
1293     if (authUiStateMgr_ == nullptr) {
1294         LOGE("DmAuthManager::RegisterUiStateCallback authUiStateMgr_ is null.");
1295         return ERR_DM_FAILED;
1296     }
1297     authUiStateMgr_->RegisterUiStateCallback(pkgName);
1298     return DM_OK;
1299 }
1300 
UnRegisterUiStateCallback(const std::string pkgName)1301 int32_t DmAuthManager::UnRegisterUiStateCallback(const std::string pkgName)
1302 {
1303     LOGI("DmAuthManager::UnRegisterUiStateCallback start");
1304     if (authUiStateMgr_ == nullptr) {
1305         LOGE("DmAuthManager::UnRegisterUiStateCallback authUiStateMgr_ is null.");
1306         return ERR_DM_FAILED;
1307     }
1308     authUiStateMgr_->UnRegisterUiStateCallback(pkgName);
1309     return DM_OK;
1310 }
1311 
GeneratePincode()1312 int32_t DmAuthManager::GeneratePincode()
1313 {
1314     return GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE);
1315 }
1316 
GenerateGroupName()1317 std::string DmAuthManager::GenerateGroupName()
1318 {
1319     if (authResponseContext_ == nullptr) {
1320         LOGE("failed to GenerateGroupName because authResponseContext_ is nullptr.");
1321         return "";
1322     }
1323     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
1324     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
1325     std::string sLocalDeviceId = localDeviceId;
1326     uint32_t interceptLength = sLocalDeviceId.size() / DEVICE_ID_HALF;
1327     std::string groupName = "";
1328     if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) {
1329         groupName += AUTH_ALWAYS;
1330     } else {
1331         groupName += AUTH_ONCE;
1332     }
1333     groupName += authResponseContext_->targetPkgName + sLocalDeviceId.substr(0, interceptLength)
1334         + authResponseContext_->localDeviceId.substr(0, interceptLength);
1335     return groupName;
1336 }
1337 
GetIsCryptoSupport()1338 bool DmAuthManager::GetIsCryptoSupport()
1339 {
1340     if (authResponseState_ == nullptr) {
1341         return false;
1342     }
1343     if (authRequestState_ == nullptr) {
1344         if (authResponseState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) {
1345             return false;
1346         }
1347     } else {
1348         if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE ||
1349             authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) {
1350             return false;
1351         }
1352     }
1353 
1354     return isCryptoSupport_;
1355 }
1356 
SetAuthRequestState(std::shared_ptr<AuthRequestState> authRequestState)1357 int32_t DmAuthManager::SetAuthRequestState(std::shared_ptr<AuthRequestState> authRequestState)
1358 {
1359     if (authRequestState == nullptr) {
1360         LOGE("authRequestState is nullptr.");
1361         return ERR_DM_INPUT_PARA_INVALID;
1362     }
1363     authRequestState_ = authRequestState;
1364     return DM_OK;
1365 }
1366 
SetAuthResponseState(std::shared_ptr<AuthResponseState> authResponseState)1367 int32_t DmAuthManager::SetAuthResponseState(std::shared_ptr<AuthResponseState> authResponseState)
1368 {
1369     if (authResponseState == nullptr) {
1370         LOGE("authResponseState is nullptr.");
1371         return ERR_DM_INPUT_PARA_INVALID;
1372     }
1373     authResponseState_ = authResponseState;
1374     return DM_OK;
1375 }
1376 
GetPinCode(int32_t & code)1377 int32_t DmAuthManager::GetPinCode(int32_t &code)
1378 {
1379     if (authResponseContext_ == nullptr) {
1380         LOGE("failed to GetPinCode because authResponseContext_ is nullptr");
1381         code = ERR_DM_AUTH_NOT_START;
1382         return ERR_DM_FAILED;
1383     }
1384     LOGI("ShowConfigDialog start add member pin code.");
1385     code = authResponseContext_->code;
1386     return DM_OK;
1387 }
1388 
ShowConfigDialog()1389 void DmAuthManager::ShowConfigDialog()
1390 {
1391     if (authResponseContext_ == nullptr) {
1392         LOGE("failed to ShowConfigDialog because authResponseContext_ is nullptr");
1393         return;
1394     }
1395     if (!authResponseContext_->isShowDialog) {
1396         LOGI("start auth process");
1397         StartAuthProcess(USER_OPERATION_TYPE_ALLOW_AUTH);
1398         return;
1399     }
1400     LOGI("ShowConfigDialog start");
1401     nlohmann::json jsonObj;
1402     jsonObj[TAG_AUTH_TYPE] = AUTH_TYPE_PIN;
1403     jsonObj[TAG_TOKEN] = authResponseContext_->token;
1404     jsonObj[TARGET_PKG_NAME_KEY] = authResponseContext_->targetPkgName;
1405     jsonObj[TAG_CUSTOM_DESCRIPTION] = authResponseContext_->customDesc;
1406     jsonObj[TAG_APP_OPERATION] = authResponseContext_->appOperation;
1407     jsonObj[TAG_LOCAL_DEVICE_TYPE] = authResponseContext_->deviceTypeId;
1408     jsonObj[TAG_REQUESTER] = authResponseContext_->deviceName;
1409     jsonObj[TAG_HOST_PKGLABEL] = authResponseContext_->hostPkgLabel;
1410     const std::string params = jsonObj.dump();
1411     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
1412     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
1413     std::string localUdid = static_cast<std::string>(localDeviceId);
1414     DeviceProfileConnector::GetInstance().SyncAclByBindType(authResponseContext_->hostPkgName,
1415         authResponseContext_->bindType, localUdid, remoteDeviceId_);
1416     DmDialogManager::GetInstance().ShowConfirmDialog(params);
1417     struct RadarInfo info = {
1418         .funcName = "ShowConfigDialog",
1419         .stageRes = static_cast<int32_t>(StageRes::STAGE_IDLE),
1420     };
1421     if (!DmRadarHelper::GetInstance().ReportAuthPullAuthBox(info)) {
1422         LOGE("ReportAuthPullAuthBox failed");
1423     }
1424     LOGI("ShowConfigDialog end");
1425 }
1426 
ShowAuthInfoDialog()1427 void DmAuthManager::ShowAuthInfoDialog()
1428 {
1429     if (authResponseContext_ == nullptr) {
1430         LOGE("failed to ShowAuthInfoDialog because authResponseContext_ is nullptr");
1431         return;
1432     }
1433     LOGI("DmAuthManager::ShowAuthInfoDialog start");
1434     if (!authResponseContext_->isShowDialog) {
1435         LOGI("not show dialog.");
1436         return;
1437     }
1438     struct RadarInfo info = {
1439         .funcName = "ShowAuthInfoDialog",
1440         .stageRes = static_cast<int32_t>(StageRes::STAGE_SUCC),
1441     };
1442     if (!DmRadarHelper::GetInstance().ReportAuthPullPinBox(info)) {
1443         LOGE("ReportAuthPullPinBox failed");
1444     }
1445     nlohmann::json jsonObj;
1446     jsonObj[PIN_CODE_KEY] = authResponseContext_->code;
1447     std::string authParam = jsonObj.dump();
1448     DmDialogManager::GetInstance().ShowPinDialog(std::to_string(authResponseContext_->code));
1449 }
1450 
ShowStartAuthDialog()1451 void DmAuthManager::ShowStartAuthDialog()
1452 {
1453     if (authResponseContext_ == nullptr) {
1454         LOGE("failed to ShowStartAuthDialog because authResponseContext_ is nullptr");
1455         return;
1456     }
1457     if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) {
1458         LOGI("Add member start");
1459         int32_t pinCode = -1;
1460         if (GetAuthCode(authResponseContext_->hostPkgName, pinCode) != DM_OK) {
1461             LOGE("failed to get auth code");
1462             return;
1463         }
1464         if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) &&
1465             (static_cast<uint32_t>(authResponseContext_->bindLevel) >= DEVICE &&
1466             static_cast<uint32_t>(authResponseContext_->bindLevel)  <= APP)) {
1467             AuthDevice(pinCode);
1468         } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) ||
1469             authResponseContext_->bindLevel == INVALIED_TYPE) {
1470             AddMember(pinCode);
1471         } else {
1472             LOGE("Invalied bind mode.");
1473         }
1474         return;
1475     }
1476     if (IsScreenLocked()) {
1477         LOGE("ShowStartAuthDialog screen is locked.");
1478         SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL, STATUS_DM_AUTH_DEFAULT);
1479         return;
1480     }
1481     LOGI("DmAuthManager::ShowStartAuthDialog start");
1482     DmDialogManager::GetInstance().ShowInputDialog(authResponseContext_->targetDeviceName);
1483 }
1484 
ProcessPincode(int32_t pinCode)1485 int32_t DmAuthManager::ProcessPincode(int32_t pinCode)
1486 {
1487     if (authResponseContext_ == nullptr) {
1488         LOGE("failed to ProcessPincode because authResponseContext_ is nullptr");
1489         return ERR_DM_FAILED;
1490     }
1491     if (timer_ != nullptr) {
1492         timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK));
1493     }
1494     if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) &&
1495         (static_cast<uint32_t>(authResponseContext_->bindLevel) >= DEVICE &&
1496         static_cast<uint32_t>(authResponseContext_->bindLevel) <= APP)) {
1497         return AuthDevice(pinCode);
1498     } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) ||
1499         authResponseContext_->bindLevel == INVALIED_TYPE) {
1500         return AddMember(pinCode);
1501     } else {
1502         LOGE("Invalied bind mode.");
1503     }
1504     return ERR_DM_FAILED;
1505 }
1506 
AuthDevice(int32_t pinCode)1507 int32_t DmAuthManager::AuthDevice(int32_t pinCode)
1508 {
1509     LOGI("DmAuthManager::AuthDevice start.");
1510     if (isAuthDevice_) {
1511         LOGE("DmAuthManager::AuthDevice doing auth device.");
1512         authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_DOING_AUTH);
1513         return ERR_DM_FAILED;
1514     }
1515     isAuthDevice_ = true;
1516     int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID();
1517     if (timer_ != nullptr) {
1518         timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK));
1519         timer_->StartTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK), AUTH_DEVICE_TIMEOUT,
1520             [this] (std::string name) {
1521                 DmAuthManager::HandleAuthenticateTimeout(name);
1522             });
1523     }
1524     if (hiChainAuthConnector_->AuthDevice(pinCode, osAccountId, remoteDeviceId_,
1525         authResponseContext_->requestId) != DM_OK) {
1526         LOGE("DmAuthManager::AuthDevice failed.");
1527         isAuthDevice_ = false;
1528         if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) {
1529             HandleMemberJoinImportAuthCode(authResponseContext_->requestId, ERR_DM_FAILED);
1530             return ERR_DM_FAILED;
1531         }
1532     }
1533     return DM_OK;
1534 }
1535 
OnUserOperation(int32_t action,const std::string & params)1536 int32_t DmAuthManager::OnUserOperation(int32_t action, const std::string &params)
1537 {
1538     if (authResponseContext_ == nullptr) {
1539         LOGE("Authenticate is not start");
1540         return ERR_DM_AUTH_NOT_START;
1541     }
1542     struct RadarInfo info = {
1543         .funcName = "OnUserOperation",
1544         .stageRes = static_cast<int32_t>(StageRes::STAGE_CANCEL),
1545         .bizState = static_cast<int32_t>(BizState::BIZ_STATE_END),
1546     };
1547     switch (action) {
1548         case USER_OPERATION_TYPE_ALLOW_AUTH:
1549         case USER_OPERATION_TYPE_CANCEL_AUTH:
1550         case USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS:
1551             StartAuthProcess(action);
1552             break;
1553         case USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT:
1554             SetReasonAndFinish(ERR_DM_TIME_OUT, STATUS_DM_AUTH_DEFAULT);
1555             info.errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_TIME_OUT);
1556             if (!DmRadarHelper::GetInstance().ReportAuthConfirmBox(info)) {
1557                 LOGE("ReportAuthConfirmBox failed");
1558             }
1559             break;
1560         case USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY:
1561             SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY, STATUS_DM_AUTH_DEFAULT);
1562             info.errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY);
1563             if (!DmRadarHelper::GetInstance().ReportAuthInputPinBox(info)) {
1564                 LOGE("ReportAuthInputPinBox failed");
1565             }
1566             break;
1567         case USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT:
1568             SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL_ERROR, STATUS_DM_AUTH_DEFAULT);
1569             info.errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_BIND_USER_CANCEL_ERROR);
1570             if (!DmRadarHelper::GetInstance().ReportAuthInputPinBox(info)) {
1571                 LOGE("ReportAuthInputPinBox failed");
1572             }
1573             break;
1574         case USER_OPERATION_TYPE_DONE_PINCODE_INPUT:
1575             ProcessPincode(std::atoi(params.c_str()));
1576             info.stageRes = static_cast<int32_t>(StageRes::STAGE_SUCC);
1577             if (!DmRadarHelper::GetInstance().ReportAuthInputPinBox(info)) {
1578                 LOGE("ReportAuthInputPinBox failed");
1579             }
1580             break;
1581         default:
1582             LOGE("this action id not support");
1583             break;
1584     }
1585     return DM_OK;
1586 }
1587 
SetPageId(int32_t pageId)1588 int32_t DmAuthManager::SetPageId(int32_t pageId)
1589 {
1590     if (authResponseContext_ == nullptr) {
1591         LOGE("Authenticate is not start");
1592         return ERR_DM_AUTH_NOT_START;
1593     }
1594     authResponseContext_->pageId = pageId;
1595     return DM_OK;
1596 }
1597 
SetReasonAndFinish(int32_t reason,int32_t state)1598 int32_t DmAuthManager::SetReasonAndFinish(int32_t reason, int32_t state)
1599 {
1600     if (authResponseContext_ == nullptr) {
1601         LOGE("Authenticate is not start");
1602         return ERR_DM_AUTH_NOT_START;
1603     }
1604     authResponseContext_->state = state;
1605     authResponseContext_->reply = reason;
1606     if (authRequestState_ != nullptr && authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) {
1607         authRequestContext_->reason = reason;
1608         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
1609     } else if (authResponseState_ != nullptr && authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) {
1610         authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
1611     }
1612     return DM_OK;
1613 }
1614 
IsIdenticalAccount()1615 bool DmAuthManager::IsIdenticalAccount()
1616 {
1617     nlohmann::json jsonObj;
1618     jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP;
1619     std::string queryParams = jsonObj.dump();
1620 
1621     int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID();
1622     if (osAccountUserId < 0) {
1623         LOGE("get current process account user id failed");
1624         return false;
1625     }
1626     std::vector<GroupInfo> groupList;
1627     if (!hiChainConnector_->GetGroupInfo(osAccountUserId, queryParams, groupList)) {
1628         return false;
1629     }
1630     if (authResponseContext_ == nullptr) {
1631         LOGE("authResponseContext_ is nullptr.");
1632         return false;
1633     }
1634     if (authResponseContext_->accountGroupIdHash == OLD_VERSION_ACCOUNT) {
1635         LOGI("The old version.");
1636         return true;
1637     }
1638     nlohmann::json jsonPeerGroupIdObj = nlohmann::json::parse(authResponseContext_->accountGroupIdHash,
1639         nullptr, false);
1640     if (jsonPeerGroupIdObj.is_discarded()) {
1641         LOGE("accountGroupIdHash string not a json type.");
1642         return false;
1643     }
1644     for (auto &groupInfo : groupList) {
1645         for (nlohmann::json::iterator it = jsonPeerGroupIdObj.begin(); it != jsonPeerGroupIdObj.end(); ++it) {
1646             if ((*it) == Crypto::GetGroupIdHash(groupInfo.groupId)) {
1647                 LOGI("Is identical Account.");
1648                 return true;
1649             }
1650         }
1651     }
1652     return false;
1653 }
1654 
GetAccountGroupIdHash()1655 std::string DmAuthManager::GetAccountGroupIdHash()
1656 {
1657     nlohmann::json jsonObj;
1658     jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP;
1659     std::string queryParams = jsonObj.dump();
1660 
1661     int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID();
1662     if (osAccountUserId < 0) {
1663         LOGE("get current process account user id failed");
1664         return "";
1665     }
1666     std::vector<GroupInfo> groupList;
1667     if (!hiChainConnector_->GetGroupInfo(osAccountUserId, queryParams, groupList)) {
1668         return "";
1669     }
1670     nlohmann::json jsonAccountObj;
1671     for (auto &groupInfo : groupList) {
1672         jsonAccountObj.push_back(Crypto::GetGroupIdHash(groupInfo.groupId));
1673     }
1674     return jsonAccountObj.dump();
1675 }
1676 
ImportAuthCode(const std::string & pkgName,const std::string & authCode)1677 int32_t DmAuthManager::ImportAuthCode(const std::string &pkgName, const std::string &authCode)
1678 {
1679     if (authCode.empty() || pkgName.empty()) {
1680         LOGE("ImportAuthCode failed, authCode or pkgName is empty");
1681         return ERR_DM_INPUT_PARA_INVALID;
1682     }
1683     importAuthCode_ = authCode;
1684     importPkgName_ = pkgName;
1685     return DM_OK;
1686 }
1687 
BindTarget(const std::string & pkgName,const PeerTargetId & targetId,const std::map<std::string,std::string> & bindParam)1688 int32_t DmAuthManager::BindTarget(const std::string &pkgName, const PeerTargetId &targetId,
1689     const std::map<std::string, std::string> &bindParam)
1690 {
1691     struct RadarInfo info = {
1692         .funcName = "AuthenticateDevice",
1693         .stageRes = static_cast<int32_t>(StageRes::STAGE_SUCC),
1694         .bizState = static_cast<int32_t>(BizState::BIZ_STATE_END),
1695     };
1696     if (!DmRadarHelper::GetInstance().ReportDiscoverUserRes(info)) {
1697         LOGE("ReportDiscoverUserRes failed");
1698     }
1699     if (pkgName.empty()) {
1700         LOGE("DmAuthManager::BindTarget failed, pkgName is empty.");
1701         return ERR_DM_INPUT_PARA_INVALID;
1702     }
1703     int32_t authType = -1;
1704     if (ParseAuthType(bindParam, authType) != DM_OK) {
1705         LOGE("DmAuthManager::BindTarget failed, key: %{public}s error.", PARAM_KEY_AUTH_TYPE);
1706         return ERR_DM_INPUT_PARA_INVALID;
1707     }
1708     peerTargetId_ = targetId;
1709     std::string deviceId = "";
1710     std::string addrType;
1711     if (bindParam.count(PARAM_KEY_CONN_ADDR_TYPE) != 0) {
1712         addrType = bindParam.at(PARAM_KEY_CONN_ADDR_TYPE);
1713     }
1714     if (ParseConnectAddr(targetId, deviceId, addrType) == DM_OK) {
1715         return AuthenticateDevice(pkgName, authType, deviceId, ParseExtraFromMap(bindParam));
1716     } else if (!targetId.deviceId.empty()) {
1717         return AuthenticateDevice(pkgName, authType, targetId.deviceId, ParseExtraFromMap(bindParam));
1718     } else {
1719         LOGE("DmAuthManager::BindTarget failed, targetId is error.");
1720         return ERR_DM_INPUT_PARA_INVALID;
1721     }
1722 }
1723 
ParseConnectAddr(const PeerTargetId & targetId,std::string & deviceId,std::string & addrType)1724 int32_t DmAuthManager::ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, std::string &addrType)
1725 {
1726     int32_t index = 0;
1727     std::shared_ptr<DeviceInfo> deviceInfo = std::make_shared<DeviceInfo>();
1728     ConnectionAddr addr;
1729     if (!targetId.wifiIp.empty() && targetId.wifiIp.length() <= IP_STR_MAX_LEN) {
1730         LOGI("DmAuthManager::ParseConnectAddr parse wifiIp: %{public}s.", GetAnonyString(targetId.wifiIp).c_str());
1731         if (!addrType.empty()) {
1732             addr.type = static_cast<ConnectionAddrType>(std::atoi(addrType.c_str()));
1733         } else {
1734             addr.type = ConnectionAddrType::CONNECTION_ADDR_WLAN;
1735         }
1736         memcpy_s(addr.info.ip.ip, IP_STR_MAX_LEN, targetId.wifiIp.c_str(), targetId.wifiIp.length());
1737         addr.info.ip.port = targetId.wifiPort;
1738         deviceInfo->addr[index] = addr;
1739         deviceId = targetId.wifiIp;
1740         index++;
1741     } else if (!targetId.brMac.empty() && targetId.brMac.length() <= BT_MAC_LEN) {
1742         LOGI("DmAuthManager::ParseConnectAddr parse brMac: %{public}s.", GetAnonyString(targetId.brMac).c_str());
1743         addr.type = ConnectionAddrType::CONNECTION_ADDR_BR;
1744         memcpy_s(addr.info.br.brMac, BT_MAC_LEN, targetId.brMac.c_str(), targetId.brMac.length());
1745         deviceInfo->addr[index] = addr;
1746         deviceId = targetId.brMac;
1747         index++;
1748     } else if (!targetId.bleMac.empty() && targetId.bleMac.length() <= BT_MAC_LEN) {
1749         LOGI("DmAuthManager::ParseConnectAddr parse bleMac: %{public}s.", GetAnonyString(targetId.bleMac).c_str());
1750         addr.type = ConnectionAddrType::CONNECTION_ADDR_BLE;
1751         memcpy_s(addr.info.ble.bleMac, BT_MAC_LEN, targetId.bleMac.c_str(), targetId.bleMac.length());
1752         if (!targetId.deviceId.empty()) {
1753             Crypto::ConvertHexStringToBytes(addr.info.ble.udidHash, UDID_HASH_LEN,
1754                 targetId.deviceId.c_str(), targetId.deviceId.length());
1755         }
1756         deviceInfo->addr[index] = addr;
1757         deviceId = targetId.bleMac;
1758         index++;
1759     } else {
1760         LOGE("DmAuthManager::ParseConnectAddr failed, not addr.");
1761         return ERR_DM_INPUT_PARA_INVALID;
1762     }
1763 
1764     deviceInfo->addrNum = static_cast<uint32_t>(index);
1765     if (softbusConnector_->AddMemberToDiscoverMap(deviceId, deviceInfo) != DM_OK) {
1766         LOGE("DmAuthManager::ParseConnectAddr failed, AddMemberToDiscoverMap failed.");
1767         return ERR_DM_INPUT_PARA_INVALID;
1768     }
1769     deviceInfo = nullptr;
1770     return DM_OK;
1771 }
1772 
ParseAuthType(const std::map<std::string,std::string> & bindParam,int32_t & authType)1773 int32_t DmAuthManager::ParseAuthType(const std::map<std::string, std::string> &bindParam, int32_t &authType)
1774 {
1775     auto iter = bindParam.find(PARAM_KEY_AUTH_TYPE);
1776     if (iter == bindParam.end()) {
1777         LOGE("DmAuthManager::ParseAuthType bind param key: %{public}s not exist.", PARAM_KEY_AUTH_TYPE);
1778         return ERR_DM_INPUT_PARA_INVALID;
1779     }
1780     std::string authTypeStr = iter->second;
1781     if (authTypeStr.empty()) {
1782         LOGE("DmAuthManager::ParseAuthType bind param %{public}s is empty.", PARAM_KEY_AUTH_TYPE);
1783         return ERR_DM_INPUT_PARA_INVALID;
1784     }
1785     if (authTypeStr.length() > 1) {
1786         LOGE("DmAuthManager::ParseAuthType bind param %{public}s length is unsupported.", PARAM_KEY_AUTH_TYPE);
1787         return ERR_DM_INPUT_PARA_INVALID;
1788     }
1789     if (!isdigit(authTypeStr[0])) {
1790         LOGE("DmAuthManager::ParseAuthType bind param %{public}s fromat is unsupported.", PARAM_KEY_AUTH_TYPE);
1791         return ERR_DM_INPUT_PARA_INVALID;
1792     }
1793     authType = std::atoi(authTypeStr.c_str());
1794     return DM_OK;
1795 }
1796 
ParseExtraFromMap(const std::map<std::string,std::string> & bindParam)1797 std::string DmAuthManager::ParseExtraFromMap(const std::map<std::string, std::string> &bindParam)
1798 {
1799     auto iter = bindParam.find(PARAM_KEY_BIND_EXTRA_DATA);
1800     if (iter != bindParam.end()) {
1801         return iter->second;
1802     }
1803     return ConvertMapToJsonString(bindParam);
1804 }
1805 
IsAuthCodeReady(const std::string & pkgName)1806 bool DmAuthManager::IsAuthCodeReady(const std::string &pkgName)
1807 {
1808     if (importAuthCode_.empty() || importPkgName_.empty()) {
1809         LOGE("DmAuthManager::IsAuthCodeReady, auth code not ready.");
1810         return false;
1811     }
1812     if (pkgName != importPkgName_) {
1813         LOGE("IsAuthCodeReady failed, pkgName not supported.");
1814         return false;
1815     }
1816     return true;
1817 }
1818 
DeleteAuthCode()1819 int32_t DmAuthManager::DeleteAuthCode()
1820 {
1821     if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) {
1822         importAuthCode_ = "";
1823         importPkgName_ = "";
1824     }
1825     return DM_OK;
1826 }
1827 
GetAuthCode(const std::string & pkgName,int32_t & pinCode)1828 int32_t DmAuthManager::GetAuthCode(const std::string &pkgName, int32_t &pinCode)
1829 {
1830     if (importAuthCode_.empty() || importPkgName_.empty()) {
1831         LOGE("GetAuthCode failed, auth code not exist.");
1832         return ERR_DM_FAILED;
1833     }
1834     if (pkgName != importPkgName_) {
1835         LOGE("GetAuthCode failed, pkgName not supported.");
1836         return ERR_DM_FAILED;
1837     }
1838     pinCode = std::atoi(importAuthCode_.c_str());
1839     return DM_OK;
1840 }
1841 
IsAuthTypeSupported(const int32_t & authType)1842 bool DmAuthManager::IsAuthTypeSupported(const int32_t &authType)
1843 {
1844     if (authenticationMap_.find(authType) == authenticationMap_.end()) {
1845         LOGE("IsAuthTypeSupported failed, authType is not supported.");
1846         return false;
1847     }
1848     return true;
1849 }
1850 
GenerateBindResultContent()1851 std::string DmAuthManager::GenerateBindResultContent()
1852 {
1853     nlohmann::json jsonObj;
1854     jsonObj[DM_BIND_RESULT_NETWORK_ID] = authResponseContext_->networkId;
1855     if (remoteDeviceId_.empty()) {
1856         jsonObj[TAG_DEVICE_ID] = "";
1857     } else {
1858         char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0};
1859         Crypto::GetUdidHash(remoteDeviceId_, reinterpret_cast<uint8_t *>(deviceIdHash));
1860         jsonObj[TAG_DEVICE_ID] = deviceIdHash;
1861     }
1862     std::string content = jsonObj.dump();
1863     return content;
1864 }
1865 
RequestCredential()1866 void DmAuthManager::RequestCredential()
1867 {
1868     LOGI("DmAuthManager::RequestCredential start.");
1869     std::string publicKey = "";
1870     GenerateCredential(publicKey);
1871     authResponseContext_->publicKey = publicKey;
1872     std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_PUBLICKEY);
1873     softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
1874 }
1875 
GenerateCredential(std::string & publicKey)1876 void DmAuthManager::GenerateCredential(std::string &publicKey)
1877 {
1878     LOGI("DmAuthManager::GenerateCredential start.");
1879     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
1880     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
1881     std::string localUdid = localDeviceId;
1882     int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID();
1883     hiChainAuthConnector_->GenerateCredential(localUdid, osAccountId, publicKey);
1884     if (publicKey == "") {
1885         hiChainAuthConnector_->GetCredential(localUdid, osAccountId, publicKey);
1886     }
1887 }
1888 
RequestCredentialDone()1889 void DmAuthManager::RequestCredentialDone()
1890 {
1891     LOGI("DmAuthManager ExchangeCredentailDone start");
1892     if (authResponseContext_ == nullptr) {
1893         LOGE("failed to JoinNeWork because authResponseContext_ is nullptr");
1894         return;
1895     }
1896     if (ImportCredential(remoteDeviceId_, authResponseContext_->publicKey) != DM_OK) {
1897         LOGE("ResponseCredential import credential failed.");
1898     }
1899     if (timer_ != nullptr) {
1900         timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK));
1901     }
1902 
1903     softbusConnector_->JoinLnn(authRequestContext_->ip);
1904     authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
1905     authRequestContext_->reason = DM_OK;
1906     authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
1907 }
1908 
ImportCredential(std::string & deviceId,std::string & publicKey)1909 int32_t DmAuthManager::ImportCredential(std::string &deviceId, std::string &publicKey)
1910 {
1911     LOGI("DmAuthManager::ImportCredential");
1912     int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID();
1913     return hiChainAuthConnector_->ImportCredential(osAccountId, deviceId, publicKey);
1914 }
1915 
EstablishUnbindChannel(const std::string & deviceIdHash)1916 int32_t DmAuthManager::EstablishUnbindChannel(const std::string &deviceIdHash)
1917 {
1918     LOGI("DmAuthManager::EstablishUnbindChannel");
1919     std::string netWorkId = softbusConnector_->GetNetworkIdByDeviceId(deviceIdHash);
1920     int32_t sessionId = softbusConnector_->GetSoftbusSession()->OpenUnbindSession(netWorkId);
1921     if (sessionId < 0) {
1922         LOGE("OpenAuthSession failed, stop the syncdeleteacl.");
1923         authResponseContext_ = std::make_shared<DmAuthResponseContext>();
1924         authResponseContext_->state = AuthState::AUTH_REQUEST_SYNCDELETE;
1925         authResponseContext_->hostPkgName = authRequestContext_->hostPkgName;
1926         authRequestContext_->reason = sessionId;
1927         if (authRequestState_ != nullptr) {
1928             authRequestState_->TransitionTo(std::make_shared<AuthRequestSyncDeleteAclNone>());
1929         }
1930     }
1931     return DM_OK;
1932 }
1933 
RequestSyncDeleteAcl()1934 void DmAuthManager::RequestSyncDeleteAcl()
1935 {
1936     LOGI("RequestSyncDeleteAcl start.");
1937     std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_SYNC_DELETE);
1938     softbusConnector_->GetSoftbusSession()->SendData(authRequestContext_->sessionId, message);
1939     if (timer_ == nullptr) {
1940         timer_ = std::make_shared<DmTimer>();
1941     }
1942     timer_->StartTimer(std::string(SYNC_DELETE_TIMEOUT_TASK), SYNC_DELETE_TIMEOUT,
1943         [this] (std::string name) {
1944             DmAuthManager::HandleSyncDeleteTimeout(name);
1945         });
1946 }
1947 
SrcSyncDeleteAclDone()1948 void DmAuthManager::SrcSyncDeleteAclDone()
1949 {
1950     LOGI("DmAuthManager::SrcSyncDeleteAclDone, isFinishOfLocal: %{public}d", isFinishOfLocal_);
1951     if (isFinishOfLocal_) {
1952         authMessageProcessor_->SetResponseContext(authResponseContext_);
1953         std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_SYNC_DELETE_DONE);
1954         softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
1955         usleep(USLEEP_TIME_MS);
1956     }
1957     if (authResponseContext_->reply == DM_OK) {
1958         char localUdid[DEVICE_UUID_LENGTH] = {0};
1959         GetDevUdid(localUdid, DEVICE_UUID_LENGTH);
1960         if (hiChainConnector_->IsDevicesInP2PGroup(remoteDeviceId_, localUdid) &&
1961             DeviceProfileConnector::GetInstance().CheckDevIdInAclForDevBind(authRequestContext_->hostPkgName,
1962             remoteDeviceId_)) {
1963             DeleteGroup(authRequestContext_->hostPkgName, remoteDeviceId_);
1964         }
1965         DeleteAcl(authRequestContext_->hostPkgName, remoteDeviceId_);
1966     }
1967     softbusConnector_->GetSoftbusSession()->CloseUnbindSession(authRequestContext_->sessionId);
1968     if (timer_ != nullptr) {
1969         timer_->DeleteAll();
1970     }
1971     isFinishOfLocal_ = true;
1972     authRequestContext_ = nullptr;
1973     authResponseContext_ = nullptr;
1974     authRequestState_ = nullptr;
1975     authMessageProcessor_ = nullptr;
1976 }
1977 
SinkSyncDeleteAclDone()1978 void DmAuthManager::SinkSyncDeleteAclDone()
1979 {
1980     LOGI("DmAuthManager::SinkSyncDeleteAclDone, isFinishOfLocal: %{public}d", isFinishOfLocal_);
1981     if (isFinishOfLocal_) {
1982         authMessageProcessor_->SetResponseContext(authResponseContext_);
1983         std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_SYNC_DELETE_DONE);
1984         softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
1985         if (authResponseContext_->reply == DM_OK) {
1986             char localUdid[DEVICE_UUID_LENGTH] = {0};
1987             GetDevUdid(localUdid, DEVICE_UUID_LENGTH);
1988             if (hiChainConnector_->IsDevicesInP2PGroup(remoteDeviceId_, localUdid) &&
1989                 DeviceProfileConnector::GetInstance().CheckDevIdInAclForDevBind(authResponseContext_->hostPkgName,
1990                 remoteDeviceId_)) {
1991                 DeleteGroup(authResponseContext_->hostPkgName, remoteDeviceId_);
1992             }
1993             DeleteAcl(authResponseContext_->hostPkgName, remoteDeviceId_);
1994         }
1995     }
1996     if (timer_ != nullptr) {
1997         timer_->DeleteAll();
1998     }
1999     isFinishOfLocal_ = true;
2000     authResponseContext_ = nullptr;
2001     authResponseState_ = nullptr;
2002     authMessageProcessor_ = nullptr;
2003 }
2004 
SyncDeleteAclDone()2005 void DmAuthManager::SyncDeleteAclDone()
2006 {
2007     LOGI("SyncDeleteAclDone start.");
2008     if (authRequestState_ != nullptr) {
2009         SrcSyncDeleteAclDone();
2010     } else if (authResponseState_ != nullptr) {
2011         SinkSyncDeleteAclDone();
2012     }
2013 }
2014 
ResponseCredential()2015 void DmAuthManager::ResponseCredential()
2016 {
2017     LOGI("DmAuthManager::ResponseCredential start.");
2018     std::string publicKey = "";
2019     GenerateCredential(publicKey);
2020     if (ImportCredential(remoteDeviceId_, authResponseContext_->publicKey) != DM_OK) {
2021         LOGE("ResponseCredential import credential failed.");
2022     }
2023     authResponseContext_->publicKey = publicKey;
2024     std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_PUBLICKEY);
2025     softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
2026 }
2027 
ResponseSyncDeleteAcl()2028 void DmAuthManager::ResponseSyncDeleteAcl()
2029 {
2030     LOGI("ResponseSyncDeleteAcl start.");
2031     if (timer_ != nullptr) {
2032         timer_->DeleteTimer(std::string(SYNC_DELETE_TIMEOUT_TASK));
2033     }
2034     remoteDeviceId_ = authResponseContext_->localDeviceId;
2035     authResponseState_->TransitionTo(std::make_shared<AuthResponseSyncDeleteAclNone>());
2036 }
2037 
AuthDeviceTransmit(int64_t requestId,const uint8_t * data,uint32_t dataLen)2038 bool DmAuthManager::AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen)
2039 {
2040     LOGI("DmAuthManager::onTransmit start.");
2041     if (requestId != authResponseContext_->requestId) {
2042         LOGE("DmAuthManager::onTransmit requestId %{public}" PRId64"is error.", requestId);
2043         return false;
2044     }
2045     std::string message = "";
2046     if (authRequestState_ != nullptr && authResponseState_ == nullptr) {
2047         LOGI("SoftbusSession send msgType %{public}d.", MSG_TYPE_REQ_AUTH_DEVICE_NEGOTIATE);
2048         message = authMessageProcessor_->CreateDeviceAuthMessage(MSG_TYPE_REQ_AUTH_DEVICE_NEGOTIATE, data, dataLen);
2049     } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) {
2050         LOGI("SoftbusSession send msgType %{public}d.", MSG_TYPE_RESP_AUTH_DEVICE_NEGOTIATE);
2051         message = authMessageProcessor_->CreateDeviceAuthMessage(MSG_TYPE_RESP_AUTH_DEVICE_NEGOTIATE, data, dataLen);
2052     }
2053     if (softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message) != DM_OK) {
2054         LOGE("SoftbusSession send data failed.");
2055         return false;
2056     }
2057     return true;
2058 }
2059 
SrcAuthDeviceFinish()2060 void DmAuthManager::SrcAuthDeviceFinish()
2061 {
2062     if (authResponseContext_->isOnline) {
2063         if (authResponseContext_->confirmOperation == USER_OPERATION_TYPE_ALLOW_AUTH ||
2064             (authResponseContext_->confirmOperation == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS &&
2065             authResponseContext_->haveCredential)) {
2066             if (authResponseContext_->bindLevel == APP && !authResponseContext_->isIdenticalAccount) {
2067                 softbusConnector_->SetPkgName(authResponseContext_->hostPkgName);
2068             }
2069             softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_);
2070             if (timer_ != nullptr) {
2071                 timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK));
2072             }
2073             authRequestContext_->reason = DM_OK;
2074             authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
2075             authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
2076             return;
2077         }
2078         if (authResponseContext_->confirmOperation == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS &&
2079             !authResponseContext_->haveCredential) {
2080             authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT);
2081             if (authResponseContext_->bindLevel == APP && !authResponseContext_->isIdenticalAccount) {
2082                 softbusConnector_->SetPkgName(authResponseContext_->hostPkgName);
2083             }
2084             softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_);
2085             authRequestState_->TransitionTo(std::make_shared<AuthRequestCredential>());
2086             return;
2087         }
2088     }
2089     if (!authResponseContext_->isOnline && authResponseContext_->haveCredential) {
2090         softbusConnector_->JoinLnn(authRequestContext_->ip);
2091         if (timer_ != nullptr) {
2092             timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK));
2093         }
2094         authRequestContext_->reason = DM_OK;
2095         authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
2096         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
2097         return;
2098     }
2099     if (!authResponseContext_->isOnline && !authResponseContext_->haveCredential) {
2100         authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT);
2101         authRequestState_->TransitionTo(std::make_shared<AuthRequestCredential>());
2102         return;
2103     }
2104 }
2105 
SinkAuthDeviceFinish()2106 void DmAuthManager::SinkAuthDeviceFinish()
2107 {
2108     if (!authResponseContext_->haveCredential) {
2109         authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW);
2110     }
2111     if (authResponseContext_->isOnline) {
2112         LOGI("The device is online.");
2113         if (authResponseContext_->bindLevel == APP && !authResponseContext_->isIdenticalAccount) {
2114             softbusConnector_->SetPkgName(authResponseContext_->hostPkgName);
2115         }
2116         softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_);
2117     }
2118 }
2119 
AuthDeviceFinish(int64_t requestId)2120 void DmAuthManager::AuthDeviceFinish(int64_t requestId)
2121 {
2122     LOGI("DmAuthManager::AuthDeviceFinish start.");
2123     if (requestId != authResponseContext_->requestId) {
2124         LOGE("DmAuthManager::onTransmit requestId %{public}" PRId64 "is error.", requestId);
2125         return;
2126     }
2127     isAuthDevice_ = false;
2128     if (timer_ != nullptr) {
2129         timer_->DeleteTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK));
2130     }
2131 
2132     if (authRequestState_ != nullptr && authResponseState_ == nullptr) {
2133         PutAccessControlList();
2134         SrcAuthDeviceFinish();
2135     } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) {
2136         PutAccessControlList();
2137         SinkAuthDeviceFinish();
2138     }
2139 }
2140 
AuthDeviceError(int64_t requestId,int32_t errorCode)2141 void DmAuthManager::AuthDeviceError(int64_t requestId, int32_t errorCode)
2142 {
2143     LOGI("AuthDeviceError start.");
2144     isAuthDevice_ = false;
2145     if (authRequestState_ == nullptr || authResponseState_ != nullptr) {
2146         LOGD("AuthDeviceError sink return.");
2147         return;
2148     }
2149     if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) {
2150         authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN;
2151         authRequestContext_->reason = ERR_DM_AUTH_CODE_INCORRECT;
2152         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
2153         return;
2154     }
2155     authTimes_++;
2156     if (timer_ != nullptr) {
2157         timer_->DeleteTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK));
2158     }
2159 
2160     if (errorCode != DM_OK || requestId != authResponseContext_->requestId) {
2161         if (authRequestState_ != nullptr && authTimes_ >= MAX_AUTH_TIMES) {
2162             authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN;
2163             authRequestContext_->reason = ERR_DM_INPUT_PARA_INVALID;
2164             authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
2165         } else {
2166             if (timer_ != nullptr) {
2167                 timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK),
2168                     GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) {
2169                         DmAuthManager::HandleAuthenticateTimeout(name);
2170                     });
2171             }
2172             authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR);
2173         }
2174     }
2175 }
2176 
AuthDeviceSessionKey(int64_t requestId,const uint8_t * sessionKey,uint32_t sessionKeyLen)2177 void DmAuthManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen)
2178 {
2179     LOGI("DmAuthManager::AuthDeviceSessionKey start.");
2180     if (requestId != authResponseContext_->requestId) {
2181         LOGE("DmAuthManager::onTransmit requestId %{public}" PRId64 "is error.", requestId);
2182         return;
2183     }
2184     sessionKey_ = sessionKey;
2185     sessionKeyLen_ = sessionKeyLen;
2186 }
2187 
GetRemoteDeviceId(std::string & deviceId)2188 void DmAuthManager::GetRemoteDeviceId(std::string &deviceId)
2189 {
2190     LOGI("GetRemoteDeviceId start.");
2191     deviceId = remoteDeviceId_;
2192 }
2193 
CompatiblePutAcl()2194 void DmAuthManager::CompatiblePutAcl()
2195 {
2196     LOGI("DmAuthManager::CompatiblePutAcl");
2197     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
2198     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
2199     std::string localUdid = static_cast<std::string>(localDeviceId);
2200     char mUdidHash[DM_MAX_DEVICE_ID_LEN] = {0};
2201     Crypto::GetUdidHash(localUdid, reinterpret_cast<uint8_t *>(mUdidHash));
2202     std::string localUdidHash = static_cast<std::string>(mUdidHash);
2203     DmAclInfo aclInfo;
2204     aclInfo.bindLevel = DEVICE;
2205     aclInfo.bindType = DM_POINT_TO_POINT;
2206     aclInfo.trustDeviceId = remoteDeviceId_;
2207     if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) {
2208         aclInfo.authenticationType = ALLOW_AUTH_ALWAYS;
2209     } else if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH) {
2210         aclInfo.authenticationType = ALLOW_AUTH_ONCE;
2211     }
2212     aclInfo.deviceIdHash = localUdidHash;
2213 
2214     DmAccesser accesser;
2215     accesser.requestTokenId = static_cast<uint64_t>(authResponseContext_->tokenId);
2216     accesser.requestBundleName = authResponseContext_->hostPkgName;
2217     if (authRequestState_ != nullptr && authResponseState_ == nullptr) {
2218         accesser.requestUserId = MultipleUserConnector::GetCurrentAccountUserID();
2219         accesser.requestAccountId = MultipleUserConnector::GetOhosAccountId();
2220         accesser.requestDeviceId = localUdid;
2221     } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) {
2222         accesser.requestDeviceId = authResponseContext_->localDeviceId;
2223     }
2224 
2225     DmAccessee accessee;
2226     accessee.trustTokenId = static_cast<uint64_t>(authResponseContext_->tokenId);
2227     accessee.trustBundleName = authResponseContext_->hostPkgName;
2228     if (authRequestState_ != nullptr && authResponseState_ == nullptr) {
2229         accessee.trustDeviceId = remoteDeviceId_;
2230     } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) {
2231         accessee.trustUserId = MultipleUserConnector::GetCurrentAccountUserID();
2232         accessee.trustAccountId = MultipleUserConnector::GetOhosAccountId();
2233         accessee.trustDeviceId = localUdid;
2234     }
2235     DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, accesser, accessee);
2236 }
2237 
CommonEventCallback(int32_t userId,std::string commonEventType)2238 void DmAuthManager::CommonEventCallback(int32_t userId, std::string commonEventType)
2239 {
2240     LOGI("DmAuthManager::CommonEventCallback");
2241     if (commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT) {
2242         AccountIdLogoutEventCallback(userId);
2243     } else if (commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED) {
2244         int32_t userId = MultipleUserConnector::GetCurrentAccountUserID();
2245         std::string accountId = MultipleUserConnector::GetOhosAccountId();
2246         LOGI("user_switched event accountId: %{public}s, userId: %{public}s",
2247             GetAnonyString(accountId).c_str(), GetAnonyInt32(userId).c_str());
2248         if (userId > 0) {
2249             MultipleUserConnector::SetSwitchOldUserId(userId);
2250             MultipleUserConnector::SetSwitchOldAccountId(accountId);
2251         }
2252     }
2253 }
2254 
AccountIdLogoutEventCallback(int32_t userId)2255 void DmAuthManager::AccountIdLogoutEventCallback(int32_t userId)
2256 {
2257     LOGI("DmAuthManager::AccountIdLogoutEventCallback");
2258     std::string oldAccountId = MultipleUserConnector::GetSwitchOldAccountId();
2259     std::string currentAccountId = MultipleUserConnector::GetOhosAccountId();
2260     MultipleUserConnector::SetSwitchOldAccountId(currentAccountId);
2261     if (oldAccountId == currentAccountId) {
2262         LOGE("The account logout is error.");
2263         return;
2264     }
2265     if (currentAccountId == "ohosAnonymousUid" &&
2266         DeviceProfileConnector::GetInstance().CheckIdenticalAccount(userId, oldAccountId)) {
2267         DeviceProfileConnector::GetInstance().DeleteAccessControlList(userId, oldAccountId);
2268         hiChainConnector_->DeleteAllGroup(userId);
2269     }
2270 }
2271 
UserSwitchEventCallback(int32_t userId)2272 void DmAuthManager::UserSwitchEventCallback(int32_t userId)
2273 {
2274     LOGI("UserSwitchEventCallback start.");
2275     std::string oldAccountId = MultipleUserConnector::GetSwitchOldAccountId();
2276     int32_t oldUserId = MultipleUserConnector::GetSwitchOldUserId();
2277     DeviceProfileConnector::GetInstance().DeleteP2PAccessControlList(oldUserId, oldAccountId);
2278     DeviceProfileConnector::GetInstance().DeleteP2PAccessControlList(userId, oldAccountId);
2279     hiChainConnector_->DeleteP2PGroup(userId);
2280 }
2281 
UserChangeEventCallback(int32_t userId)2282 void DmAuthManager::UserChangeEventCallback(int32_t userId)
2283 {
2284     LOGI("DmAuthManager::UserChangeEventCallback");
2285     std::string oldAccountId = MultipleUserConnector::GetSwitchOldAccountId();
2286     int32_t oldUseId = MultipleUserConnector::GetSwitchOldUserId();
2287     DeviceProfileConnector::GetInstance().DeleteP2PAccessControlList(oldUseId, oldAccountId);
2288     DeviceProfileConnector::GetInstance().DeleteP2PAccessControlList(userId, oldAccountId);
2289     hiChainConnector_->DeleteP2PGroup(userId);
2290 }
2291 
HandleSyncDeleteTimeout(std::string name)2292 void DmAuthManager::HandleSyncDeleteTimeout(std::string name)
2293 {
2294     LOGI("DmAuthManager::HandleSyncDeleteTimeout start timer name %{public}s", name.c_str());
2295     if (authRequestState_ != nullptr && authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_SYNCDELETE_DONE) {
2296         if (authResponseContext_ == nullptr) {
2297             authResponseContext_ = std::make_shared<DmAuthResponseContext>();
2298         }
2299         authResponseContext_->state = authRequestState_->GetStateType();
2300         authResponseContext_->reply = ERR_DM_TIME_OUT;
2301         authRequestState_->TransitionTo(std::make_shared<AuthRequestSyncDeleteAclNone>());
2302     }
2303 
2304     if (authResponseState_ != nullptr &&
2305         authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_SYNCDELETE_DONE) {
2306         authResponseContext_->state = authResponseState_->GetStateType();
2307         authResponseContext_->reply = ERR_DM_TIME_OUT;
2308         authResponseState_->TransitionTo(std::make_shared<AuthResponseSyncDeleteAclNone>());
2309     }
2310     LOGI("DmAuthManager::HandleSyncDeleteTimeout start complete");
2311 }
2312 
DeleteAcl(const std::string & pkgName,const std::string & deviceId)2313 int32_t DmAuthManager::DeleteAcl(const std::string &pkgName, const std::string &deviceId)
2314 {
2315     char localUdid[DEVICE_UUID_LENGTH] = {0};
2316     GetDevUdid(localUdid, DEVICE_UUID_LENGTH);
2317     std::string localDeviceId = static_cast<std::string>(localUdid);
2318     DmOfflineParam offlineParam =
2319         DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localDeviceId, deviceId);
2320     if (offlineParam.bindType == INVALIED_TYPE) {
2321         LOGE("Acl not contain the pkgName bind data.");
2322         return ERR_DM_FAILED;
2323     } else if (offlineParam.bindType == APP_PEER_TO_PEER_TYPE && offlineParam.leftAclNumber != 0) {
2324         LOGI("The pkgName unbind app-level type leftAclNumber not zero.");
2325         softbusConnector_->SetPkgName(pkgName);
2326         softbusConnector_->HandleDeviceOffline(deviceId);
2327     } else if (offlineParam.bindType == APP_PEER_TO_PEER_TYPE && offlineParam.leftAclNumber == 0) {
2328         LOGI("The pkgName unbind app-level type leftAclNumber is zero.");
2329         softbusConnector_->SetPkgName(pkgName);
2330         hiChainAuthConnector_->DeleteCredential(deviceId, MultipleUserConnector::GetCurrentAccountUserID());
2331     } else if (offlineParam.bindType == DEVICE_PEER_TO_PEER_TYPE && offlineParam.leftAclNumber != 0) {
2332         LOGI("Unbind deivce-level, retain identical account bind type.");
2333     } else if (offlineParam.bindType == DEVICE_PEER_TO_PEER_TYPE && offlineParam.leftAclNumber == 0) {
2334         LOGI("Unbind deivce-level, retain null.");
2335         hiChainAuthConnector_->DeleteCredential(deviceId, MultipleUserConnector::GetCurrentAccountUserID());
2336     }
2337     return DM_OK;
2338 }
2339 
ProcRespNegotiateExt(const int32_t & sessionId)2340 void DmAuthManager::ProcRespNegotiateExt(const int32_t &sessionId)
2341 {
2342     LOGI("DmAuthManager::ProcRespNegotiateExt start.");
2343     remoteDeviceId_ = authResponseContext_->localDeviceId;
2344     std::string accountId = MultipleUserConnector::GetOhosAccountId();
2345     int32_t userId = MultipleUserConnector::GetCurrentAccountUserID();
2346     MultipleUserConnector::SetSwitchOldAccountId(accountId);
2347     MultipleUserConnector::SetSwitchOldUserId(userId);
2348     authResponseContext_->isIdenticalAccount = false;
2349     if (authResponseContext_->localAccountId == accountId && accountId != "ohosAnonymousUid") {
2350         authResponseContext_->isIdenticalAccount = true;
2351     }
2352     authResponseContext_->remoteAccountId = authResponseContext_->localAccountId;
2353     authResponseContext_->localAccountId = accountId;
2354     authResponseContext_->remoteUserId = authResponseContext_->localUserId;
2355     authResponseContext_->localUserId = userId;
2356     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
2357     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
2358     authResponseContext_->deviceId = authResponseContext_->localDeviceId;
2359     authResponseContext_->localDeviceId = static_cast<std::string>(localDeviceId);
2360     authResponseContext_->bindType =
2361         DeviceProfileConnector::GetInstance().GetBindTypeByPkgName(authResponseContext_->hostPkgName,
2362         authResponseContext_->localDeviceId, authResponseContext_->deviceId);
2363     authResponseContext_->authed = !authResponseContext_->bindType.empty();
2364     if (authResponseContext_->authed && authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE &&
2365         !importAuthCode_.empty()) {
2366         authResponseContext_->importAuthCode = Crypto::Sha256(importAuthCode_);
2367     }
2368     authResponseContext_->isOnline = softbusConnector_->CheckIsOnline(remoteDeviceId_);
2369     authResponseContext_->haveCredential =
2370         hiChainAuthConnector_->QueryCredential(authResponseContext_->deviceId, authResponseContext_->localUserId);
2371     if (!IsAuthTypeSupported(authResponseContext_->authType)) {
2372         LOGE("DmAuthManager::AuthenticateDevice authType %{public}d not support.", authResponseContext_->authType);
2373         authResponseContext_->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE;
2374     } else {
2375         authPtr_ = authenticationMap_[authResponseContext_->authType];
2376     }
2377     if (IsAuthCodeReady(authResponseContext_->hostPkgName)) {
2378         authResponseContext_->isAuthCodeReady = true;
2379     } else {
2380         authResponseContext_->isAuthCodeReady = false;
2381     }
2382     std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_NEGOTIATE);
2383     softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
2384 }
2385 
ProcRespNegotiate(const int32_t & sessionId)2386 void DmAuthManager::ProcRespNegotiate(const int32_t &sessionId)
2387 {
2388     LOGI("DmAuthManager::ProcRespNegotiate session id");
2389     AbilityNegotiate();
2390     authResponseContext_->isOnline = softbusConnector_->CheckIsOnline(remoteDeviceId_);
2391     std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_NEGOTIATE);
2392     nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false);
2393     if (jsonObject.is_discarded()) {
2394         softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
2395         return;
2396     }
2397     if (!IsBool(jsonObject, TAG_CRYPTO_SUPPORT)) {
2398         LOGE("err json string.");
2399         softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
2400         return;
2401     }
2402     if (IsIdenticalAccount()) {
2403         jsonObject[TAG_IDENTICAL_ACCOUNT] = true;
2404         if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && !importAuthCode_.empty()) {
2405             jsonObject[TAG_IMPORT_AUTH_CODE] = Crypto::Sha256(importAuthCode_);
2406         }
2407     }
2408     jsonObject[TAG_ACCOUNT_GROUPID] = GetAccountGroupIdHash();
2409     authResponseContext_ = authResponseState_->GetAuthContext();
2410     if (jsonObject[TAG_CRYPTO_SUPPORT] == true && authResponseContext_->cryptoSupport) {
2411         if (IsString(jsonObject, TAG_CRYPTO_NAME) && IsString(jsonObject, TAG_CRYPTO_VERSION)) {
2412             if (jsonObject[TAG_CRYPTO_NAME] == authResponseContext_->cryptoName &&
2413                 jsonObject[TAG_CRYPTO_VERSION] == authResponseContext_->cryptoVer) {
2414                 isCryptoSupport_ = true;
2415                 softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
2416                 return;
2417             }
2418         }
2419     }
2420     jsonObject[TAG_CRYPTO_SUPPORT] = false;
2421     message = jsonObject.dump();
2422     softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
2423 }
2424 
ProcIncompatible(const int32_t & sessionId)2425 void DmAuthManager::ProcIncompatible(const int32_t &sessionId)
2426 {
2427     LOGI("DmAuthManager::ProcIncompatible sessionId %{public}d.", sessionId);
2428     nlohmann::json respNegotiateMsg;
2429     respNegotiateMsg[TAG_REPLY] = ERR_DM_VERSION_INCOMPATIBLE;
2430     respNegotiateMsg[TAG_VER] = DM_ITF_VER;
2431     respNegotiateMsg[TAG_MSG_TYPE] = MSG_TYPE_RESP_NEGOTIATE;
2432     std::string message = respNegotiateMsg.dump();
2433     softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
2434 }
2435 
OnAuthDeviceDataReceived(const int32_t sessionId,const std::string message)2436 void DmAuthManager::OnAuthDeviceDataReceived(const int32_t sessionId, const std::string message)
2437 {
2438     authResponseContext_->sessionId = sessionId;
2439     authMessageProcessor_->SetResponseContext(authResponseContext_);
2440     nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false);
2441     if (jsonObject.is_discarded()) {
2442         LOGE("DecodeRequestAuth jsonStr error");
2443         return;
2444     }
2445     if (!IsString(jsonObject, TAG_DATA) || !IsInt32(jsonObject, TAG_DATA_LEN) || !IsInt32(jsonObject, TAG_MSG_TYPE)) {
2446         LOGE("Auth device data is error.");
2447         return;
2448     }
2449     LOGI("OnAuthDeviceDataReceived start msgType %{public}d.", jsonObject[TAG_MSG_TYPE].get<int32_t>());
2450     std::string authData = jsonObject[TAG_DATA].get<std::string>();
2451     int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID();
2452     hiChainAuthConnector_->ProcessAuthData(authResponseContext_->requestId, authData, osAccountId);
2453 }
2454 
BindSocketFail()2455 void DmAuthManager::BindSocketFail()
2456 {
2457     LOGE("BindSocketFail");
2458     authResponseContext_->reply = DM_OK;
2459     isFinishOfLocal_ = false;
2460     authResponseContext_->hostPkgName = authRequestContext_->hostPkgName;
2461 }
2462 
BindSocketSuccess(int32_t socket)2463 void DmAuthManager::BindSocketSuccess(int32_t socket)
2464 {
2465     LOGI("BindSocketSuccess");
2466     if (authResponseState_ == nullptr && authRequestState_ != nullptr &&
2467         authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_DELETE_INIT) {
2468         authRequestContext_->sessionId = socket;
2469         authRequestState_->SetAuthContext(authRequestContext_);
2470         authMessageProcessor_->SetRequestContext(authRequestContext_);
2471         authResponseContext_->localDeviceId = authRequestContext_->localDeviceId;
2472         authResponseContext_->hostPkgName = authRequestContext_->hostPkgName;
2473         authMessageProcessor_->SetResponseContext(authResponseContext_);
2474         authRequestState_->TransitionTo(std::make_shared<AuthRequestSyncDeleteAcl>());
2475     } else {
2476         softbusConnector_->GetSoftbusSession()->CloseUnbindSession(socket);
2477         LOGE("DmAuthManager::BindSocketSuccess but request state is wrong");
2478     }
2479 }
2480 
OnUnbindSessionOpened(int32_t socket,PeerSocketInfo info)2481 void DmAuthManager::OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info)
2482 {
2483     LOGI("DmAuthManager::OnUnbindSessionOpened socket: %{public}d, peerSocketName: %{public}s, peerNetworkId:"
2484         "%{public}s, peerPkgName: %{public}s", socket, info.name, GetAnonyString(info.networkId).c_str(), info.pkgName);
2485     if (authResponseState_ == nullptr && authRequestState_ == nullptr) {
2486         authMessageProcessor_ = std::make_shared<AuthMessageProcessor>(shared_from_this());
2487         authResponseState_ = std::make_shared<AuthResponseInitState>();
2488         authResponseState_->SetAuthManager(shared_from_this());
2489         authResponseState_->Enter();
2490         authResponseContext_ = std::make_shared<DmAuthResponseContext>();
2491         if (timer_ == nullptr) {
2492             timer_ = std::make_shared<DmTimer>();
2493         }
2494         timer_->StartTimer(std::string(SYNC_DELETE_TIMEOUT_TASK), SYNC_DELETE_TIMEOUT,
2495             [this] (std::string name) {
2496                 DmAuthManager::HandleSyncDeleteTimeout(name);
2497             });
2498     } else {
2499         std::shared_ptr<AuthMessageProcessor> authMessageProcessor =
2500             std::make_shared<AuthMessageProcessor>(shared_from_this());
2501         std::shared_ptr<DmAuthResponseContext> authResponseContext = std::make_shared<DmAuthResponseContext>();
2502         authResponseContext->reply = ERR_DM_SYNC_DELETE_DEVICE_REPEATED;
2503         authMessageProcessor->SetResponseContext(authResponseContext);
2504         std::string message = authMessageProcessor->CreateSimpleMessage(MSG_TYPE_REQ_SYNC_DELETE_DONE);
2505         softbusConnector_->GetSoftbusSession()->SendData(socket, message);
2506     }
2507 }
2508 
DeleteGroup(const std::string & pkgName,const std::string & deviceId)2509 int32_t DmAuthManager::DeleteGroup(const std::string &pkgName, const std::string &deviceId)
2510 {
2511     LOGI("DmAuthManager::DeleteGroup");
2512     if (pkgName.empty()) {
2513         LOGE("Invalid parameter, pkgName is empty.");
2514         return ERR_DM_FAILED;
2515     }
2516     std::vector<OHOS::DistributedHardware::GroupInfo> groupList;
2517     hiChainConnector_->GetRelatedGroups(deviceId, groupList);
2518     if (groupList.size() > 0) {
2519         std::string groupId = "";
2520         groupId = groupList.front().groupId;
2521         hiChainConnector_->DeleteGroup(groupId);
2522     } else {
2523         LOGE("DmAuthManager::UnAuthenticateDevice groupList.size = 0");
2524         return ERR_DM_FAILED;
2525     }
2526     if (softbusConnector_ != nullptr) {
2527         softbusConnector_->EraseUdidFromMap(deviceId);
2528     }
2529     return DM_OK;
2530 }
2531 
PutAccessControlList()2532 void DmAuthManager::PutAccessControlList()
2533 {
2534     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
2535     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
2536     std::string localUdid = static_cast<std::string>(localDeviceId);
2537     char mUdidHash[DM_MAX_DEVICE_ID_LEN] = {0};
2538     Crypto::GetUdidHash(localUdid, reinterpret_cast<uint8_t *>(mUdidHash));
2539     std::string localUdidHash = static_cast<std::string>(mUdidHash);
2540     DmAclInfo aclInfo;
2541     aclInfo.bindType = DM_ACROSS_ACCOUNT;
2542     if (authResponseContext_->isIdenticalAccount) {
2543         aclInfo.bindType = DM_IDENTICAL_ACCOUNT;
2544         authForm_ = DmAuthForm::IDENTICAL_ACCOUNT;
2545     } else if (authResponseContext_->localAccountId == "ohosAnonymousUid" ||
2546         authResponseContext_->remoteAccountId == "ohosAnonymousUid") {
2547         aclInfo.bindType = DM_POINT_TO_POINT;
2548         authForm_ = DmAuthForm::PEER_TO_PEER;
2549     }
2550     aclInfo.bindLevel = authResponseContext_->bindLevel;
2551     aclInfo.trustDeviceId = remoteDeviceId_;
2552     aclInfo.authenticationType = ALLOW_AUTH_ONCE;
2553     if (authResponseContext_->confirmOperation == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) {
2554         aclInfo.authenticationType = ALLOW_AUTH_ALWAYS;
2555     }
2556     aclInfo.deviceIdHash = localUdidHash;
2557     DmAccesser accesser;
2558     accesser.requestTokenId = static_cast<uint64_t>(authResponseContext_->tokenId);
2559     accesser.requestBundleName = authResponseContext_->hostPkgName;
2560     if (authRequestState_ != nullptr && authResponseState_ == nullptr) {
2561         accesser.requestUserId = authRequestContext_->localUserId;
2562         accesser.requestAccountId = authRequestContext_->localAccountId;
2563         accesser.requestDeviceId = authRequestContext_->localDeviceId;
2564     } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) {
2565         accesser.requestUserId = authResponseContext_->remoteUserId;
2566         accesser.requestAccountId = authResponseContext_->remoteAccountId;
2567         accesser.requestDeviceId = authResponseContext_->localDeviceId;
2568     }
2569     DmAccessee accessee;
2570     accessee.trustTokenId = static_cast<uint64_t>(authResponseContext_->tokenId);
2571     accessee.trustBundleName = authResponseContext_->hostPkgName;
2572     if (authRequestState_ != nullptr && authResponseState_ == nullptr) {
2573         accessee.trustUserId = authRequestContext_->remoteUserId;
2574         accessee.trustAccountId = authRequestContext_->remoteAccountId;
2575         accessee.trustDeviceId = authResponseContext_->deviceId;
2576     } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) {
2577         accessee.trustUserId = authResponseContext_->localUserId;
2578         accessee.trustAccountId = authResponseContext_->localAccountId;
2579         accessee.trustDeviceId = localUdid;
2580     }
2581     DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, accesser, accessee);
2582 }
2583 
HandleSessionHeartbeat(std::string name)2584 void DmAuthManager::HandleSessionHeartbeat(std::string name)
2585 {
2586     if (timer_ != nullptr) {
2587         timer_->DeleteTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK));
2588     }
2589     LOGI("DmAuthManager::HandleSessionHeartbeat name %{public}s", name.c_str());
2590     nlohmann::json jsonObj;
2591     jsonObj[TAG_SESSION_HEARTBEAT] = TAG_SESSION_HEARTBEAT;
2592     std::string message = jsonObj.dump();
2593     softbusConnector_->GetSoftbusSession()->SendHeartbeatData(authResponseContext_->sessionId, message);
2594 
2595     if (authRequestState_ != nullptr) {
2596         if (timer_ != nullptr) {
2597             timer_->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK),
2598                 GetTaskTimeout(SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), [this] (std::string name) {
2599                     DmAuthManager::HandleSessionHeartbeat(name);
2600                 });
2601         }
2602     }
2603     LOGI("DmAuthManager::HandleSessionHeartbeat complete");
2604 }
2605 
CheckTrustState()2606 int32_t DmAuthManager::CheckTrustState()
2607 {
2608     if (authResponseContext_->isOnline && authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) {
2609         SetReasonAndFinish(DM_OK, AuthState::AUTH_REQUEST_FINISH);
2610         return ALREADY_BIND;
2611     }
2612     if (authResponseContext_->isIdenticalAccount) {
2613         if (IsIdenticalAccount()) {
2614             softbusConnector_->JoinLnn(authResponseContext_->deviceId);
2615             authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
2616             authRequestContext_->reason = DM_OK;
2617             authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
2618             return ALREADY_BIND;
2619         }
2620     }
2621     if (authResponseContext_->reply == ERR_DM_AUTH_PEER_REJECT) {
2622         if (hiChainConnector_->IsDevicesInP2PGroup(authResponseContext_->localDeviceId,
2623                                                    authRequestContext_->localDeviceId)) {
2624             if (!DeviceProfileConnector::GetInstance().CheckSrcDevIdInAclForDevBind(authResponseContext_->hostPkgName,
2625                 authResponseContext_->localDeviceId)) {
2626                 CompatiblePutAcl();
2627             }
2628             softbusConnector_->JoinLnn(authResponseContext_->deviceId);
2629             authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
2630             authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
2631             return ALREADY_BIND;
2632         }
2633     }
2634     if (authResponseContext_->reply == ERR_DM_UNSUPPORTED_AUTH_TYPE ||
2635         (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE &&
2636         authResponseContext_->isAuthCodeReady == false)) {
2637         authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
2638         authRequestContext_->reason = ERR_DM_BIND_PEER_UNSUPPORTED;
2639         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
2640         return ERR_DM_BIND_PEER_UNSUPPORTED;
2641     }
2642     return DM_OK;
2643 }
2644 
GetBundleLable(const std::string & bundleName)2645 std::string DmAuthManager::GetBundleLable(const std::string &bundleName)
2646 {
2647     auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
2648     if (samgr == nullptr) {
2649         LOGE("Get ability manager failed");
2650         return bundleName;
2651     }
2652 
2653     sptr<IRemoteObject> object = samgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
2654     if (object == nullptr) {
2655         LOGE("object is NULL.");
2656         return bundleName;
2657     }
2658 
2659     sptr<OHOS::AppExecFwk::IBundleMgr> bms = iface_cast<OHOS::AppExecFwk::IBundleMgr>(object);
2660     if (bms == nullptr) {
2661         LOGE("bundle manager service is NULL.");
2662         return bundleName;
2663     }
2664 
2665     auto bundleResourceProxy = bms->GetBundleResourceProxy();
2666     if (bundleResourceProxy == nullptr) {
2667         LOGE("GetBundleResourceProxy fail");
2668         return bundleName;
2669     }
2670     AppExecFwk::BundleResourceInfo resourceInfo;
2671     auto result = bundleResourceProxy->GetBundleResourceInfo(bundleName,
2672         static_cast<uint32_t>(OHOS::AppExecFwk::ResourceFlag::GET_RESOURCE_INFO_ALL), resourceInfo);
2673     if (result != ERR_OK) {
2674         LOGE("GetBundleResourceInfo failed");
2675         return bundleName;
2676     }
2677     LOGI("bundle resource label is %{public}s ", (resourceInfo.label).c_str());
2678     return resourceInfo.label;
2679 }
2680 
IsScreenLocked()2681 bool DmAuthManager::IsScreenLocked()
2682 {
2683     bool isLocked = false;
2684 #if defined(SUPPORT_SCREENLOCK)
2685     isLocked = OHOS::ScreenLock::ScreenLockManager::GetInstance()->IsScreenLocked();
2686 #endif
2687     LOGI("IsScreenLocked isLocked: %{public}d.", isLocked);
2688     return isLocked;
2689 }
2690 
OnScreenLocked()2691 void DmAuthManager::OnScreenLocked()
2692 {
2693     if (authResponseContext_ != nullptr && AUTH_TYPE_IMPORT_AUTH_CODE == authResponseContext_->authType) {
2694         LOGI("OnScreenLocked authtype is: %{public}d, no need stop bind.", authResponseContext_->authType);
2695         return;
2696     }
2697     if (authRequestState_ == nullptr) {
2698         LOGE("OnScreenLocked authRequestState_ is nullptr.");
2699         return;
2700     }
2701     if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE ||
2702         authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT) {
2703         LOGI("OnScreenLocked stop bind.");
2704         SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL, STATUS_DM_AUTH_DEFAULT);
2705         return;
2706     }
2707     if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_JOIN) {
2708         LOGI("OnScreenLocked stop user input.");
2709         if (authUiStateMgr_ != nullptr) {
2710             authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT);
2711         }
2712         SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL, STATUS_DM_AUTH_DEFAULT);
2713         return;
2714     }
2715     if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) {
2716         LOGI("OnScreenLocked stop confirm.");
2717         SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL, STATUS_DM_AUTH_DEFAULT);
2718     }
2719 }
2720 
HandleDeviceNotTrust(const std::string & udid)2721 void DmAuthManager::HandleDeviceNotTrust(const std::string &udid)
2722 {
2723     LOGI("DmAuthManager::HandleDeviceNotTrust udid: %{public}s.", GetAnonyString(udid).c_str());
2724     if (udid.empty()) {
2725         LOGE("DmAuthManager::HandleDeviceNotTrust udid is empty.");
2726         return;
2727     }
2728     DeviceProfileConnector::GetInstance().DeleteAccessControlList(udid);
2729     CHECK_NULL_VOID(hiChainConnector_);
2730     hiChainConnector_->DeleteAllGroupByUdid(udid);
2731 }
2732 
ConvertSrcVersion(const std::string & version,const std::string & edition)2733 std::string DmAuthManager::ConvertSrcVersion(const std::string &version, const std::string &edition)
2734 {
2735     std::string srcVersion = "";
2736     if (version == "" && edition != "") {
2737         srcVersion = edition;
2738     } else if (version == "" && edition == "") {
2739         srcVersion = DM_VERSION_5_0_1;
2740     } else if (version != "" && edition == "") {
2741         srcVersion = version;
2742     }
2743     LOGI("ConvertSrcVersion version %{public}s, edition %{public}s, srcVersion is %{public}s.",
2744         version.c_str(), edition.c_str(), srcVersion.c_str());
2745     return srcVersion;
2746 }
2747 
ConvertSinkVersion(const std::string & version)2748 std::string DmAuthManager::ConvertSinkVersion(const std::string &version)
2749 {
2750     std::string sinkVersion = "";
2751     if (version == "") {
2752         sinkVersion = DM_VERSION_4_1_5_1;
2753     } else {
2754         sinkVersion = version;
2755     }
2756     LOGI("ConvertSinkVersion version %{public}s, sinkVersion is %{public}s.", version.c_str(), sinkVersion.c_str());
2757     return sinkVersion;
2758 }
2759 
CompareVersion(const std::string & remoteVersion,const std::string & oldVersion)2760 bool DmAuthManager::CompareVersion(const std::string &remoteVersion, const std::string &oldVersion)
2761 {
2762     LOGI("remoteVersion %{public}s, oldVersion %{public}s.", remoteVersion.c_str(), oldVersion.c_str());
2763     std::vector<int32_t> remoteVersionVec;
2764     std::vector<int32_t> oldVersionVec;
2765     VersionSplitToInt(remoteVersion, '.', remoteVersionVec);
2766     VersionSplitToInt(oldVersion, '.', oldVersionVec);
2767     return CompareVecNum(remoteVersionVec, oldVersionVec);
2768 }
2769 
SetAuthType(int32_t authType)2770 void DmAuthManager::SetAuthType(int32_t authType)
2771 {
2772     authType_ = authType;
2773 }
2774 
GetTaskTimeout(const char * taskName,int32_t taskTimeOut)2775 int32_t DmAuthManager::GetTaskTimeout(const char* taskName, int32_t taskTimeOut)
2776 {
2777     LOGI("GetTaskTimeout, taskName: %{public}s, authType_: %{public}d", taskName, authType_.load());
2778     if (AUTH_TYPE_IMPORT_AUTH_CODE == authType_) {
2779         auto timeout = TASK_TIME_OUT_MAP.find(std::string(taskName));
2780         if (timeout != TASK_TIME_OUT_MAP.end()) {
2781             return timeout->second;
2782         }
2783     }
2784     return taskTimeOut;
2785 }
2786 } // namespace DistributedHardware
2787 } // namespace OHOS