• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <algorithm>
19 #include <mutex>
20 #include <string>
21 #include <unistd.h>
22 
23 #include "iservice_registry.h"
24 #if defined(SUPPORT_SCREENLOCK)
25 #include "screenlock_manager.h"
26 #endif
27 
28 #include "app_manager.h"
29 #include "auth_message_processor.h"
30 #include "common_event_support.h"
31 #include "dm_ability_manager.h"
32 #include "dm_anonymous.h"
33 #include "dm_config_manager.h"
34 #include "dm_constants.h"
35 #include "dm_crypto.h"
36 #include "dm_dialog_manager.h"
37 #include "dm_language_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 "json_object.h"
43 #include "openssl/sha.h"
44 #include "parameter.h"
45 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
46 #include "multiple_user_connector.h"
47 #endif
48 
49 namespace OHOS {
50 namespace DistributedHardware {
51 const int32_t CANCEL_PIN_CODE_DISPLAY = 1;
52 const int32_t DEVICE_ID_HALF = 2;
53 const int32_t MAX_AUTH_TIMES = 3;
54 const int32_t MIN_PIN_TOKEN = 10000000;
55 const int32_t MAX_PIN_TOKEN = 90000000;
56 const int32_t MIN_PIN_CODE = 100000;
57 const int32_t MAX_PIN_CODE = 999999;
58 const int32_t DM_AUTH_TYPE_MAX = 6;
59 const int32_t DM_AUTH_TYPE_MIN = 0;
60 const int32_t AUTH_SESSION_SIDE_SERVER = 0;
61 const int32_t USLEEP_TIME_US_500000 = 500000; // 500ms
62 const int32_t AUTH_DEVICE_TIMEOUT = 10;
63 const int32_t ALREADY_BIND = 1;
64 const int32_t STRTOLL_BASE_10 = 10;
65 const int32_t MAX_PUT_SESSIONKEY_TIMEOUT = 100; //ms
66 const int32_t SESSION_CLOSE_TIMEOUT = 2;
67 const char* IS_NEED_JOIN_LNN = "IsNeedJoinLnn";
68 constexpr const char* NEED_JOIN_LNN = "0";
69 constexpr const char* NO_NEED_JOIN_LNN = "1";
70 
71 // clone task timeout map
72 const std::map<std::string, int32_t> TASK_TIME_OUT_MAP = {
73     { std::string(AUTHENTICATE_TIMEOUT_TASK), CLONE_AUTHENTICATE_TIMEOUT },
74     { std::string(NEGOTIATE_TIMEOUT_TASK), CLONE_NEGOTIATE_TIMEOUT },
75     { std::string(CONFIRM_TIMEOUT_TASK), CLONE_CONFIRM_TIMEOUT },
76     { std::string(ADD_TIMEOUT_TASK), CLONE_ADD_TIMEOUT },
77     { std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), CLONE_WAIT_NEGOTIATE_TIMEOUT },
78     { std::string(WAIT_REQUEST_TIMEOUT_TASK), CLONE_WAIT_REQUEST_TIMEOUT },
79     { std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), CLONE_SESSION_HEARTBEAT_TIMEOUT }
80 };
81 const std::map<AuthState, DmAuthStatus> OLD_STATE_MAPPING = {
82     { AuthState::AUTH_REQUEST_INIT, DmAuthStatus::STATUS_DM_AUTH_DEFAULT },
83     { AuthState::AUTH_REQUEST_NEGOTIATE, DmAuthStatus::STATUS_DM_AUTH_DEFAULT },
84     { AuthState::AUTH_REQUEST_NEGOTIATE_DONE, DmAuthStatus::STATUS_DM_AUTH_DEFAULT },
85     { AuthState::AUTH_REQUEST_REPLY, DmAuthStatus::STATUS_DM_AUTH_DEFAULT },
86     { AuthState::AUTH_REQUEST_JOIN, DmAuthStatus::STATUS_DM_AUTH_DEFAULT },
87     { AuthState::AUTH_REQUEST_NETWORK, DmAuthStatus::STATUS_DM_AUTH_DEFAULT },
88     { AuthState::AUTH_REQUEST_FINISH, DmAuthStatus::STATUS_DM_AUTH_FINISH },
89     { AuthState::AUTH_REQUEST_CREDENTIAL, DmAuthStatus::STATUS_DM_AUTH_DEFAULT },
90     { AuthState::AUTH_REQUEST_CREDENTIAL_DONE, DmAuthStatus::STATUS_DM_AUTH_DEFAULT },
91     { AuthState::AUTH_REQUEST_AUTH_FINISH, DmAuthStatus::STATUS_DM_AUTH_DEFAULT },
92     { AuthState::AUTH_REQUEST_RECHECK_MSG, DmAuthStatus::STATUS_DM_AUTH_DEFAULT },
93     { AuthState::AUTH_REQUEST_RECHECK_MSG_DONE, DmAuthStatus::STATUS_DM_AUTH_DEFAULT },
94     { AuthState::AUTH_RESPONSE_FINISH, DmAuthStatus::STATUS_DM_SINK_AUTH_FINISH }
95 };
96 constexpr int32_t PROCESS_NAME_WHITE_LIST_NUM = 1;
97 constexpr const static char* PROCESS_NAME_WHITE_LIST[PROCESS_NAME_WHITE_LIST_NUM] = {
98     "com.example.myapplication"
99 };
100 
101 constexpr const char* DM_VERSION_4_1_5_1 = "4.1.5.1";
102 std::mutex g_authFinishLock;
103 
DmAuthManager(std::shared_ptr<SoftbusConnector> softbusConnector,std::shared_ptr<HiChainConnector> hiChainConnector,std::shared_ptr<IDeviceManagerServiceListener> listener,std::shared_ptr<HiChainAuthConnector> hiChainAuthConnector)104 DmAuthManager::DmAuthManager(std::shared_ptr<SoftbusConnector> softbusConnector,
105                              std::shared_ptr<HiChainConnector> hiChainConnector,
106                              std::shared_ptr<IDeviceManagerServiceListener> listener,
107                              std::shared_ptr<HiChainAuthConnector> hiChainAuthConnector)
108     : softbusConnector_(softbusConnector), hiChainConnector_(hiChainConnector), listener_(listener),
109       hiChainAuthConnector_(hiChainAuthConnector)
110 {
111     LOGI("DmAuthManager constructor");
112     DmConfigManager &dmConfigManager = DmConfigManager::GetInstance();
113     dmConfigManager.GetAuthAdapter(authenticationMap_);
114     authUiStateMgr_ = std::make_shared<AuthUiStateManager>(listener_);
115     authenticationMap_[AUTH_TYPE_IMPORT_AUTH_CODE] = nullptr;
116     authenticationMap_[AUTH_TYPE_CRE] = nullptr;
117     authenticationMap_[AUTH_TYPE_NFC] = nullptr;
118     dmVersion_ = DM_VERSION_5_0_5;
119 }
120 
~DmAuthManager()121 DmAuthManager::~DmAuthManager()
122 {
123     LOGI("DmAuthManager destructor");
124 }
125 
IsHmlSessionType()126 bool DmAuthManager::IsHmlSessionType()
127 {
128     CHECK_NULL_RETURN(authRequestContext_, false);
129     return authRequestContext_->connSessionType == CONN_SESSION_TYPE_HML;
130 }
131 
CheckAuthParamVaild(const std::string & pkgName,int32_t authType,const std::string & deviceId,const std::string & extra)132 int32_t DmAuthManager::CheckAuthParamVaild(const std::string &pkgName, int32_t authType,
133     const std::string &deviceId, const std::string &extra)
134 {
135     LOGI("start.");
136     if (authType < DM_AUTH_TYPE_MIN || authType > DM_AUTH_TYPE_MAX) {
137         LOGE("CheckAuthParamVaild failed, authType is illegal.");
138         return ERR_DM_AUTH_FAILED;
139     }
140     if (pkgName.empty() || deviceId.empty()) {
141         LOGE("DmAuthManager::CheckAuthParamVaild failed, pkgName is %{public}s, deviceId is %{public}s, extra is"
142             "%{public}s.", pkgName.c_str(), GetAnonyString(deviceId).c_str(), extra.c_str());
143         return ERR_DM_INPUT_PARA_INVALID;
144     }
145     if (listener_ == nullptr || authUiStateMgr_ == nullptr) {
146         LOGE("DmAuthManager::CheckAuthParamVaild listener or authUiStateMgr is nullptr.");
147         return ERR_DM_INPUT_PARA_INVALID;
148     }
149 
150     if (!IsAuthTypeSupported(authType)) {
151         LOGE("DmAuthManager::CheckAuthParamVaild authType %{public}d not support.", authType);
152         listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT,
153             ERR_DM_UNSUPPORTED_AUTH_TYPE);
154         listener_->OnBindResult(processInfo_, peerTargetId_, ERR_DM_UNSUPPORTED_AUTH_TYPE, STATUS_DM_AUTH_DEFAULT, "");
155         return ERR_DM_UNSUPPORTED_AUTH_TYPE;
156     }
157 
158     if (authRequestState_ != nullptr || authResponseState_ != nullptr) {
159         LOGE("DmAuthManager::CheckAuthParamVaild %{public}s is request authentication.", pkgName.c_str());
160         return ERR_DM_AUTH_BUSINESS_BUSY;
161     }
162 
163     if ((authType == AUTH_TYPE_IMPORT_AUTH_CODE || authType == AUTH_TYPE_NFC) && (!IsAuthCodeReady(pkgName))) {
164         LOGE("Auth code not exist.");
165         listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT,
166             ERR_DM_INPUT_PARA_INVALID);
167         listener_->OnBindResult(processInfo_, peerTargetId_, ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, "");
168         return ERR_DM_INPUT_PARA_INVALID;
169     }
170     return DM_OK;
171 }
172 
CheckAuthParamVaildExtra(const std::string & extra,const std::string & deviceId)173 int32_t DmAuthManager::CheckAuthParamVaildExtra(const std::string &extra, const std::string &deviceId)
174 {
175     JsonObject jsonObject(extra);
176     if ((jsonObject.IsDiscarded() || !IsString(jsonObject, PARAM_KEY_CONN_SESSIONTYPE) ||
177         jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get<std::string>() != CONN_SESSION_TYPE_HML) &&
178         !softbusConnector_->HaveDeviceInMap(deviceId)) {
179         LOGE("CheckAuthParamVaild failed, the discoveryDeviceInfoMap_ not have this device.");
180         listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT,
181             ERR_DM_INPUT_PARA_INVALID);
182         listener_->OnBindResult(processInfo_, peerTargetId_, ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, "");
183         return ERR_DM_INPUT_PARA_INVALID;
184     }
185     if (jsonObject.IsDiscarded()) {
186         return DM_OK;
187     }
188     std::string connSessionType;
189     if (IsString(jsonObject, PARAM_KEY_CONN_SESSIONTYPE)) {
190         connSessionType = jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get<std::string>();
191     }
192     if (connSessionType == CONN_SESSION_TYPE_HML && !CheckHmlParamValid(jsonObject)) {
193         LOGE("CONN_SESSION_TYPE_HML, CheckHmlParamValid failed");
194         return ERR_DM_INPUT_PARA_INVALID;
195     }
196 
197     if (jsonObject.IsDiscarded() || !jsonObject.Contains(TAG_BIND_LEVEL)) {
198         return DM_OK;
199     }
200     return DM_OK;
201 }
202 
CheckHmlParamValid(JsonObject & jsonObject)203 bool DmAuthManager::CheckHmlParamValid(JsonObject &jsonObject)
204 {
205     if (!IsString(jsonObject, PARAM_KEY_HML_ACTIONID)) {
206         LOGE("PARAM_KEY_HML_ACTIONID is not string");
207         return false;
208     }
209     std::string actionIdStr = jsonObject[PARAM_KEY_HML_ACTIONID].Get<std::string>();
210     if (!IsNumberString(actionIdStr)) {
211         LOGE("PARAM_KEY_HML_ACTIONID is not number");
212         return false;
213     }
214     int32_t actionId = std::atoi(actionIdStr.c_str());
215     if (actionId <= 0) {
216         LOGE("PARAM_KEY_HML_ACTIONID is <= 0");
217         return false;
218     }
219     return true;
220 }
221 
GetAuthParam(const std::string & pkgName,int32_t authType,const std::string & deviceId,const std::string & extra)222 void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType,
223     const std::string &deviceId, const std::string &extra)
224 {
225     LOGI("Get auth param.");
226     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
227     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
228     std::string localUdid = static_cast<std::string>(localDeviceId);
229     authRequestContext_->hostPkgName = pkgName;
230     authRequestContext_->authType = authType;
231     authRequestContext_->localDeviceName = softbusConnector_->GetLocalDeviceName();
232     authRequestContext_->localDeviceTypeId = softbusConnector_->GetLocalDeviceTypeId();
233     authRequestContext_->localDeviceId = localUdid;
234     authRequestContext_->deviceId = deviceId;
235     authRequestContext_->addr = deviceId;
236     authRequestContext_->dmVersion = DM_VERSION_5_0_5;
237     authRequestContext_->localUserId = MultipleUserConnector::GetFirstForegroundUserId();
238     authRequestContext_->localAccountId =
239         MultipleUserConnector::GetOhosAccountIdByUserId(authRequestContext_->localUserId);
240     authRequestContext_->isOnline = false;
241     authRequestContext_->authed = !authRequestContext_->bindType.empty();
242     authRequestContext_->bindLevel = INVALIED_TYPE;
243     JsonObject jsonObject(extra);
244     if (jsonObject.IsDiscarded()) {
245         LOGE("extra string not a json type.");
246         return;
247     }
248     ParseJsonObject(jsonObject);
249     authRequestContext_->token = std::to_string(GenRandInt(MIN_PIN_TOKEN, MAX_PIN_TOKEN));
250 }
251 
ParseJsonObject(JsonObject & jsonObject)252 void DmAuthManager::ParseJsonObject(JsonObject &jsonObject)
253 {
254     if (!jsonObject.IsDiscarded()) {
255         if (IsString(jsonObject, TARGET_PKG_NAME_KEY)) {
256             authRequestContext_->targetPkgName = jsonObject[TARGET_PKG_NAME_KEY].Get<std::string>();
257         }
258         if (IsString(jsonObject, APP_OPERATION_KEY)) {
259             authRequestContext_->appOperation = jsonObject[APP_OPERATION_KEY].Get<std::string>();
260         }
261         if (IsString(jsonObject, CUSTOM_DESCRIPTION_KEY)) {
262             authRequestContext_->customDesc = DmLanguageManager::GetInstance().
263                 GetTextBySystemLanguage(jsonObject[CUSTOM_DESCRIPTION_KEY].Get<std::string>());
264         }
265         if (IsString(jsonObject, TAG_APP_THUMBNAIL2)) {
266             authRequestContext_->appThumbnail = jsonObject[TAG_APP_THUMBNAIL2].Get<std::string>();
267         }
268         authRequestContext_->closeSessionDelaySeconds = 0;
269         if (IsString(jsonObject, PARAM_CLOSE_SESSION_DELAY_SECONDS)) {
270             std::string delaySecondsStr = jsonObject[PARAM_CLOSE_SESSION_DELAY_SECONDS].Get<std::string>();
271             authRequestContext_->closeSessionDelaySeconds = GetCloseSessionDelaySeconds(delaySecondsStr);
272         }
273         if (IsString(jsonObject, TAG_PEER_BUNDLE_NAME)) {
274             authRequestContext_->peerBundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get<std::string>();
275             if (authRequestContext_->peerBundleName == "") {
276                 authRequestContext_->peerBundleName = authRequestContext_->hostPkgName;
277             }
278             LOGI("ParseJsonObject peerBundleName = %{public}s", authRequestContext_->peerBundleName.c_str());
279         } else {
280             authRequestContext_->peerBundleName = authRequestContext_->hostPkgName;
281         }
282         ParseHmlInfoInJsonObject(jsonObject);
283     }
284 }
285 
ParseHmlInfoInJsonObject(JsonObject & jsonObject)286 void DmAuthManager::ParseHmlInfoInJsonObject(JsonObject &jsonObject)
287 {
288     CHECK_NULL_VOID(authRequestContext_);
289     if (IsString(jsonObject, PARAM_KEY_CONN_SESSIONTYPE)) {
290         authRequestContext_->connSessionType = jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get<std::string>();
291         LOGI("connSessionType %{public}s", authRequestContext_->connSessionType.c_str());
292     }
293     if (!IsHmlSessionType()) {
294         return;
295     }
296     if (IsString(jsonObject, PARAM_KEY_HML_ACTIONID)) {
297         std::string actionIdStr = jsonObject[PARAM_KEY_HML_ACTIONID].Get<std::string>();
298         if (IsNumberString(actionIdStr)) {
299             authRequestContext_->hmlActionId = std::atoi(actionIdStr.c_str());
300         }
301         if (authRequestContext_->hmlActionId <= 0) {
302             authRequestContext_->hmlActionId = 0;
303         }
304         LOGI("hmlActionId %{public}d", authRequestContext_->hmlActionId);
305     }
306 }
307 
GetCloseSessionDelaySeconds(std::string & delaySecondsStr)308 int32_t DmAuthManager::GetCloseSessionDelaySeconds(std::string &delaySecondsStr)
309 {
310     if (!IsNumberString(delaySecondsStr)) {
311         LOGE("Invalid parameter, param is not number.");
312         return 0;
313     }
314     const int32_t CLOSE_SESSION_DELAY_SECONDS_MAX = 10;
315     int32_t delaySeconds = std::atoi(delaySecondsStr.c_str());
316     if (delaySeconds < 0 || delaySeconds > CLOSE_SESSION_DELAY_SECONDS_MAX) {
317         LOGE("Invalid parameter, param out of range.");
318         return 0;
319     }
320     return delaySeconds;
321 }
322 
InitAuthState(const std::string & pkgName,int32_t authType,const std::string & deviceId,const std::string & extra)323 void DmAuthManager::InitAuthState(const std::string &pkgName, int32_t authType,
324     const std::string &deviceId, const std::string &extra)
325 {
326     auto iter = authenticationMap_.find(authType);
327     if (iter != authenticationMap_.end()) {
328         authPtr_ = iter->second;
329     }
330 
331     if (timer_ == nullptr) {
332         timer_ = std::make_shared<DmTimer>();
333     }
334     timer_->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK),
335         GetTaskTimeout(AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT), [this] (std::string name) {
336             DmAuthManager::HandleAuthenticateTimeout(name);
337         });
338     authMessageProcessor_ = std::make_shared<AuthMessageProcessor>(shared_from_this());
339     authResponseContext_ = std::make_shared<DmAuthResponseContext>();
340     authRequestContext_ = std::make_shared<DmAuthRequestContext>();
341     JsonObject jsonObject(extra);
342     if (jsonObject.IsDiscarded()) {
343         LOGE("extra string not a json type.");
344         return;
345     }
346 
347     GetAuthParam(pkgName, authType, deviceId, extra);
348     authMessageProcessor_->SetRequestContext(authRequestContext_);
349     authRequestState_ = std::make_shared<AuthRequestInitState>();
350     authRequestState_->SetAuthManager(shared_from_this());
351     authRequestState_->SetAuthContext(authRequestContext_);
352     if (!DmRadarHelper::GetInstance().ReportAuthStart(peerTargetId_.deviceId, pkgName)) {
353         LOGE("ReportAuthStart failed");
354     }
355     GetBindCallerInfo();
356     authRequestState_->Enter();
357     LOGI("DmAuthManager::AuthenticateDevice complete");
358 }
359 
AuthenticateDevice(const std::string & pkgName,int32_t authType,const std::string & deviceId,const std::string & extra)360 int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t authType,
361     const std::string &deviceId, const std::string &extra)
362 {
363     LOGI("start auth type %{public}d.", authType);
364     processInfo_.pkgName = pkgName;
365     {
366         std::lock_guard<std::mutex> lock(bindParamMutex_);
367         if (bindParam_.find("bindCallerUserId") != bindParam_.end()) {
368             processInfo_.userId = std::atoi(bindParam_["bindCallerUserId"].c_str());
369         }
370     }
371     SetAuthType(authType);
372     int32_t ret = CheckAuthParamVaild(pkgName, authType, deviceId, extra);
373     if (ret != DM_OK) {
374         LOGE("DmAuthManager::AuthenticateDevice failed, param is invaild.");
375         listener_->OnBindResult(processInfo_, peerTargetId_, ret, STATUS_DM_AUTH_DEFAULT, "");
376         return ret;
377     }
378     ret = CheckAuthParamVaildExtra(extra, deviceId);
379     if (ret != DM_OK) {
380         LOGE("CheckAuthParamVaildExtra failed, param is invaild.");
381         listener_->OnBindResult(processInfo_, peerTargetId_, ret, STATUS_DM_AUTH_DEFAULT, "");
382         return ret;
383     }
384     isAuthenticateDevice_ = true;
385     if (authType == AUTH_TYPE_CRE) {
386         LOGI("DmAuthManager::AuthenticateDevice for credential type, joinLNN directly.");
387         softbusConnector_->JoinLnn(deviceId, true);
388         listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, DM_OK);
389         listener_->OnBindResult(processInfo_, peerTargetId_, DM_OK, STATUS_DM_AUTH_DEFAULT, "");
390     }
391     InitAuthState(pkgName, authType, deviceId, extra);
392     return DM_OK;
393 }
394 
UnAuthenticateDevice(const std::string & pkgName,const std::string & udid,int32_t bindLevel)395 int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel)
396 {
397     if (pkgName.empty()) {
398         LOGE("Invalid parameter, pkgName is empty.");
399         return ERR_DM_FAILED;
400     }
401     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
402     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
403     struct RadarInfo info = {
404         .funcName = "UnAuthenticateDevice",
405         .toCallPkg = HICHAINNAME,
406         .hostName = pkgName,
407         .peerUdid = udid,
408     };
409     if (!DmRadarHelper::GetInstance().ReportDeleteTrustRelation(info)) {
410         LOGE("ReportDeleteTrustRelation failed");
411     }
412     remoteDeviceId_ = udid;
413     if (static_cast<uint32_t>(bindLevel) == USER) {
414         DeleteGroup(pkgName, udid);
415     }
416     std::string extra = "";
417     return DeleteAcl(pkgName, std::string(localDeviceId), udid, bindLevel, extra);
418 }
419 
StopAuthenticateDevice(const std::string & pkgName)420 int32_t DmAuthManager::StopAuthenticateDevice(const std::string &pkgName)
421 {
422     if (pkgName.empty() || authRequestContext_ == nullptr || authResponseContext_ == nullptr) {
423         LOGE("Invalid parameter, pkgName is empty.");
424         return ERR_DM_INPUT_PARA_INVALID;
425     }
426     if (((authRequestState_!= nullptr && authRequestContext_->hostPkgName == pkgName) ||
427         (authResponseContext_ != nullptr && authResponseContext_->hostPkgName == pkgName)) &&
428         isAuthenticateDevice_) {
429         LOGI("Stop previous AuthenticateDevice.");
430         authRequestContext_->reason = STOP_BIND;
431         authResponseContext_->state = authRequestState_->GetStateType();
432         authResponseContext_->reply = STOP_BIND;
433         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
434     }
435     return DM_OK;
436 }
437 
DeleteAcl(const std::string & pkgName,const std::string & localUdid,const std::string & remoteUdid,int32_t bindLevel,const std::string & extra)438 int32_t DmAuthManager::DeleteAcl(const std::string &pkgName, const std::string &localUdid,
439     const std::string &remoteUdid, int32_t bindLevel, const std::string &extra)
440 {
441     LOGI("DeleteAcl pkgName %{public}s, localUdid %{public}s, remoteUdid %{public}s, bindLevel %{public}d.",
442         pkgName.c_str(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str(), bindLevel);
443     DmOfflineParam offlineParam =
444         DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localUdid, remoteUdid, bindLevel, extra);
445     if (offlineParam.bindType == INVALIED_TYPE) {
446         LOGE("Acl not contain the pkgname bind data.");
447         return ERR_DM_FAILED;
448     }
449     if (static_cast<uint32_t>(bindLevel) == APP) {
450         ProcessInfo processInfo;
451         processInfo.pkgName = pkgName;
452         processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId();
453         if (offlineParam.leftAclNumber != 0) {
454             LOGI("The pkgName unbind app-level type leftAclNumber not zero.");
455             softbusConnector_->SetProcessInfoVec(offlineParam.processVec);
456             softbusConnector_->HandleDeviceOffline(remoteUdid);
457             return DM_OK;
458         }
459         if (offlineParam.leftAclNumber == 0) {
460             LOGI("The pkgName unbind app-level type leftAclNumber is zero.");
461             softbusConnector_->SetProcessInfoVec(offlineParam.processVec);
462             hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(),
463                 offlineParam.peerUserId);
464             return DM_OK;
465         }
466     }
467     if (static_cast<uint32_t>(bindLevel) == USER && offlineParam.leftAclNumber != 0) {
468         LOGI("Unbind deivce-level, retain identical account bind type.");
469         return DM_OK;
470     }
471     if (static_cast<uint32_t>(bindLevel) == USER && offlineParam.leftAclNumber == 0) {
472         LOGI("Unbind deivce-level, retain null.");
473         hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(),
474             offlineParam.peerUserId);
475         return DM_OK;
476     }
477     return ERR_DM_FAILED;
478 }
479 
UnBindDevice(const std::string & pkgName,const std::string & udid,int32_t bindLevel,const std::string & extra)480 int32_t DmAuthManager::UnBindDevice(const std::string &pkgName, const std::string &udid,
481     int32_t bindLevel, const std::string &extra)
482 {
483     if (pkgName.empty()) {
484         LOGE("Invalid parameter, pkgName is empty.");
485         return ERR_DM_FAILED;
486     }
487     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
488     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
489     if (static_cast<uint32_t>(bindLevel) == USER) {
490         DeleteGroup(pkgName, udid);
491     }
492     return DeleteAcl(pkgName, std::string(localDeviceId), udid, bindLevel, extra);
493 }
494 
GetPeerUdidHash(int32_t sessionId,std::string & peerUdidHash)495 void DmAuthManager::GetPeerUdidHash(int32_t sessionId, std::string &peerUdidHash)
496 {
497     std::string peerUdid = "";
498     int32_t ret = softbusConnector_->GetSoftbusSession()->GetPeerDeviceId(sessionId, peerUdid);
499     if (ret != DM_OK) {
500         LOGE("DmAuthManager::GetPeerUdidHash failed.");
501         peerUdidHash = "";
502         return;
503     }
504     char udidHashTmp[DM_MAX_DEVICE_ID_LEN] = {0};
505     if (Crypto::GetUdidHash(peerUdid, reinterpret_cast<uint8_t *>(udidHashTmp)) != DM_OK) {
506         LOGE("get udidhash by udid: %{public}s failed.", GetAnonyString(peerUdid).c_str());
507         peerUdidHash = "";
508         return;
509     }
510     peerUdidHash = std::string(udidHashTmp);
511 }
512 
DeleteOffLineTimer(int32_t sessionId)513 void DmAuthManager::DeleteOffLineTimer(int32_t sessionId)
514 {
515     GetPeerUdidHash(sessionId, remoteUdidHash_);
516     if (remoteUdidHash_.empty()) {
517         LOGE("DeleteOffLineTimer remoteUdidHash is empty.");
518         return;
519     }
520     if (softbusConnector_ != nullptr) {
521         softbusConnector_->DeleteOffLineTimer(remoteUdidHash_);
522     }
523 }
524 
OnSessionOpened(int32_t sessionId,int32_t sessionSide,int32_t result)525 void DmAuthManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result)
526 {
527     LOGI("sessionId = %{public}d and sessionSide = %{public}d result = %{public}d", sessionId, sessionSide, result);
528     DeleteOffLineTimer(sessionId);
529     if (sessionSide == AUTH_SESSION_SIDE_SERVER) {
530         if (authResponseState_ == nullptr && authRequestState_ == nullptr) {
531             authMessageProcessor_ = std::make_shared<AuthMessageProcessor>(shared_from_this());
532             authResponseState_ = std::make_shared<AuthResponseInitState>();
533             authResponseState_->SetAuthManager(shared_from_this());
534             authResponseState_->Enter();
535             authResponseContext_ = std::make_shared<DmAuthResponseContext>();
536             authResponseContext_->sessionId = sessionId;
537             if (timer_ == nullptr) {
538                 timer_ = std::make_shared<DmTimer>();
539             }
540             timer_->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK),
541                 GetTaskTimeout(AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT), [this] (std::string name) {
542                     DmAuthManager::HandleAuthenticateTimeout(name);
543                 });
544             timer_->StartTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK),
545                 GetTaskTimeout(WAIT_NEGOTIATE_TIMEOUT_TASK, WAIT_NEGOTIATE_TIMEOUT), [this] (std::string name) {
546                     DmAuthManager::HandleAuthenticateTimeout(name);
547                 });
548         } else {
549             std::shared_ptr<AuthMessageProcessor> authMessageProcessor =
550                 std::make_shared<AuthMessageProcessor>(shared_from_this());
551             std::shared_ptr<DmAuthResponseContext> authResponseContext = std::make_shared<DmAuthResponseContext>();
552             authResponseContext->reply = ERR_DM_AUTH_BUSINESS_BUSY;
553             authMessageProcessor->SetResponseContext(authResponseContext);
554             std::string message = authMessageProcessor->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE);
555             softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
556             softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId);
557         }
558     } else {
559         if (authResponseState_ == nullptr && authRequestState_ != nullptr &&
560             authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT) {
561             authRequestContext_->sessionId = sessionId;
562             authResponseContext_->sessionId = sessionId;
563             authMessageProcessor_->SetRequestContext(authRequestContext_);
564             authRequestState_->SetAuthContext(authRequestContext_);
565             authRequestState_->TransitionTo(std::make_shared<AuthRequestNegotiateState>());
566             struct RadarInfo info = { .funcName = "OnSessionOpened" };
567             info.channelId = sessionId;
568             DmRadarHelper::GetInstance().ReportAuthSendRequest(info);
569         } else {
570             softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId);
571             LOGE("DmAuthManager::OnSessionOpened but request state is wrong");
572         }
573     }
574 }
575 
OnSessionClosed(const int32_t sessionId)576 void DmAuthManager::OnSessionClosed(const int32_t sessionId)
577 {
578     LOGI("DmAuthManager::OnSessionClosed sessionId = %{public}d", sessionId);
579     if (authResponseState_ != nullptr && authResponseContext_ != nullptr) {
580         {
581             std::lock_guard<std::mutex> lock(groupMutex_);
582             if (authResponseState_->GetStateType() == AUTH_RESPONSE_SHOW &&
583                 authResponseContext_->reply == DM_OK && isCreateGroup_ && !isAddMember_) {
584                 LOGI("wait addmemer callback");
585                 return;
586             }
587         }
588         isFinishOfLocal_ = false;
589         authResponseContext_->state = authResponseState_->GetStateType();
590         authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
591     }
592 }
593 
ClearSoftbusSessionCallback()594 void DmAuthManager::ClearSoftbusSessionCallback()
595 {
596     LOGI("DmAuthManager ClearSoftbusSessionCallback");
597     if (softbusConnector_ != nullptr && softbusConnector_->GetSoftbusSession() != nullptr) {
598         softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback();
599     }
600 }
601 
PrepareSoftbusSessionCallback()602 void DmAuthManager::PrepareSoftbusSessionCallback()
603 {
604     LOGI("DmAuthManager PrepareSoftbusSessionCallback");
605     if (softbusConnector_ != nullptr && softbusConnector_->GetSoftbusSession() != nullptr) {
606         softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(shared_from_this());
607     }
608 }
609 
ProcessSourceMsg()610 void DmAuthManager::ProcessSourceMsg()
611 {
612     authRequestContext_ = authMessageProcessor_->GetRequestContext();
613     authRequestState_->SetAuthContext(authRequestContext_);
614     LOGI("OnDataReceived for source device, authResponseContext msgType = %{public}d, authRequestState stateType ="
615         "%{public}d", authResponseContext_->msgType, authRequestState_->GetStateType());
616 
617     switch (authResponseContext_->msgType) {
618         case MSG_TYPE_RESP_AUTH:
619         case MSG_TYPE_RESP_AUTH_EXT:
620             if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) {
621                 authRequestState_->TransitionTo(std::make_shared<AuthRequestReplyState>());
622             }
623             break;
624         case MSG_TYPE_RESP_NEGOTIATE:
625             if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE) {
626                 authRequestState_->TransitionTo(std::make_shared<AuthRequestNegotiateDoneState>());
627             }
628             break;
629         case MSG_TYPE_REQ_AUTH_TERMINATE:
630             if (authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) {
631                 isFinishOfLocal_ = false;
632                 authResponseContext_->state = authRequestState_->GetStateType();
633                 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
634             }
635             break;
636         case MSG_TYPE_RESP_PUBLICKEY:
637             if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_CREDENTIAL) {
638                 authRequestState_->TransitionTo(std::make_shared<AuthRequestCredentialDone>());
639             }
640             break;
641         case MSG_TYPE_RESP_RECHECK_MSG:
642             if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_RECHECK_MSG) {
643                 authRequestState_->TransitionTo(std::make_shared<AuthRequestReCheckMsgDone>());
644             }
645             break;
646         default:
647             break;
648     }
649 }
650 
ProcessSinkMsg()651 void DmAuthManager::ProcessSinkMsg()
652 {
653     authResponseState_->SetAuthContext(authResponseContext_);
654     LOGI("OnDataReceived for sink device, authResponseContext msgType = %{public}d, authResponseState stateType ="
655         "%{public}d", authResponseContext_->msgType, authResponseState_->GetStateType());
656 
657     switch (authResponseContext_->msgType) {
658         case MSG_TYPE_NEGOTIATE:
659             if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_INIT) {
660                 if (timer_ != nullptr) {
661                     timer_->DeleteTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK));
662                 }
663                 authResponseState_->TransitionTo(std::make_shared<AuthResponseNegotiateState>());
664             }
665             break;
666         case MSG_TYPE_REQ_AUTH:
667             if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_NEGOTIATE) {
668                 if (timer_ != nullptr) {
669                     timer_->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK));
670                 }
671                 authResponseState_->TransitionTo(std::make_shared<AuthResponseConfirmState>());
672             }
673             break;
674         case MSG_TYPE_REQ_AUTH_TERMINATE:
675             ProcessReqAuthTerminate();
676             break;
677         case MSG_TYPE_REQ_PUBLICKEY:
678             ProcessReqPublicKey();
679             break;
680         case MSG_TYPE_REQ_RECHECK_MSG:
681             if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_AUTH_FINISH) {
682                 authResponseState_->TransitionTo(std::make_shared<AuthResponseReCheckMsg>());
683                 break;
684             }
685             if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW) {
686                 std::lock_guard<std::mutex> lock(srcReqMsgLock_);
687                 isNeedProcCachedSrcReqMsg_ = true;
688             }
689             break;
690         default:
691             break;
692     }
693 }
694 
ProcessReqAuthTerminate()695 void DmAuthManager::ProcessReqAuthTerminate()
696 {
697     {
698         std::lock_guard<std::mutex> lock(groupMutex_);
699         if (authResponseState_->GetStateType() == AUTH_RESPONSE_SHOW &&
700             authResponseContext_->reply == DM_OK && isCreateGroup_ && !isAddMember_) {
701             LOGI("wait addmemer callback");
702             transitToFinishState_ = true;
703             return;
704         }
705     }
706     if (authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) {
707         isFinishOfLocal_ = false;
708         authResponseContext_->state = authResponseState_->GetStateType();
709         if (authResponseContext_->reply == DM_OK) {
710             authResponseContext_->state = AuthState::AUTH_RESPONSE_FINISH;
711         }
712         authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
713     }
714 }
715 
OnDataReceived(const int32_t sessionId,const std::string message)716 void DmAuthManager::OnDataReceived(const int32_t sessionId, const std::string message)
717 {
718     if (authResponseContext_ == nullptr || authMessageProcessor_ == nullptr ||
719         sessionId != authResponseContext_->sessionId) {
720         LOGE("OnDataReceived failed, authResponseContext or authMessageProcessor_ is nullptr.");
721         return;
722     }
723 
724     authResponseContext_->sessionId = sessionId;
725     authMessageProcessor_->SetResponseContext(authResponseContext_);
726     int32_t ret = authMessageProcessor_->ParseMessage(message);
727     if (ret != DM_OK) {
728         LOGE("OnDataReceived failed, parse input message error.");
729         return;
730     }
731 
732     if ((authRequestState_ != nullptr) && (authResponseState_ == nullptr)) {
733         // source device auth process
734         ProcessSourceMsg();
735     } else if ((authResponseState_ != nullptr) && (authRequestState_ == nullptr)) {
736         // sink device auth process
737         {
738             std::lock_guard<std::mutex> lock(srcReqMsgLock_);
739             srcReqMsg_ = message;
740         }
741         ProcessSinkMsg();
742     } else {
743         LOGE("DmAuthManager::OnDataReceived failed, authRequestState_ or authResponseState_ is invalid.");
744     }
745 }
746 
OnGroupCreated(int64_t requestId,const std::string & groupId)747 void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId)
748 {
749     if (authResponseContext_ == nullptr) {
750         LOGE("failed to OnGroupCreated because authResponseContext_ is nullptr");
751         return;
752     }
753     if (authResponseState_ == nullptr) {
754         LOGE("DmAuthManager::AuthenticateDevice end");
755         return;
756     }
757     LOGI("DmAuthManager::OnGroupCreated start group id %{public}s", GetAnonyString(groupId).c_str());
758     if (groupId == "{}") {
759         authResponseContext_->reply = ERR_DM_CREATE_GROUP_FAILED;
760         authMessageProcessor_->SetResponseContext(authResponseContext_);
761         std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH);
762         softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
763         return;
764     }
765     std::string pinCode = "";
766     if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && !importAuthCode_.empty()) {
767         GetAuthCode(authResponseContext_->hostPkgName, pinCode);
768     } else if (authResponseContext_->authType != AUTH_TYPE_IMPORT_AUTH_CODE) {
769         pinCode = GeneratePincode();
770     } else {
771         LOGE("authType invalied.");
772     }
773     JsonObject jsonObj;
774     jsonObj[PIN_TOKEN] = authResponseContext_->token;
775     jsonObj[QR_CODE_KEY] = GenerateGroupName();
776     jsonObj[NFC_CODE_KEY] = GenerateGroupName();
777     authResponseContext_->authToken = jsonObj.Dump();
778     LOGI("DmAuthManager::OnGroupCreated start group id %{public}s", GetAnonyString(groupId).c_str());
779     authResponseContext_->groupId = groupId;
780     authResponseContext_->code = pinCode;
781     authMessageProcessor_->SetResponseContext(authResponseContext_);
782     std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH);
783     softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
784     authResponseContext_->isFinish = true;
785     authResponseState_->TransitionTo(std::make_shared<AuthResponseShowState>());
786 }
787 
OnMemberJoin(int64_t requestId,int32_t status,int32_t operationCode)788 void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status, int32_t operationCode)
789 {
790     isAddingMember_ = false;
791     if (authResponseContext_ == nullptr || authUiStateMgr_ == nullptr) {
792         LOGE("failed to OnMemberJoin because authResponseContext_ or authUiStateMgr is nullptr");
793         return;
794     }
795     LOGI("DmAuthManager OnMemberJoin start authTimes %{public}d", authTimes_);
796     if (status == DM_OK && operationCode == GroupOperationCode::MEMBER_JOIN) {
797         LOGI("join group success.");
798         CompatiblePutAcl();
799         {
800             std::lock_guard<std::mutex> lock(groupMutex_);
801             isAddMember_ = true;
802             if (transitToFinishState_) {
803                 LOGI("Have received src finish state.");
804                 authResponseContext_->state = AuthState::AUTH_RESPONSE_FINISH;
805                 authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
806             }
807         }
808     }
809     if (status == DM_OK && operationCode == GroupOperationCode::GROUP_CREATE) {
810         {
811             std::lock_guard<std::mutex> lock(groupMutex_);
812             isCreateGroup_ = true;
813         }
814     }
815     if ((authRequestState_ != nullptr) && (authResponseState_ == nullptr)) {
816         MemberJoinAuthRequest(requestId, status);
817     } else if ((authResponseState_ != nullptr) && (authRequestState_ == nullptr)) {
818         if (status == DM_OK && authResponseContext_->requestId == requestId &&
819             authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW) {
820             authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW);
821         } else {
822             if (++authTimes_ >= MAX_AUTH_TIMES) {
823                 authResponseContext_->isFinish = false;
824                 authResponseContext_->reply = ERR_DM_BIND_PIN_CODE_ERROR;
825                 authResponseContext_->state = AuthState::AUTH_RESPONSE_SHOW;
826                 isFinishOfLocal_ = false;
827                 authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
828             }
829         }
830     } else {
831         LOGE("DmAuthManager::OnMemberJoin failed, authRequestState_ or authResponseState_ is invalid.");
832     }
833 }
834 
MemberJoinAuthRequest(int64_t requestId,int32_t status)835 void DmAuthManager::MemberJoinAuthRequest(int64_t requestId, int32_t status)
836 {
837     authTimes_++;
838     if (timer_ != nullptr) {
839         timer_->DeleteTimer(std::string(ADD_TIMEOUT_TASK));
840     }
841     if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) {
842         HandleMemberJoinImportAuthCode(requestId, status);
843         return;
844     }
845     if (status != DM_OK || authResponseContext_->requestId != requestId) {
846         if (authRequestState_ != nullptr && authTimes_ >= MAX_AUTH_TIMES) {
847             authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN;
848             authResponseContext_->reply = ERR_DM_BIND_PIN_CODE_ERROR;
849             authRequestContext_->reason = ERR_DM_BIND_PIN_CODE_ERROR;
850             authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
851             return;
852         }
853         if (timer_ != nullptr) {
854             timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK),
855                 GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) {
856                     DmAuthManager::HandleAuthenticateTimeout(name);
857                 });
858         }
859         authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR);
860     } else {
861         authRequestState_->TransitionTo(std::make_shared<AuthRequestNetworkState>());
862         if (timer_ != nullptr) {
863             timer_->DeleteTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK));
864         }
865     }
866 }
867 
HandleMemberJoinImportAuthCode(const int64_t requestId,const int32_t status)868 void DmAuthManager::HandleMemberJoinImportAuthCode(const int64_t requestId, const int32_t status)
869 {
870     if (status != DM_OK || authResponseContext_->requestId != requestId) {
871         authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN;
872         authResponseContext_->reply = ERR_DM_AUTH_CODE_INCORRECT;
873         authRequestContext_->reason = ERR_DM_AUTH_CODE_INCORRECT;
874         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
875     } else {
876         authRequestState_->TransitionTo(std::make_shared<AuthRequestNetworkState>());
877     }
878 }
879 
HandleAuthenticateTimeout(std::string name)880 void DmAuthManager::HandleAuthenticateTimeout(std::string name)
881 {
882     LOGI("DmAuthManager::HandleAuthenticateTimeout start timer name %{public}s", name.c_str());
883     if (authRequestState_ != nullptr && authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) {
884         if (authResponseContext_ == nullptr) {
885             authResponseContext_ = std::make_shared<DmAuthResponseContext>();
886         }
887         authResponseContext_->state = authRequestState_->GetStateType();
888         authRequestContext_->reason = ERR_DM_TIME_OUT;
889         authResponseContext_->reply = ERR_DM_TIME_OUT;
890         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
891     }
892 
893     if (authResponseState_ != nullptr && authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) {
894         authResponseContext_->state = authResponseState_->GetStateType();
895         authResponseContext_->reply = ERR_DM_TIME_OUT;
896         authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
897     }
898     LOGI("DmAuthManager::HandleAuthenticateTimeout start complete");
899 }
900 
EstablishAuthChannel(const std::string & deviceId)901 int32_t DmAuthManager::EstablishAuthChannel(const std::string &deviceId)
902 {
903     if (NeedInsensibleSwitching()) {
904         return DM_OK;
905     }
906     int32_t sessionId = 0;
907     if (IsHmlSessionType()) {
908         CHECK_NULL_RETURN(authRequestContext_, ERR_DM_FAILED);
909         CHECK_NULL_RETURN(listener_, ERR_DM_FAILED);
910         LOGI("hmlActionId %{public}d, hmlReleaseTime %{public}d, hmlEnable160M %{public}d",
911             authRequestContext_->hmlActionId, authRequestContext_->closeSessionDelaySeconds,
912             authRequestContext_->hmlEnable160M);
913         sessionId = listener_->OpenAuthSessionWithPara(deviceId,
914             authRequestContext_->hmlActionId, authRequestContext_->hmlEnable160M);
915     } else {
916         sessionId = softbusConnector_->GetSoftbusSession()->OpenAuthSession(deviceId);
917     }
918     struct RadarInfo info = {
919         .funcName = "EstablishAuthChannel",
920         .stageRes = (sessionId > 0) ?
921             static_cast<int32_t>(StageRes::STAGE_IDLE) : static_cast<int32_t>(StageRes::STAGE_FAIL),
922         .bizState = (sessionId > 0) ?
923             static_cast<int32_t>(BizState::BIZ_STATE_START) : static_cast<int32_t>(BizState::BIZ_STATE_END),
924         .localSessName = DM_SESSION_NAME,
925         .peerSessName = DM_SESSION_NAME,
926         .isTrust = static_cast<int32_t>(TrustStatus::NOT_TRUST),
927         .commServ = static_cast<int32_t>(CommServ::USE_SOFTBUS),
928         .peerUdid = peerTargetId_.deviceId,
929         .channelId = sessionId,
930         .errCode = sessionId,
931     };
932     if (!DmRadarHelper::GetInstance().ReportAuthOpenSession(info)) {
933         LOGE("ReportAuthOpenSession failed");
934     }
935     if (sessionId < 0) {
936         LOGE("OpenAuthSession failed, stop the authentication");
937         if (authResponseContext_ == nullptr) {
938             authResponseContext_ = std::make_shared<DmAuthResponseContext>();
939         }
940         authResponseContext_->state = AuthState::AUTH_REQUEST_NEGOTIATE;
941         authResponseContext_->reply = sessionId;
942         if (authRequestContext_ == nullptr) {
943             authRequestContext_ = std::make_shared<DmAuthRequestContext>();
944         }
945         authRequestContext_->reason = sessionId;
946         if (authRequestState_ != nullptr) {
947             authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
948         }
949     }
950     return DM_OK;
951 }
952 
StartNegotiate(const int32_t & sessionId)953 void DmAuthManager::StartNegotiate(const int32_t &sessionId)
954 {
955     if (authResponseContext_ == nullptr) {
956         LOGE("DmAuthManager::StartNegotiate error, authResponseContext_ is nullptr");
957         return;
958     }
959     LOGI("DmAuthManager::StartNegotiate sessionId %{public}d.", sessionId);
960     authResponseContext_->localDeviceId = authRequestContext_->localDeviceId;
961     authResponseContext_->reply = ERR_DM_AUTH_REJECT;
962     authResponseContext_->authType = authRequestContext_->authType;
963     authResponseContext_->deviceId = authRequestContext_->deviceId;
964     authResponseContext_->accountGroupIdHash = GetAccountGroupIdHash();
965     authResponseContext_->hostPkgName = authRequestContext_->hostPkgName;
966     authResponseContext_->bundleName = authRequestContext_->bundleName;
967     authResponseContext_->peerBundleName = authRequestContext_->peerBundleName;
968     authResponseContext_->hostPkgLabel = authRequestContext_->hostPkgLabel;
969     authResponseContext_->tokenId = authRequestContext_->tokenId;
970     authResponseContext_->bindLevel = authRequestContext_->bindLevel;
971     authResponseContext_->bindType = authRequestContext_->bindType;
972     authResponseContext_->isOnline = authRequestContext_->isOnline;
973     authResponseContext_->authed = authRequestContext_->authed;
974     authResponseContext_->dmVersion = "";
975     authResponseContext_->localAccountId = authRequestContext_->localAccountId;
976     authResponseContext_->localUserId = authRequestContext_->localUserId;
977     authResponseContext_->isIdenticalAccount = false;
978     authResponseContext_->edition = DM_VERSION_5_0_5;
979     authResponseContext_->remoteDeviceName = authRequestContext_->localDeviceName;
980     authMessageProcessor_->SetResponseContext(authResponseContext_);
981     std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_NEGOTIATE);
982     if (!NeedInsensibleSwitching()) {
983         softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
984     }
985     if (timer_ != nullptr) {
986         timer_->StartTimer(std::string(NEGOTIATE_TIMEOUT_TASK),
987             GetTaskTimeout(NEGOTIATE_TIMEOUT_TASK, NEGOTIATE_TIMEOUT), [this] (std::string name) {
988                 DmAuthManager::HandleAuthenticateTimeout(name);
989             });
990     }
991 }
992 
AbilityNegotiate()993 void DmAuthManager::AbilityNegotiate()
994 {
995     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
996     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
997     authResponseContext_->remoteAccountId = authResponseContext_->localAccountId;
998     authResponseContext_->remoteUserId = authResponseContext_->localUserId;
999     GetBinderInfo();
1000     bool ret = hiChainConnector_->IsDevicesInP2PGroup(authResponseContext_->localDeviceId, localDeviceId);
1001     if (ret) {
1002         LOGE("DmAuthManager::EstablishAuthChannel device is in group");
1003         if (!DeviceProfileConnector::GetInstance().CheckSinkDevIdInAclForDevBind(authResponseContext_->hostPkgName,
1004             authResponseContext_->localDeviceId)) {
1005             CompatiblePutAcl();
1006         }
1007         authResponseContext_->reply = ERR_DM_AUTH_PEER_REJECT;
1008     } else {
1009         authResponseContext_->reply = ERR_DM_AUTH_REJECT;
1010     }
1011     authResponseContext_->localDeviceId = localDeviceId;
1012 
1013     if (!IsAuthTypeSupported(authResponseContext_->authType)) {
1014         LOGE("DmAuthManager::AuthenticateDevice authType %{public}d not support.", authResponseContext_->authType);
1015         authResponseContext_->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE;
1016     } else {
1017         authPtr_ = authenticationMap_[authResponseContext_->authType];
1018     }
1019 
1020     if (IsAuthCodeReady(authResponseContext_->hostPkgName)) {
1021         authResponseContext_->isAuthCodeReady = true;
1022     } else {
1023         authResponseContext_->isAuthCodeReady = false;
1024     }
1025 }
1026 
RespNegotiate(const int32_t & sessionId)1027 void DmAuthManager::RespNegotiate(const int32_t &sessionId)
1028 {
1029     if (authResponseContext_ == nullptr || authRequestState_ != nullptr) {
1030         LOGE("failed to RespNegotiate because authResponseContext_ is nullptr");
1031         return;
1032     }
1033     LOGI("DmAuthManager::RespNegotiate sessionid %{public}d", sessionId);
1034     remoteDeviceId_ = authResponseContext_->localDeviceId;
1035     authResponseContext_->networkId = softbusConnector_->GetLocalDeviceNetworkId();
1036     authResponseContext_->targetDeviceName = softbusConnector_->GetLocalDeviceName();
1037     remoteVersion_ = AuthManagerBase::ConvertSrcVersion(authResponseContext_->dmVersion, authResponseContext_->edition);
1038     NegotiateRespMsg(remoteVersion_);
1039     if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) &&
1040         (static_cast<uint32_t>(authResponseContext_->bindLevel) >= USER &&
1041         static_cast<uint32_t>(authResponseContext_->bindLevel) <= APP)) {
1042         ProcRespNegotiateExt(sessionId);
1043         timer_->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK),
1044             GetTaskTimeout(WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), [this] (std::string name) {
1045                 DmAuthManager::HandleAuthenticateTimeout(name);
1046             });
1047     } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) ||
1048         static_cast<uint32_t>(authResponseContext_->bindLevel) == INVALIED_TYPE) {
1049         ProcRespNegotiate(sessionId);
1050         timer_->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK),
1051             GetTaskTimeout(WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), [this] (std::string name) {
1052                 DmAuthManager::HandleAuthenticateTimeout(name);
1053             });
1054     } else {
1055         ProcIncompatible(sessionId);
1056     }
1057 }
1058 
NegotiateRespMsg(const std::string & version)1059 void DmAuthManager::NegotiateRespMsg(const std::string &version)
1060 {
1061     if (version == DM_VERSION_5_0_1) {
1062         authResponseContext_->dmVersion = DM_VERSION_5_0_1;
1063     } else if (version < DM_VERSION_5_0_1) {
1064         authResponseContext_->dmVersion = "";
1065         authResponseContext_->bindLevel = INVALIED_TYPE;
1066     } else if (version > DM_VERSION_5_0_1) {
1067         authResponseContext_->dmVersion = dmVersion_;
1068     }
1069 }
1070 
SendAuthRequest(const int32_t & sessionId)1071 void DmAuthManager::SendAuthRequest(const int32_t &sessionId)
1072 {
1073     LOGI("DmAuthManager::SendAuthRequest sessionId %{public}d.", sessionId);
1074     if (authResponseContext_ == nullptr) {
1075         LOGE("failed to SendAuthRequest because authResponseContext_ is nullptr");
1076         return;
1077     }
1078     if (authResponseContext_->reply == ERR_DM_VERSION_INCOMPATIBLE) {
1079         LOGE("The peer device version is not supported");
1080         authRequestContext_->reason = authResponseContext_->reply;
1081         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
1082         return;
1083     }
1084     remoteDeviceId_ = authResponseContext_->localDeviceId;
1085     authRequestContext_->remoteDeviceName = authResponseContext_->targetDeviceName;
1086     remoteVersion_ = ConvertSinkVersion(authResponseContext_->dmVersion);
1087     if (timer_ != nullptr) {
1088         timer_->DeleteTimer(std::string(NEGOTIATE_TIMEOUT_TASK));
1089     }
1090     if (authResponseContext_->cryptoSupport) {
1091         isCryptoSupport_ = true;
1092     }
1093     LOGI("SendAuthRequest dmversion %{public}s, level %{public}d",
1094         authResponseContext_->dmVersion.c_str(), authResponseContext_->bindLevel);
1095     if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) &&
1096         (static_cast<uint32_t>(authResponseContext_->bindLevel) >= USER &&
1097         static_cast<uint32_t>(authResponseContext_->bindLevel) <= APP)) {
1098         ProcessAuthRequestExt(sessionId);
1099     } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) ||
1100         static_cast<uint32_t>(authResponseContext_->bindLevel) == INVALIED_TYPE) {
1101         ProcessAuthRequest(sessionId);
1102     } else {
1103         LOGE("Invalied bind mode.");
1104     }
1105 }
1106 
ProcessAuthRequest(const int32_t & sessionId)1107 void DmAuthManager::ProcessAuthRequest(const int32_t &sessionId)
1108 {
1109     LOGI("ProcessAuthRequest start.");
1110     if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE &&
1111         !authResponseContext_->importAuthCode.empty() && !importAuthCode_.empty()) {
1112         if (authResponseContext_->importAuthCode != Crypto::Sha256(importAuthCode_)) {
1113             SetReasonAndFinish(ERR_DM_AUTH_CODE_INCORRECT, AuthState::AUTH_REQUEST_FINISH);
1114             return;
1115         }
1116     }
1117 
1118     if (authResponseContext_->isOnline && softbusConnector_->CheckIsOnline(remoteDeviceId_)) {
1119         authResponseContext_->isOnline = true;
1120     } else {
1121         authResponseContext_->isOnline = false;
1122     }
1123     if (CheckTrustState() != DM_OK) {
1124         LOGI("CheckTrustState end.");
1125         return;
1126     }
1127 
1128     std::vector<std::string> messageList = authMessageProcessor_->CreateAuthRequestMessage();
1129     for (auto msg : messageList) {
1130         softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg);
1131     }
1132 
1133     listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, authRequestContext_->token,
1134         STATUS_DM_SHOW_AUTHORIZE_UI, DM_OK);
1135     listener_->OnBindResult(processInfo_, peerTargetId_, DM_OK, STATUS_DM_SHOW_AUTHORIZE_UI, "");
1136     timer_->StartTimer(std::string(CONFIRM_TIMEOUT_TASK),
1137         GetTaskTimeout(CONFIRM_TIMEOUT_TASK, CONFIRM_TIMEOUT), [this] (std::string name) {
1138             DmAuthManager::HandleAuthenticateTimeout(name);
1139         });
1140 }
1141 
GetAuthRequestContext()1142 void DmAuthManager::GetAuthRequestContext()
1143 {
1144     char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0};
1145     Crypto::GetUdidHash(authResponseContext_->localDeviceId, reinterpret_cast<uint8_t *>(deviceIdHash));
1146     authRequestContext_->deviceId = static_cast<std::string>(deviceIdHash);
1147     authResponseContext_->deviceId = authResponseContext_->localDeviceId;
1148     authResponseContext_->localDeviceId = authRequestContext_->localDeviceId;
1149     authRequestContext_->remoteAccountId = authResponseContext_->localAccountId;
1150     authResponseContext_->remoteAccountId = authRequestContext_->remoteAccountId;
1151     authResponseContext_->localAccountId = authRequestContext_->localAccountId;
1152     authRequestContext_->remoteUserId = authResponseContext_->localUserId;
1153     if (authResponseContext_->isOnline && softbusConnector_->CheckIsOnline(remoteDeviceId_)) {
1154         authResponseContext_->isOnline = true;
1155     } else {
1156         authResponseContext_->isOnline = false;
1157     }
1158     authResponseContext_->haveCredential = false;
1159 }
1160 
ProcessAuthRequestExt(const int32_t & sessionId)1161 void DmAuthManager::ProcessAuthRequestExt(const int32_t &sessionId)
1162 {
1163     LOGI("ProcessAuthRequestExt start.");
1164     if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_3)) &&
1165         authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE &&
1166         !authResponseContext_->importAuthCode.empty() && !importAuthCode_.empty()) {
1167         if (authResponseContext_->importAuthCode != Crypto::Sha256(importAuthCode_)) {
1168             SetReasonAndFinish(ERR_DM_AUTH_CODE_INCORRECT, AuthState::AUTH_REQUEST_FINISH);
1169             return;
1170         }
1171     }
1172 
1173     GetAuthRequestContext();
1174     std::vector<int32_t> bindType =
1175         DeviceProfileConnector::GetInstance().SyncAclByBindType(authResponseContext_->hostPkgName,
1176         authResponseContext_->bindType, authResponseContext_->localDeviceId, authResponseContext_->deviceId);
1177     authResponseContext_->authed = !bindType.empty();
1178     if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_3)) &&
1179         authResponseContext_->isOnline && authResponseContext_->authed &&
1180         authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE &&
1181         (authResponseContext_->importAuthCode.empty() || importAuthCode_.empty())) {
1182         SetReasonAndFinish(ERR_DM_AUTH_CODE_INCORRECT, AuthState::AUTH_REQUEST_FINISH);
1183         return;
1184     }
1185     authResponseContext_->bindType = bindType;
1186     if (IsAuthFinish()) {
1187         return;
1188     }
1189 
1190     std::vector<std::string> messageList = authMessageProcessor_->CreateAuthRequestMessage();
1191     for (auto msg : messageList) {
1192         softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg);
1193     }
1194     listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, authRequestContext_->token,
1195         STATUS_DM_SHOW_AUTHORIZE_UI, DM_OK);
1196     listener_->OnBindResult(processInfo_, peerTargetId_, DM_OK, STATUS_DM_SHOW_AUTHORIZE_UI, "");
1197     timer_->StartTimer(std::string(CONFIRM_TIMEOUT_TASK),
1198         GetTaskTimeout(CONFIRM_TIMEOUT_TASK, CONFIRM_TIMEOUT), [this] (std::string name) {
1199             DmAuthManager::HandleAuthenticateTimeout(name);
1200         });
1201 }
1202 
IsAuthFinish()1203 bool DmAuthManager::IsAuthFinish()
1204 {
1205     if (authResponseContext_->reply == ERR_DM_UNSUPPORTED_AUTH_TYPE) {
1206         listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId,
1207             authRequestContext_->token, AuthState::AUTH_REQUEST_NEGOTIATE_DONE, ERR_DM_UNSUPPORTED_AUTH_TYPE);
1208         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
1209         return true;
1210     }
1211 
1212     if ((authResponseContext_->isIdenticalAccount && !authResponseContext_->authed) ||
1213         (authResponseContext_->authed && !authResponseContext_->isOnline)) {
1214         JoinLnn(authRequestContext_->addr);
1215         authRequestContext_->reason = DM_OK;
1216         authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
1217         authResponseContext_->reply = DM_OK;
1218         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
1219         return true;
1220     }
1221 
1222     if (authResponseContext_->reply == ERR_DM_UNSUPPORTED_AUTH_TYPE ||
1223         (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE &&
1224         authResponseContext_->isAuthCodeReady == false)) {
1225         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
1226         return true;
1227     }
1228     return false;
1229 }
1230 
ConfirmProcess(const int32_t & action)1231 int32_t DmAuthManager::ConfirmProcess(const int32_t &action)
1232 {
1233     LOGI("ConfirmProcess start.");
1234     CHECK_NULL_RETURN(authResponseContext_, ERR_DM_POINT_NULL);
1235     authResponseContext_->confirmOperation = action;
1236     if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH || action_ == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) {
1237         authResponseContext_->reply = USER_OPERATION_TYPE_ALLOW_AUTH;
1238     } else {
1239         authResponseContext_->reply = action_;
1240     }
1241 
1242     if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH &&
1243         authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_CONFIRM) {
1244         authResponseState_->TransitionTo(std::make_shared<AuthResponseGroupState>());
1245     } else {
1246         authMessageProcessor_->SetResponseContext(authResponseContext_);
1247         std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH);
1248         softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
1249     }
1250     return DM_OK;
1251 }
1252 
ConfirmProcessExt(const int32_t & action)1253 int32_t DmAuthManager::ConfirmProcessExt(const int32_t &action)
1254 {
1255     LOGI("ConfirmProcessExt start.");
1256     authResponseContext_->confirmOperation = action;
1257     if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH || action_ == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) {
1258         authResponseContext_->reply = USER_OPERATION_TYPE_ALLOW_AUTH;
1259     } else {
1260         authResponseContext_->reply = USER_OPERATION_TYPE_CANCEL_AUTH;
1261     }
1262     authMessageProcessor_->SetResponseContext(authResponseContext_);
1263     if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH &&
1264         authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_CONFIRM) {
1265         if (CanUsePincodeFromDp()) {
1266             authResponseContext_->code = serviceInfoProfile_.GetPinCode();
1267             LOGI("import pincode from dp");
1268         } else if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && !importAuthCode_.empty()) {
1269             GetAuthCode(authResponseContext_->hostPkgName, authResponseContext_->code);
1270         } else {
1271             authResponseContext_->code = GeneratePincode();
1272         }
1273         authResponseContext_->requestId = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE);
1274         authResponseState_->TransitionTo(std::make_shared<AuthResponseShowState>());
1275     }
1276     authMessageProcessor_->SetResponseContext(authResponseContext_);
1277     std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH_EXT);
1278     softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
1279     return DM_OK;
1280 }
1281 
StartAuthProcess(const int32_t & action)1282 int32_t DmAuthManager::StartAuthProcess(const int32_t &action)
1283 {
1284     if (authResponseContext_ == nullptr) {
1285         LOGE("failed to StartAuthProcess because authResponseContext_ is nullptr");
1286         return ERR_DM_AUTH_NOT_START;
1287     }
1288     LOGI("DmAuthManager::StartAuthProcess");
1289     action_ = action;
1290     struct RadarInfo info = {
1291         .funcName = "StartAuthProcess",
1292         .stageRes = (action_ == USER_OPERATION_TYPE_CANCEL_AUTH) ?
1293             static_cast<int32_t>(StageRes::STAGE_CANCEL) : static_cast<int32_t>(StageRes::STAGE_SUCC),
1294         .bizState = (action_ == USER_OPERATION_TYPE_CANCEL_AUTH) ?
1295             static_cast<int32_t>(BizState::BIZ_STATE_END) : static_cast<int32_t>(BizState::BIZ_STATE_START),
1296         .errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_AUTH_REJECT),
1297     };
1298     if (!DmRadarHelper::GetInstance().ReportAuthConfirmBox(info)) {
1299         LOGE("ReportAuthConfirmBox failed");
1300     }
1301     if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) &&
1302         (static_cast<uint32_t>(authResponseContext_->bindLevel) >= USER &&
1303         static_cast<uint32_t>(authResponseContext_->bindLevel) <= APP)) {
1304         return ConfirmProcessExt(action);
1305     } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) ||
1306         static_cast<uint32_t>(authResponseContext_->bindLevel) == INVALIED_TYPE) {
1307         return ConfirmProcess(action);
1308     } else {
1309         LOGE("Invalied bind mode.");
1310     }
1311     return DM_OK;
1312 }
1313 
StartRespAuthProcess()1314 void DmAuthManager::StartRespAuthProcess()
1315 {
1316     if (authResponseContext_ == nullptr) {
1317         LOGE("failed to StartRespAuthProcess because authResponseContext_ is nullptr");
1318         return;
1319     }
1320     LOGI("DmAuthManager::StartRespAuthProcess sessionId = %{public}d", authResponseContext_->sessionId);
1321     if (timer_ != nullptr) {
1322         timer_->DeleteTimer(std::string(CONFIRM_TIMEOUT_TASK));
1323     }
1324     if (authResponseContext_->groupName[CHECK_AUTH_ALWAYS_POS] == AUTH_ALWAYS) {
1325         action_ = USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS;
1326     } else if (authResponseContext_->groupName[CHECK_AUTH_ALWAYS_POS] == AUTH_ONCE) {
1327         action_ = USER_OPERATION_TYPE_ALLOW_AUTH;
1328     }
1329     if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH) {
1330         timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK),
1331             GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) {
1332                 DmAuthManager::HandleAuthenticateTimeout(name);
1333             });
1334         timer_->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK),
1335             GetTaskTimeout(SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), [this] (std::string name) {
1336                 DmAuthManager::HandleSessionHeartbeat(name);
1337             });
1338         listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId,
1339             authRequestContext_->token, STATUS_DM_SHOW_PIN_INPUT_UI, DM_OK);
1340         listener_->OnBindResult(processInfo_, peerTargetId_, DM_OK, STATUS_DM_SHOW_PIN_INPUT_UI, "");
1341         authRequestState_->TransitionTo(std::make_shared<AuthRequestJoinState>());
1342     } else {
1343         LOGE("do not accept");
1344         authResponseContext_->state = AuthState::AUTH_REQUEST_REPLY;
1345         authRequestContext_->reason = ERR_DM_AUTH_PEER_REJECT;
1346         authResponseContext_->reply = ERR_DM_AUTH_PEER_REJECT;
1347         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
1348     }
1349 }
1350 
CreateGroup()1351 int32_t DmAuthManager::CreateGroup()
1352 {
1353     if (authResponseContext_ == nullptr) {
1354         LOGE("failed to CreateGroup because authResponseContext_ is nullptr");
1355         return ERR_DM_FAILED;
1356     }
1357     LOGI("DmAuthManager::CreateGroup start");
1358     authResponseContext_->groupName = GenerateGroupName();
1359     authResponseContext_->requestId = GenRandLongLong(MIN_REQUEST_ID, MAX_REQUEST_ID);
1360     hiChainConnector_->CreateGroup(authResponseContext_->requestId, authResponseContext_->groupName);
1361     return DM_OK;
1362 }
1363 
AddMember(const std::string & pinCode)1364 int32_t DmAuthManager::AddMember(const std::string &pinCode)
1365 {
1366     if (authResponseContext_ == nullptr) {
1367         LOGE("failed to AddMember because authResponseContext_ is nullptr");
1368         return ERR_DM_FAILED;
1369     }
1370     LOGI("DmAuthManager::AddMember start group id %{public}s", GetAnonyString(authResponseContext_->groupId).c_str());
1371     if (timer_ != nullptr) {
1372         timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK));
1373     }
1374     JsonObject jsonObject;
1375     jsonObject[TAG_GROUP_ID] = authResponseContext_->groupId;
1376     jsonObject[TAG_GROUP_NAME] = authResponseContext_->groupName;
1377     jsonObject[PIN_CODE_KEY] = pinCode;
1378     jsonObject[TAG_REQUEST_ID] = authResponseContext_->requestId;
1379     jsonObject[TAG_DEVICE_ID] = authResponseContext_->deviceId;
1380     std::string connectInfo = jsonObject.Dump();
1381     if (timer_ != nullptr) {
1382         timer_->StartTimer(std::string(ADD_TIMEOUT_TASK),
1383             GetTaskTimeout(ADD_TIMEOUT_TASK, ADD_TIMEOUT), [this] (std::string name) {
1384                 DmAuthManager::HandleAuthenticateTimeout(name);
1385             });
1386     }
1387     if (authUiStateMgr_ == nullptr) {
1388         LOGE("DmAuthManager::AddMember authUiStateMgr is null.");
1389         return ERR_DM_FAILED;
1390     }
1391     if (isAddingMember_) {
1392         LOGE("DmAuthManager::AddMember doing add member.");
1393         authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_DOING_AUTH);
1394         return ERR_DM_FAILED;
1395     }
1396     isAddingMember_ = true;
1397     int32_t ret = hiChainConnector_->AddMember(authRequestContext_->addr, connectInfo);
1398     struct RadarInfo info = {
1399         .funcName = "AddMember",
1400         .stageRes = (ret == 0) ?
1401             static_cast<int32_t>(StageRes::STAGE_IDLE) : static_cast<int32_t>(StageRes::STAGE_FAIL),
1402         .peerUdid = authResponseContext_ == nullptr ? "" : authResponseContext_->deviceId,
1403         .errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_ADD_GROUP_FAILED),
1404     };
1405     if (!DmRadarHelper::GetInstance().ReportAuthAddGroup(info)) {
1406         LOGE("ReportAuthAddGroup failed");
1407     }
1408     if (ret != 0) {
1409         LOGE("DmAuthManager::AddMember failed, ret: %{public}d", ret);
1410         isAddingMember_ = false;
1411         return ERR_DM_ADD_GROUP_FAILED;
1412     }
1413     return DM_OK;
1414 }
1415 
GetConnectAddr(std::string deviceId)1416 std::string DmAuthManager::GetConnectAddr(std::string deviceId)
1417 {
1418     std::string connectAddr;
1419     if (softbusConnector_->GetConnectAddr(deviceId, connectAddr) == nullptr) {
1420         LOGE("DmAuthManager::GetConnectAddr error");
1421     }
1422     return connectAddr;
1423 }
1424 
JoinNetwork()1425 int32_t DmAuthManager::JoinNetwork()
1426 {
1427     if (authResponseContext_ == nullptr) {
1428         LOGE("failed to JoinNeWork because authResponseContext_ is nullptr");
1429         return ERR_DM_FAILED;
1430     }
1431     LOGI("DmAuthManager JoinNetwork start");
1432     if (timer_ != nullptr) {
1433         timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK));
1434     }
1435     authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
1436     authResponseContext_->isFinish = true;
1437     authRequestContext_->reason = DM_OK;
1438     authResponseContext_->reply = DM_OK;
1439     authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
1440     return DM_OK;
1441 }
1442 
SinkAuthenticateFinish()1443 void DmAuthManager::SinkAuthenticateFinish()
1444 {
1445     LOGI("DmAuthManager::SinkAuthenticateFinish, isFinishOfLocal: %{public}d", isFinishOfLocal_);
1446     processInfo_.pkgName = authResponseContext_->peerBundleName;
1447     listener_->OnSinkBindResult(processInfo_, peerTargetId_, authResponseContext_->reply,
1448         authResponseContext_->state, GenerateBindResultContent());
1449     if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_FINISH &&
1450         (authResponseContext_->authType == AUTH_TYPE_NFC || authPtr_ != nullptr)) {
1451         authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW);
1452         authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_CONFIRM_SHOW);
1453     }
1454     if (isFinishOfLocal_) {
1455         authMessageProcessor_->SetResponseContext(authResponseContext_);
1456         std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE);
1457         softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
1458     }
1459     authResponseState_ = nullptr;
1460     authTimes_ = 0;
1461 }
1462 
GetOutputState(int32_t state)1463 int32_t DmAuthManager::GetOutputState(int32_t state)
1464 {
1465     LOGI("state %{public}d.", state);
1466     auto it = OLD_STATE_MAPPING.find(static_cast<AuthState>(state));
1467     if (it != OLD_STATE_MAPPING.end()) {
1468         return static_cast<int32_t>(it->second);
1469     }
1470     return static_cast<int32_t>(STATUS_DM_AUTH_DEFAULT);
1471 }
1472 
SrcAuthenticateFinish()1473 void DmAuthManager::SrcAuthenticateFinish()
1474 {
1475     LOGI("DmAuthManager::SrcAuthenticateFinish, isFinishOfLocal: %{public}d", isFinishOfLocal_);
1476     if (isFinishOfLocal_) {
1477         authMessageProcessor_->SetResponseContext(authResponseContext_);
1478         std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE);
1479         softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
1480     } else {
1481         authRequestContext_->reason = authResponseContext_->reply;
1482     }
1483     if ((authResponseContext_->state == AuthState::AUTH_REQUEST_JOIN ||
1484         authResponseContext_->state == AuthState::AUTH_REQUEST_FINISH) &&
1485         (authResponseContext_->authType == AUTH_TYPE_NFC || authPtr_ != nullptr)) {
1486         authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT);
1487     }
1488     if (timer_ == nullptr) {
1489         timer_ = std::make_shared<DmTimer>();
1490     }
1491     int32_t closeSessionDelaySeconds = authRequestContext_->closeSessionDelaySeconds;
1492     if (IsHmlSessionType() && closeSessionDelaySeconds == 0 && isWaitingJoinLnnCallback_) {
1493         closeSessionDelaySeconds = SESSION_CLOSE_TIMEOUT;
1494     }
1495     timer_->StartTimer(std::string(WAIT_SESSION_CLOSE_TIMEOUT_TASK) + std::string(CLOSE_SESSION_TASK_SEPARATOR) +
1496         std::to_string(authRequestContext_->sessionId),
1497         closeSessionDelaySeconds, [this] (std::string name) {
1498             int32_t sessionIdIndex = 1;
1499             std::string sessionStr = GetSubStr(name, std::string(CLOSE_SESSION_TASK_SEPARATOR), sessionIdIndex);
1500             if (!sessionStr.empty()) {
1501                 int32_t sessionId = std::atoi(sessionStr.c_str());
1502                 DmAuthManager::CloseAuthSession(sessionId);
1503             }
1504         });
1505     int32_t status = GetOutputState(authResponseContext_->state);
1506     listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, authRequestContext_->token, status,
1507         authRequestContext_->reason);
1508     listener_->OnBindResult(processInfo_, peerTargetId_, authRequestContext_->reason, status,
1509         GenerateBindResultContent());
1510 
1511     authRequestContext_ = nullptr;
1512     authRequestState_ = nullptr;
1513     authTimes_ = 0;
1514     isWaitingJoinLnnCallback_ = false;
1515 }
1516 
AuthenticateFinish()1517 void DmAuthManager::AuthenticateFinish()
1518 {
1519     {
1520         std::lock_guard<std::mutex> lock(srcReqMsgLock_);
1521         srcReqMsg_ = "";
1522         isNeedProcCachedSrcReqMsg_ = false;
1523         std::lock_guard<std::mutex> guard(sessionKeyIdMutex_);
1524         sessionKeyIdAsyncResult_.clear();
1525     }
1526     pincodeDialogEverShown_ = false;
1527     serviceInfoProfile_ = {};
1528     authType_ = AUTH_TYPE_UNKNOW;
1529     std::lock_guard<std::mutex> autoLock(g_authFinishLock);
1530     if (authResponseContext_ == nullptr || authUiStateMgr_ == nullptr) {
1531         LOGE("failed to AuthenticateFinish because authResponseContext_ or authUiStateMgr is nullptr");
1532         return;
1533     }
1534     LOGI("DmAuthManager::AuthenticateFinish start");
1535     isAddingMember_ = false;
1536     isAuthenticateDevice_ = false;
1537     isAuthDevice_ = false;
1538     isNeedJoinLnn_ = true;
1539     if (DeviceProfileConnector::GetInstance().GetTrustNumber(remoteDeviceId_) >= 1 &&
1540         CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) &&
1541         softbusConnector_->CheckIsOnline(remoteDeviceId_) && authResponseContext_->isFinish) {
1542         softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_);
1543     }
1544 
1545     DeleteAuthCode();
1546     if (timer_ != nullptr) {
1547         timer_->DeleteAll();
1548     }
1549     if (authResponseState_ != nullptr) {
1550         SinkAuthenticateFinish();
1551     } else if (authRequestState_ != nullptr) {
1552         SrcAuthenticateFinish();
1553     }
1554     ResetParams();
1555     LOGI("DmAuthManager::AuthenticateFinish complete");
1556 }
1557 
ResetParams()1558 void DmAuthManager::ResetParams()
1559 {
1560     isFinishOfLocal_ = true;
1561     authResponseContext_ = nullptr;
1562     authMessageProcessor_ = nullptr;
1563     authPtr_ = nullptr;
1564     authRequestStateTemp_ = nullptr;
1565     authenticationType_ = USER_OPERATION_TYPE_ALLOW_AUTH;
1566     bundleName_ = "";
1567     isAddMember_ = false;
1568     isCreateGroup_ = false;
1569     transitToFinishState_ = false;
1570     if (cleanNotifyCallback_ != nullptr) {
1571         cleanNotifyCallback_(0);
1572     }
1573 }
1574 
RegisterUiStateCallback(const std::string pkgName)1575 int32_t DmAuthManager::RegisterUiStateCallback(const std::string pkgName)
1576 {
1577     LOGI("DmAuthManager::RegisterUiStateCallback start");
1578     if (authUiStateMgr_ == nullptr) {
1579         LOGE("DmAuthManager::RegisterUiStateCallback authUiStateMgr_ is null.");
1580         return ERR_DM_FAILED;
1581     }
1582     authUiStateMgr_->RegisterUiStateCallback(pkgName);
1583     return DM_OK;
1584 }
1585 
UnRegisterUiStateCallback(const std::string pkgName)1586 int32_t DmAuthManager::UnRegisterUiStateCallback(const std::string pkgName)
1587 {
1588     LOGI("DmAuthManager::UnRegisterUiStateCallback start");
1589     if (authUiStateMgr_ == nullptr) {
1590         LOGE("DmAuthManager::UnRegisterUiStateCallback authUiStateMgr_ is null.");
1591         return ERR_DM_FAILED;
1592     }
1593     authUiStateMgr_->UnRegisterUiStateCallback(pkgName);
1594     return DM_OK;
1595 }
1596 
GeneratePincode()1597 std::string DmAuthManager::GeneratePincode()
1598 {
1599     int32_t pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE);
1600     return std::to_string(pinCode);
1601 }
1602 
IsPinCodeValid(const std::string strpin)1603 bool DmAuthManager::IsPinCodeValid(const std::string strpin)
1604 {
1605     if (strpin.empty()) {
1606         return false;
1607     }
1608     for (size_t i = 0; i < strpin.length(); i++) {
1609         if (!isdigit(strpin[i])) {
1610             return false;
1611         }
1612     }
1613     int32_t pinnum = std::atoi(strpin.c_str());
1614     return IsPinCodeValid(pinnum);
1615 }
1616 
IsPinCodeValid(int32_t numpin)1617 bool DmAuthManager::IsPinCodeValid(int32_t numpin)
1618 {
1619     if (numpin < MIN_PIN_CODE || numpin > MAX_PIN_CODE) {
1620         return false;
1621     }
1622     return true;
1623 }
1624 
CanUsePincodeFromDp()1625 bool DmAuthManager::CanUsePincodeFromDp()
1626 {
1627     CHECK_NULL_RETURN(authResponseContext_, false);
1628     return (IsPinCodeValid(serviceInfoProfile_.GetPinCode()) &&
1629         serviceInfoProfile_.GetPinExchangeType() == (int32_t)DMLocalServiceInfoPinExchangeType::FROMDP);
1630 }
1631 
IsServiceInfoAuthTypeValid(int32_t authType)1632 bool DmAuthManager::IsServiceInfoAuthTypeValid(int32_t authType)
1633 {
1634     if (authType != (int32_t)DMLocalServiceInfoAuthType::TRUST_ONETIME &&
1635         authType != (int32_t)DMLocalServiceInfoAuthType::TRUST_ALWAYS &&
1636         authType != (int32_t)DMLocalServiceInfoAuthType::CANCEL) {
1637         return false;
1638     }
1639     return true;
1640 }
1641 
IsServiceInfoAuthBoxTypeValid(int32_t authBoxType)1642 bool DmAuthManager::IsServiceInfoAuthBoxTypeValid(int32_t authBoxType)
1643 {
1644     if (authBoxType != (int32_t)DMLocalServiceInfoAuthBoxType::STATE3 &&
1645         authBoxType != (int32_t)DMLocalServiceInfoAuthBoxType::SKIP_CONFIRM) {
1646         return false;
1647     }
1648     return true;
1649 }
1650 
IsServiceInfoPinExchangeTypeValid(int32_t pinExchangeType)1651 bool DmAuthManager::IsServiceInfoPinExchangeTypeValid(int32_t pinExchangeType)
1652 {
1653     if (pinExchangeType != (int32_t)DMLocalServiceInfoPinExchangeType::PINBOX &&
1654         pinExchangeType != (int32_t)DMLocalServiceInfoPinExchangeType::FROMDP &&
1655         pinExchangeType != (int32_t)DMLocalServiceInfoPinExchangeType::ULTRASOUND &&
1656         pinExchangeType != (int32_t)DMLocalServiceInfoPinExchangeType::IMPORT_AUTH_CODE) {
1657         return false;
1658     }
1659     return true;
1660 }
1661 
IsLocalServiceInfoValid(const DistributedDeviceProfile::LocalServiceInfo & localServiceInfo)1662 bool DmAuthManager::IsLocalServiceInfoValid(const DistributedDeviceProfile::LocalServiceInfo &localServiceInfo)
1663 {
1664     if (!IsServiceInfoAuthTypeValid(localServiceInfo.GetAuthType())) {
1665         LOGE("AuthType not valid, %{public}d", localServiceInfo.GetAuthType());
1666         return false;
1667     }
1668     if (!IsServiceInfoAuthBoxTypeValid(localServiceInfo.GetAuthBoxType())) {
1669         LOGE("AuthBoxType not valid, %{public}d", localServiceInfo.GetAuthBoxType());
1670         return false;
1671     }
1672     if (!IsServiceInfoPinExchangeTypeValid(localServiceInfo.GetPinExchangeType())) {
1673         LOGE("PinExchangeType not valid, %{public}d", localServiceInfo.GetPinExchangeType());
1674         return false;
1675     }
1676     return true;
1677 }
1678 
GenerateGroupName()1679 std::string DmAuthManager::GenerateGroupName()
1680 {
1681     if (authResponseContext_ == nullptr) {
1682         LOGE("failed to GenerateGroupName because authResponseContext_ is nullptr.");
1683         return "";
1684     }
1685     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
1686     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
1687     std::string sLocalDeviceId = localDeviceId;
1688     uint32_t interceptLength = sLocalDeviceId.size() / DEVICE_ID_HALF;
1689     std::string groupName = "";
1690     if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) {
1691         groupName += AUTH_ALWAYS;
1692     } else {
1693         groupName += AUTH_ONCE;
1694     }
1695     groupName += authResponseContext_->targetPkgName + sLocalDeviceId.substr(0, interceptLength)
1696         + authResponseContext_->localDeviceId.substr(0, interceptLength);
1697     return groupName;
1698 }
1699 
GetIsCryptoSupport()1700 bool DmAuthManager::GetIsCryptoSupport()
1701 {
1702     if (authResponseState_ == nullptr) {
1703         return false;
1704     }
1705     if (authRequestState_ == nullptr) {
1706         if (authResponseState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) {
1707             return false;
1708         }
1709     } else {
1710         if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE ||
1711             authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) {
1712             return false;
1713         }
1714     }
1715 
1716     return isCryptoSupport_;
1717 }
1718 
SetAuthRequestState(std::shared_ptr<AuthRequestState> authRequestState)1719 int32_t DmAuthManager::SetAuthRequestState(std::shared_ptr<AuthRequestState> authRequestState)
1720 {
1721     if (authRequestState == nullptr) {
1722         LOGE("authRequestState is nullptr.");
1723         return ERR_DM_INPUT_PARA_INVALID;
1724     }
1725     // Keep current state, avoid deconstructed during state transitions
1726     authRequestStateTemp_ = authRequestState_;
1727     authRequestState_ = authRequestState;
1728     return DM_OK;
1729 }
1730 
SetAuthResponseState(std::shared_ptr<AuthResponseState> authResponseState)1731 int32_t DmAuthManager::SetAuthResponseState(std::shared_ptr<AuthResponseState> authResponseState)
1732 {
1733     if (authResponseState == nullptr) {
1734         LOGE("authResponseState is nullptr.");
1735         return ERR_DM_INPUT_PARA_INVALID;
1736     }
1737     authResponseState_ = authResponseState;
1738     return DM_OK;
1739 }
1740 
GetPinCode(std::string & code)1741 int32_t DmAuthManager::GetPinCode(std::string &code)
1742 {
1743     if (authResponseContext_ == nullptr) {
1744         LOGE("failed to GetPinCode because authResponseContext_ is nullptr");
1745         return ERR_DM_FAILED;
1746     }
1747     LOGI("ShowConfigDialog start add member pin code, pinCode: %{public}s",
1748         GetAnonyString(authResponseContext_->code).c_str());
1749     code = authResponseContext_->code;
1750     return DM_OK;
1751 }
1752 
CheckAndEndTvDream()1753 void DmAuthManager::CheckAndEndTvDream()
1754 {
1755     NodeBasicInfo nodeBasicInfo;
1756     int32_t result = GetLocalNodeDeviceInfo(DM_PKG_NAME, &nodeBasicInfo);
1757     if (result != SOFTBUS_OK) {
1758         LOGE("GetLocalNodeDeviceInfo from dsofbus fail, result=%{public}d", result);
1759         return;
1760     }
1761 
1762     if (nodeBasicInfo.deviceTypeId == TYPE_TV_ID) {
1763         int32_t ret = AuthManagerBase::EndDream();
1764         if (ret != DM_OK) {
1765             LOGE("fail to end dream, err:%{public}d", ret);
1766             return;
1767         }
1768     }
1769 }
1770 
ShowConfigDialog()1771 void DmAuthManager::ShowConfigDialog()
1772 {
1773     if (authResponseContext_ == nullptr) {
1774         LOGE("failed to ShowConfigDialog because authResponseContext_ is nullptr");
1775         return;
1776     }
1777     if (authResponseContext_->authType == AUTH_TYPE_NFC &&
1778         serviceInfoProfile_.GetAuthBoxType() == (int32_t)DMLocalServiceInfoAuthBoxType::SKIP_CONFIRM) {
1779         LOGI("no need confirm dialog");
1780         StartAuthProcess(serviceInfoProfile_.GetAuthType());
1781         return;
1782     }
1783     if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && !importAuthCode_.empty()) {
1784         LOGI("start auth process");
1785         StartAuthProcess(authenticationType_);
1786         return;
1787     }
1788     CheckAndEndTvDream();
1789     LOGI("ShowConfigDialog start");
1790     JsonObject jsonObj;
1791     jsonObj[TAG_AUTH_TYPE] = AUTH_TYPE_PIN;
1792     jsonObj[TAG_TOKEN] = authResponseContext_->token;
1793     jsonObj[TARGET_PKG_NAME_KEY] = authResponseContext_->targetPkgName;
1794     jsonObj[TAG_CUSTOM_DESCRIPTION] = authResponseContext_->customDesc;
1795     jsonObj[TAG_APP_OPERATION] = authResponseContext_->appOperation;
1796     jsonObj[TAG_LOCAL_DEVICE_TYPE] = authResponseContext_->deviceTypeId;
1797     jsonObj[TAG_REQUESTER] = authResponseContext_->deviceName;
1798     jsonObj[TAG_HOST_PKGLABEL] = authResponseContext_->hostPkgLabel;
1799     const std::string params = jsonObj.Dump();
1800     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
1801     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
1802     std::string localUdid = static_cast<std::string>(localDeviceId);
1803     DeviceProfileConnector::GetInstance().SyncAclByBindType(authResponseContext_->peerBundleName,
1804         authResponseContext_->bindType, localUdid, remoteDeviceId_);
1805     DmDialogManager::GetInstance().ShowConfirmDialog(params);
1806     struct RadarInfo info = {
1807         .funcName = "ShowConfigDialog",
1808         .stageRes = static_cast<int32_t>(StageRes::STAGE_IDLE),
1809     };
1810     if (!DmRadarHelper::GetInstance().ReportAuthPullAuthBox(info)) {
1811         LOGE("ReportAuthPullAuthBox failed");
1812     }
1813     LOGI("ShowConfigDialog end");
1814 }
1815 
ShowAuthInfoDialog(bool authDeviceError)1816 void DmAuthManager::ShowAuthInfoDialog(bool authDeviceError)
1817 {
1818     if (authResponseContext_ == nullptr) {
1819         LOGE("failed to ShowAuthInfoDialog because authResponseContext_ is nullptr");
1820         return;
1821     }
1822     LOGI("DmAuthManager::ShowAuthInfoDialog start");
1823     if (!authDeviceError && CanUsePincodeFromDp()) {
1824         LOGI("pin import from dp, not show dialog");
1825         return;
1826     }
1827     if (pincodeDialogEverShown_) {
1828         return;
1829     }
1830     if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && !importAuthCode_.empty()) {
1831         LOGI("not show dialog.");
1832         return;
1833     }
1834     struct RadarInfo info = {
1835         .funcName = "ShowAuthInfoDialog",
1836         .stageRes = static_cast<int32_t>(StageRes::STAGE_SUCC),
1837     };
1838     if (!DmRadarHelper::GetInstance().ReportAuthPullPinBox(info)) {
1839         LOGE("ReportAuthPullPinBox failed");
1840     }
1841     pincodeDialogEverShown_ = true;
1842     DmDialogManager::GetInstance().ShowPinDialog(authResponseContext_->code);
1843 }
1844 
ShowStartAuthDialog()1845 void DmAuthManager::ShowStartAuthDialog()
1846 {
1847     if (authResponseContext_ == nullptr) {
1848         LOGE("failed to ShowStartAuthDialog because authResponseContext_ is nullptr");
1849         return;
1850     }
1851     if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) {
1852         LOGI("Add member start");
1853         std::string pinCode = "";
1854         if (GetAuthCode(authResponseContext_->hostPkgName, pinCode) != DM_OK) {
1855             LOGE("failed to get auth code");
1856             return;
1857         }
1858         if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) &&
1859             (static_cast<uint32_t>(authResponseContext_->bindLevel) >= USER &&
1860             static_cast<uint32_t>(authResponseContext_->bindLevel) <= APP)) {
1861             AuthDevice(pinCode);
1862         } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) ||
1863             static_cast<uint32_t>(authResponseContext_->bindLevel) == INVALIED_TYPE) {
1864             AddMember(pinCode);
1865         } else {
1866             LOGE("Invalied bind mode.");
1867         }
1868         return;
1869     }
1870     if (IsScreenLocked()) {
1871         LOGE("ShowStartAuthDialog screen is locked.");
1872         SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL, STATUS_DM_AUTH_DEFAULT);
1873         return;
1874     }
1875     LOGI("DmAuthManager::ShowStartAuthDialog start");
1876     std::string pincode = "";
1877     if (authResponseContext_->authType == AUTH_TYPE_NFC &&
1878         GetAuthCode(authResponseContext_->hostPkgName, pincode) == DM_OK) {
1879         LOGI("already has pin code");
1880         ProcessPincode(pincode);
1881         return;
1882     }
1883 
1884     pincodeDialogEverShown_ = true;
1885     DmDialogManager::GetInstance().ShowInputDialog(authResponseContext_->targetDeviceName);
1886 }
1887 
ProcessPincode(const std::string & pinCode)1888 int32_t DmAuthManager::ProcessPincode(const std::string &pinCode)
1889 {
1890     if (authResponseContext_ == nullptr) {
1891         LOGE("failed to ProcessPincode because authResponseContext_ is nullptr");
1892         return ERR_DM_FAILED;
1893     }
1894     if (timer_ != nullptr) {
1895         timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK));
1896     }
1897     if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) &&
1898         (static_cast<uint32_t>(authResponseContext_->bindLevel) >= USER &&
1899         static_cast<uint32_t>(authResponseContext_->bindLevel) <= APP)) {
1900         return AuthDevice(pinCode);
1901     } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) ||
1902         static_cast<uint32_t>(authResponseContext_->bindLevel) == INVALIED_TYPE) {
1903         return AddMember(pinCode);
1904     } else {
1905         LOGE("Invalied bind mode.");
1906     }
1907     return ERR_DM_FAILED;
1908 }
1909 
AuthDevice(const std::string & pinCode)1910 int32_t DmAuthManager::AuthDevice(const std::string &pinCode)
1911 {
1912     LOGI("DmAuthManager::AuthDevice start.");
1913     if (isAuthDevice_) {
1914         LOGE("DmAuthManager::AuthDevice doing auth device.");
1915         authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_DOING_AUTH);
1916         return ERR_DM_FAILED;
1917     }
1918     isAuthDevice_ = true;
1919     int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID();
1920     if (timer_ != nullptr) {
1921         timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK));
1922         timer_->StartTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK), AUTH_DEVICE_TIMEOUT,
1923             [this] (std::string name) {
1924                 DmAuthManager::HandleAuthenticateTimeout(name);
1925             });
1926     }
1927     if (hiChainAuthConnector_->AuthDevice(pinCode, osAccountId, remoteDeviceId_,
1928         authResponseContext_->requestId) != DM_OK) {
1929         LOGE("DmAuthManager::AuthDevice failed.");
1930         isAuthDevice_ = false;
1931         if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) {
1932             HandleMemberJoinImportAuthCode(authResponseContext_->requestId, ERR_DM_FAILED);
1933             return ERR_DM_FAILED;
1934         }
1935     }
1936     return DM_OK;
1937 }
1938 
OnUserOperation(int32_t action,const std::string & params)1939 int32_t DmAuthManager::OnUserOperation(int32_t action, const std::string &params)
1940 {
1941     if (authResponseContext_ == nullptr) {
1942         LOGE("Authenticate is not start");
1943         return ERR_DM_AUTH_NOT_START;
1944     }
1945     struct RadarInfo info = {
1946         .funcName = "OnUserOperation",
1947         .stageRes = static_cast<int32_t>(StageRes::STAGE_CANCEL),
1948         .bizState = static_cast<int32_t>(BizState::BIZ_STATE_END),
1949     };
1950     switch (action) {
1951         case USER_OPERATION_TYPE_ALLOW_AUTH:
1952         case USER_OPERATION_TYPE_CANCEL_AUTH:
1953         case USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS:
1954             StartAuthProcess(action);
1955             break;
1956         case USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT:
1957             SetReasonAndFinish(ERR_DM_TIME_OUT, STATUS_DM_AUTH_DEFAULT);
1958             info.errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_TIME_OUT);
1959             break;
1960         case USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY:
1961             SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY, STATUS_DM_AUTH_DEFAULT);
1962             info.errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY);
1963             break;
1964         case USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT:
1965             SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL_ERROR, STATUS_DM_AUTH_DEFAULT);
1966             info.errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_BIND_USER_CANCEL_ERROR);
1967             break;
1968         case USER_OPERATION_TYPE_DONE_PINCODE_INPUT:
1969             ProcessPincode(params);
1970             info.stageRes = static_cast<int32_t>(StageRes::STAGE_SUCC);
1971             break;
1972         default:
1973             LOGE("this action id not support");
1974             break;
1975     }
1976     if (!DmRadarHelper::GetInstance().ReportAuthConfirmBox(info)) {
1977         LOGE("ReportAuthConfirmBox failed");
1978     }
1979     return DM_OK;
1980 }
1981 
SetPageId(int32_t pageId)1982 int32_t DmAuthManager::SetPageId(int32_t pageId)
1983 {
1984     if (authResponseContext_ == nullptr) {
1985         LOGE("Authenticate is not start");
1986         return ERR_DM_AUTH_NOT_START;
1987     }
1988     authResponseContext_->pageId = pageId;
1989     return DM_OK;
1990 }
1991 
SetReasonAndFinish(int32_t reason,int32_t state)1992 int32_t DmAuthManager::SetReasonAndFinish(int32_t reason, int32_t state)
1993 {
1994     if (authResponseContext_ == nullptr) {
1995         LOGE("Authenticate is not start");
1996         return ERR_DM_AUTH_NOT_START;
1997     }
1998     authResponseContext_->state = state;
1999     authResponseContext_->reply = reason;
2000     if (authRequestState_ != nullptr && authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) {
2001         authRequestContext_->reason = reason;
2002         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
2003     } else if (authResponseState_ != nullptr && authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) {
2004         authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
2005     }
2006     return DM_OK;
2007 }
2008 
IsIdenticalAccount()2009 bool DmAuthManager::IsIdenticalAccount()
2010 {
2011     JsonObject jsonObj;
2012     jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP;
2013     std::string queryParams = jsonObj.Dump();
2014 
2015     int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID();
2016     if (osAccountUserId < 0) {
2017         LOGE("get current process account user id failed");
2018         return false;
2019     }
2020     std::vector<GroupInfo> groupList;
2021     if (!hiChainConnector_->GetGroupInfo(osAccountUserId, queryParams, groupList)) {
2022         return false;
2023     }
2024     if (authResponseContext_ == nullptr) {
2025         LOGE("authResponseContext_ is nullptr.");
2026         return false;
2027     }
2028     if (authResponseContext_->accountGroupIdHash == OLD_VERSION_ACCOUNT) {
2029         LOGI("The old version.");
2030         return true;
2031     }
2032     JsonObject jsonPeerGroupIdObj(authResponseContext_->accountGroupIdHash);
2033     if (jsonPeerGroupIdObj.IsDiscarded()) {
2034         LOGE("accountGroupIdHash string not a json type.");
2035         return false;
2036     }
2037 
2038     std::vector<JsonItemObject> items = jsonPeerGroupIdObj.Items();
2039     for (auto &groupInfo : groupList) {
2040         for (auto it = items.begin(); it != items.end(); ++it) {
2041             if (it->IsString() && it->Get<std::string>() == Crypto::GetGroupIdHash(groupInfo.groupId)) {
2042                 LOGI("Is identical Account.");
2043                 return true;
2044             }
2045         }
2046     }
2047     return false;
2048 }
2049 
GetAccountGroupIdHash()2050 std::string DmAuthManager::GetAccountGroupIdHash()
2051 {
2052     JsonObject jsonObj;
2053     jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP;
2054     std::string queryParams = jsonObj.Dump();
2055 
2056     int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID();
2057     if (osAccountUserId < 0) {
2058         LOGE("get current process account user id failed");
2059         return "";
2060     }
2061     std::vector<GroupInfo> groupList;
2062     if (!hiChainConnector_->GetGroupInfo(osAccountUserId, queryParams, groupList)) {
2063         return "";
2064     }
2065     JsonObject jsonAccountObj(JsonCreateType::JSON_CREATE_TYPE_ARRAY);
2066     for (auto &groupInfo : groupList) {
2067         jsonAccountObj.PushBack(Crypto::GetGroupIdHash(groupInfo.groupId));
2068     }
2069     return jsonAccountObj.Dump();
2070 }
2071 
ImportAuthCode(const std::string & pkgName,const std::string & authCode)2072 int32_t DmAuthManager::ImportAuthCode(const std::string &pkgName, const std::string &authCode)
2073 {
2074     if (authCode.empty() || pkgName.empty()) {
2075         LOGE("ImportAuthCode failed, authCode or pkgName is empty");
2076         return ERR_DM_INPUT_PARA_INVALID;
2077     }
2078     importAuthCode_ = authCode;
2079     importPkgName_ = pkgName;
2080     return DM_OK;
2081 }
2082 
BindTarget(const std::string & pkgName,const PeerTargetId & targetId,const std::map<std::string,std::string> & bindParam,int sessionId,uint64_t logicalSessionId)2083 int32_t DmAuthManager::BindTarget(const std::string &pkgName, const PeerTargetId &targetId,
2084     const std::map<std::string, std::string> &bindParam, int sessionId, uint64_t logicalSessionId)
2085 {
2086     struct RadarInfo info = {
2087         .funcName = "AuthenticateDevice",
2088         .stageRes = static_cast<int32_t>(StageRes::STAGE_SUCC),
2089         .bizState = static_cast<int32_t>(BizState::BIZ_STATE_END),
2090     };
2091     if (!DmRadarHelper::GetInstance().ReportDiscoverUserRes(info)) {
2092         LOGE("ReportDiscoverUserRes failed");
2093     }
2094     std::string isNeedJoinLnnStr;
2095     if (bindParam.find(IS_NEED_JOIN_LNN) != bindParam.end()) {
2096         isNeedJoinLnnStr = bindParam.at(IS_NEED_JOIN_LNN);
2097     }
2098     if (isNeedJoinLnnStr == NEED_JOIN_LNN || isNeedJoinLnnStr == NO_NEED_JOIN_LNN) {
2099         isNeedJoinLnn_ = std::atoi(isNeedJoinLnnStr.c_str());
2100         LOGI("isNeedJoinLnn: %{public}d.", isNeedJoinLnn_);
2101     }
2102     if (pkgName.empty()) {
2103         LOGE("DmAuthManager::BindTarget failed, pkgName is empty.");
2104         return ERR_DM_INPUT_PARA_INVALID;
2105     }
2106     int32_t authType = -1;
2107     if (ParseAuthType(bindParam, authType) != DM_OK) {
2108         LOGE("DmAuthManager::BindTarget failed, key: %{public}s error.", PARAM_KEY_AUTH_TYPE);
2109         return ERR_DM_INPUT_PARA_INVALID;
2110     }
2111     peerTargetId_ = targetId;
2112     std::string deviceId = "";
2113     std::string addrType;
2114     if (bindParam.count(PARAM_KEY_CONN_ADDR_TYPE) != 0) {
2115         addrType = bindParam.at(PARAM_KEY_CONN_ADDR_TYPE);
2116     }
2117     {
2118         std::lock_guard<std::mutex> lock(bindParamMutex_);
2119         bindParam_ = bindParam;
2120     }
2121     if (ParseConnectAddr(targetId, deviceId, addrType) == DM_OK) {
2122         return AuthenticateDevice(pkgName, authType, deviceId, ParseExtraFromMap(bindParam));
2123     } else if (!targetId.deviceId.empty()) {
2124         return AuthenticateDevice(pkgName, authType, targetId.deviceId, ParseExtraFromMap(bindParam));
2125     } else {
2126         LOGE("DmAuthManager::BindTarget failed, targetId is error.");
2127         return ERR_DM_INPUT_PARA_INVALID;
2128     }
2129 }
2130 
ParseConnectAddr(const PeerTargetId & targetId,std::string & deviceId,std::string & addrType)2131 int32_t DmAuthManager::ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, std::string &addrType)
2132 {
2133     int32_t index = 0;
2134     std::shared_ptr<DeviceInfo> deviceInfo = std::make_shared<DeviceInfo>();
2135     ConnectionAddr addr;
2136     if (!targetId.wifiIp.empty() && targetId.wifiIp.length() <= IP_STR_MAX_LEN) {
2137         LOGI("DmAuthManager::ParseConnectAddr parse wifiIp: %{public}s.", GetAnonyString(targetId.wifiIp).c_str());
2138         if (!addrType.empty()) {
2139             addr.type = static_cast<ConnectionAddrType>(std::atoi(addrType.c_str()));
2140         } else {
2141             addr.type = ConnectionAddrType::CONNECTION_ADDR_WLAN;
2142         }
2143         memcpy_s(addr.info.ip.ip, IP_STR_MAX_LEN, targetId.wifiIp.c_str(), targetId.wifiIp.length());
2144         addr.info.ip.port = targetId.wifiPort;
2145         deviceInfo->addr[index] = addr;
2146         deviceId = targetId.wifiIp;
2147         index++;
2148     } else if (!targetId.brMac.empty() && targetId.brMac.length() <= BT_MAC_LEN) {
2149         LOGI("DmAuthManager::ParseConnectAddr parse brMac: %{public}s.", GetAnonyString(targetId.brMac).c_str());
2150         addr.type = ConnectionAddrType::CONNECTION_ADDR_BR;
2151         memcpy_s(addr.info.br.brMac, BT_MAC_LEN, targetId.brMac.c_str(), targetId.brMac.length());
2152         deviceInfo->addr[index] = addr;
2153         deviceId = targetId.brMac;
2154         index++;
2155     } else if (!targetId.bleMac.empty() && targetId.bleMac.length() <= BT_MAC_LEN) {
2156         LOGI("DmAuthManager::ParseConnectAddr parse bleMac: %{public}s.", GetAnonyString(targetId.bleMac).c_str());
2157         addr.type = ConnectionAddrType::CONNECTION_ADDR_BLE;
2158         memcpy_s(addr.info.ble.bleMac, BT_MAC_LEN, targetId.bleMac.c_str(), targetId.bleMac.length());
2159         if (!targetId.deviceId.empty()) {
2160             Crypto::ConvertHexStringToBytes(addr.info.ble.udidHash, UDID_HASH_LEN,
2161                 targetId.deviceId.c_str(), targetId.deviceId.length());
2162         }
2163         deviceInfo->addr[index] = addr;
2164         deviceId = targetId.bleMac;
2165         index++;
2166     } else {
2167         LOGE("DmAuthManager::ParseConnectAddr failed, not addr.");
2168         return ERR_DM_INPUT_PARA_INVALID;
2169     }
2170 
2171     deviceInfo->addrNum = static_cast<uint32_t>(index);
2172     if (softbusConnector_->AddMemberToDiscoverMap(deviceId, deviceInfo) != DM_OK) {
2173         LOGE("DmAuthManager::ParseConnectAddr failed, AddMemberToDiscoverMap failed.");
2174         return ERR_DM_INPUT_PARA_INVALID;
2175     }
2176     deviceInfo = nullptr;
2177     return DM_OK;
2178 }
2179 
ParseExtraFromMap(const std::map<std::string,std::string> & bindParam)2180 std::string DmAuthManager::ParseExtraFromMap(const std::map<std::string, std::string> &bindParam)
2181 {
2182     auto iter = bindParam.find(PARAM_KEY_BIND_EXTRA_DATA);
2183     if (iter != bindParam.end()) {
2184         return iter->second;
2185     }
2186     return ConvertMapToJsonString(bindParam);
2187 }
2188 
IsAuthCodeReady(const std::string & pkgName)2189 bool DmAuthManager::IsAuthCodeReady(const std::string &pkgName)
2190 {
2191     if (importAuthCode_.empty() || importPkgName_.empty()) {
2192         LOGE("DmAuthManager::IsAuthCodeReady, auth code not ready.");
2193         return false;
2194     }
2195     if (pkgName != importPkgName_) {
2196         LOGE("IsAuthCodeReady failed, pkgName not supported.");
2197         return false;
2198     }
2199     return true;
2200 }
2201 
DeleteAuthCode()2202 int32_t DmAuthManager::DeleteAuthCode()
2203 {
2204     importAuthCode_ = "";
2205     importPkgName_ = "";
2206     return DM_OK;
2207 }
2208 
GetAuthCode(const std::string & pkgName,std::string & pinCode)2209 int32_t DmAuthManager::GetAuthCode(const std::string &pkgName, std::string &pinCode)
2210 {
2211     if (importAuthCode_.empty() || importPkgName_.empty()) {
2212         LOGE("GetAuthCode failed, auth code not exist.");
2213         return ERR_DM_FAILED;
2214     }
2215     if (pkgName != importPkgName_) {
2216         LOGE("GetAuthCode failed, pkgName not supported.");
2217         return ERR_DM_FAILED;
2218     }
2219     pinCode = std::to_string(std::atoi(importAuthCode_.c_str()));
2220     return DM_OK;
2221 }
2222 
IsImportedAuthCodeValid()2223 bool DmAuthManager::IsImportedAuthCodeValid()
2224 {
2225     std::string pinCode = "";
2226     if (GetAuthCode(authRequestContext_->hostPkgName, pinCode) == DM_OK) {
2227         return true;
2228     }
2229     return false;
2230 }
2231 
IsSrc()2232 bool DmAuthManager::IsSrc()
2233 {
2234     if (authRequestState_ != nullptr) {
2235         return true;
2236     } else {
2237         return false;
2238     }
2239 }
2240 
IsAuthTypeSupported(const int32_t & authType)2241 bool DmAuthManager::IsAuthTypeSupported(const int32_t &authType)
2242 {
2243     if (authenticationMap_.find(authType) == authenticationMap_.end()) {
2244         LOGE("IsAuthTypeSupported failed, authType is not supported.");
2245         return false;
2246     }
2247     return true;
2248 }
2249 
GenerateBindResultContent()2250 std::string DmAuthManager::GenerateBindResultContent()
2251 {
2252     JsonObject jsonObj;
2253     jsonObj[DM_BIND_RESULT_NETWORK_ID] = authResponseContext_->networkId;
2254     if (remoteDeviceId_.empty()) {
2255         jsonObj[TAG_DEVICE_ID] = "";
2256     } else {
2257         char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0};
2258         Crypto::GetUdidHash(remoteDeviceId_, reinterpret_cast<uint8_t *>(deviceIdHash));
2259         jsonObj[TAG_DEVICE_ID] = deviceIdHash;
2260     }
2261     jsonObj[TAG_CONFIRM_OPERATION] = authResponseContext_->confirmOperation;
2262     std::string content = jsonObj.Dump();
2263     return content;
2264 }
2265 
RequestCredential()2266 void DmAuthManager::RequestCredential()
2267 {
2268     LOGI("DmAuthManager::RequestCredential start.");
2269     std::string publicKey = "";
2270     GenerateCredential(publicKey);
2271     authResponseContext_->publicKey = publicKey;
2272     std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_PUBLICKEY);
2273     softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
2274 }
2275 
GenerateCredential(std::string & publicKey)2276 void DmAuthManager::GenerateCredential(std::string &publicKey)
2277 {
2278     LOGI("DmAuthManager::GenerateCredential start.");
2279     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
2280     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
2281     std::string localUdid = localDeviceId;
2282     int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID();
2283     hiChainAuthConnector_->GetCredential(localUdid, osAccountId, publicKey);
2284     if (publicKey == "") {
2285         hiChainAuthConnector_->GenerateCredential(localUdid, osAccountId, publicKey);
2286     }
2287 }
2288 
RequestCredentialDone()2289 void DmAuthManager::RequestCredentialDone()
2290 {
2291     LOGI("DmAuthManager ExchangeCredentailDone start");
2292     CHECK_NULL_VOID(authResponseContext_);
2293     if (authResponseContext_->publicKey == "" ||
2294         ImportCredential(remoteDeviceId_, authResponseContext_->publicKey) != DM_OK) {
2295         LOGE("RequestCredentialDone import credential failed.");
2296     }
2297     if (timer_ != nullptr) {
2298         timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK));
2299     }
2300     if (softbusConnector_->CheckIsOnline(remoteDeviceId_) && !authResponseContext_->isOnline) {
2301         JoinLnn(authRequestContext_->addr, true);
2302     } else {
2303         JoinLnn(authRequestContext_->addr, false);
2304     }
2305     authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
2306     authRequestContext_->reason = DM_OK;
2307     authResponseContext_->reply = DM_OK;
2308     authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
2309 }
2310 
ImportCredential(std::string & deviceId,std::string & publicKey)2311 int32_t DmAuthManager::ImportCredential(std::string &deviceId, std::string &publicKey)
2312 {
2313     LOGI("DmAuthManager::ImportCredential, deviceId %{public}s", GetAnonyString(deviceId).c_str());
2314     int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID();
2315     if ((authRequestState_ != nullptr) && (authResponseState_ == nullptr)) {
2316         // Source Import Credential
2317         LOGI("Source Import Credential remoteUserId: %{public}d", authRequestContext_->remoteUserId);
2318         CHECK_NULL_RETURN(authRequestContext_, ERR_DM_POINT_NULL);
2319         CHECK_NULL_RETURN(hiChainAuthConnector_, ERR_DM_POINT_NULL);
2320         return hiChainAuthConnector_->ImportCredential(osAccountId, authRequestContext_->remoteUserId, deviceId,
2321             publicKey);
2322     } else if ((authResponseState_ != nullptr) && (authRequestState_ == nullptr)) {
2323         // Sink Import Credential
2324         LOGI("Source Import Credential remoteUserId: %{public}d", authResponseContext_->remoteUserId);
2325         CHECK_NULL_RETURN(authResponseContext_, ERR_DM_POINT_NULL);
2326         CHECK_NULL_RETURN(hiChainAuthConnector_, ERR_DM_POINT_NULL);
2327         return hiChainAuthConnector_->ImportCredential(osAccountId, authResponseContext_->remoteUserId, deviceId,
2328             publicKey);
2329     } else {
2330         LOGE("DmAuthManager::ImportCredential failed, authRequestState_ or authResponseState_ is invalid.");
2331         return ERR_DM_AUTH_FAILED;
2332     }
2333 }
2334 
ResponseCredential()2335 void DmAuthManager::ResponseCredential()
2336 {
2337     LOGI("DmAuthManager::ResponseCredential start.");
2338     CHECK_NULL_VOID(authResponseContext_);
2339     if (authResponseContext_->publicKey == "") {
2340         LOGE("authResponseContext_->publicKey is empty.");
2341         authResponseContext_->isFinish = false;
2342         isFinishOfLocal_ = false;
2343         authMessageProcessor_->SetEncryptFlag(false);
2344         authResponseContext_->state = authResponseState_->GetStateType();
2345         authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
2346         return;
2347     }
2348     std::string publicKey = "";
2349     GenerateCredential(publicKey);
2350     if (ImportCredential(remoteDeviceId_, authResponseContext_->publicKey) != DM_OK) {
2351         LOGE("ResponseCredential import credential failed.");
2352         authResponseContext_->state = authResponseState_->GetStateType();
2353         authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
2354         return;
2355     }
2356     authResponseContext_->publicKey = publicKey;
2357     std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_PUBLICKEY);
2358     softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
2359 }
2360 
AuthDeviceTransmit(int64_t requestId,const uint8_t * data,uint32_t dataLen)2361 bool DmAuthManager::AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen)
2362 {
2363     LOGI("DmAuthManager::onTransmit start.");
2364     CHECK_NULL_RETURN(authResponseContext_, false);
2365     if (requestId != authResponseContext_->requestId) {
2366         LOGE("DmAuthManager::onTransmit requestId %{public}" PRId64"is error.", requestId);
2367         return false;
2368     }
2369     std::string message = "";
2370     if (authRequestState_ != nullptr && authResponseState_ == nullptr) {
2371         LOGI("SoftbusSession send msgType %{public}d.", MSG_TYPE_REQ_AUTH_DEVICE_NEGOTIATE);
2372         message = authMessageProcessor_->CreateDeviceAuthMessage(MSG_TYPE_REQ_AUTH_DEVICE_NEGOTIATE, data, dataLen);
2373     } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) {
2374         LOGI("SoftbusSession send msgType %{public}d.", MSG_TYPE_RESP_AUTH_DEVICE_NEGOTIATE);
2375         message = authMessageProcessor_->CreateDeviceAuthMessage(MSG_TYPE_RESP_AUTH_DEVICE_NEGOTIATE, data, dataLen);
2376     }
2377     if (softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message) != DM_OK) {
2378         LOGE("SoftbusSession send data failed.");
2379         return false;
2380     }
2381     return true;
2382 }
2383 
SrcAuthDeviceFinish()2384 void DmAuthManager::SrcAuthDeviceFinish()
2385 {
2386     LOGI("DmAuthManager::SrcAuthDeviceFinish Start.");
2387     CHECK_NULL_VOID(authRequestState_);
2388     authRequestState_->TransitionTo(std::make_shared<AuthRequestAuthFinish>());
2389     if (authResponseContext_->confirmOperation != USER_OPERATION_TYPE_ALLOW_AUTH &&
2390         authResponseContext_->confirmOperation != USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) {
2391         LOGE("auth failed %{public}d.", authResponseContext_->confirmOperation);
2392         return;
2393     }
2394     if (authResponseContext_->isOnline && authResponseContext_->haveCredential) {
2395         if (!authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) {
2396             SetProcessInfo();
2397         }
2398         softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_);
2399         if (timer_ != nullptr) {
2400             timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK));
2401         }
2402         ConverToFinish();
2403         return;
2404     }
2405     if (authResponseContext_->isOnline && !authResponseContext_->haveCredential) {
2406         authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT);
2407         if (!authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) {
2408             SetProcessInfo();
2409         }
2410         softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_);
2411         if (CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_2))) {
2412             authRequestState_->TransitionTo(std::make_shared<AuthRequestReCheckMsg>());
2413         } else {
2414             authRequestState_->TransitionTo(std::make_shared<AuthRequestCredential>());
2415         }
2416         return;
2417     }
2418     if (!authResponseContext_->isOnline && authResponseContext_->haveCredential) {
2419         JoinLnn(authRequestContext_->addr);
2420         timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK));
2421         ConverToFinish();
2422         return;
2423     }
2424     if (!authResponseContext_->isOnline && !authResponseContext_->haveCredential) {
2425         authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT);
2426         if (CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_2))) {
2427             authRequestState_->TransitionTo(std::make_shared<AuthRequestReCheckMsg>());
2428         } else {
2429             authRequestState_->TransitionTo(std::make_shared<AuthRequestCredential>());
2430         }
2431         return;
2432     }
2433 }
2434 
SinkAuthDeviceFinish()2435 void DmAuthManager::SinkAuthDeviceFinish()
2436 {
2437     LOGI("isNeedProcCachedSrcReqMsg %{public}d.", isNeedProcCachedSrcReqMsg_);
2438     CHECK_NULL_VOID(authResponseState_);
2439     authResponseState_->TransitionTo(std::make_shared<AuthResponseAuthFinish>());
2440     if (!authResponseContext_->haveCredential) {
2441         authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW);
2442     }
2443     if (authResponseContext_->isOnline) {
2444         LOGI("The device is online.");
2445         SetProcessInfo();
2446         softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_);
2447     }
2448     std::string srcReqMsg = "";
2449     bool isNeedProcCachedSrcReqMsg = false;
2450     {
2451         std::lock_guard<std::mutex> lock(srcReqMsgLock_);
2452         srcReqMsg = srcReqMsg_;
2453         isNeedProcCachedSrcReqMsg = isNeedProcCachedSrcReqMsg_;
2454         srcReqMsg_ = "";
2455         isNeedProcCachedSrcReqMsg_ = false;
2456     }
2457     if (!isNeedProcCachedSrcReqMsg || srcReqMsg.empty()) {
2458         LOGI("please wait client request.");
2459         return;
2460     }
2461     authMessageProcessor_->SetResponseContext(authResponseContext_);
2462     if (authMessageProcessor_->ParseMessage(srcReqMsg) != DM_OK) {
2463         LOGE("ParseMessage failed.");
2464         return;
2465     }
2466     if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_2))) {
2467         authResponseState_->TransitionTo(std::make_shared<AuthResponseCredential>());
2468     } else {
2469         authResponseState_->TransitionTo(std::make_shared<AuthResponseReCheckMsg>());
2470     }
2471 }
2472 
AuthDeviceFinish(int64_t requestId)2473 void DmAuthManager::AuthDeviceFinish(int64_t requestId)
2474 {
2475     LOGI("DmAuthManager::AuthDeviceFinish start.");
2476     if (requestId != authResponseContext_->requestId) {
2477         LOGE("DmAuthManager::onTransmit requestId %{public}" PRId64 "is error.", requestId);
2478         return;
2479     }
2480     isAuthDevice_ = false;
2481     if (timer_ != nullptr) {
2482         timer_->DeleteTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK));
2483     }
2484     if (CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_2))) {
2485         LOGI("Set EncryptFlag true.");
2486         authMessageProcessor_->SetEncryptFlag(true);
2487     } else {
2488         PutAccessControlList();
2489     }
2490     if (authRequestState_ != nullptr && authResponseState_ == nullptr) {
2491         SrcAuthDeviceFinish();
2492     } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) {
2493         SinkAuthDeviceFinish();
2494     }
2495 }
2496 
AuthDeviceError(int64_t requestId,int32_t errorCode)2497 void DmAuthManager::AuthDeviceError(int64_t requestId, int32_t errorCode)
2498 {
2499     LOGI("AuthDeviceError start.");
2500     CHECK_NULL_VOID(authResponseContext_);
2501     if (requestId != authResponseContext_->requestId) {
2502         LOGE("reqId: %{public}" PRId64", RespReqId: %{public}" PRId64".", requestId, authResponseContext_->requestId);
2503         return;
2504     }
2505     isAuthDevice_ = false;
2506     if (authRequestState_ == nullptr || authResponseState_ != nullptr) {
2507         if (CheckNeedShowAuthInfoDialog(errorCode)) {
2508             return;
2509         }
2510         authTimes_++;
2511         if (authTimes_ >= MAX_AUTH_TIMES) {
2512             authResponseContext_->isFinish = false;
2513             authResponseContext_->reply = ERR_DM_AUTH_CODE_INCORRECT;
2514             authResponseContext_->state = AuthState::AUTH_RESPONSE_SHOW;
2515             isFinishOfLocal_ = false;
2516             authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
2517         }
2518         return;
2519     }
2520     if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) {
2521         authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN;
2522         authRequestContext_->reason = ERR_DM_AUTH_CODE_INCORRECT;
2523         authResponseContext_->reply = ERR_DM_AUTH_CODE_INCORRECT;
2524         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
2525         return;
2526     }
2527     authTimes_++;
2528     if (timer_ != nullptr) {
2529         timer_->DeleteTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK));
2530     }
2531     if (errorCode != DM_OK || requestId != authResponseContext_->requestId) {
2532         if (authRequestState_ != nullptr && authTimes_ >= MAX_AUTH_TIMES) {
2533             authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN;
2534             authRequestContext_->reason = ERR_DM_INPUT_PARA_INVALID;
2535             authResponseContext_->reply = ERR_DM_INPUT_PARA_INVALID;
2536             authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
2537         } else {
2538             if (timer_ != nullptr) {
2539                 timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK),
2540                     GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) {
2541                         DmAuthManager::HandleAuthenticateTimeout(name);
2542                     });
2543             }
2544             UpdateInputPincodeDialog(errorCode);
2545         }
2546     }
2547 }
2548 
AuthDeviceSessionKey(int64_t requestId,const uint8_t * sessionKey,uint32_t sessionKeyLen)2549 void DmAuthManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen)
2550 {
2551     LOGI("DmAuthManager::AuthDeviceSessionKey start. keyLen: %{public}u", sessionKeyLen);
2552     if (requestId != authResponseContext_->requestId) {
2553         LOGE("DmAuthManager::onTransmit requestId %{public}" PRId64 "is error.", requestId);
2554         return;
2555     }
2556     CHECK_NULL_VOID(authMessageProcessor_);
2557     if (CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_4))) {
2558         if (authMessageProcessor_->ProcessSessionKey(sessionKey, sessionKeyLen) != DM_OK) {
2559             LOGE("Process session key err.");
2560             return;
2561         }
2562     } else {
2563         if (authMessageProcessor_->SaveSessionKey(sessionKey, sessionKeyLen) != DM_OK) {
2564             LOGE("Save session key err.");
2565             return;
2566         }
2567     }
2568     authResponseContext_->localSessionKeyId = 0;
2569     {
2570         std::lock_guard<std::mutex> guard(sessionKeyIdMutex_);
2571         sessionKeyIdAsyncResult_.clear();
2572         sessionKeyIdAsyncResult_[requestId] = std::optional<int32_t>();
2573     }
2574     unsigned char hash[SHA256_DIGEST_LENGTH] = { 0 };
2575     Crypto::DmGenerateStrHash(sessionKey, sessionKeyLen, hash, SHA256_DIGEST_LENGTH, 0);
2576     std::vector<unsigned char> hashVector(hash, hash + SHA256_DIGEST_LENGTH);
2577     std::shared_ptr<DmAuthManager> sharePtrThis = shared_from_this();
2578     auto asyncTaskFunc = [sharePtrThis, requestId, hashVector]() {
2579         sharePtrThis->PutSessionKeyAsync(requestId, hashVector);
2580     };
2581     ffrt::submit(asyncTaskFunc, ffrt::task_attr().delay(0));
2582 }
2583 
PutSessionKeyAsync(int64_t requestId,std::vector<unsigned char> hash)2584 void DmAuthManager::PutSessionKeyAsync(int64_t requestId, std::vector<unsigned char> hash)
2585 {
2586     {
2587         std::lock_guard<std::mutex> guard(sessionKeyIdMutex_);
2588         int32_t sessionKeyId = 0;
2589         int32_t ret =
2590             DeviceProfileConnector::GetInstance().PutSessionKey(MultipleUserConnector::GetCurrentAccountUserID(),
2591                 hash, sessionKeyId);
2592         if (ret != DM_OK) {
2593             LOGI("PutSessionKey failed.");
2594             sessionKeyId = 0;
2595         }
2596         sessionKeyIdAsyncResult_[requestId] = sessionKeyId;
2597     }
2598     sessionKeyIdCondition_.notify_one();
2599 }
2600 
GetSessionKeyIdSync(int64_t requestId)2601 int32_t DmAuthManager::GetSessionKeyIdSync(int64_t requestId)
2602 {
2603     std::unique_lock<std::mutex> guard(sessionKeyIdMutex_);
2604     if (sessionKeyIdAsyncResult_.find(requestId) == sessionKeyIdAsyncResult_.end()) {
2605         LOGW("GetSessionKeyIdSync failed, not find by requestId");
2606         return 0;
2607     }
2608     if (sessionKeyIdAsyncResult_[requestId].has_value()) {
2609         LOGI("GetSessionKeyIdSync, already ready");
2610         return sessionKeyIdAsyncResult_[requestId].value();
2611     }
2612     LOGI("GetSessionKeyIdSync need wait");
2613     sessionKeyIdCondition_.wait_for(guard, std::chrono::milliseconds(MAX_PUT_SESSIONKEY_TIMEOUT));
2614     int32_t keyid = sessionKeyIdAsyncResult_[requestId].value_or(0);
2615     LOGI("GetSessionKeyIdSync exit");
2616     return keyid;
2617 }
2618 
AuthDeviceRequest(int64_t requestId,int operationCode,const char * reqParams)2619 char *DmAuthManager::AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams)
2620 {
2621     LOGI("DmAuthManager::AuthDeviceRequest start.");
2622     (void)requestId;
2623     (void)reqParams;
2624     JsonObject jsonObj;
2625     std::string pinCode = "";
2626     if (GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == "") {
2627         jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED;
2628     } else {
2629         jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED;
2630         jsonObj[FIELD_PIN_CODE] = pinCode;
2631     }
2632     std::string pinCodeHash = GetAnonyString(Crypto::Sha256(pinCode));
2633     LOGI("AuthDeviceRequest pinCodeHash: %{public}s", pinCodeHash.c_str());
2634     std::string deviceId = "";
2635     GetRemoteDeviceId(deviceId);
2636     jsonObj[FIELD_PEER_CONN_DEVICE_ID] = deviceId;
2637     std::string jsonStr = jsonObj.Dump();
2638     char *buffer = strdup(jsonStr.c_str());
2639     return buffer;
2640 }
2641 
GetRemoteDeviceId(std::string & deviceId)2642 void DmAuthManager::GetRemoteDeviceId(std::string &deviceId)
2643 {
2644     LOGI("GetRemoteDeviceId start.");
2645     deviceId = remoteDeviceId_;
2646 }
2647 
CompatiblePutAcl()2648 void DmAuthManager::CompatiblePutAcl()
2649 {
2650     LOGI("DmAuthManager::CompatiblePutAcl");
2651     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
2652     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
2653     std::string localUdid = static_cast<std::string>(localDeviceId);
2654     char mUdidHash[DM_MAX_DEVICE_ID_LEN] = {0};
2655     Crypto::GetUdidHash(localUdid, reinterpret_cast<uint8_t *>(mUdidHash));
2656     std::string localUdidHash = static_cast<std::string>(mUdidHash);
2657     DmAclInfo aclInfo;
2658     aclInfo.bindLevel = USER;
2659     aclInfo.bindType = DM_POINT_TO_POINT;
2660     aclInfo.trustDeviceId = remoteDeviceId_;
2661     if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) {
2662         aclInfo.authenticationType = ALLOW_AUTH_ALWAYS;
2663     } else if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH) {
2664         aclInfo.authenticationType = ALLOW_AUTH_ONCE;
2665     }
2666     aclInfo.deviceIdHash = localUdidHash;
2667 
2668     DmAccesser accesser;
2669     DmAccessee accessee;
2670     if (authRequestState_ != nullptr && authResponseState_ == nullptr) {
2671         accesser.requestBundleName = authResponseContext_->hostPkgName;
2672         accesser.requestDeviceId = localUdid;
2673         accesser.requestUserId = MultipleUserConnector::GetCurrentAccountUserID();
2674         accesser.requestAccountId = MultipleUserConnector::GetAccountInfoByUserId(accesser.requestUserId).accountId;
2675         accesser.requestTokenId = static_cast<uint64_t>(authRequestContext_->tokenId);
2676         accessee.trustBundleName = authResponseContext_->hostPkgName;
2677         accessee.trustDeviceId = remoteDeviceId_;
2678         accessee.trustUserId = -1;
2679     }
2680     if (authRequestState_ == nullptr && authResponseState_ != nullptr) {
2681         accesser.requestBundleName = authResponseContext_->hostPkgName;
2682         accesser.requestDeviceId = remoteDeviceId_;
2683         accesser.requestUserId = authResponseContext_->remoteUserId;
2684         accesser.requestAccountId = authResponseContext_->remoteAccountId;
2685         accesser.requestTokenId = static_cast<uint64_t>(authResponseContext_->remoteTokenId);
2686         accessee.trustBundleName = authResponseContext_->hostPkgName;
2687         accessee.trustDeviceId = localUdid;
2688         accessee.trustUserId = MultipleUserConnector::GetCurrentAccountUserID();
2689         accessee.trustAccountId = MultipleUserConnector::GetAccountInfoByUserId(accessee.trustUserId).accountId;
2690         accessee.trustTokenId = static_cast<uint64_t>(authResponseContext_->tokenId);
2691     }
2692     DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, accesser, accessee);
2693 }
2694 
ProcRespNegotiateExt(const int32_t & sessionId)2695 void DmAuthManager::ProcRespNegotiateExt(const int32_t &sessionId)
2696 {
2697     LOGI("DmAuthManager::ProcRespNegotiateExt start.");
2698     remoteDeviceId_ = authResponseContext_->localDeviceId;
2699     authResponseContext_->remoteAccountId = authResponseContext_->localAccountId;
2700     authResponseContext_->remoteUserId = authResponseContext_->localUserId;
2701     GetBinderInfo();
2702     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
2703     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
2704     authResponseContext_->deviceId = authResponseContext_->localDeviceId;
2705     authResponseContext_->localDeviceId = static_cast<std::string>(localDeviceId);
2706     authResponseContext_->bindType =
2707         DeviceProfileConnector::GetInstance().GetBindTypeByPkgName(authResponseContext_->hostPkgName,
2708         authResponseContext_->localDeviceId, authResponseContext_->deviceId);
2709     authResponseContext_->authed = !authResponseContext_->bindType.empty();
2710 
2711     authResponseContext_->isIdenticalAccount = false;
2712     if (authResponseContext_->localAccountId == authResponseContext_->remoteAccountId &&
2713         authResponseContext_->localAccountId != "ohosAnonymousUid" && authResponseContext_->authed) {
2714         authResponseContext_->isIdenticalAccount = true;
2715     }
2716 
2717     authResponseContext_->isOnline = softbusConnector_->CheckIsOnline(remoteDeviceId_);
2718     authResponseContext_->haveCredential =
2719         hiChainAuthConnector_->QueryCredential(authResponseContext_->deviceId,
2720             MultipleUserConnector::GetFirstForegroundUserId(), authResponseContext_->remoteUserId);
2721     if (!IsAuthTypeSupported(authResponseContext_->authType)) {
2722         LOGE("DmAuthManager::AuthenticateDevice authType %{public}d not support.", authResponseContext_->authType);
2723         authResponseContext_->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE;
2724     } else {
2725         authPtr_ = authenticationMap_[authResponseContext_->authType];
2726     }
2727     if (IsAuthCodeReady(authResponseContext_->hostPkgName)) {
2728         authResponseContext_->isAuthCodeReady = true;
2729     } else {
2730         authResponseContext_->isAuthCodeReady = false;
2731     }
2732     std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_NEGOTIATE);
2733     softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
2734 
2735     if (authResponseContext_->authType == AUTH_TYPE_NFC) {
2736         GetLocalServiceInfoInDp();
2737     }
2738 }
2739 
ProcRespNegotiate(const int32_t & sessionId)2740 void DmAuthManager::ProcRespNegotiate(const int32_t &sessionId)
2741 {
2742     LOGI("DmAuthManager::ProcRespNegotiate session id");
2743     AbilityNegotiate();
2744     authResponseContext_->isOnline = softbusConnector_->CheckIsOnline(remoteDeviceId_);
2745     std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_NEGOTIATE);
2746     JsonObject jsonObject(message);
2747     if (jsonObject.IsDiscarded()) {
2748         softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
2749         return;
2750     }
2751     if (!IsBool(jsonObject, TAG_CRYPTO_SUPPORT)) {
2752         LOGE("err json string.");
2753         softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
2754         return;
2755     }
2756     jsonObject[TAG_ACCOUNT_GROUPID] = GetAccountGroupIdHash();
2757     authResponseContext_ = authResponseState_->GetAuthContext();
2758     if (jsonObject[TAG_CRYPTO_SUPPORT].Get<bool>() == true && authResponseContext_->cryptoSupport) {
2759         if (IsString(jsonObject, TAG_CRYPTO_NAME) && IsString(jsonObject, TAG_CRYPTO_VERSION)) {
2760             if (jsonObject[TAG_CRYPTO_NAME].Get<std::string>() == authResponseContext_->cryptoName &&
2761                 jsonObject[TAG_CRYPTO_VERSION].Get<std::string>() == authResponseContext_->cryptoVer) {
2762                 isCryptoSupport_ = true;
2763                 softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
2764                 return;
2765             }
2766         }
2767     }
2768     jsonObject[TAG_CRYPTO_SUPPORT] = false;
2769     message = jsonObject.Dump();
2770     softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
2771 }
2772 
ProcIncompatible(const int32_t & sessionId)2773 void DmAuthManager::ProcIncompatible(const int32_t &sessionId)
2774 {
2775     LOGI("DmAuthManager::ProcIncompatible sessionId %{public}d.", sessionId);
2776     JsonObject respNegotiateMsg;
2777     respNegotiateMsg[TAG_REPLY] = ERR_DM_VERSION_INCOMPATIBLE;
2778     respNegotiateMsg[TAG_VER] = DM_ITF_VER;
2779     respNegotiateMsg[TAG_MSG_TYPE] = MSG_TYPE_RESP_NEGOTIATE;
2780     std::string message = respNegotiateMsg.Dump();
2781     softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
2782 }
2783 
OnAuthDeviceDataReceived(const int32_t sessionId,const std::string message)2784 void DmAuthManager::OnAuthDeviceDataReceived(const int32_t sessionId, const std::string message)
2785 {
2786     if (authResponseContext_ == nullptr || authMessageProcessor_ == nullptr || hiChainAuthConnector_ == nullptr ||
2787         authResponseContext_->sessionId != sessionId) {
2788         LOGE("OnAuthDeviceDataReceived param is invalid");
2789         return;
2790     }
2791     authResponseContext_->sessionId = sessionId;
2792     authMessageProcessor_->SetResponseContext(authResponseContext_);
2793     JsonObject jsonObject(message);
2794     if (jsonObject.IsDiscarded()) {
2795         LOGE("DecodeRequestAuth jsonStr error");
2796         return;
2797     }
2798     if (!IsString(jsonObject, TAG_DATA) || !IsInt32(jsonObject, TAG_DATA_LEN) || !IsInt32(jsonObject, TAG_MSG_TYPE)) {
2799         LOGE("Auth device data is error.");
2800         return;
2801     }
2802     LOGI("OnAuthDeviceDataReceived start msgType %{public}d.", jsonObject[TAG_MSG_TYPE].Get<int32_t>());
2803     std::string authData = jsonObject[TAG_DATA].Get<std::string>();
2804     int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID();
2805     hiChainAuthConnector_->ProcessAuthData(authResponseContext_->requestId, authData, osAccountId);
2806 }
2807 
DeleteGroup(const std::string & pkgName,const std::string & deviceId)2808 int32_t DmAuthManager::DeleteGroup(const std::string &pkgName, const std::string &deviceId)
2809 {
2810     LOGI("DmAuthManager::DeleteGroup");
2811     if (pkgName.empty()) {
2812         LOGE("Invalid parameter, pkgName is empty.");
2813         return ERR_DM_FAILED;
2814     }
2815     std::vector<OHOS::DistributedHardware::GroupInfo> groupList;
2816     CHECK_NULL_RETURN(hiChainConnector_, ERR_DM_POINT_NULL);
2817     hiChainConnector_->GetRelatedGroups(deviceId, groupList);
2818     for (const auto &item : groupList) {
2819         std::string groupId = item.groupId;
2820         hiChainConnector_->DeleteGroup(groupId);
2821     }
2822     return DM_OK;
2823 }
2824 
DeleteGroup(const std::string & pkgName,int32_t userId,const std::string & deviceId)2825 int32_t DmAuthManager::DeleteGroup(const std::string &pkgName, int32_t userId, const std::string &deviceId)
2826 {
2827     LOGI("DmAuthManager::DeleteGroup");
2828     if (pkgName.empty()) {
2829         LOGE("Invalid parameter, pkgName is empty.");
2830         return ERR_DM_FAILED;
2831     }
2832     std::vector<OHOS::DistributedHardware::GroupInfo> groupList;
2833     hiChainConnector_->GetRelatedGroups(userId, deviceId, groupList);
2834     if (groupList.size() > 0) {
2835         std::string groupId = "";
2836         groupId = groupList.front().groupId;
2837         hiChainConnector_->DeleteGroup(userId, groupId);
2838     } else {
2839         LOGE("DmAuthManager::UnAuthenticateDevice groupList.size = 0");
2840         return ERR_DM_FAILED;
2841     }
2842     if (softbusConnector_ != nullptr) {
2843         softbusConnector_->EraseUdidFromMap(deviceId);
2844     }
2845     return DM_OK;
2846 }
2847 
PutAccessControlList()2848 void DmAuthManager::PutAccessControlList()
2849 {
2850     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
2851     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
2852     std::string localUdid = static_cast<std::string>(localDeviceId);
2853     char mUdidHash[DM_MAX_DEVICE_ID_LEN] = {0};
2854     Crypto::GetUdidHash(localUdid, reinterpret_cast<uint8_t *>(mUdidHash));
2855     std::string localUdidHash = static_cast<std::string>(mUdidHash);
2856     DmAclInfo aclInfo;
2857     aclInfo.bindType = DM_ACROSS_ACCOUNT;
2858     if (authResponseContext_->localAccountId == "ohosAnonymousUid" ||
2859         authResponseContext_->remoteAccountId == "ohosAnonymousUid") {
2860         aclInfo.bindType = DM_POINT_TO_POINT;
2861         authForm_ = DmAuthForm::PEER_TO_PEER;
2862     }
2863     aclInfo.bindLevel = authResponseContext_->bindLevel;
2864     aclInfo.trustDeviceId = remoteDeviceId_;
2865     aclInfo.authenticationType = ALLOW_AUTH_ONCE;
2866     if (authResponseContext_->confirmOperation == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) {
2867         aclInfo.authenticationType = ALLOW_AUTH_ALWAYS;
2868     }
2869     aclInfo.deviceIdHash = localUdidHash;
2870     DmAccesser accesser;
2871     accesser.requestBundleName = authResponseContext_->hostPkgName;
2872     DmAccessee accessee;
2873     accessee.trustBundleName = authResponseContext_->peerBundleName;
2874     if (authRequestState_ != nullptr && authResponseState_ == nullptr) {
2875         PutSrcAccessControlList(accesser, accessee, localUdid);
2876     } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) {
2877         PutSinkAccessControlList(accesser, accessee, localUdid);
2878     }
2879     DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, accesser, accessee);
2880 }
2881 
PutSrcAccessControlList(DmAccesser & accesser,DmAccessee & accessee,const std::string & localUdid)2882 void DmAuthManager::PutSrcAccessControlList(DmAccesser &accesser, DmAccessee &accessee,
2883     const std::string &localUdid)
2884 {
2885     accesser.requestTokenId = static_cast<uint64_t>(authRequestContext_->tokenId);
2886     accesser.requestUserId = authRequestContext_->localUserId;
2887     accesser.requestAccountId = authRequestContext_->localAccountId;
2888     accesser.requestDeviceId = authRequestContext_->localDeviceId;
2889     accesser.requestDeviceName = authRequestContext_->localDeviceName;
2890     if (authResponseContext_->remoteTokenId == authRequestContext_->tokenId) {
2891         accessee.trustTokenId = 0;
2892     } else {
2893         accessee.trustTokenId = static_cast<uint64_t>(authResponseContext_->remoteTokenId);
2894     }
2895     accessee.trustUserId = authRequestContext_->remoteUserId;
2896     accessee.trustAccountId = authRequestContext_->remoteAccountId;
2897     accessee.trustDeviceId = remoteDeviceId_;
2898     accessee.trustDeviceName = authRequestContext_->remoteDeviceName;
2899 }
2900 
PutSinkAccessControlList(DmAccesser & accesser,DmAccessee & accessee,const std::string & localUdid)2901 void DmAuthManager::PutSinkAccessControlList(DmAccesser &accesser, DmAccessee &accessee,
2902     const std::string &localUdid)
2903 {
2904     accesser.requestTokenId = static_cast<uint64_t>(authResponseContext_->remoteTokenId);
2905     accesser.requestUserId = authResponseContext_->remoteUserId;
2906     accesser.requestAccountId = authResponseContext_->remoteAccountId;
2907     accesser.requestDeviceId = remoteDeviceId_;
2908     accesser.requestDeviceName = authResponseContext_->remoteDeviceName;
2909     if (authResponseContext_->remoteTokenId == authResponseContext_->tokenId) {
2910         accessee.trustTokenId = 0;
2911     } else {
2912         accessee.trustTokenId = static_cast<uint64_t>(authResponseContext_->tokenId);
2913     }
2914     accessee.trustUserId = authResponseContext_->localUserId;
2915     accessee.trustAccountId = authResponseContext_->localAccountId;
2916     accessee.trustDeviceId = localUdid;
2917     accessee.trustDeviceName = authResponseContext_->targetDeviceName;
2918 }
2919 
HandleSessionHeartbeat(std::string name)2920 void DmAuthManager::HandleSessionHeartbeat(std::string name)
2921 {
2922     if (timer_ != nullptr) {
2923         timer_->DeleteTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK));
2924     }
2925     LOGI("DmAuthManager::HandleSessionHeartbeat name %{public}s", name.c_str());
2926     JsonObject jsonObj;
2927     jsonObj[TAG_SESSION_HEARTBEAT] = TAG_SESSION_HEARTBEAT;
2928     std::string message = jsonObj.Dump();
2929     softbusConnector_->GetSoftbusSession()->SendHeartbeatData(authResponseContext_->sessionId, message);
2930 
2931     if (authRequestState_ != nullptr) {
2932         if (timer_ != nullptr) {
2933             timer_->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK),
2934                 GetTaskTimeout(SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), [this] (std::string name) {
2935                     DmAuthManager::HandleSessionHeartbeat(name);
2936                 });
2937         }
2938     }
2939     LOGI("DmAuthManager::HandleSessionHeartbeat complete");
2940 }
2941 
CheckTrustState()2942 int32_t DmAuthManager::CheckTrustState()
2943 {
2944     bool isSameGroup = false;
2945     if (authResponseContext_->reply == ERR_DM_AUTH_PEER_REJECT &&
2946         hiChainConnector_->IsDevicesInP2PGroup(authResponseContext_->localDeviceId,
2947                                                authRequestContext_->localDeviceId)) {
2948         isSameGroup = true;
2949     }
2950     if (isSameGroup && authResponseContext_->isOnline && authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) {
2951         authResponseContext_->isFinish = true;
2952         SetReasonAndFinish(DM_OK, AuthState::AUTH_REQUEST_FINISH);
2953         return ALREADY_BIND;
2954     }
2955     if (authResponseContext_->isIdenticalAccount) {
2956         if (IsIdenticalAccount()) {
2957             JoinLnn(authResponseContext_->deviceId);
2958             authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
2959             authRequestContext_->reason = DM_OK;
2960             authResponseContext_->reply = DM_OK;
2961             authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
2962             return ALREADY_BIND;
2963         }
2964     }
2965     if (isSameGroup) {
2966         if (!DeviceProfileConnector::GetInstance().CheckSrcDevIdInAclForDevBind(authResponseContext_->hostPkgName,
2967             authResponseContext_->localDeviceId)) {
2968             CompatiblePutAcl();
2969         }
2970         JoinLnn(authResponseContext_->deviceId);
2971         authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
2972         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
2973         return ALREADY_BIND;
2974     }
2975     if (authResponseContext_->reply == ERR_DM_UNSUPPORTED_AUTH_TYPE ||
2976         (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE &&
2977         authResponseContext_->isAuthCodeReady == false)) {
2978         authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
2979         authRequestContext_->reason = ERR_DM_BIND_PEER_UNSUPPORTED;
2980         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
2981         return ERR_DM_BIND_PEER_UNSUPPORTED;
2982     }
2983     return DM_OK;
2984 }
2985 
IsScreenLocked()2986 bool DmAuthManager::IsScreenLocked()
2987 {
2988     bool isLocked = false;
2989 #if defined(SUPPORT_SCREENLOCK)
2990     isLocked = OHOS::ScreenLock::ScreenLockManager::GetInstance()->IsScreenLocked();
2991 #endif
2992     LOGI("IsScreenLocked isLocked: %{public}d.", isLocked);
2993     return isLocked;
2994 }
2995 
OnScreenLocked()2996 void DmAuthManager::OnScreenLocked()
2997 {
2998     if (authResponseContext_ != nullptr && AUTH_TYPE_IMPORT_AUTH_CODE == authResponseContext_->authType) {
2999         LOGI("OnScreenLocked authtype is: %{public}d, no need stop bind.", authResponseContext_->authType);
3000         return;
3001     }
3002     if (authRequestState_ == nullptr) {
3003         LOGE("OnScreenLocked authRequestState_ is nullptr.");
3004         return;
3005     }
3006     if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE ||
3007         authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT) {
3008         LOGI("OnScreenLocked stop bind.");
3009         SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL, STATUS_DM_AUTH_DEFAULT);
3010         return;
3011     }
3012     if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_JOIN) {
3013         LOGI("OnScreenLocked stop user input.");
3014         if (authUiStateMgr_ != nullptr) {
3015             authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT);
3016         }
3017         SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL, STATUS_DM_AUTH_DEFAULT);
3018         return;
3019     }
3020     if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) {
3021         LOGI("OnScreenLocked stop confirm.");
3022         SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL, STATUS_DM_AUTH_DEFAULT);
3023     }
3024 }
3025 
HandleDeviceNotTrust(const std::string & udid)3026 void DmAuthManager::HandleDeviceNotTrust(const std::string &udid)
3027 {
3028     LOGI("DmAuthManager::HandleDeviceNotTrust udid: %{public}s.", GetAnonyString(udid).c_str());
3029     if (udid.empty()) {
3030         LOGE("DmAuthManager::HandleDeviceNotTrust udid is empty.");
3031         return;
3032     }
3033     DeviceProfileConnector::GetInstance().DeleteAccessControlList(udid);
3034     CHECK_NULL_VOID(hiChainConnector_);
3035     hiChainConnector_->DeleteAllGroupByUdid(udid);
3036 }
3037 
ConvertSinkVersion(const std::string & version)3038 std::string DmAuthManager::ConvertSinkVersion(const std::string &version)
3039 {
3040     std::string sinkVersion = "";
3041     if (version == "") {
3042         sinkVersion = DM_VERSION_4_1_5_1;
3043     } else {
3044         sinkVersion = version;
3045     }
3046     LOGI("ConvertSinkVersion version %{public}s, sinkVersion is %{public}s.", version.c_str(), sinkVersion.c_str());
3047     return sinkVersion;
3048 }
3049 
SetAuthType(int32_t authType)3050 void DmAuthManager::SetAuthType(int32_t authType)
3051 {
3052     authType_ = authType;
3053 }
3054 
GetTaskTimeout(const char * taskName,int32_t taskTimeOut)3055 int32_t DmAuthManager::GetTaskTimeout(const char* taskName, int32_t taskTimeOut)
3056 {
3057     LOGI("GetTaskTimeout, taskName: %{public}s, authType_: %{public}d", taskName, authType_.load());
3058     if (AUTH_TYPE_IMPORT_AUTH_CODE == authType_) {
3059         auto timeout = TASK_TIME_OUT_MAP.find(std::string(taskName));
3060         if (timeout != TASK_TIME_OUT_MAP.end()) {
3061             return timeout->second;
3062         }
3063     }
3064     return taskTimeOut;
3065 }
3066 
GetBinderInfo()3067 int32_t DmAuthManager::GetBinderInfo()
3068 {
3069     CHECK_NULL_RETURN(authResponseContext_, ERR_DM_POINT_NULL);
3070     if (authResponseContext_->bundleName.empty()) {
3071         LOGI("bundleName is empty");
3072         authResponseContext_->localUserId = MultipleUserConnector::GetCurrentAccountUserID();
3073         authResponseContext_->localAccountId = MultipleUserConnector::GetOhosAccountId();
3074         return DM_OK;
3075     }
3076     authResponseContext_->localUserId = MultipleUserConnector::GetFirstForegroundUserId();
3077     authResponseContext_->localAccountId =
3078         MultipleUserConnector::GetOhosAccountIdByUserId(authResponseContext_->localUserId);
3079     if (authResponseContext_->peerBundleName == authResponseContext_->hostPkgName) {
3080         bundleName_ = authResponseContext_->bundleName;
3081     } else {
3082         bundleName_ = authResponseContext_->peerBundleName;
3083     }
3084     int32_t ret = AppManager::GetInstance().
3085         GetNativeTokenIdByName(authResponseContext_->bundleName, authResponseContext_->tokenId);
3086     if (ret == DM_OK) {
3087         LOGI("bundleName is sa");
3088         return DM_OK;
3089     }
3090     ret = AppManager::GetInstance().GetHapTokenIdByName(authResponseContext_->localUserId,
3091         authResponseContext_->peerBundleName, 0, authResponseContext_->tokenId);
3092 #ifndef DEVICE_MANAGER_COMMON_FLAG
3093     if (ret == DM_OK && static_cast<uint32_t>(authResponseContext_->bindLevel) != APP) {
3094         LOGI("get tokenId by bundleName failed %{public}s", GetAnonyString(authResponseContext_->bundleName).c_str());
3095         return ERR_DM_FAILED;
3096     }
3097 #endif
3098     return ret;
3099 }
3100 
SetProcessInfo()3101 void DmAuthManager::SetProcessInfo()
3102 {
3103     CHECK_NULL_VOID(authResponseContext_);
3104     ProcessInfo processInfo;
3105     if (static_cast<uint32_t>(authResponseContext_->bindLevel) == APP) {
3106         if ((authRequestState_ != nullptr) && (authResponseState_ == nullptr)) {
3107             processInfo.pkgName = authResponseContext_->hostPkgName;
3108             processInfo.userId = authRequestContext_->localUserId;
3109         } else if ((authRequestState_ == nullptr) && (authResponseState_ != nullptr)) {
3110             processInfo.pkgName = authResponseContext_->peerBundleName;
3111             processInfo.userId = authResponseContext_->localUserId;
3112         } else {
3113             LOGE("DMAuthManager::SetProcessInfo failed, state is invalid.");
3114         }
3115     } else if (static_cast<uint32_t>(authResponseContext_->bindLevel) == USER ||
3116         static_cast<uint32_t>(authResponseContext_->bindLevel) == INVALIED_TYPE) {
3117         processInfo.pkgName = std::string(DM_PKG_NAME);
3118         processInfo.userId = authResponseContext_->localUserId;
3119     } else {
3120         LOGE("bindlevel error %{public}d.", authResponseContext_->bindLevel);
3121         return;
3122     }
3123     softbusConnector_->SetProcessInfo(processInfo);
3124 }
3125 
ConverToFinish()3126 void DmAuthManager::ConverToFinish()
3127 {
3128     authRequestContext_->reason = DM_OK;
3129     authResponseContext_->reply = DM_OK;
3130     authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
3131     authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
3132 }
3133 
RequestReCheckMsg()3134 void DmAuthManager::RequestReCheckMsg()
3135 {
3136     LOGI("dmVersion %{public}s.", DM_VERSION_5_0_5);
3137     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
3138     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
3139     uint32_t tokenId = 0;
3140     int32_t localUserId = 0;
3141     MultipleUserConnector::GetTokenIdAndForegroundUserId(tokenId, localUserId);
3142     std::string localAccountId = MultipleUserConnector::GetOhosAccountIdByUserId(localUserId);
3143     authResponseContext_->edition = DM_VERSION_5_0_5;
3144     authResponseContext_->localDeviceId = static_cast<std::string>(localDeviceId);
3145     authResponseContext_->localUserId = localUserId;
3146     authResponseContext_->bundleName = authRequestContext_->hostPkgName;
3147     authResponseContext_->bindLevel = authRequestContext_->bindLevel;
3148     authResponseContext_->localAccountId = localAccountId;
3149     authResponseContext_->tokenId = authRequestContext_->tokenId;
3150     authMessageProcessor_->SetResponseContext(authResponseContext_);
3151     std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_RECHECK_MSG);
3152     softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
3153 }
3154 
ResponseReCheckMsg()3155 void DmAuthManager::ResponseReCheckMsg()
3156 {
3157     LOGI("remoteVersion %{public}s, authResponseContext_->edition %{public}s.",
3158         remoteVersion_.c_str(), authResponseContext_->edition.c_str());
3159     if (!IsSinkMsgValid()) {
3160         LOGE("peer deviceId not trust.");
3161         authResponseContext_->isFinish = false;
3162         isFinishOfLocal_ = false;
3163         authMessageProcessor_->SetEncryptFlag(false);
3164         int32_t sessionId = authResponseContext_->sessionId;
3165         authResponseContext_->state = authResponseState_->GetStateType();
3166         authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
3167         return;
3168     }
3169     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
3170     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
3171     authResponseContext_->edition = DM_VERSION_5_0_5;
3172     authResponseContext_->localDeviceId = std::string(localDeviceId);
3173     authResponseContext_->localUserId = MultipleUserConnector::GetFirstForegroundUserId();
3174     authResponseContext_->localAccountId =
3175         MultipleUserConnector::GetOhosAccountIdByUserId(authResponseContext_->localUserId);
3176     if (AppManager::GetInstance().GetNativeTokenIdByName(bundleName_, authResponseContext_->tokenId) != DM_OK) {
3177         LOGE("BundleName %{public}s, GetNativeTokenIdByName failed.", GetAnonyString(bundleName_).c_str());
3178         if (AppManager::GetInstance().GetHapTokenIdByName(authResponseContext_->localUserId,
3179             bundleName_, 0, authResponseContext_->tokenId) != DM_OK) {
3180             LOGE("get tokenId by bundleName failed %{public}s", GetAnonyString(bundleName_).c_str());
3181             authResponseContext_->tokenId = 0;
3182         }
3183     }
3184     authResponseContext_->bundleName = authResponseContext_->peerBundleName;
3185     authMessageProcessor_->SetEncryptFlag(true);
3186     std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_RECHECK_MSG);
3187     softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
3188     PutAccessControlList();
3189 }
3190 
RequestReCheckMsgDone()3191 void DmAuthManager::RequestReCheckMsgDone()
3192 {
3193     LOGI("remoteVersion %{public}s, authResponseContext_->edition %{public}s.",
3194         remoteVersion_.c_str(), authResponseContext_->edition.c_str());
3195     if (!IsSourceMsgValid()) {
3196         LOGE("peer deviceId not trust.");
3197         authResponseContext_->isFinish = false;
3198         isFinishOfLocal_ = false;
3199         authMessageProcessor_->SetEncryptFlag(false);
3200         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
3201         return;
3202     }
3203     authRequestState_->TransitionTo(std::make_shared<AuthRequestCredential>());
3204     PutAccessControlList();
3205 }
3206 
IsSinkMsgValid()3207 bool DmAuthManager::IsSinkMsgValid()
3208 {
3209     LOGI("sink remoteVersion %{public}s, remoteDeviceId %{public}s, remoteUserId %{public}d,"
3210         "remoteHostPkgName %{public}s, remoteBindLevel %{public}d", remoteVersion_.c_str(),
3211         GetAnonyString(remoteDeviceId_).c_str(), authResponseContext_->remoteUserId,
3212         authResponseContext_->hostPkgName.c_str(), authResponseContext_->bindLevel);
3213     LOGI("src version %{public}s, deviceId %{public}s, userId %{public}d, hostPkgName %{public}s, bindLevel %{public}d",
3214         authResponseContext_->edition.c_str(), GetAnonyString(authResponseContext_->localDeviceId).c_str(),
3215         authResponseContext_->localUserId, authResponseContext_->bundleName.c_str(),
3216         authResponseContext_->localBindLevel);
3217     if (authResponseContext_->edition != remoteVersion_ ||
3218         authResponseContext_->localDeviceId != remoteDeviceId_ ||
3219         authResponseContext_->localUserId != authResponseContext_->remoteUserId ||
3220         authResponseContext_->bundleName != authResponseContext_->hostPkgName ||
3221         authResponseContext_->localBindLevel != authResponseContext_->bindLevel) {
3222         return false;
3223     }
3224     return true;
3225 }
3226 
IsSourceMsgValid()3227 bool DmAuthManager::IsSourceMsgValid()
3228 {
3229     if (authResponseContext_->edition != remoteVersion_ ||
3230         authResponseContext_->localDeviceId != remoteDeviceId_ ||
3231         authResponseContext_->localUserId != authRequestContext_->remoteUserId ||
3232         authResponseContext_->bundleName != authResponseContext_->peerBundleName ||
3233         authResponseContext_->localBindLevel != authResponseContext_->bindLevel) {
3234         return false;
3235     }
3236     authResponseContext_->localAccountId = authRequestContext_->localAccountId;
3237     return true;
3238 }
3239 
RegisterAuthenticationType(int32_t authenticationType)3240 int32_t DmAuthManager::RegisterAuthenticationType(int32_t authenticationType)
3241 {
3242     authenticationType_ = authenticationType;
3243     return DM_OK;
3244 }
3245 
ProcessReqPublicKey()3246 void DmAuthManager::ProcessReqPublicKey()
3247 {
3248     if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_AUTH_FINISH ||
3249         authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_RECHECK_MSG) {
3250         authResponseState_->TransitionTo(std::make_shared<AuthResponseCredential>());
3251         return;
3252     }
3253     if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW) {
3254         std::lock_guard<std::mutex> lock(srcReqMsgLock_);
3255         isNeedProcCachedSrcReqMsg_ = true;
3256     }
3257 }
3258 
GetLocalServiceInfoInDp()3259 void DmAuthManager::GetLocalServiceInfoInDp()
3260 {
3261     DistributedDeviceProfile::LocalServiceInfo localServiceInfo;
3262     int32_t result = DeviceProfileConnector::GetInstance().GetLocalServiceInfoByBundleNameAndPinExchangeType(
3263         authResponseContext_->hostPkgName, (int32_t)DMLocalServiceInfoPinExchangeType::FROMDP, localServiceInfo);
3264     if (result != DM_OK) {
3265         return;
3266     }
3267     if (IsLocalServiceInfoValid(localServiceInfo)) {
3268         serviceInfoProfile_ = localServiceInfo;
3269         LOGI("authBoxType %{public}d, authType %{public}d, pinExchangeType %{public}d",
3270             serviceInfoProfile_.GetAuthBoxType(), serviceInfoProfile_.GetAuthType(),
3271             serviceInfoProfile_.GetPinExchangeType());
3272         auto updateProfile = serviceInfoProfile_;
3273         updateProfile.SetPinCode("******");
3274         DeviceProfileConnector::GetInstance().UpdateLocalServiceInfo(updateProfile);
3275     }
3276 }
3277 
CheckNeedShowAuthInfoDialog(int32_t errorCode)3278 bool DmAuthManager::CheckNeedShowAuthInfoDialog(int32_t errorCode)
3279 {
3280     CHECK_NULL_RETURN(authResponseContext_, false);
3281     if (errorCode == ERR_DM_HICHAIN_PROOFMISMATCH && !pincodeDialogEverShown_ && CanUsePincodeFromDp()) {
3282         authResponseContext_->code = GeneratePincode();
3283         LOGI("AuthDeviceError, GeneratePincode, ShowAuthInfoDialog");
3284         authTimes_ = 0;
3285         ShowAuthInfoDialog(true);
3286         return true;
3287     }
3288     return false;
3289 }
3290 
UpdateInputPincodeDialog(int32_t errorCode)3291 void DmAuthManager::UpdateInputPincodeDialog(int32_t errorCode)
3292 {
3293     CHECK_NULL_VOID(authResponseContext_);
3294     CHECK_NULL_VOID(authUiStateMgr_);
3295     if (authResponseContext_->authType == AUTH_TYPE_NFC && !pincodeDialogEverShown_ &&
3296         IsImportedAuthCodeValid() && errorCode == ERR_DM_HICHAIN_PROOFMISMATCH) {
3297         LOGI("AuthDeviceError, ShowStartAuthDialog");
3298         authTimes_ = 0;
3299         DeleteAuthCode();
3300         ShowStartAuthDialog();
3301     } else {
3302         authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR);
3303     }
3304 }
3305 
JoinLnn(const std::string & deviceId,bool isForceJoin)3306 void DmAuthManager::JoinLnn(const std::string &deviceId, bool isForceJoin)
3307 {
3308     CHECK_NULL_VOID(authRequestContext_);
3309     CHECK_NULL_VOID(authResponseContext_);
3310     CHECK_NULL_VOID(softbusConnector_);
3311     if (IsHmlSessionType()) {
3312         if (authRequestContext_->closeSessionDelaySeconds == 0) {
3313             isWaitingJoinLnnCallback_ = true;
3314         }
3315         authResponseContext_->localSessionKeyId = GetSessionKeyIdSync(authResponseContext_->requestId);
3316         softbusConnector_->JoinLnnByHml(authRequestContext_->sessionId, authResponseContext_->localSessionKeyId,
3317             authResponseContext_->remoteSessionKeyId);
3318         return;
3319     }
3320     if (isNeedJoinLnn_) {
3321         LOGI("isNeedJoinLnn %{public}d", isNeedJoinLnn_);
3322         softbusConnector_->JoinLnn(deviceId, isForceJoin);
3323     }
3324 }
3325 
OnSoftbusJoinLNNResult(const int32_t sessionId,const char * networkId,int32_t result)3326 void DmAuthManager::OnSoftbusJoinLNNResult(const int32_t sessionId, const char *networkId, int32_t result)
3327 {
3328     (void)sessionId;
3329     (void)networkId;
3330     (void)result;
3331 }
3332 
CloseAuthSession(const int32_t sessionId)3333 void DmAuthManager::CloseAuthSession(const int32_t sessionId)
3334 {
3335     if (timer_ != nullptr) {
3336         timer_->DeleteTimer(std::string(WAIT_SESSION_CLOSE_TIMEOUT_TASK) + std::string(CLOSE_SESSION_TASK_SEPARATOR) +
3337             std::to_string(sessionId));
3338     }
3339     CHECK_NULL_VOID(softbusConnector_);
3340     CHECK_NULL_VOID(softbusConnector_->GetSoftbusSession());
3341     softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId);
3342 }
3343 
RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback)3344 void DmAuthManager::RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback)
3345 {
3346     cleanNotifyCallback_ = cleanNotifyCallback;
3347     return;
3348 }
3349 
GetBindCallerInfo()3350 void DmAuthManager::GetBindCallerInfo()
3351 {
3352     LOGI("start.");
3353     CHECK_NULL_VOID(authRequestContext_);
3354     {
3355         std::lock_guard<std::mutex> lock(bindParamMutex_);
3356         if (bindParam_.find("bindCallerTokenId") != bindParam_.end()) {
3357             authRequestContext_->tokenId = std::atoi(bindParam_["bindCallerTokenId"].c_str());
3358         }
3359         if (bindParam_.find("bindCallerOldBindLevel") != bindParam_.end()) {
3360             authRequestContext_->bindLevel = std::atoi(bindParam_["bindCallerOldBindLevel"].c_str());
3361         }
3362         if (bindParam_.find("bindCallerBundleName") != bindParam_.end()) {
3363             authRequestContext_->bundleName = bindParam_["bindCallerBundleName"];
3364         }
3365         if (bindParam_.find("bindCallerHostPkgLabel") != bindParam_.end()) {
3366             authRequestContext_->hostPkgLabel = bindParam_["bindCallerHostPkgLabel"];
3367         }
3368     }
3369 }
3370 } // namespace DistributedHardware
3371 } // namespace OHOS
3372