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