• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "dm_auth_manager.h"
17 
18 #include <string>
19 #include <unistd.h>
20 
21 #include "auth_message_processor.h"
22 #include "dm_ability_manager.h"
23 #include "dm_anonymous.h"
24 #include "dm_config_manager.h"
25 #include "dm_constants.h"
26 #include "dm_log.h"
27 #include "dm_random.h"
28 #include "multiple_user_connector.h"
29 #include "nlohmann/json.hpp"
30 #include "parameter.h"
31 #include "show_confirm.h"
32 
33 namespace OHOS {
34 namespace DistributedHardware {
35 const int32_t AUTHENTICATE_TIMEOUT = 120;
36 const int32_t CONFIRM_TIMEOUT = 60;
37 const int32_t NEGOTIATE_TIMEOUT = 10;
38 const int32_t INPUT_TIMEOUT = 60;
39 const int32_t ADD_TIMEOUT = 10;
40 const int32_t WAIT_NEGOTIATE_TIMEOUT = 10;
41 const int32_t WAIT_REQUEST_TIMEOUT = 10;
42 const int32_t CANCEL_PIN_CODE_DISPLAY = 1;
43 const int32_t DEVICE_ID_HALF = 2;
44 const int32_t MAX_AUTH_TIMES = 3;
45 const int32_t MIN_PIN_TOKEN = 10000000;
46 const int32_t MAX_PIN_TOKEN = 90000000;
47 const int32_t MIN_PIN_CODE = 100000;
48 const int32_t MAX_PIN_CODE = 999999;
49 const int32_t DM_AUTH_TYPE_MAX = 4;
50 const int32_t DM_AUTH_TYPE_MIN = 1;
51 const int32_t AUTH_SESSION_SIDE_SERVER = 0;
52 const int32_t USLEEP_TIME_MS = 500000; // 500ms
53 
54 constexpr const char* APP_OPERATION_KEY = "appOperation";
55 constexpr const char* TARGET_PKG_NAME_KEY = "targetPkgName";
56 constexpr const char* CUSTOM_DESCRIPTION_KEY = "customDescription";
57 constexpr const char* CANCEL_DISPLAY_KEY = "cancelPinCodeDisplay";
58 
DmAuthManager(std::shared_ptr<SoftbusConnector> softbusConnector,std::shared_ptr<IDeviceManagerServiceListener> listener,std::shared_ptr<HiChainConnector> hiChainConnector)59 DmAuthManager::DmAuthManager(std::shared_ptr<SoftbusConnector> softbusConnector,
60                              std::shared_ptr<IDeviceManagerServiceListener> listener,
61                              std::shared_ptr<HiChainConnector> hiChainConnector)
62     : softbusConnector_(softbusConnector), hiChainConnector_(hiChainConnector), listener_(listener)
63 {
64     LOGI("DmAuthManager constructor");
65     DmConfigManager &dmConfigManager = DmConfigManager::GetInstance();
66     dmConfigManager.GetAuthAdapter(authenticationMap_);
67     authUiStateMgr_ = std::make_shared<AuthUiStateManager>(listener_);
68 }
69 
~DmAuthManager()70 DmAuthManager::~DmAuthManager()
71 {
72     LOGI("DmAuthManager destructor");
73 }
74 
CheckAuthParamVaild(const std::string & pkgName,int32_t authType,const std::string & deviceId,const std::string & extra)75 int32_t DmAuthManager::CheckAuthParamVaild(const std::string &pkgName, int32_t authType,
76     const std::string &deviceId, const std::string &extra)
77 {
78     LOGI("DmAuthManager::CheckAuthParamVaild start.");
79     if (authType < DM_AUTH_TYPE_MIN || authType > DM_AUTH_TYPE_MAX) {
80         LOGE("CheckAuthParamVaild failed, authType is illegal.");
81         return ERR_DM_AUTH_FAILED;
82     }
83     if (pkgName.empty() || deviceId.empty()) {
84         LOGE("DmAuthManager::CheckAuthParamVaild failed, pkgName is %s, deviceId is %s, extra is %s.",
85             pkgName.c_str(), GetAnonyString(deviceId).c_str(), extra.c_str());
86         return ERR_DM_INPUT_PARA_INVALID;
87     }
88     std::shared_ptr<IAuthentication> authentication = authenticationMap_[authType];
89     if (listener_ == nullptr || authUiStateMgr_ == nullptr) {
90         LOGE("DmAuthManager::CheckAuthParamVaild listener or authUiStateMgr is nullptr.");
91         return ERR_DM_INPUT_PARA_INVALID;
92     }
93     if (authentication == nullptr) {
94         LOGE("DmAuthManager::CheckAuthParamVaild authType %d not support.", authType);
95         listener_->OnAuthResult(pkgName, deviceId, "", AuthState::AUTH_REQUEST_INIT, ERR_DM_UNSUPPORTED_AUTH_TYPE);
96         return ERR_DM_UNSUPPORTED_AUTH_TYPE;
97     }
98 
99     if (authRequestState_ != nullptr || authResponseState_ != nullptr) {
100         LOGE("DmAuthManager::CheckAuthParamVaild %s is request authentication.", pkgName.c_str());
101         listener_->OnAuthResult(pkgName, deviceId, "", AuthState::AUTH_REQUEST_INIT, ERR_DM_AUTH_BUSINESS_BUSY);
102         return ERR_DM_AUTH_BUSINESS_BUSY;
103     }
104 
105     if (!softbusConnector_->HaveDeviceInMap(deviceId)) {
106         LOGE("CheckAuthParamVaild failed, the discoveryDeviceInfoMap_ not have this device.");
107         listener_->OnAuthResult(pkgName, deviceId, "", AuthState::AUTH_REQUEST_INIT, ERR_DM_INPUT_PARA_INVALID);
108         return ERR_DM_INPUT_PARA_INVALID;
109     }
110     return DM_OK;
111 }
112 
AuthenticateDevice(const std::string & pkgName,int32_t authType,const std::string & deviceId,const std::string & extra)113 int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t authType,
114     const std::string &deviceId, const std::string &extra)
115 {
116     LOGI("DmAuthManager::AuthenticateDevice start auth type %d.", authType);
117     int32_t ret = CheckAuthParamVaild(pkgName, authType, deviceId, extra);
118     if (ret != DM_OK) {
119         LOGE("DmAuthManager::AuthenticateDevice failed, param is invaild.");
120         return ret;
121     }
122 
123     authPtr_ = authenticationMap_[authType];
124     if (timer_ == nullptr) {
125         timer_ = std::make_shared<DmTimer>();
126     }
127     timer_->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), AUTHENTICATE_TIMEOUT,
128         [this] (std::string name) {
129             DmAuthManager::HandleAuthenticateTimeout(name);
130         });
131     authMessageProcessor_ = std::make_shared<AuthMessageProcessor>(shared_from_this());
132     authResponseContext_ = std::make_shared<DmAuthResponseContext>();
133     authRequestContext_ = std::make_shared<DmAuthRequestContext>();
134     authRequestContext_->hostPkgName = pkgName;
135     authRequestContext_->authType = authType;
136     authRequestContext_->localDeviceName = softbusConnector_->GetLocalDeviceName();
137     authRequestContext_->localDeviceTypeId = softbusConnector_->GetLocalDeviceTypeId();
138     authRequestContext_->deviceId = deviceId;
139     nlohmann::json jsonObject = nlohmann::json::parse(extra, nullptr, false);
140     if (!jsonObject.is_discarded()) {
141         if (IsString(jsonObject, TARGET_PKG_NAME_KEY)) {
142             authRequestContext_->targetPkgName = jsonObject[TARGET_PKG_NAME_KEY].get<std::string>();
143         }
144         if (IsString(jsonObject, APP_OPERATION_KEY)) {
145             authRequestContext_->appOperation = jsonObject[APP_OPERATION_KEY].get<std::string>();
146         }
147         if (IsString(jsonObject, CUSTOM_DESCRIPTION_KEY)) {
148             authRequestContext_->customDesc = jsonObject[CUSTOM_DESCRIPTION_KEY].get<std::string>();
149         }
150         if (IsString(jsonObject, APP_THUMBNAIL)) {
151             authRequestContext_->appThumbnail = jsonObject[APP_THUMBNAIL].get<std::string>();
152         }
153     }
154     authRequestContext_->token = std::to_string(GenRandInt(MIN_PIN_TOKEN, MAX_PIN_TOKEN));
155     authMessageProcessor_->SetRequestContext(authRequestContext_);
156     authRequestState_ = std::make_shared<AuthRequestInitState>();
157     authRequestState_->SetAuthManager(shared_from_this());
158     authRequestState_->SetAuthContext(authRequestContext_);
159     authRequestState_->Enter();
160     LOGI("DmAuthManager::AuthenticateDevice complete");
161     return DM_OK;
162 }
163 
UnAuthenticateDevice(const std::string & pkgName,const std::string & networkId)164 int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const std::string &networkId)
165 {
166     if (pkgName.empty()) {
167         LOGE("Invalid parameter, pkgName is empty.");
168         return ERR_DM_FAILED;
169     }
170     std::string deviceUdid;
171     int32_t ret = SoftbusConnector::GetUdidByNetworkId(networkId.c_str(), deviceUdid);
172     if (ret != DM_OK) {
173         LOGE("UnAuthenticateDevice GetNodeKeyInfo failed");
174         return ERR_DM_FAILED;
175     }
176 
177     std::vector<OHOS::DistributedHardware::GroupInfo> groupList;
178     hiChainConnector_->GetRelatedGroups(deviceUdid, groupList);
179     if (groupList.size() > 0) {
180         std::string groupId = "";
181         groupId = groupList.front().groupId;
182         LOGI("DmAuthManager::UnAuthenticateDevice groupId = %s, networkId = %s, deviceUdid = %s",
183             GetAnonyString(groupId).c_str(), GetAnonyString(networkId).c_str(), GetAnonyString(deviceUdid).c_str());
184         hiChainConnector_->DeleteGroup(groupId);
185     } else {
186         LOGE("DmAuthManager::UnAuthenticateDevice groupList.size = 0");
187         return ERR_DM_FAILED;
188     }
189     if (softbusConnector_ != nullptr) {
190         softbusConnector_->EraseUdidFromMap(deviceUdid);
191     }
192     return DM_OK;
193 }
194 
UnBindDevice(const std::string & pkgName,const std::string & udidHash)195 int32_t DmAuthManager::UnBindDevice(const std::string &pkgName, const std::string &udidHash)
196 {
197     if (pkgName.empty()) {
198         LOGE("Invalid parameter, pkgName is empty.");
199         return ERR_DM_FAILED;
200     }
201     std::string udid = "";
202     udid = SoftbusConnector::GetDeviceUdidByUdidHash(udidHash);
203 
204     std::vector<OHOS::DistributedHardware::GroupInfo> groupList;
205     hiChainConnector_->GetRelatedGroups(udid, groupList);
206     if (groupList.size() > 0) {
207         std::string groupId = "";
208         groupId = groupList.front().groupId;
209         LOGI("DmAuthManager::UnBindDevice groupId = %s, udidHash = %s, udid = %s",
210             GetAnonyString(groupId).c_str(), GetAnonyString(udidHash).c_str(), GetAnonyString(udid).c_str());
211         hiChainConnector_->DeleteGroup(groupId);
212     } else {
213         LOGE("DmAuthManager::UnBindDevice groupList.size = 0");
214         return ERR_DM_FAILED;
215     }
216     return DM_OK;
217 }
218 
VerifyAuthentication(const std::string & authParam)219 int32_t DmAuthManager::VerifyAuthentication(const std::string &authParam)
220 {
221     LOGI("DmAuthManager::VerifyAuthentication");
222     if (authResponseContext_ == nullptr) {
223         LOGE("authResponseContext_ is not init");
224         return ERR_DM_AUTH_NOT_START;
225     }
226     timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK));
227     int32_t ret = authPtr_->VerifyAuthentication(authResponseContext_->authToken, authParam);
228     switch (ret) {
229         case DM_OK:
230             authRequestState_->TransitionTo(std::make_shared<AuthRequestJoinState>());
231             break;
232         case ERR_DM_INPUT_PARA_INVALID:
233             listener_->OnVerifyAuthResult(authRequestContext_->hostPkgName, authRequestContext_->deviceId,
234                                           ERR_DM_INPUT_PARA_INVALID, "");
235             break;
236         default:
237             authRequestContext_->reason = ERR_DM_INPUT_PARA_INVALID;
238             authResponseContext_->state = authRequestState_->GetStateType();
239             authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
240             break;
241     }
242     LOGI("DmAuthManager::VerifyAuthentication complete");
243     return DM_OK;
244 }
245 
OnSessionOpened(int32_t sessionId,int32_t sessionSide,int32_t result)246 void DmAuthManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result)
247 {
248     LOGI("DmAuthManager::OnSessionOpened sessionId = %d result = %d", sessionId, result);
249     if (sessionSide == AUTH_SESSION_SIDE_SERVER) {
250         if (authResponseState_ == nullptr && authRequestState_ == nullptr) {
251             authMessageProcessor_ = std::make_shared<AuthMessageProcessor>(shared_from_this());
252             authResponseState_ = std::make_shared<AuthResponseInitState>();
253             authResponseState_->SetAuthManager(shared_from_this());
254             authResponseState_->Enter();
255             authResponseContext_ = std::make_shared<DmAuthResponseContext>();
256             if (timer_ == nullptr) {
257                 timer_ = std::make_shared<DmTimer>();
258             }
259             timer_->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), AUTHENTICATE_TIMEOUT,
260                 [this] (std::string name) {
261                     DmAuthManager::HandleAuthenticateTimeout(name);
262                 });
263             timer_->StartTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), WAIT_NEGOTIATE_TIMEOUT,
264                 [this] (std::string name) {
265                     DmAuthManager::HandleAuthenticateTimeout(name);
266                 });
267         } else {
268             std::shared_ptr<AuthMessageProcessor> authMessageProcessor =
269                 std::make_shared<AuthMessageProcessor>(shared_from_this());
270             std::shared_ptr<DmAuthResponseContext> authResponseContext = std::make_shared<DmAuthResponseContext>();
271             authResponseContext->reply = ERR_DM_AUTH_BUSINESS_BUSY;
272             authMessageProcessor->SetResponseContext(authResponseContext);
273             std::string message = authMessageProcessor->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE);
274             softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
275         }
276     } else {
277         if (authResponseState_ == nullptr && authRequestState_ != nullptr &&
278             authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT) {
279             authRequestContext_->sessionId = sessionId;
280             authRequestState_->SetAuthContext(authRequestContext_);
281             authMessageProcessor_->SetRequestContext(authRequestContext_);
282             authRequestState_->TransitionTo(std::make_shared<AuthRequestNegotiateState>());
283         } else {
284             softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId);
285             LOGE("DmAuthManager::OnSessionOpened but request state is wrong");
286         }
287     }
288 }
289 
OnSessionClosed(const int32_t sessionId)290 void DmAuthManager::OnSessionClosed(const int32_t sessionId)
291 {
292     LOGI("DmAuthManager::OnSessionOpened sessionId = %d", sessionId);
293 }
294 
ProcessSourceMsg()295 void DmAuthManager::ProcessSourceMsg()
296 {
297     authRequestContext_ = authMessageProcessor_->GetRequestContext();
298     authRequestState_->SetAuthContext(authRequestContext_);
299     LOGI("OnDataReceived for source device, authResponseContext msgType = %d, authRequestState stateType = %d",
300         authResponseContext_->msgType, authRequestState_->GetStateType());
301 
302     switch (authResponseContext_->msgType) {
303         case MSG_TYPE_RESP_AUTH:
304             if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) {
305                 authRequestState_->TransitionTo(std::make_shared<AuthRequestReplyState>());
306             }
307             break;
308         case MSG_TYPE_RESP_NEGOTIATE:
309             if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE) {
310                 authRequestState_->TransitionTo(std::make_shared<AuthRequestNegotiateDoneState>());
311             }
312             break;
313         case MSG_TYPE_REQ_AUTH_TERMINATE:
314             if (authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) {
315                 isFinishOfLocal_ = false;
316                 authResponseContext_->state = authRequestState_->GetStateType();
317                 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
318             }
319             break;
320         default:
321             break;
322     }
323 }
324 
ProcessSinkMsg()325 void DmAuthManager::ProcessSinkMsg()
326 {
327     authResponseState_->SetAuthContext(authResponseContext_);
328     LOGI("OnDataReceived for sink device, authResponseContext msgType = %d, authResponseState stateType = %d",
329         authResponseContext_->msgType, authResponseState_->GetStateType());
330 
331     switch (authResponseContext_->msgType) {
332         case MSG_TYPE_NEGOTIATE:
333             if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_INIT) {
334                 timer_->DeleteTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK));
335                 authResponseState_->TransitionTo(std::make_shared<AuthResponseNegotiateState>());
336             } else {
337                 LOGE("Device manager auth state error");
338             }
339             break;
340         case MSG_TYPE_REQ_AUTH:
341             if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_NEGOTIATE) {
342                 timer_->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK));
343                 authResponseState_->TransitionTo(std::make_shared<AuthResponseConfirmState>());
344             } else {
345                 LOGE("Device manager auth state error");
346             }
347             break;
348         case MSG_TYPE_REQ_AUTH_TERMINATE:
349             if (authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) {
350                 isFinishOfLocal_ = false;
351                 authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
352             }
353             break;
354         default:
355             break;
356     }
357 }
358 
OnDataReceived(const int32_t sessionId,const std::string message)359 void DmAuthManager::OnDataReceived(const int32_t sessionId, const std::string message)
360 {
361     if (authResponseContext_ == nullptr || authMessageProcessor_ == nullptr) {
362         LOGE("OnDataReceived failed, authResponseContext or authMessageProcessor_ is nullptr.");
363         return;
364     }
365 
366     authResponseContext_->sessionId = sessionId;
367     authMessageProcessor_->SetResponseContext(authResponseContext_);
368     int32_t ret = authMessageProcessor_->ParseMessage(message);
369     if (ret != DM_OK) {
370         LOGE("OnDataReceived failed, parse input message error.");
371         return;
372     }
373 
374     if ((authRequestState_ != nullptr) && (authResponseState_ == nullptr)) {
375         // source device auth process
376         ProcessSourceMsg();
377     } else if ((authResponseState_ != nullptr) && (authRequestState_ == nullptr)) {
378         // sink device auth process
379         ProcessSinkMsg();
380     } else {
381         LOGE("DmAuthManager::OnDataReceived failed, authRequestState_ or authResponseState_ is invalid.");
382     }
383 }
384 
OnGroupCreated(int64_t requestId,const std::string & groupId)385 void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId)
386 {
387     if (authResponseContext_ == nullptr) {
388         LOGE("failed to OnGroupCreated because authResponseContext_ is nullptr");
389         return;
390     }
391     if (authResponseState_ == nullptr) {
392         LOGE("DmAuthManager::AuthenticateDevice end");
393         return;
394     }
395     LOGI("DmAuthManager::OnGroupCreated start group id %s", GetAnonyString(groupId).c_str());
396     if (groupId == "{}") {
397         authResponseContext_->reply = ERR_DM_CREATE_GROUP_FAILED;
398         authMessageProcessor_->SetResponseContext(authResponseContext_);
399         std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH);
400         softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
401         return;
402     }
403 
404     int32_t pinCode = GeneratePincode();
405     nlohmann::json jsonObj;
406     jsonObj[PIN_TOKEN] = authResponseContext_->token;
407     jsonObj[QR_CODE_KEY] = GenerateGroupName();
408     jsonObj[NFC_CODE_KEY] = GenerateGroupName();
409     authResponseContext_->authToken = jsonObj.dump();
410     LOGI("DmAuthManager::OnGroupCreated start group id %s", GetAnonyString(groupId).c_str());
411     authResponseContext_->groupId = groupId;
412     authResponseContext_->code = pinCode;
413     authMessageProcessor_->SetResponseContext(authResponseContext_);
414     std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH);
415     softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
416     authResponseState_->TransitionTo(std::make_shared<AuthResponseShowState>());
417 }
418 
OnMemberJoin(int64_t requestId,int32_t status)419 void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status)
420 {
421     if (authResponseContext_ == nullptr || authUiStateMgr_ == nullptr) {
422         LOGE("failed to OnMemberJoin because authResponseContext_ or authUiStateMgr is nullptr");
423         return;
424     }
425     LOGI("DmAuthManager OnMemberJoin start authTimes %d", authTimes_);
426     isAddingMember_ = false;
427     if ((authRequestState_ != nullptr) && (authResponseState_ == nullptr)) {
428         authTimes_++;
429         timer_->DeleteTimer(std::string(ADD_TIMEOUT_TASK));
430         if (status != DM_OK || authResponseContext_->requestId != requestId) {
431             if (authRequestState_ != nullptr && authTimes_ >= MAX_AUTH_TIMES) {
432                 authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN;
433                 authRequestContext_->reason = ERR_DM_INPUT_PARA_INVALID;
434                 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
435             } else {
436                 timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), INPUT_TIMEOUT,
437                     [this] (std::string name) {
438                         DmAuthManager::HandleAuthenticateTimeout(name);
439                     });
440                 authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR);
441             }
442         } else {
443             authRequestState_->TransitionTo(std::make_shared<AuthRequestNetworkState>());
444         }
445     } else if ((authResponseState_ != nullptr) && (authRequestState_ == nullptr)) {
446         if (status == DM_OK && authResponseContext_->requestId == requestId &&
447             authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW) {
448             authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW);
449         }
450     } else {
451         LOGE("DmAuthManager::OnMemberJoin failed, authRequestState_ or authResponseState_ is invalid.");
452     }
453 }
454 
HandleAuthenticateTimeout(std::string name)455 void DmAuthManager::HandleAuthenticateTimeout(std::string name)
456 {
457     LOGI("DmAuthManager::HandleAuthenticateTimeout start timer name %s", name.c_str());
458     if (authRequestState_ != nullptr && authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) {
459         if (authResponseContext_ == nullptr) {
460             authResponseContext_ = std::make_shared<DmAuthResponseContext>();
461         }
462         authResponseContext_->state = authRequestState_->GetStateType();
463         authRequestContext_->reason = ERR_DM_TIME_OUT;
464         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
465     }
466 
467     if (authResponseState_ != nullptr && authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) {
468         authResponseContext_->state = authResponseState_->GetStateType();
469         authResponseContext_->reply = ERR_DM_TIME_OUT;
470         authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
471     }
472     LOGI("DmAuthManager::HandleAuthenticateTimeout start complete");
473 }
474 
EstablishAuthChannel(const std::string & deviceId)475 int32_t DmAuthManager::EstablishAuthChannel(const std::string &deviceId)
476 {
477     int32_t sessionId = softbusConnector_->GetSoftbusSession()->OpenAuthSession(deviceId);
478     if (sessionId < 0) {
479         LOGE("OpenAuthSession failed, stop the authentication");
480         authResponseContext_ = std::make_shared<DmAuthResponseContext>();
481         authResponseContext_->state = AuthState::AUTH_REQUEST_NEGOTIATE;
482         authRequestContext_->reason = ERR_DM_AUTH_OPEN_SESSION_FAILED;
483         if (authRequestState_ != nullptr) {
484             authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
485         }
486     }
487     return DM_OK;
488 }
489 
StartNegotiate(const int32_t & sessionId)490 void DmAuthManager::StartNegotiate(const int32_t &sessionId)
491 {
492     if (authResponseContext_ == nullptr) {
493         LOGE("DmAuthManager::StartNegotiate error, authResponseContext_ is nullptr");
494         return;
495     }
496     LOGI("DmAuthManager::StartNegotiate session id is %d", sessionId);
497     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
498     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
499     authRequestContext_->localDeviceId = localDeviceId;
500     authResponseContext_->localDeviceId = localDeviceId;
501     authResponseContext_->reply = ERR_DM_AUTH_REJECT;
502     authResponseContext_->authType = authRequestContext_->authType;
503     authResponseContext_->deviceId = authRequestContext_->deviceId;
504     authMessageProcessor_->SetResponseContext(authResponseContext_);
505     std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_NEGOTIATE);
506     softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
507     timer_->StartTimer(std::string(NEGOTIATE_TIMEOUT_TASK), NEGOTIATE_TIMEOUT,
508         [this] (std::string name) {
509             DmAuthManager::HandleAuthenticateTimeout(name);
510         });
511 }
512 
RespNegotiate(const int32_t & sessionId)513 void DmAuthManager::RespNegotiate(const int32_t &sessionId)
514 {
515     if (authResponseContext_ == nullptr || authRequestState_ != nullptr) {
516         LOGE("failed to RespNegotiate because authResponseContext_ is nullptr");
517         return;
518     }
519     LOGI("DmAuthManager::EstablishAuthChannel session id is %d", sessionId);
520     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
521     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
522     bool ret = hiChainConnector_->IsDevicesInGroup(authResponseContext_->localDeviceId, localDeviceId);
523     if (ret) {
524         LOGE("DmAuthManager::EstablishAuthChannel device is in group");
525         authResponseContext_->reply = ERR_DM_AUTH_PEER_REJECT;
526     } else {
527         authResponseContext_->reply = ERR_DM_AUTH_REJECT;
528     }
529     authResponseContext_->localDeviceId = localDeviceId;
530 
531     std::shared_ptr<IAuthentication> authentication = authenticationMap_[authResponseContext_->authType];
532     if (authentication == nullptr) {
533         LOGE("DmAuthManager::AuthenticateDevice authType %d not support.", authResponseContext_->authType);
534         authResponseContext_->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE;
535     } else {
536         authPtr_ = authenticationMap_[authResponseContext_->authType];
537     }
538 
539     std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_NEGOTIATE);
540     nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false);
541     if (jsonObject.is_discarded()) {
542         softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
543     }
544 
545     if (IsIdenticalAccount()) {
546         jsonObject[TAG_IDENTICAL_ACCOUNT] = true;
547     }
548     authResponseContext_ = authResponseState_->GetAuthContext();
549     if (jsonObject[TAG_CRYPTO_SUPPORT] == true && authResponseContext_->cryptoSupport) {
550         if (jsonObject[TAG_CRYPTO_NAME] == authResponseContext_->cryptoName &&
551             jsonObject[TAG_CRYPTO_VERSION] == authResponseContext_->cryptoVer) {
552             isCryptoSupport_ = true;
553             softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
554             return;
555         }
556     }
557     jsonObject[TAG_CRYPTO_SUPPORT] = false;
558     message = jsonObject.dump();
559     softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
560     timer_->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), WAIT_REQUEST_TIMEOUT,
561         [this] (std::string name) {
562             DmAuthManager::HandleAuthenticateTimeout(name);
563         });
564 }
565 
SendAuthRequest(const int32_t & sessionId)566 void DmAuthManager::SendAuthRequest(const int32_t &sessionId)
567 {
568     if (authResponseContext_ == nullptr) {
569         LOGE("failed to SendAuthRequest because authResponseContext_ is nullptr");
570         return;
571     }
572     LOGI("DmAuthManager::EstablishAuthChannel session id");
573     timer_->DeleteTimer(std::string(NEGOTIATE_TIMEOUT_TASK));
574     if (authResponseContext_->cryptoSupport) {
575         isCryptoSupport_ = true;
576     }
577 
578     if (authResponseContext_->isIdenticalAccount) { // identicalAccount joinLNN indirectly, no need to verify
579         if (IsIdenticalAccount()) {
580             softbusConnector_->JoinLnn(authResponseContext_->deviceId);
581             authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
582             authRequestContext_->reason = DM_OK;
583             authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
584             return;
585         }
586     }
587     if (authResponseContext_->reply == ERR_DM_AUTH_PEER_REJECT) {
588         if (hiChainConnector_->IsDevicesInGroup(authResponseContext_->localDeviceId,
589                                                 authRequestContext_->localDeviceId)) {
590             softbusConnector_->JoinLnn(authResponseContext_->deviceId);
591             authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
592             return;
593         }
594     }
595 
596     std::vector<std::string> messageList = authMessageProcessor_->CreateAuthRequestMessage();
597     for (auto msg : messageList) {
598         softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg);
599     }
600     timer_->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), CONFIRM_TIMEOUT,
601         [this] (std::string name) {
602             DmAuthManager::HandleAuthenticateTimeout(name);
603         });
604 }
605 
StartAuthProcess(const int32_t & action)606 int32_t DmAuthManager::StartAuthProcess(const int32_t &action)
607 {
608     if (authResponseContext_ == nullptr) {
609         LOGE("failed to StartAuthProcess because authResponseContext_ is nullptr");
610         return ERR_DM_AUTH_NOT_START;
611     }
612     LOGI("DmAuthManager::StartAuthProcess");
613     action_ = action;
614     if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH || action_ == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) {
615         authResponseContext_->reply = USER_OPERATION_TYPE_ALLOW_AUTH;
616     } else {
617         authResponseContext_->reply = action_;
618     }
619 
620     if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH &&
621         authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_CONFIRM) {
622         authResponseState_->TransitionTo(std::make_shared<AuthResponseGroupState>());
623     } else {
624         authMessageProcessor_->SetResponseContext(authResponseContext_);
625         std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH);
626         softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
627     }
628     return DM_OK;
629 }
630 
StartRespAuthProcess()631 void DmAuthManager::StartRespAuthProcess()
632 {
633     if (authResponseContext_ == nullptr) {
634         LOGE("failed to StartRespAuthProcess because authResponseContext_ is nullptr");
635         return;
636     }
637     LOGI("DmAuthManager::StartRespAuthProcess sessionId = %d", authResponseContext_->sessionId);
638     timer_->DeleteTimer(std::string(CONFIRM_TIMEOUT_TASK));
639     if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH) {
640         timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), INPUT_TIMEOUT,
641             [this] (std::string name) {
642                 DmAuthManager::HandleAuthenticateTimeout(name);
643             });
644         authRequestState_->TransitionTo(std::make_shared<AuthRequestJoinState>());
645     } else {
646         LOGE("do not accept");
647         authResponseContext_->state = AuthState::AUTH_REQUEST_REPLY;
648         authRequestContext_->reason = ERR_DM_AUTH_PEER_REJECT;
649         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
650     }
651 }
652 
CreateGroup()653 int32_t DmAuthManager::CreateGroup()
654 {
655     if (authResponseContext_ == nullptr) {
656         LOGE("failed to CreateGroup because authResponseContext_ is nullptr");
657         return ERR_DM_FAILED;
658     }
659     LOGI("DmAuthManager::CreateGroup start");
660     authResponseContext_->groupName = GenerateGroupName();
661     authResponseContext_->requestId = GenRandLongLong(MIN_REQUEST_ID, MAX_REQUEST_ID);
662     hiChainConnector_->CreateGroup(authResponseContext_->requestId, authResponseContext_->groupName);
663     return DM_OK;
664 }
665 
AddMember(int32_t pinCode)666 int32_t DmAuthManager::AddMember(int32_t pinCode)
667 {
668     if (authResponseContext_ == nullptr) {
669         LOGE("failed to AddMember because authResponseContext_ is nullptr");
670         return ERR_DM_FAILED;
671     }
672     LOGI("DmAuthManager::AddMember start group id %s", GetAnonyString(authResponseContext_->groupId).c_str());
673     timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK));
674     nlohmann::json jsonObject;
675     jsonObject[TAG_GROUP_ID] = authResponseContext_->groupId;
676     jsonObject[TAG_GROUP_NAME] = authResponseContext_->groupName;
677     jsonObject[PIN_CODE_KEY] = pinCode;
678     jsonObject[TAG_REQUEST_ID] = authResponseContext_->requestId;
679     jsonObject[TAG_DEVICE_ID] = authResponseContext_->deviceId;
680     std::string connectInfo = jsonObject.dump();
681     timer_->StartTimer(std::string(ADD_TIMEOUT_TASK), ADD_TIMEOUT,
682         [this] (std::string name) {
683             DmAuthManager::HandleAuthenticateTimeout(name);
684         });
685     if (authUiStateMgr_ == nullptr) {
686         LOGE("DmAuthManager::AddMember authUiStateMgr is null.");
687         return ERR_DM_FAILED;
688     }
689     if (isAddingMember_) {
690         LOGE("DmAuthManager::AddMember doing add member.");
691         authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_DOING_AUTH);
692         return ERR_DM_FAILED;
693     }
694     isAddingMember_ = true;
695     int32_t ret = hiChainConnector_->AddMember(authRequestContext_->deviceId, connectInfo);
696     if (ret != 0) {
697         LOGE("DmAuthManager::AddMember failed, ret: %d", ret);
698         isAddingMember_ = false;
699         return ERR_DM_FAILED;
700     }
701     return DM_OK;
702 }
703 
GetConnectAddr(std::string deviceId)704 std::string DmAuthManager::GetConnectAddr(std::string deviceId)
705 {
706     LOGI("DmAuthManager::GetConnectAddr");
707     std::string connectAddr;
708     if (softbusConnector_->GetConnectAddr(deviceId, connectAddr) == nullptr) {
709         LOGE("DmAuthManager::GetConnectAddr error");
710     }
711     return connectAddr;
712 }
713 
JoinNetwork()714 int32_t DmAuthManager::JoinNetwork()
715 {
716     if (authResponseContext_ == nullptr) {
717         LOGE("failed to JoinNeWork because authResponseContext_ is nullptr");
718         return ERR_DM_FAILED;
719     }
720     LOGI("DmAuthManager JoinNetwork start");
721     timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK));
722     authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
723     authRequestContext_->reason = DM_OK;
724     authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
725     return DM_OK;
726 }
727 
AuthenticateFinish()728 void DmAuthManager::AuthenticateFinish()
729 {
730     if (authResponseContext_ == nullptr || authUiStateMgr_ == nullptr) {
731         LOGE("failed to AuthenticateFinish because authResponseContext_ or authUiStateMgr is nullptr");
732         return;
733     }
734     LOGI("DmAuthManager::AuthenticateFinish start");
735     isAddingMember_ = false;
736     if (authResponseState_ != nullptr) {
737         if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_FINISH && authPtr_ != nullptr) {
738             authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW);
739         }
740         if (isFinishOfLocal_) {
741             authMessageProcessor_->SetResponseContext(authResponseContext_);
742             std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE);
743             softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
744         }
745         timer_->DeleteAll();
746         isFinishOfLocal_ = true;
747         authResponseContext_ = nullptr;
748         authResponseState_ = nullptr;
749         authMessageProcessor_ = nullptr;
750         authPtr_ = nullptr;
751     } else if (authRequestState_ != nullptr) {
752         if (isFinishOfLocal_) {
753             authMessageProcessor_->SetResponseContext(authResponseContext_);
754             std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE);
755             softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
756         } else {
757             authRequestContext_->reason = authResponseContext_->reply;
758         }
759         if ((authResponseContext_->state == AuthState::AUTH_REQUEST_JOIN ||
760             authResponseContext_->state == AuthState::AUTH_REQUEST_FINISH) && authPtr_ != nullptr) {
761             authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT);
762         }
763         listener_->OnAuthResult(authRequestContext_->hostPkgName, authRequestContext_->deviceId,
764                                 authRequestContext_->token, authResponseContext_->state, authRequestContext_->reason);
765         usleep(USLEEP_TIME_MS); // 500ms
766         softbusConnector_->GetSoftbusSession()->CloseAuthSession(authRequestContext_->sessionId);
767         timer_->DeleteAll();
768         isFinishOfLocal_ = true;
769         authRequestContext_ = nullptr;
770         authResponseContext_ = nullptr;
771         authRequestState_ = nullptr;
772         authMessageProcessor_ = nullptr;
773         authPtr_ = nullptr;
774         authTimes_ = 0;
775     }
776     LOGI("DmAuthManager::AuthenticateFinish complete");
777 }
778 
CancelDisplay()779 void DmAuthManager::CancelDisplay()
780 {
781     LOGI("DmAuthManager::CancelDisplay start");
782     nlohmann::json jsonObj;
783     jsonObj[CANCEL_DISPLAY_KEY] = CANCEL_PIN_CODE_DISPLAY;
784     std::string paramJson = jsonObj.dump();
785     std::string pkgName = "com.ohos.devicemanagerui";
786     listener_->OnUiCall(pkgName, paramJson);
787 }
788 
RegisterUiStateCallback(const std::string pkgName)789 int32_t DmAuthManager::RegisterUiStateCallback(const std::string pkgName)
790 {
791     LOGI("DmAuthManager::RegisterUiStateCallback start");
792     if (authUiStateMgr_ == nullptr) {
793         LOGE("DmAuthManager::RegisterUiStateCallback authUiStateMgr_ is null.");
794         return ERR_DM_FAILED;
795     }
796     authUiStateMgr_->RegisterUiStateCallback(pkgName);
797     return DM_OK;
798 }
799 
UnRegisterUiStateCallback(const std::string pkgName)800 int32_t DmAuthManager::UnRegisterUiStateCallback(const std::string pkgName)
801 {
802     LOGI("DmAuthManager::UnRegisterUiStateCallback start");
803     if (authUiStateMgr_ == nullptr) {
804         LOGE("DmAuthManager::UnRegisterUiStateCallback authUiStateMgr_ is null.");
805         return ERR_DM_FAILED;
806     }
807     authUiStateMgr_->UnRegisterUiStateCallback(pkgName);
808     return DM_OK;
809 }
810 
GeneratePincode()811 int32_t DmAuthManager::GeneratePincode()
812 {
813     return GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE);
814 }
815 
GenerateGroupName()816 std::string DmAuthManager::GenerateGroupName()
817 {
818     if (authResponseContext_ == nullptr) {
819         LOGE("failed to GenerateGroupName because authResponseContext_ is nullptr.");
820         return "";
821     }
822     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
823     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
824     std::string sLocalDeviceId = localDeviceId;
825     uint32_t interceptLength = sLocalDeviceId.size() / DEVICE_ID_HALF;
826     std::string groupName = "";
827     if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) {
828         groupName += AUTH_ALWAYS;
829     } else {
830         groupName += AUTH_ONCE;
831     }
832     groupName += authResponseContext_->targetPkgName + sLocalDeviceId.substr(0, interceptLength)
833         + authResponseContext_->localDeviceId.substr(0, interceptLength);
834     return groupName;
835 }
836 
GetIsCryptoSupport()837 bool DmAuthManager::GetIsCryptoSupport()
838 {
839     if (authResponseState_ == nullptr) {
840         return false;
841     }
842     if (authRequestState_ == nullptr) {
843         if (authResponseState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) {
844             return false;
845         }
846     } else {
847         if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE ||
848             authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) {
849             return false;
850         }
851     }
852 
853     return isCryptoSupport_;
854 }
855 
SetAuthRequestState(std::shared_ptr<AuthRequestState> authRequestState)856 int32_t DmAuthManager::SetAuthRequestState(std::shared_ptr<AuthRequestState> authRequestState)
857 {
858     if (authRequestState == nullptr) {
859         LOGE("authRequestState is nullptr.");
860         return ERR_DM_INPUT_PARA_INVALID;
861     }
862     authRequestState_ = authRequestState;
863     return DM_OK;
864 }
865 
SetAuthResponseState(std::shared_ptr<AuthResponseState> authResponseState)866 int32_t DmAuthManager::SetAuthResponseState(std::shared_ptr<AuthResponseState> authResponseState)
867 {
868     if (authResponseState == nullptr) {
869         LOGE("authResponseState is nullptr.");
870         return ERR_DM_INPUT_PARA_INVALID;
871     }
872     authResponseState_ = authResponseState;
873     return DM_OK;
874 }
875 
GetPinCode()876 int32_t DmAuthManager::GetPinCode()
877 {
878     if (authResponseContext_ == nullptr) {
879         LOGE("failed to GetPinCode because authResponseContext_ is nullptr");
880         return ERR_DM_AUTH_NOT_START;
881     }
882     LOGI("ShowConfigDialog start add member pin code.");
883     return authResponseContext_->code;
884 }
885 
ShowConfigDialog()886 void DmAuthManager::ShowConfigDialog()
887 {
888     if (authResponseContext_ == nullptr) {
889         LOGE("failed to ShowConfigDialog because authResponseContext_ is nullptr");
890         return;
891     }
892     LOGI("ShowConfigDialog start");
893     dmAbilityMgr_ = std::make_shared<DmAbilityManager>();
894     nlohmann::json jsonObj;
895     jsonObj[TAG_AUTH_TYPE] = AUTH_TYPE_PIN;
896     jsonObj[TAG_TOKEN] = authResponseContext_->token;
897     jsonObj[TARGET_PKG_NAME_KEY] = authResponseContext_->targetPkgName;
898     jsonObj[TAG_CUSTOM_DESCRIPTION] = authResponseContext_->customDesc;
899     jsonObj[TAG_APP_OPERATION] = authResponseContext_->appOperation;
900     jsonObj[TAG_LOCAL_DEVICE_TYPE] = authResponseContext_->deviceTypeId;
901     jsonObj[TAG_REQUESTER] = authResponseContext_->deviceName;
902     const std::string params = jsonObj.dump();
903     std::shared_ptr<ShowConfirm> showConfirm_ = std::make_shared<ShowConfirm>();
904     showConfirm_->ShowConfirmDialog(params, shared_from_this(), dmAbilityMgr_);
905     LOGI("ShowConfigDialog end");
906 }
907 
ShowAuthInfoDialog()908 void DmAuthManager::ShowAuthInfoDialog()
909 {
910     if (authResponseContext_ == nullptr) {
911         LOGE("failed to ShowAuthInfoDialog because authResponseContext_ is nullptr");
912         return;
913     }
914     LOGI("DmAuthManager::ShowAuthInfoDialog start %d", authResponseContext_->code);
915     nlohmann::json jsonObj;
916     jsonObj[PIN_CODE_KEY] = authResponseContext_->code;
917     std::string authParam = jsonObj.dump();
918     authPtr_->ShowAuthInfo(authParam, shared_from_this());
919 }
920 
ShowStartAuthDialog()921 void DmAuthManager::ShowStartAuthDialog()
922 {
923     if (authResponseContext_ == nullptr) {
924         LOGE("failed to ShowStartAuthDialog because authResponseContext_ is nullptr");
925         return;
926     }
927     LOGI("DmAuthManager::ShowStartAuthDialog start");
928     authPtr_->StartAuth(authResponseContext_->authToken, shared_from_this());
929 }
930 
GetAuthenticationParam(DmAuthParam & authParam)931 int32_t DmAuthManager::GetAuthenticationParam(DmAuthParam &authParam)
932 {
933     (void)authParam;
934     return DM_OK;
935 }
936 
OnUserOperation(int32_t action,const std::string & params)937 int32_t DmAuthManager::OnUserOperation(int32_t action, const std::string &params)
938 {
939     if (authResponseContext_ == nullptr) {
940         LOGE("Authenticate is not start");
941         return ERR_DM_AUTH_NOT_START;
942     }
943 
944     switch (action) {
945         case USER_OPERATION_TYPE_ALLOW_AUTH:
946         case USER_OPERATION_TYPE_CANCEL_AUTH:
947         case USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS:
948             StartAuthProcess(action);
949             break;
950         case USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT:
951         case USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY:
952             AuthenticateFinish();
953             break;
954         case USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT:
955             SetReasonAndFinish(ERR_DM_INPUT_PARA_INVALID, AuthState::AUTH_REQUEST_JOIN);
956             break;
957         case USER_OPERATION_TYPE_DONE_PINCODE_INPUT:
958             AddMember(std::stoi(params));
959             break;
960         default:
961             LOGE("this action id not support");
962             break;
963     }
964     return DM_OK;
965 }
966 
UserSwitchEventCallback(int32_t userId)967 void DmAuthManager::UserSwitchEventCallback(int32_t userId)
968 {
969     LOGI("switch user event happen and this user groups will be deleted with userId: %d", userId);
970     nlohmann::json jsonObj;
971     jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_PEER_TO_PEER_GROUP;
972     std::string queryParams = jsonObj.dump();
973     std::vector<GroupInfo> groupList;
974 
975     int32_t oldUserId = MultipleUserConnector::GetSwitchOldUserId();
976     MultipleUserConnector::SetSwitchOldUserId(userId);
977     if (!hiChainConnector_->GetGroupInfo(oldUserId, queryParams, groupList)) {
978         LOGE("failed to get the old user id groups");
979         return;
980     }
981     for (auto iter = groupList.begin(); iter != groupList.end(); iter++) {
982         int32_t ret = hiChainConnector_->DeleteGroup(oldUserId, iter->groupId);
983         if (ret != DM_OK) {
984             LOGE("failed to delete the old user id group");
985         }
986     }
987 
988     if (!hiChainConnector_->GetGroupInfo(userId, queryParams, groupList)) {
989         LOGE("failed to get the user id groups");
990         return;
991     }
992     for (auto iter = groupList.begin(); iter != groupList.end(); iter++) {
993         int32_t ret = hiChainConnector_->DeleteGroup(userId, iter->groupId);
994         if (ret != DM_OK) {
995             LOGE("failed to delete the user id group");
996         }
997     }
998 }
999 
SetPageId(int32_t pageId)1000 int32_t DmAuthManager::SetPageId(int32_t pageId)
1001 {
1002     if (authResponseContext_ == nullptr) {
1003         LOGE("Authenticate is not start");
1004         return ERR_DM_AUTH_NOT_START;
1005     }
1006     authResponseContext_->pageId = pageId;
1007     return DM_OK;
1008 }
1009 
SetReasonAndFinish(int32_t reason,int32_t state)1010 int32_t DmAuthManager::SetReasonAndFinish(int32_t reason, int32_t state)
1011 {
1012     if (authResponseContext_ == nullptr) {
1013         LOGE("Authenticate is not start");
1014         return ERR_DM_AUTH_NOT_START;
1015     }
1016     authResponseContext_->state = state;
1017     authResponseContext_->reply = reason;
1018     if (authRequestState_ != nullptr && authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) {
1019         authRequestContext_->reason = reason;
1020         authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
1021     } else if (authResponseState_ != nullptr && authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) {
1022         authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
1023     }
1024     return DM_OK;
1025 }
1026 
IsIdenticalAccount()1027 bool DmAuthManager::IsIdenticalAccount()
1028 {
1029     nlohmann::json jsonObj;
1030     jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP;
1031     std::string queryParams = jsonObj.dump();
1032 
1033     int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID();
1034     if (osAccountUserId < 0) {
1035         LOGE("get current process account user id failed");
1036         return false;
1037     }
1038     std::vector<GroupInfo> groupList;
1039     if (!hiChainConnector_->GetGroupInfo(osAccountUserId, queryParams, groupList)) {
1040         return false;
1041     }
1042     return true;
1043 }
1044 } // namespace DistributedHardware
1045 } // namespace OHOS