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