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