• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2025 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 "device_manager_service_impl.h"
17 
18 #include <chrono>
19 #include <random>
20 #include <algorithm>
21 #include <functional>
22 
23 #include "app_manager.h"
24 #include "bundle_mgr_interface.h"
25 #include "bundle_mgr_proxy.h"
26 #include "dm_error_type.h"
27 #include "dm_anonymous.h"
28 #include "dm_constants.h"
29 #include "dm_crypto.h"
30 #include "dm_distributed_hardware_load.h"
31 #include "dm_log.h"
32 #include "dm_radar_helper.h"
33 #include "dm_softbus_cache.h"
34 #include "multiple_user_connector.h"
35 #include "iservice_registry.h"
36 #include "system_ability_definition.h"
37 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
38 #include "dm_common_event_manager.h"
39 #include "parameter.h"
40 #include "dm_random.h"
41 #include "common_event_support.h"
42 #include "ffrt.h"
43 using namespace OHOS::EventFwk;
44 #endif
45 
46 namespace OHOS {
47 namespace DistributedHardware {
48 
49 namespace {
50 
51 // One year 365 * 24 * 60 * 60
52 constexpr int32_t MAX_ALWAYS_ALLOW_SECONDS = 31536000;
53 constexpr int32_t BROADCAST_CREDID_LENGTH = 6;
54 constexpr int32_t MIN_PIN_CODE = 100000;
55 constexpr int32_t MAX_PIN_CODE = 999999;
56 // New protocol field definition. To avoid dependency on the new protocol header file,
57 // do not directly depend on the new protocol header file.
58 constexpr int32_t MSG_TYPE_REQ_ACL_NEGOTIATE = 80;
59 constexpr int32_t MSG_TYPE_RESP_ACL_NEGOTIATE = 90;
60 constexpr int32_t MSG_TYPE_REQ_AUTH_TERMINATE = 104;
61 constexpr int32_t AUTH_SRC_FINISH_STATE = 12;
62 constexpr int32_t MAX_DATA_LEN = 65535;
63 constexpr int32_t ULTRASONIC_AUTHTYPE = 6;
64 constexpr const char* DM_TAG_LOGICAL_SESSION_ID = "logicalSessionId";
65 constexpr const char* DM_TAG_PEER_DISPLAY_ID = "peerDisplayId";
66 constexpr const char* DM_TAG_ACCESSEE_USER_ID = "accesseeUserId";
67 constexpr const char* DM_TAG_EXTRA_INFO = "extraInfo";
68 constexpr const char* FILED_AUTHORIZED_APP_LIST = "authorizedAppList";
69 constexpr const char* CHANGE_PINTYPE = "1";
70 constexpr const char* BIND_CALLER_USERID = "bindCallerUserId";
71 const char* IS_NEED_JOIN_LNN = "IsNeedJoinLnn";
72 constexpr const char* NEED_JOIN_LNN = "0";
73 constexpr const char* NO_NEED_JOIN_LNN = "1";
74 // currently, we just support one bind session in one device at same time
75 constexpr size_t MAX_NEW_PROC_SESSION_COUNT_TEMP = 1;
76 const int32_t USLEEP_TIME_US_500000 = 500000; // 500ms
77 const int32_t USLEEP_TIME_US_550000 = 550000; // 550ms
78 const int32_t USLEEP_TIME_US_20000 = 20000; // 20ms
79 const int32_t OPEN_AUTH_SESSION_TIMEOUT = 15000; // 15000ms
80 const int32_t MAX_TRY_STOP_CNT = 5;
81 const int32_t DEFAULT_SESSION_ID = -1;
82 
83 const std::map<std::string, std::string> BUNDLENAME_MAPPING = {
84     { "wear_link_service", "watch_system_service" }
85 };
86 
IsMessageOldVersion(const JsonObject & jsonObject,std::shared_ptr<Session> session)87 static bool IsMessageOldVersion(const JsonObject &jsonObject, std::shared_ptr<Session> session)
88 {
89     std::string dmVersion = "";
90     std::string edition = "";
91     if (jsonObject[TAG_DMVERSION].IsString()) {
92         dmVersion = jsonObject[TAG_DMVERSION].Get<std::string>();
93     }
94     if (jsonObject[TAG_EDITION].IsString()) {
95         edition = jsonObject[TAG_EDITION].Get<std::string>();
96     }
97     dmVersion = AuthManagerBase::ConvertSrcVersion(dmVersion, edition);
98 
99     // Assign the physical session version and release the semaphore.
100     session->version_ = dmVersion;
101 
102     // If the version number is higher than 5.0.4 (the highest version of the old protocol),
103     // there is no need to switch to the old protocol.
104     if (CompareVersion(dmVersion, DM_VERSION_5_0_OLD_MAX) == true) {
105         return false;
106     }
107 
108     return true;
109 }
110 
CreateTerminateMessage(void)111 std::string CreateTerminateMessage(void)
112 {
113     JsonObject jsonObject;
114     jsonObject[TAG_MSG_TYPE] = MSG_TYPE_REQ_AUTH_TERMINATE;
115     jsonObject[TAG_REPLY] = ERR_DM_VERSION_INCOMPATIBLE;
116     jsonObject[TAG_AUTH_FINISH] = false;
117 
118     return jsonObject.Dump();
119 }
120 
121 }
122 
Session(int sessionId,std::string deviceId)123 Session::Session(int sessionId, std::string deviceId)
124 {
125     sessionId_ = sessionId;
126     deviceId_ = deviceId;
127 }
128 
DeviceManagerServiceImpl()129 DeviceManagerServiceImpl::DeviceManagerServiceImpl()
130 {
131     LOGI("DeviceManagerServiceImpl constructor");
132 }
133 
~DeviceManagerServiceImpl()134 DeviceManagerServiceImpl::~DeviceManagerServiceImpl()
135 {
136     LOGI("DeviceManagerServiceImpl destructor");
137 }
138 
StringToUint64(const std::string & str)139 static uint64_t StringToUint64(const std::string& str)
140 {
141     // Calculate the length of the substring, taking the minimum of the string length and 8
142     size_t subStrLength = std::min(str.length(), static_cast<size_t>(8U));
143 
144     // Extract substring
145     std::string substr = str.substr(str.length() - subStrLength);
146 
147     // Convert substring to uint64_t
148     uint64_t result = 0;
149     for (size_t i = 0; i < subStrLength; ++i) {
150         result <<= 8; // Shift left 8 bits
151         result |= static_cast<uint64_t>(substr[i]);
152     }
153 
154     return result;
155 }
156 
157 
GetTokenId(bool isSrcSide,int32_t displayId,std::string & bundleName)158 static uint64_t GetTokenId(bool isSrcSide, int32_t displayId, std::string &bundleName)
159 {
160     uint64_t tokenId = 0;
161     if (isSrcSide) {
162         // src end
163         tokenId = IPCSkeleton::GetCallingTokenID();
164     } else {
165         // sink end
166         int64_t tmpTokenId;
167         // get userId
168         int32_t targetUserId = AuthManagerBase::DmGetUserId(displayId);
169         if (targetUserId == -1) {
170             return tokenId;
171         }
172         if (AppManager::GetInstance().GetHapTokenIdByName(targetUserId, bundleName, 0, tmpTokenId) == DM_OK) {
173             tokenId = static_cast<uint64_t>(tmpTokenId);
174         } else if (AppManager::GetInstance().GetNativeTokenIdByName(bundleName, tmpTokenId) == DM_OK) {
175             tokenId = static_cast<uint64_t>(tmpTokenId);
176         } else {
177             // get deviceId, take the 8 character value as tokenId
178             char localDeviceId[DEVICE_UUID_LENGTH] = {0};
179             GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
180             std::string deviceId = std::string(localDeviceId);
181             if (deviceId.length() != 0) {
182                 tokenId = StringToUint64(deviceId);
183             }
184         }
185     }
186     return tokenId;
187 }
188 
NotifyCleanEvent(uint64_t logicalSessionId)189 void DeviceManagerServiceImpl::NotifyCleanEvent(uint64_t logicalSessionId)
190 {
191     LOGI("logicalSessionId: %{public}" PRIu64 ".", logicalSessionId);
192     ffrt::submit([=]() { CleanAuthMgrByLogicalSessionId(logicalSessionId); });
193 }
194 
ImportConfig(std::shared_ptr<AuthManagerBase> authMgr,uint64_t tokenId,const std::string & pkgName)195 void DeviceManagerServiceImpl::ImportConfig(std::shared_ptr<AuthManagerBase> authMgr, uint64_t tokenId,
196     const std::string &pkgName)
197 {
198     // Import configuration
199     std::lock_guard<std::mutex> configsLock(configsMapMutex_);
200     if (configsMap_.find(tokenId) != configsMap_.end()) {
201         authMgr->ImportAuthCode(configsMap_[tokenId]->pkgName, configsMap_[tokenId]->authCode);
202         authMgr->RegisterAuthenticationType(configsMap_[tokenId]->authenticationType);
203         LOGI("import authCode Successful tokenId %{public}s, pkgName %{public}s, authCode %{public}s.",
204             GetAnonyInt32(tokenId).c_str(), pkgName.c_str(), GetAnonyString(configsMap_[tokenId]->authCode).c_str());
205         configsMap_[tokenId] = nullptr;
206         configsMap_.erase(tokenId);
207         return;
208     }
209     for (auto it = configsMap_.begin(); it != configsMap_.end();) {
210         if (it->second != nullptr && pkgName == it->second->pkgName) {
211             authMgr->ImportAuthCode(it->second->pkgName, it->second->authCode);
212             authMgr->RegisterAuthenticationType(it->second->authenticationType);
213             LOGI("import authCode by pkgName Successful.");
214             it->second = nullptr;
215             it = configsMap_.erase(it);
216             return;
217         } else {
218             ++it;
219         }
220     }
221 }
222 
ImportAuthCodeToConfig(std::shared_ptr<AuthManagerBase> authMgr,uint64_t tokenId)223 void DeviceManagerServiceImpl::ImportAuthCodeToConfig(std::shared_ptr<AuthManagerBase> authMgr, uint64_t tokenId)
224 {
225     if (authMgr == nullptr) {
226         LOGE("authMgr is null.");
227         return;
228     }
229     std::string pkgName;
230     std::string authCode;
231     authMgr->GetAuthCodeAndPkgName(pkgName, authCode);
232     std::lock_guard<std::mutex> configsLock(configsMapMutex_);
233     if (configsMap_.find(tokenId) == configsMap_.end()) {
234         configsMap_[tokenId] = std::make_shared<Config>();
235     }
236     configsMap_[tokenId]->pkgName = pkgName;
237     configsMap_[tokenId]->authCode = authCode;
238 }
239 
InitNewProtocolAuthMgr(bool isSrcSide,uint64_t tokenId,uint64_t logicalSessionId,const std::string & pkgName,int sessionId)240 int32_t DeviceManagerServiceImpl::InitNewProtocolAuthMgr(bool isSrcSide, uint64_t tokenId, uint64_t logicalSessionId,
241     const std::string &pkgName, int sessionId)
242 {
243     LOGI("isSrcSide:%{public}d, tokenId: %{public}s, logicalSesId: %{public}" PRIu64 ", pkgname:%{public}s",
244         isSrcSide, GetAnonyInt32(tokenId).c_str(), logicalSessionId, pkgName.c_str());
245     std::shared_ptr<AuthManagerBase> authMgr = nullptr;
246     // Create a new auth_mgr, create authMgr
247     if (isSrcSide) {
248         // src end
249         authMgr = std::make_shared<AuthSrcManager>(softbusConnector_, hiChainConnector_,
250             listener_, hiChainAuthConnector_);
251     } else {
252         // sink end
253         authMgr = std::make_shared<AuthSinkManager>(softbusConnector_, hiChainConnector_,
254             listener_, hiChainAuthConnector_);
255     }
256     CleanNotifyCallback cleanNotifyCallback = [=](const auto &logicalSessionId) {
257         this->NotifyCleanEvent(logicalSessionId);
258     };
259     // Register resource destruction notification function
260     authMgr->RegisterCleanNotifyCallback(cleanNotifyCallback);
261     CHECK_NULL_RETURN(hiChainAuthConnector_, ERR_DM_POINT_NULL);
262     hiChainAuthConnector_->RegisterHiChainAuthCallbackById(logicalSessionId, authMgr);
263     LOGI("Initialize authMgr token: %{public}" PRId64 ".", tokenId);
264     ImportConfig(authMgr, tokenId, pkgName);
265     return AddAuthMgr(tokenId, sessionId, authMgr);
266 }
267 
InitOldProtocolAuthMgr(uint64_t tokenId,const std::string & pkgName,int sessionId)268 int32_t DeviceManagerServiceImpl::InitOldProtocolAuthMgr(uint64_t tokenId, const std::string &pkgName, int sessionId)
269 {
270     LOGI("tokenId: %{public}s, pkgname:%{public}s", GetAnonyInt32(tokenId).c_str(), pkgName.c_str());
271     {
272         std::lock_guard<std::mutex> lock(authMgrMtx_);
273         if (authMgr_ == nullptr) {
274             CreateGlobalClassicalAuthMgr();
275         }
276         authMgr_->PrepareSoftbusSessionCallback();
277         ImportConfig(authMgr_, tokenId, pkgName);
278         int32_t ret = AddAuthMgr(tokenId, sessionId, authMgr_);
279         if (ret != DM_OK) {
280             authMgr_->ClearSoftbusSessionCallback();
281             return ret;
282         }
283     }
284     {
285         // The value of logicalSessionId in the old protocol is always 0.
286         std::lock_guard<std::mutex> tokenIdLock(logicalSessionId2TokenIdMapMtx_);
287         logicalSessionId2TokenIdMap_[0] = tokenId;
288     }
289     return DM_OK;
290 }
291 
InitAndRegisterAuthMgr(bool isSrcSide,uint64_t tokenId,std::shared_ptr<Session> session,uint64_t logicalSessionId,const std::string & pkgName)292 int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide, uint64_t tokenId,
293     std::shared_ptr<Session> session, uint64_t logicalSessionId, const std::string &pkgName)
294 {
295     if (session == nullptr) {
296         LOGE("InitAndRegisterAuthMgr, The physical link is not created.");
297         return ERR_DM_AUTH_OPEN_SESSION_FAILED;
298     }
299     // If version is empty, allow creation for the first time, create a new protocol auth_mgr to negotiate version;
300     // subsequent creations wait, and directly use version to create the corresponding auth_mgr after release.
301     if (session->version_ == "") {
302         bool expected = false;
303         if (session->flag_.compare_exchange_strong(expected, true)) {
304             LOGI("The physical link is being created and the dual-end device version is aligned.");
305         } else {
306             // Do not allow simultaneous version negotiation, return error directly
307             LOGE("Version negotiation is not allowed at the same time.");
308             return ERR_DM_AUTH_BUSINESS_BUSY;
309         }
310     }
311     if (session->version_ == "" || CompareVersion(session->version_, DM_VERSION_5_0_OLD_MAX)) {
312         return InitNewProtocolAuthMgr(isSrcSide, tokenId, logicalSessionId, pkgName, session->sessionId_);
313     }
314     LOGI("InitAndRegisterAuthMgr old authMgr.");
315     return InitOldProtocolAuthMgr(tokenId, pkgName, session->sessionId_);
316 }
317 
CleanSessionMap(std::shared_ptr<Session> session)318 void DeviceManagerServiceImpl::CleanSessionMap(std::shared_ptr<Session> session)
319 {
320     if (session == nullptr) {
321         return;
322     }
323     session->logicalSessionCnt_.fetch_sub(1);
324     if (session->logicalSessionCnt_.load(std::memory_order_relaxed) <= 0) {
325         {
326             std::lock_guard<std::mutex> lock(isNeedJoinLnnMtx_);
327             if (isNeedJoinLnn_) {
328                 usleep(USLEEP_TIME_US_500000);
329             }
330             isNeedJoinLnn_ = true;
331         }
332         CleanSessionMap(session->sessionId_);
333     }
334 }
335 
CleanSessionMap(int sessionId)336 void DeviceManagerServiceImpl::CleanSessionMap(int sessionId)
337 {
338     LOGI("In sessionId:%{public}d.", sessionId);
339     if (softbusConnector_ != nullptr) {
340         softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId);
341     }
342     {
343         std::lock_guard<std::mutex> lock(mapMutex_);
344         std::shared_ptr<Session> session = nullptr;
345         if (sessionsMap_.find(sessionId) != sessionsMap_.end()) {
346             session = sessionsMap_[sessionId];
347             sessionsMap_.erase(sessionId);
348         }
349         if (session != nullptr && deviceId2SessionIdMap_.find(session->deviceId_) != deviceId2SessionIdMap_.end()) {
350             deviceId2SessionIdMap_.erase(session->deviceId_);
351         }
352         if (sessionEnableMutexMap_.find(sessionId) != sessionEnableMutexMap_.end()) {
353             sessionStopMap_.erase(sessionId);
354             sessionEnableMap_.erase(sessionId);
355             sessionEnableCvReadyMap_.erase(sessionId);
356             sessionEnableMutexMap_.erase(sessionId);
357         }
358     }
359 }
360 
CleanSessionMapByLogicalSessionId(uint64_t logicalSessionId)361 void DeviceManagerServiceImpl::CleanSessionMapByLogicalSessionId(uint64_t logicalSessionId)
362 {
363     {
364         std::lock_guard<std::mutex> tokenIdLock(logicalSessionId2TokenIdMapMtx_);
365         logicalSessionId2TokenIdMap_.erase(logicalSessionId);
366     }
367     int32_t sessionId = 0;
368     {
369         std::lock_guard<std::mutex> sessionIdLock(logicalSessionId2SessionIdMapMtx_);
370         if (logicalSessionId2SessionIdMap_.find(logicalSessionId) == logicalSessionId2SessionIdMap_.end()) {
371             return;
372         }
373         sessionId = logicalSessionId2SessionIdMap_[logicalSessionId];
374         logicalSessionId2SessionIdMap_.erase(logicalSessionId);
375     }
376     auto session = GetCurSession(sessionId);
377     if (session != nullptr) {
378         CleanSessionMap(session);
379     }
380     return;
381 }
382 
CleanAuthMgrByLogicalSessionId(uint64_t logicalSessionId)383 void DeviceManagerServiceImpl::CleanAuthMgrByLogicalSessionId(uint64_t logicalSessionId)
384 {
385     uint64_t tokenId = 0;
386     {
387         std::lock_guard<std::mutex> tokenIdLock(logicalSessionId2TokenIdMapMtx_);
388         if (logicalSessionId2TokenIdMap_.find(logicalSessionId) != logicalSessionId2TokenIdMap_.end()) {
389             tokenId = logicalSessionId2TokenIdMap_[logicalSessionId];
390         } else {
391             LOGE("logicalSessionId(%{public}" PRIu64 ") can not find the tokenId.", logicalSessionId);
392             return;
393         }
394     }
395 
396     CleanSessionMapByLogicalSessionId(logicalSessionId);
397     if (logicalSessionId == 0 && authMgr_ != nullptr) {
398         authMgr_->SetTransferReady(true);
399         authMgr_->ClearSoftbusSessionCallback();
400     }
401     hiChainAuthConnector_->UnRegisterHiChainAuthCallbackById(logicalSessionId);
402     EraseAuthMgr(tokenId);
403     return;
404 }
405 
GetAuthMgr()406 std::shared_ptr<AuthManagerBase> DeviceManagerServiceImpl::GetAuthMgr()
407 {
408     uint64_t tokenId = IPCSkeleton::GetCallingTokenID();
409     return GetAuthMgrByTokenId(tokenId);
410 }
411 
AddAuthMgr(uint64_t tokenId,int sessionId,std::shared_ptr<AuthManagerBase> authMgr)412 int32_t DeviceManagerServiceImpl::AddAuthMgr(uint64_t tokenId, int sessionId, std::shared_ptr<AuthManagerBase> authMgr)
413 {
414     if (authMgr == nullptr) {
415         LOGE("authMgr is nullptr.");
416         return ERR_DM_POINT_NULL;
417     }
418     {
419         std::lock_guard<std::mutex> mapLock(mapMutex_);
420         if (sessionEnableMap_.find(sessionId) != sessionEnableMap_.end() && !sessionEnableMap_[sessionId]) {
421             LOGE("session is not open, no need add authMgr.");
422             return ERR_DM_AUTH_OPEN_SESSION_FAILED;
423         }
424     }
425     {
426         std::lock_guard<std::mutex> lock(authMgrMapMtx_);
427         if (authMgrMap_.size() >= MAX_NEW_PROC_SESSION_COUNT_TEMP) {
428             LOGE("Other bind session exist, can not start new one. authMgrMap_.size:%{public}zu", authMgrMap_.size());
429             return ERR_DM_AUTH_BUSINESS_BUSY;
430         }
431         authMgrMap_[tokenId] = authMgr;
432     }
433     {
434         std::lock_guard<std::mutex> mapLock(tokenIdSessionIdMapMtx_);
435         if (tokenIdSessionIdMap_.find(tokenId) == tokenIdSessionIdMap_.end()) {
436             tokenIdSessionIdMap_[tokenId] = sessionId;
437         }
438     }
439     return DM_OK;
440 }
441 
EraseAuthMgr(uint64_t tokenId)442 void DeviceManagerServiceImpl::EraseAuthMgr(uint64_t tokenId)
443 {
444     {
445         std::lock_guard<std::mutex> lock(authMgrMapMtx_);
446         if (authMgrMap_.find(tokenId) != authMgrMap_.end()) {
447             LOGI("authMgrMap_ erase token: %{public}" PRIu64 ".", tokenId);
448             authMgrMap_.erase(tokenId);
449         }
450     }
451     {
452         std::lock_guard<std::mutex> lock(tokenIdSessionIdMapMtx_);
453         LOGI("tokenIdSessionIdMap_ erase token: %{public}" PRIu64 ".", tokenId);
454         tokenIdSessionIdMap_.erase(tokenId);
455     }
456 }
457 
458 // Needed in the callback function
GetAuthMgrByTokenId(uint64_t tokenId)459 std::shared_ptr<AuthManagerBase> DeviceManagerServiceImpl::GetAuthMgrByTokenId(uint64_t tokenId)
460 {
461     {
462         std::lock_guard<std::mutex> lock(authMgrMapMtx_);
463         if (authMgrMap_.find(tokenId) != authMgrMap_.end()) {
464             LOGI("authMgrMap_ token: %{public}" PRIu64 ".", tokenId);
465             return authMgrMap_[tokenId];
466         }
467     }
468     LOGE("authMgrMap_ not found, token: %{public}" PRIu64 ".", tokenId);
469     return nullptr;
470 }
471 
GetCurrentAuthMgr()472 std::shared_ptr<AuthManagerBase> DeviceManagerServiceImpl::GetCurrentAuthMgr()
473 {
474     uint64_t tokenId = 0;
475     {
476         std::lock_guard<std::mutex> tokenIdLock(logicalSessionId2TokenIdMapMtx_);
477         if (logicalSessionId2TokenIdMap_.find(0) != logicalSessionId2TokenIdMap_.end()) {
478             tokenId = logicalSessionId2TokenIdMap_[0];
479         }
480     }
481     {
482         std::lock_guard<std::mutex> lock(authMgrMapMtx_);
483         for (auto &pair : authMgrMap_) {
484             if (pair.first != tokenId) {
485                 return pair.second;
486             }
487         }
488     }
489     return authMgr_;
490 }
491 
GenerateRandNum(int sessionId)492 static uint64_t GenerateRandNum(int sessionId)
493 {
494     // Get the current timestamp
495     auto timestamp = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock::now().
496         time_since_epoch()).count();
497 
498     // Generate random numbers
499     std::random_device rd;
500     std::mt19937 gen(rd());
501     std::uniform_int_distribution<> rand_dis(1, 0xFFFFFFFF);
502     uint32_t randomNumber = static_cast<uint32_t>(rand_dis(gen));
503 
504     // Combination of random numbers
505     uint64_t randNum = (static_cast<uint64_t>(timestamp) << 32) |
506                       (static_cast<uint64_t>(sessionId) << 16) |
507                       static_cast<uint64_t>(randomNumber);
508 
509     return randNum;
510 }
511 
Initialize(const std::shared_ptr<IDeviceManagerServiceListener> & listener)512 int32_t DeviceManagerServiceImpl::Initialize(const std::shared_ptr<IDeviceManagerServiceListener> &listener)
513 {
514     LOGI("Initialize");
515     if (softbusConnector_ == nullptr) {
516         softbusConnector_ = std::make_shared<SoftbusConnector>();
517     }
518     if (hiChainConnector_ == nullptr) {
519         hiChainConnector_ = std::make_shared<HiChainConnector>();
520     }
521     if (mineHiChainConnector_ == nullptr) {
522         mineHiChainConnector_ = std::make_shared<MineHiChainConnector>();
523     }
524     if (hiChainAuthConnector_ == nullptr) {
525         hiChainAuthConnector_ = std::make_shared<HiChainAuthConnector>();
526     }
527     if (deviceStateMgr_ == nullptr) {
528         deviceStateMgr_ = std::make_shared<DmDeviceStateManager>(softbusConnector_, listener,
529                                                                  hiChainConnector_, hiChainAuthConnector_);
530         deviceStateMgr_->RegisterSoftbusStateCallback();
531     }
532     if (credentialMgr_ == nullptr) {
533         credentialMgr_ = std::make_shared<DmCredentialManager>(hiChainConnector_, listener);
534     }
535     if (dpInitedCallback_ == nullptr) {
536         dpInitedCallback_ = sptr<DpInitedCallback>(new DpInitedCallback());
537         DeviceProfileConnector::GetInstance().SubscribeDeviceProfileInited(dpInitedCallback_);
538     }
539     listener_ = listener;
540     CreateGlobalClassicalAuthMgr();
541     if (authMgr_ != nullptr) {
542         authMgr_->ClearSoftbusSessionCallback();
543     }
544     LOGI("Init success, singleton initialized");
545     return DM_OK;
546 }
547 
ReleaseMaps()548 void DeviceManagerServiceImpl::ReleaseMaps()
549 {
550     {
551         std::lock_guard<std::mutex> lock(authMgrMapMtx_);
552         for (auto& pair : authMgrMap_) {
553             pair.second = nullptr;
554         }
555         authMgrMap_.clear();
556     }
557     for (auto& pair : sessionsMap_) {
558         pair.second = nullptr;
559     }
560     sessionsMap_.clear();
561     {
562         std::lock_guard<std::mutex> configsLock(configsMapMutex_);
563         for (auto& pair : configsMap_) {
564             pair.second = nullptr;
565         }
566         configsMap_.clear();
567     }
568     deviceId2SessionIdMap_.clear();
569     sessionEnableMutexMap_.clear();
570     sessionEnableCvMap_.clear();
571     sessionStopMap_.clear();
572     sessionEnableMap_.clear();
573     sessionEnableCvReadyMap_.clear();
574     {
575         std::lock_guard<std::mutex> tokenIdLock(logicalSessionId2TokenIdMapMtx_);
576         logicalSessionId2TokenIdMap_.clear();
577     }
578     {
579         std::lock_guard<std::mutex> sessionIdLock(logicalSessionId2SessionIdMapMtx_);
580         logicalSessionId2SessionIdMap_.clear();
581     }
582 }
583 
Release()584 void DeviceManagerServiceImpl::Release()
585 {
586     LOGI("Release");
587 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
588     commonEventManager_ = nullptr;
589 #endif
590     if (softbusConnector_ != nullptr) {
591         softbusConnector_->UnRegisterConnectorCallback();
592         softbusConnector_->UnRegisterSoftbusStateCallback();
593         if (softbusConnector_->GetSoftbusSession() != nullptr) {
594             softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback();
595         }
596     }
597     if (hiChainConnector_ != nullptr) {
598         hiChainConnector_->UnRegisterHiChainCallback();
599     }
600     if (hiChainAuthConnector_ != nullptr) {
601         hiChainAuthConnector_->UnRegisterHiChainAuthCallback();
602     }
603     authMgr_ = nullptr;
604     ReleaseMaps();
605     deviceStateMgr_ = nullptr;
606     softbusConnector_ = nullptr;
607     abilityMgr_ = nullptr;
608     hiChainConnector_ = nullptr;
609     DeviceProfileConnector::GetInstance().UnSubscribeDeviceProfileInited();
610     dpInitedCallback_ = nullptr;
611 }
612 
UnAuthenticateDevice(const std::string & pkgName,const std::string & udid,int32_t bindLevel)613 int32_t DeviceManagerServiceImpl::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid,
614     int32_t bindLevel)
615 {
616     if (pkgName.empty() || udid.empty()) {
617         LOGE("DeviceManagerServiceImpl::UnAuthenticateDevice failed, pkgName is %{public}s, udid is %{public}s",
618             pkgName.c_str(), GetAnonyString(udid).c_str());
619         return ERR_DM_INPUT_PARA_INVALID;
620     }
621     auto authMgr = GetAuthMgr();
622     if (authMgr == nullptr) {
623         LOGE("authMgr is nullptr, invoke the old protocal.");
624         if (authMgr_ == nullptr) {
625             LOGE("classical authMgr_ is nullptr");
626             return ERR_DM_POINT_NULL;
627         }
628         return authMgr_->UnAuthenticateDevice(pkgName, udid, bindLevel);
629     }
630     return authMgr->UnAuthenticateDevice(pkgName, udid, bindLevel);
631 }
632 
StopAuthenticateDevice(const std::string & pkgName)633 int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgName)
634 {
635     if (pkgName.empty()) {
636         LOGE("DeviceManagerServiceImpl::StopAuthenticateDevice failed");
637         return ERR_DM_INPUT_PARA_INVALID;
638     }
639     uint64_t tokenId = IPCSkeleton::GetCallingTokenID();
640     int32_t sessionId = DEFAULT_SESSION_ID;
641     int32_t tryCnt = 0;
642     while (tryCnt < MAX_TRY_STOP_CNT) {
643         {
644             std::lock_guard<std::mutex> lock(tokenIdSessionIdMapMtx_);
645             if (tokenIdSessionIdMap_.find(tokenId) == tokenIdSessionIdMap_.end()) {
646                 LOGI("sessionId not create, pkgName:%{public}s, tokenId:%{public}" PRIu64, pkgName.c_str(), tokenId);
647                 return DM_OK;
648             }
649             sessionId = tokenIdSessionIdMap_[tokenId];
650         }
651         if (sessionId > 0) {
652             break;
653         }
654         usleep(USLEEP_TIME_US_20000);
655         tryCnt++;
656     }
657     if (sessionId == DEFAULT_SESSION_ID) {
658         LOGE("sessionId is creating, pkgName:%{public}s, tokenId:%{public}" PRIu64, pkgName.c_str(), tokenId);
659         return ERR_DM_AUTH_BUSINESS_BUSY;
660     }
661     LOGI("pkgName:%{public}s, sessionId:%{public}d, tokenId:%{public}" PRIu64, pkgName.c_str(), sessionId, tokenId);
662     if (sessionEnableCvMap_.find(sessionId) != sessionEnableCvMap_.end()) {
663         std::unique_lock<std::mutex> cvLock(sessionEnableMutexMap_[sessionId]);
664         if (sessionEnableMap_.find(sessionId) != sessionEnableMap_.end() && !sessionEnableMap_[sessionId]) {
665             sessionStopMap_[sessionId] = true;
666         }
667         sessionEnableCvReadyMap_[sessionId] = true;
668         sessionEnableCvMap_[sessionId].notify_all();
669         LOGI("notify_all by stop, sessionId:%{public}d, tokenId:%{public}" PRIu64, sessionId, tokenId);
670     }
671     auto authMgr = GetAuthMgrByTokenId(tokenId);
672     int32_t ret = DM_OK;
673     if (authMgr != nullptr) {
674         ret = authMgr->StopAuthenticateDevice(pkgName);
675         if (ret == DM_OK) {
676             usleep(USLEEP_TIME_US_550000);
677         }
678     } else {
679         CleanSessionMap(sessionId);
680     }
681     EraseAuthMgr(tokenId);
682     return ret;
683 }
684 
UnBindDevice(const std::string & pkgName,const std::string & udid,int32_t bindLevel)685 int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string &udid,
686     int32_t bindLevel)
687 {
688     if (pkgName.empty() || udid.empty()) {
689         LOGE("DeviceManagerServiceImpl::UnBindDevice failed, pkgName is %{public}s, udid is %{public}s",
690             pkgName.c_str(), GetAnonyString(udid).c_str());
691         return ERR_DM_INPUT_PARA_INVALID;
692     }
693     std::string extra = "";
694     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
695     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
696     return DeleteAclV2(pkgName, std::string(localDeviceId), udid, bindLevel, extra);
697 }
698 
UnBindDevice(const std::string & pkgName,const std::string & udid,int32_t bindLevel,const std::string & extra)699 int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string &udid,
700     int32_t bindLevel, const std::string &extra)
701 {
702     if (pkgName.empty() || udid.empty()) {
703         LOGE("DeviceManagerServiceImpl::UnBindDevice failed, pkgName is %{public}s, udid is %{public}s",
704             pkgName.c_str(), GetAnonyString(udid).c_str());
705         return ERR_DM_INPUT_PARA_INVALID;
706     }
707     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
708     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
709     return DeleteAclV2(pkgName, std::string(localDeviceId), udid, bindLevel, extra);
710 }
711 
SetUserOperation(std::string & pkgName,int32_t action,const std::string & params)712 int32_t DeviceManagerServiceImpl::SetUserOperation(std::string &pkgName, int32_t action,
713     const std::string &params)
714 {
715     if (pkgName.empty() || params.empty()) {
716         LOGE("DeviceManagerServiceImpl::SetUserOperation error: Invalid parameter, pkgName: %{public}s, extra:"
717             "%{public}s", pkgName.c_str(), params.c_str());
718         return ERR_DM_INPUT_PARA_INVALID;
719     }
720     auto authMgr = GetCurrentAuthMgr();
721     if (authMgr != nullptr) {
722         authMgr->OnUserOperation(action, params);
723     }
724     return DM_OK;
725 }
726 
CreateGlobalClassicalAuthMgr()727 void DeviceManagerServiceImpl::CreateGlobalClassicalAuthMgr()
728 {
729     LOGI("global classical authMgr_ not exit, create one");
730     CHECK_NULL_VOID(softbusConnector_);
731     CHECK_NULL_VOID(hiChainConnector_);
732     CHECK_NULL_VOID(hiChainAuthConnector_);
733     // Create old auth_mar, only create an independent one
734     authMgr_ = std::make_shared<DmAuthManager>(softbusConnector_, hiChainConnector_, listener_,
735         hiChainAuthConnector_);
736     CleanNotifyCallback cleanNotifyCallback = [=](const auto &logicalSessionId) {
737         this->NotifyCleanEvent(logicalSessionId);
738     };
739     authMgr_->RegisterCleanNotifyCallback(cleanNotifyCallback);
740     softbusConnector_->RegisterConnectorCallback(authMgr_);
741     softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_);
742     hiChainConnector_->RegisterHiChainCallback(authMgr_);
743     hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_);
744 }
745 
HandleOffline(DmDeviceState devState,DmDeviceInfo & devInfo)746 void DeviceManagerServiceImpl::HandleOffline(DmDeviceState devState, DmDeviceInfo &devInfo)
747 {
748     std::string trustDeviceId = deviceStateMgr_->GetUdidByNetWorkId(std::string(devInfo.networkId));
749     LOGI("deviceStateMgr Udid: %{public}s", GetAnonyString(trustDeviceId).c_str());
750     if (trustDeviceId == "") {
751         LOGE("HandleOffline not get udid in deviceStateMgr.");
752         return;
753     }
754     std::string udisHash = softbusConnector_->GetDeviceUdidHashByUdid(trustDeviceId);
755     if (memcpy_s(devInfo.deviceId, DM_MAX_DEVICE_ID_LEN, udisHash.c_str(), udisHash.length()) != 0) {
756         return;
757     }
758     char localUdid[DEVICE_UUID_LENGTH] = {0};
759     GetDevUdid(localUdid, DEVICE_UUID_LENGTH);
760     std::string requestDeviceId = std::string(localUdid);
761     ProcessInfo processInfo;
762     processInfo.pkgName = std::string(DM_PKG_NAME);
763     processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId();
764     uint32_t bindType = DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId);
765     std::map<int32_t, int32_t> userIdAndBindLevel =
766         DeviceProfileConnector::GetInstance().GetUserIdAndBindLevel(requestDeviceId, trustDeviceId);
767     if (userIdAndBindLevel.empty() || userIdAndBindLevel.find(processInfo.userId) == userIdAndBindLevel.end()) {
768         userIdAndBindLevel[processInfo.userId] = INVALIED_TYPE;
769     }
770     std::vector<ProcessInfo> processInfoVec;
771     for (const auto &item : userIdAndBindLevel) {
772         if (static_cast<uint32_t>(item.second) == INVALIED_TYPE) {
773             LOGI("The offline device is identical account bind type.");
774             devInfo.authForm = DmAuthForm::IDENTICAL_ACCOUNT;
775             processInfo.userId = item.first;
776             processInfoVec.push_back(processInfo);
777         } else if (static_cast<uint32_t>(item.second) == USER && bindType == SHARE_TYPE) {
778             LOGI("The offline device is device bind level and share bind type.");
779             devInfo.authForm = DmAuthForm::SHARE;
780             processInfo.userId = item.first;
781             processInfoVec.push_back(processInfo);
782         } else if (static_cast<uint32_t>(item.second) == USER && bindType != SHARE_TYPE) {
783             LOGI("The offline device is device bind type.");
784             devInfo.authForm = DmAuthForm::PEER_TO_PEER;
785             processInfo.userId = item.first;
786             processInfoVec.push_back(processInfo);
787         } else if (static_cast<uint32_t>(item.second) == SERVICE || static_cast<uint32_t>(item.second) == APP) {
788             LOGI("The offline device is PEER_TO_PEER_TYPE bind type, %{public}" PRIu32, item.second);
789             processInfoVec = DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(
790                 requestDeviceId, trustDeviceId, item.first);
791             std::set<ProcessInfo> processInfoSet(processInfoVec.begin(), processInfoVec.end());
792             processInfoVec.assign(processInfoSet.begin(), processInfoSet.end());
793         }
794         deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo, processInfoVec);
795     }
796 }
797 
HandleOnline(DmDeviceState devState,DmDeviceInfo & devInfo)798 void DeviceManagerServiceImpl::HandleOnline(DmDeviceState devState, DmDeviceInfo &devInfo)
799 {
800     LOGI("networkId: %{public}s.", GetAnonyString(devInfo.networkId).c_str());
801     std::string trustDeviceId = "";
802     if (softbusConnector_->GetUdidByNetworkId(devInfo.networkId, trustDeviceId) != DM_OK) {
803         LOGE("HandleOnline get udid failed.");
804         return;
805     }
806     std::string udisHash = softbusConnector_->GetDeviceUdidHashByUdid(trustDeviceId);
807     if (memcpy_s(devInfo.deviceId, DM_MAX_DEVICE_ID_LEN, udisHash.c_str(), udisHash.length()) != 0) {
808         LOGE("get deviceId: %{public}s failed", GetAnonyString(udisHash).c_str());
809         return;
810     }
811     char localUdid[DEVICE_UUID_LENGTH] = {0};
812     GetDevUdid(localUdid, DEVICE_UUID_LENGTH);
813     std::string requestDeviceId = std::string(localUdid);
814     uint32_t bindType = DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId);
815     LOGI("The online device bind type is %{public}" PRIu32, bindType);
816     ProcessInfo processInfo;
817     processInfo.pkgName = std::string(DM_PKG_NAME);
818     processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId();
819     SetOnlineProcessInfo(bindType, processInfo, devInfo, requestDeviceId, trustDeviceId, devState);
820 }
821 
SetOnlineProcessInfo(const uint32_t & bindType,ProcessInfo & processInfo,DmDeviceInfo & devInfo,const std::string & requestDeviceId,const std::string & trustDeviceId,DmDeviceState devState)822 void DeviceManagerServiceImpl::SetOnlineProcessInfo(const uint32_t &bindType, ProcessInfo &processInfo,
823     DmDeviceInfo &devInfo, const std::string &requestDeviceId, const std::string &trustDeviceId, DmDeviceState devState)
824 {
825     std::vector<ProcessInfo> processInfoVec;
826     if (bindType == IDENTICAL_ACCOUNT_TYPE) {
827         devInfo.authForm = DmAuthForm::IDENTICAL_ACCOUNT;
828         processInfoVec.push_back(processInfo);
829     } else if (bindType == DEVICE_PEER_TO_PEER_TYPE) {
830         devInfo.authForm = DmAuthForm::PEER_TO_PEER;
831         processInfoVec.push_back(processInfo);
832     } else if (bindType == DEVICE_ACROSS_ACCOUNT_TYPE) {
833         devInfo.authForm = DmAuthForm::ACROSS_ACCOUNT;
834         processInfoVec.push_back(processInfo);
835     } else if (bindType == APP_PEER_TO_PEER_TYPE || bindType == SERVICE_PEER_TO_PEER_TYPE) {
836         processInfoVec = DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId,
837             trustDeviceId, MultipleUserConnector::GetFirstForegroundUserId());
838         std::set<ProcessInfo> processInfoSet(processInfoVec.begin(), processInfoVec.end());
839         processInfoVec.assign(processInfoSet.begin(), processInfoSet.end());
840         devInfo.authForm = DmAuthForm::PEER_TO_PEER;
841     } else if (bindType == APP_ACROSS_ACCOUNT_TYPE || bindType == SERVICE_ACROSS_ACCOUNT_TYPE) {
842         processInfoVec = DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId,
843             trustDeviceId, MultipleUserConnector::GetFirstForegroundUserId());
844         std::set<ProcessInfo> processInfoSet(processInfoVec.begin(), processInfoVec.end());
845         processInfoVec.assign(processInfoSet.begin(), processInfoSet.end());
846         devInfo.authForm = DmAuthForm::ACROSS_ACCOUNT;
847     } else if (bindType == SHARE_TYPE) {
848         if (CheckSharePeerSrc(trustDeviceId, requestDeviceId)) {
849             LOGI("ProcessDeviceStateChange authForm is share, peer is src.");
850             return;
851         }
852         devInfo.authForm = DmAuthForm::SHARE;
853         processInfoVec.push_back(processInfo);
854     }
855     LOGI("HandleOnline success devInfo authForm is %{public}d.", devInfo.authForm);
856     deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo, processInfoVec);
857     return;
858 }
859 
CheckSharePeerSrc(const std::string & peerUdid,const std::string & localUdid)860 bool DeviceManagerServiceImpl::CheckSharePeerSrc(const std::string &peerUdid, const std::string &localUdid)
861 {
862     std::vector<DistributedDeviceProfile::AccessControlProfile> profiles =
863         DeviceProfileConnector::GetInstance().GetAccessControlProfile();
864     for (auto &aclItem : profiles) {
865         if (aclItem.GetBindType() == DM_SHARE && aclItem.GetTrustDeviceId() == peerUdid) {
866             if (aclItem.GetAccesser().GetAccesserDeviceId() == peerUdid &&
867                 aclItem.GetAccessee().GetAccesseeDeviceId() == localUdid) {
868                 return true;
869             }
870             if (aclItem.GetAccesser().GetAccesserDeviceId() == localUdid &&
871                 aclItem.GetAccessee().GetAccesseeDeviceId() == peerUdid) {
872                 return false;
873             }
874         }
875     }
876     return false;
877 }
878 
HandleDeviceStatusChange(DmDeviceState devState,DmDeviceInfo & devInfo)879 void DeviceManagerServiceImpl::HandleDeviceStatusChange(DmDeviceState devState, DmDeviceInfo &devInfo)
880 {
881     LOGI("start, devState = %{public}d, networkId: %{public}s.",
882         devState, GetAnonyString(devInfo.networkId).c_str());
883     if (deviceStateMgr_ == nullptr) {
884         LOGE("deviceStateMgr_ is nullpter!");
885         return;
886     }
887     if (devState == DEVICE_STATE_ONLINE) {
888         HandleOnline(devState, devInfo);
889     } else if (devState == DEVICE_STATE_OFFLINE) {
890         HandleOffline(devState, devInfo);
891     } else {
892         std::string udiddHash = GetUdidHashByNetworkId(devInfo.networkId);
893         if (memcpy_s(devInfo.deviceId, DM_MAX_DEVICE_ID_LEN, udiddHash.c_str(), udiddHash.length()) != 0) {
894             LOGE("get deviceId: %{public}s failed", GetAnonyString(udiddHash).c_str());
895             return;
896         }
897         ProcessInfo processInfo;
898         processInfo.pkgName = std::string(DM_PKG_NAME);
899         processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId();
900         std::vector<ProcessInfo> processInfoVec;
901         processInfoVec.push_back(processInfo);
902         deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo, processInfoVec);
903     }
904 }
905 
GetUdidHashByNetworkId(const std::string & networkId)906 std::string DeviceManagerServiceImpl::GetUdidHashByNetworkId(const std::string &networkId)
907 {
908     if (softbusConnector_ == nullptr) {
909         LOGE("softbusConnector_ is nullpter!");
910         return "";
911     }
912     std::string udid = "";
913     int32_t ret = softbusConnector_->GetUdidByNetworkId(networkId.c_str(), udid);
914     if (ret != DM_OK) {
915         LOGE("GetUdidByNetworkId failed ret: %{public}d", ret);
916         return "";
917     }
918     return softbusConnector_->GetDeviceUdidHashByUdid(udid);
919 }
920 
OnSessionOpened(int sessionId,int result)921 int DeviceManagerServiceImpl::OnSessionOpened(int sessionId, int result)
922 {
923     bool isNeedCloseSession = false;
924     if (sessionEnableCvMap_.find(sessionId) != sessionEnableCvMap_.end()) {
925         std::lock_guard<std::mutex> lock(sessionEnableMutexMap_[sessionId]);
926         if (result == 0) {
927             LOGI("OnSessionOpened successful, sessionId: %{public}d", sessionId);
928             if (sessionStopMap_.find(sessionId) != sessionStopMap_.end() && sessionStopMap_[sessionId]) {
929                 isNeedCloseSession = true;
930             } else {
931                 sessionEnableMap_[sessionId] = true;
932             }
933         } else {
934             LOGE("OnSessionOpened failed, sessionId: %{public}d, res: %{public}d", sessionId, result);
935         }
936         sessionEnableCvReadyMap_[sessionId] = true;
937         sessionEnableCvMap_[sessionId].notify_all();
938     }
939     std::string peerUdid = "";
940     softbusConnector_->GetSoftbusSession()->GetPeerDeviceId(sessionId, peerUdid);
941     struct RadarInfo info = {
942         .funcName = "OnSessionOpened",
943         .stageRes = static_cast<int32_t>(StageRes::STAGE_SUCC),
944         .isTrust = static_cast<int32_t>(TrustStatus::NOT_TRUST),
945         .peerUdid = peerUdid,
946         .channelId = sessionId,
947     };
948     if (!DmRadarHelper::GetInstance().ReportAuthSessionOpenCb(info)) {
949         LOGE("ReportAuthSessionOpenCb failed");
950     }
951     if (isNeedCloseSession) {
952         CleanSessionMap(sessionId);
953         return DM_OK;
954     }
955     // Get the remote deviceId, sink end gives sessionsMap[deviceId] = session;
956     {
957         std::lock_guard<std::mutex> lock(mapMutex_);
958         if (sessionsMap_.find(sessionId) == sessionsMap_.end()) {
959             sessionsMap_[sessionId] = std::make_shared<Session>(sessionId, peerUdid);
960         }
961     }
962 
963     return SoftbusSession::OnSessionOpened(sessionId, result);
964 }
965 
OnSessionClosed(int sessionId)966 void DeviceManagerServiceImpl::OnSessionClosed(int sessionId)
967 {
968     SoftbusSession::OnSessionClosed(sessionId);
969 }
970 
GetJsonObjectFromData(const void * data,unsigned int dataLen)971 static JsonObject GetJsonObjectFromData(const void *data, unsigned int dataLen)
972 {
973     std::string message = std::string(reinterpret_cast<const char *>(data), dataLen);
974     return JsonObject(message);
975 }
976 
977 // When downgrading the version, determine whether it is src or sink based on the message.
978 // src: Received 90 message.
979 // sink: Received 80 message.
IsAuthManagerSourceByMessage(int32_t msgType)980 static bool IsAuthManagerSourceByMessage(int32_t msgType)
981 {
982     return msgType == MSG_TYPE_RESP_ACL_NEGOTIATE;
983 }
984 
985 // Get the current session object
GetCurSession(int sessionId)986 std::shared_ptr<Session> DeviceManagerServiceImpl::GetCurSession(int sessionId)
987 {
988     std::shared_ptr<Session> curSession = nullptr;
989     // Get the remote deviceId, sink end gives sessionsMap[deviceId] = session;
990     {
991         std::lock_guard<std::mutex> lock(mapMutex_);
992         if (sessionsMap_.find(sessionId) != sessionsMap_.end()) {
993             curSession = sessionsMap_[sessionId];
994         } else {
995             LOGE("OnBytesReceived, The local session cannot be found.");
996         }
997     }
998     return curSession;
999 }
1000 
GetAuthMgrByMessage(int32_t msgType,uint64_t logicalSessionId,const JsonObject & jsonObject,std::shared_ptr<Session> curSession)1001 std::shared_ptr<AuthManagerBase> DeviceManagerServiceImpl::GetAuthMgrByMessage(int32_t msgType,
1002     uint64_t logicalSessionId, const JsonObject &jsonObject, std::shared_ptr<Session> curSession)
1003 {
1004     uint64_t tokenId = 0;
1005     if (msgType == MSG_TYPE_REQ_ACL_NEGOTIATE) {
1006         std::string bundleName;
1007         int32_t displayId = 0;
1008         if (jsonObject[TAG_PEER_BUNDLE_NAME_V2].IsString()) {
1009             bundleName = jsonObject[TAG_PEER_BUNDLE_NAME_V2].Get<std::string>();
1010         }
1011         if (jsonObject[DM_TAG_PEER_DISPLAY_ID].IsNumberInteger()) {
1012             displayId = jsonObject[DM_TAG_PEER_DISPLAY_ID].Get<int32_t>();
1013         }
1014         tokenId = GetTokenId(false, displayId, bundleName);
1015         if (tokenId == 0) {
1016             LOGE("GetAuthMgrByMessage, Get tokenId failed.");
1017             return nullptr;
1018         }
1019         if (InitAndRegisterAuthMgr(false, tokenId, curSession, logicalSessionId, "") != DM_OK) {
1020             return nullptr;
1021         }
1022         curSession->logicalSessionSet_.insert(logicalSessionId);
1023         std::lock_guard<std::mutex> tokenIdLock(logicalSessionId2TokenIdMapMtx_);
1024         if (logicalSessionId2TokenIdMap_.find(logicalSessionId) != logicalSessionId2TokenIdMap_.end()) {
1025             LOGE("GetAuthMgrByMessage, logicalSessionId exists in logicalSessionId2TokenIdMap_.");
1026             return nullptr;
1027         }
1028         logicalSessionId2TokenIdMap_[logicalSessionId] = tokenId;
1029     } else {
1030         if (curSession->logicalSessionSet_.find(logicalSessionId) == curSession->logicalSessionSet_.end()) {
1031             LOGE("GetAuthMgrByMessage, The logical session ID does not exist in the physical session.");
1032             return nullptr;
1033         }
1034         std::lock_guard<std::mutex> tokenIdLock(logicalSessionId2TokenIdMapMtx_);
1035         tokenId = logicalSessionId2TokenIdMap_[logicalSessionId];
1036     }
1037 
1038     return GetAuthMgrByTokenId(tokenId);
1039 }
1040 
GetLogicalIdAndTokenIdBySessionId(uint64_t & logicalSessionId,uint64_t & tokenId,int32_t sessionId)1041 int32_t DeviceManagerServiceImpl::GetLogicalIdAndTokenIdBySessionId(uint64_t &logicalSessionId,
1042     uint64_t &tokenId, int32_t sessionId)
1043 {
1044     std::lock_guard<std::mutex> sessionIdLock(logicalSessionId2SessionIdMapMtx_);
1045     for (auto& pair : logicalSessionId2SessionIdMap_) {
1046         if (pair.second == sessionId) {
1047             logicalSessionId = pair.first;
1048             std::lock_guard<std::mutex> tokenIdLock(logicalSessionId2TokenIdMapMtx_);
1049             tokenId = logicalSessionId2TokenIdMap_[logicalSessionId];
1050         }
1051     }
1052     if (logicalSessionId == 0 || tokenId == 0) {
1053         LOGE("can not find logicalSessionId and tokenId.");
1054         return ERR_DM_AUTH_FAILED;
1055     }
1056     return DM_OK;
1057 }
1058 
TransferSrcOldAuthMgr(std::shared_ptr<Session> curSession)1059 int32_t DeviceManagerServiceImpl::TransferSrcOldAuthMgr(std::shared_ptr<Session> curSession)
1060 {
1061     // New Old Receive 90, destroy new authMgr, create old authMgr, source side
1062     // The old protocol has only one session, reverse lookup logicalSessionId and tokenId
1063     CHECK_NULL_RETURN(curSession, ERR_DM_POINT_NULL);
1064     int sessionId = curSession->sessionId_;
1065     uint64_t logicalSessionId = 0;
1066     uint64_t tokenId = 0;
1067     int32_t ret = GetLogicalIdAndTokenIdBySessionId(logicalSessionId, tokenId, sessionId);
1068     if (ret != DM_OK) {
1069         LOGE("failed, logicalSessionId: %{public}" PRIu64 ", tokenId: %{public}s", logicalSessionId,
1070             GetAnonyInt32(tokenId).c_str());
1071         return ret;
1072     }
1073     std::string pkgName;
1074     PeerTargetId peerTargetId;
1075     std::map<std::string, std::string> bindParam;
1076     auto authMgr = GetAuthMgrByTokenId(tokenId);
1077     if (authMgr == nullptr) {
1078         LOGE("DeviceManagerServiceImpl::TransferSrcOldAuthMgr authManager is nullptr");
1079         return ERR_DM_POINT_NULL;
1080     }
1081     authMgr->GetBindTargetParams(pkgName, peerTargetId, bindParam);
1082     int32_t authType = -1;
1083     authMgr->ParseAuthType(bindParam, authType);
1084     ImportAuthCodeToConfig(authMgr, tokenId);
1085     EraseAuthMgr(tokenId);
1086     if (InitAndRegisterAuthMgr(true, tokenId, curSession, logicalSessionId, "") != DM_OK) {
1087         return ERR_DM_AUTH_FAILED;
1088     }
1089 
1090     ret = TransferByAuthType(authType, curSession, authMgr, bindParam, logicalSessionId);
1091     if (ret != DM_OK) {
1092         LOGE("DeviceManagerServiceImpl::TransferByAuthType TransferByAuthType failed.");
1093         return ret;
1094     }
1095     authMgr->DeleteTimer();
1096     authMgr = nullptr;
1097     if (authMgr_->BindTarget(pkgName, peerTargetId, bindParam, sessionId, 0) != DM_OK) {
1098         LOGE("DeviceManagerServiceImpl::TransferSrcOldAuthMgr authManager BindTarget failed");
1099         return ERR_DM_AUTH_FAILED;
1100     }
1101 
1102     if (authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) {
1103         int32_t sessionSide = GetSessionSide(curSession->sessionId_);
1104         authMgr_->OnSessionOpened(curSession->sessionId_, sessionSide, 0);
1105     }
1106 
1107     LOGI("src transfer to old version success");
1108     authMgr_->SetTransferReady(false);
1109     return DM_OK;
1110 }
1111 
TransferByAuthType(int32_t authType,std::shared_ptr<Session> curSession,std::shared_ptr<AuthManagerBase> authMgr,std::map<std::string,std::string> & bindParam,uint64_t logicalSessionId)1112 int32_t DeviceManagerServiceImpl::TransferByAuthType(int32_t authType,
1113     std::shared_ptr<Session> curSession, std::shared_ptr<AuthManagerBase> authMgr,
1114     std::map<std::string, std::string> &bindParam, uint64_t logicalSessionId)
1115 {
1116     int sessionId = curSession->sessionId_;
1117     if (authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) {
1118         authMgr_->EnableInsensibleSwitching();
1119         curSession->logicalSessionSet_.insert(0);
1120         {
1121             std::lock_guard<std::mutex> sessionIdLock(logicalSessionId2SessionIdMapMtx_);
1122             logicalSessionId2SessionIdMap_[0] = sessionId;
1123         }
1124         authMgr->OnSessionDisable();
1125     } else {
1126         authMgr_->DisableInsensibleSwitching();
1127         // send stop message
1128         // Cannot stop using the new protocol. The new protocol is a signal mechanism and cannot be stopped serially.
1129         // There will be a delay, causing new objects to be created before the stop is complete.
1130         // Then the timeout mechanism of the new protocol will stop SoftBus again.
1131         std::string endMessage = CreateTerminateMessage();
1132         CHECK_NULL_RETURN(softbusConnector_, ERR_DM_POINT_NULL);
1133         (void)softbusConnector_->GetSoftbusSession()->SendData(sessionId, endMessage);
1134         // Close new protocol session
1135         CleanAuthMgrByLogicalSessionId(logicalSessionId);
1136     }
1137     if (authType == ULTRASONIC_AUTHTYPE) {
1138         int32_t ret = ChangeUltrasonicTypeToPin(bindParam);
1139         if (ret != DM_OK) {
1140             LOGE("DeviceManagerServiceImpl::TransferSrcOldAuthMgr ChangeUltrasonicTypeToPin failed.");
1141             return ret;
1142         }
1143     }
1144     return DM_OK;
1145 }
1146 
ChangeUltrasonicTypeToPin(std::map<std::string,std::string> & bindParam)1147 int32_t DeviceManagerServiceImpl::ChangeUltrasonicTypeToPin(std::map<std::string, std::string> &bindParam)
1148 {
1149     auto iter = bindParam.find(PARAM_KEY_AUTH_TYPE);
1150     if (iter == bindParam.end()) {
1151         LOGE("DeviceManagerServiceImpl::ChangeUltrasonicTypeToPin bindParam:%{public}s not exist.",
1152             PARAM_KEY_AUTH_TYPE);
1153         return ERR_DM_AUTH_FAILED;
1154     }
1155     iter->second = CHANGE_PINTYPE;
1156     LOGI("bindParam:%{public}s PINTYPE.", PARAM_KEY_AUTH_TYPE);
1157     return DM_OK;
1158 }
1159 
TransferSinkOldAuthMgr(const JsonObject & jsonObject,std::shared_ptr<Session> curSession)1160 int32_t DeviceManagerServiceImpl::TransferSinkOldAuthMgr(const JsonObject &jsonObject,
1161     std::shared_ptr<Session> curSession)
1162 {
1163     // Old New Received 80, New Old authMgr, Sink End
1164     std::string bundleName;
1165     if (jsonObject[TAG_BUNDLE_NAME].IsString()) {
1166         bundleName = jsonObject[TAG_BUNDLE_NAME].Get<std::string>();
1167     } else if (jsonObject[TAG_PEER_BUNDLE_NAME].IsString()) {
1168         bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get<std::string>();
1169     } else if (jsonObject[TAG_HOST_PKGLABEL].IsString()) {
1170         bundleName = jsonObject[TAG_HOST_PKGLABEL].Get<std::string>();
1171     } else {
1172         LOGE("DeviceManagerServiceImpl::TransferSinkOldAuthMgr can not find bundleName.");
1173         return ERR_DM_AUTH_FAILED;
1174     }
1175     if (softbusConnector_ == nullptr) {
1176         LOGE("softbusConnector_ is nullpter!");
1177         return ERR_DM_AUTH_FAILED;
1178     }
1179     int32_t deviceType = softbusConnector_->GetLocalDeviceTypeId();
1180     if (deviceType == DmDeviceType::DEVICE_TYPE_WATCH &&
1181         BUNDLENAME_MAPPING.find(bundleName) != BUNDLENAME_MAPPING.end()) {
1182         bundleName = BUNDLENAME_MAPPING.find(bundleName)->second;
1183     }
1184     uint64_t tokenId = GetTokenId(false, -1, bundleName);
1185     if (InitAndRegisterAuthMgr(false, tokenId, curSession, 0, bundleName) != DM_OK) {
1186         // Internal error log printing completed
1187         return ERR_DM_AUTH_FAILED;
1188     }
1189 
1190     // Parameter 2 sessionSide is 0, authMgr_ is empty, it must be the sink end.
1191     // The src end will create the protocol object when BindTarget.
1192     authMgr_->OnSessionOpened(curSession->sessionId_, 0, 0);
1193     LOGI("sink transfer to old version success");
1194     authMgr_->SetTransferReady(false);
1195     return DM_OK;
1196 }
1197 
TransferOldAuthMgr(int32_t msgType,const JsonObject & jsonObject,std::shared_ptr<Session> curSession)1198 int32_t DeviceManagerServiceImpl::TransferOldAuthMgr(int32_t msgType, const JsonObject &jsonObject,
1199     std::shared_ptr<Session> curSession)
1200 {
1201     int ret = DM_OK;
1202     if ((authMgr_ == nullptr || authMgr_->IsTransferReady()) &&
1203         (msgType == MSG_TYPE_REQ_ACL_NEGOTIATE || msgType == MSG_TYPE_RESP_ACL_NEGOTIATE)) {
1204         if (IsMessageOldVersion(jsonObject, curSession)) {
1205             if (IsAuthManagerSourceByMessage(msgType)) {
1206                 ret = TransferSrcOldAuthMgr(curSession);
1207             } else {
1208                 ret = TransferSinkOldAuthMgr(jsonObject, curSession);
1209             }
1210         }
1211     }
1212 
1213     return ret;
1214 }
1215 
1216 
OnBytesReceived(int sessionId,const void * data,unsigned int dataLen)1217 void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, unsigned int dataLen)
1218 {
1219     if (sessionId < 0 || data == nullptr || dataLen <= 0 || dataLen > MAX_DATA_LEN) {
1220         LOGE("[OnBytesReceived] Fail to receive data from softbus with sessionId: %{public}d, dataLen: %{public}d.",
1221             sessionId, dataLen);
1222         return;
1223     }
1224 
1225     LOGI("start, sessionId: %{public}d, dataLen: %{public}d.", sessionId, dataLen);
1226 
1227     JsonObject jsonObject = GetJsonObjectFromData(data, dataLen);
1228     if (jsonObject.IsDiscarded() || !IsInt32(jsonObject, TAG_MSG_TYPE)) {
1229         LOGE("OnBytesReceived, MSG_TYPE parse failed.");
1230         return;
1231     }
1232     int32_t msgType = jsonObject[TAG_MSG_TYPE].Get<int32_t>();
1233     uint64_t logicalSessionId = 0;
1234     if (IsUint64(jsonObject, DM_TAG_LOGICAL_SESSION_ID)) {
1235         logicalSessionId = jsonObject[DM_TAG_LOGICAL_SESSION_ID].Get<std::uint64_t>();
1236     }
1237 
1238     std::shared_ptr<Session> curSession = GetCurSession(sessionId);
1239     if (curSession == nullptr) {
1240         LOGE("InitAndRegisterAuthMgr, The physical link is not created.");
1241         return;
1242     }
1243 
1244     std::shared_ptr<AuthManagerBase> authMgr = nullptr;
1245     if  (logicalSessionId != 0) {
1246         authMgr = GetAuthMgrByMessage(msgType, logicalSessionId, jsonObject, curSession);
1247         if (authMgr == nullptr) {
1248             return;
1249         }
1250         if (msgType == MSG_TYPE_REQ_ACL_NEGOTIATE || msgType == MSG_TYPE_RESP_ACL_NEGOTIATE) {
1251             curSession->version_ = DM_CURRENT_VERSION;
1252         }
1253     } else {
1254         /**
1255         Monitor old messages on ports 80/90
1256         1. New-to-old: When the src side receives a 90 message and detects a version mismatch, it receives
1257         the 90 message, destroys the current new authMgr, creates a new old protocol authMgr, and re-BindTarget.
1258         2. Old-to-new: When the sink side receives an 80 message and detects a version mismatch, it receives the 80
1259         message, directly creates a new old protocol authMgr, and re-OnSessionOpened and OnBytesReceived.
1260         */
1261         if (curSession->version_ == "") {
1262             if (TransferOldAuthMgr(msgType, jsonObject, curSession) != DM_OK) {
1263                 LOGE("DeviceManagerServiceImpl::OnBytesReceived TransferOldAuthMgr failed");
1264                 return;
1265             }
1266         } else {
1267             LOGI("Reuse Old AuthMgr, sessionId: %{public}d.", sessionId);
1268         }
1269         authMgr = authMgr_;
1270     }
1271 
1272     std::string message = std::string(reinterpret_cast<const char *>(data), dataLen);
1273     if (msgType == AUTH_DEVICE_REQ_NEGOTIATE || msgType == AUTH_DEVICE_RESP_NEGOTIATE) {
1274         authMgr->OnAuthDeviceDataReceived(sessionId, message);
1275     } else {
1276         authMgr->OnDataReceived(sessionId, message);
1277     }
1278     return;
1279 }
1280 
RequestCredential(const std::string & reqJsonStr,std::string & returnJsonStr)1281 int32_t DeviceManagerServiceImpl::RequestCredential(const std::string &reqJsonStr, std::string &returnJsonStr)
1282 {
1283     if (reqJsonStr.empty()) {
1284         LOGE("reqJsonStr is empty");
1285         return ERR_DM_INPUT_PARA_INVALID;
1286     }
1287     if (credentialMgr_== nullptr) {
1288         LOGE("credentialMgr_ is nullptr");
1289         return ERR_DM_POINT_NULL;
1290     }
1291     return credentialMgr_->RequestCredential(reqJsonStr, returnJsonStr);
1292 }
1293 
ImportCredential(const std::string & pkgName,const std::string & credentialInfo)1294 int32_t DeviceManagerServiceImpl::ImportCredential(const std::string &pkgName, const std::string &credentialInfo)
1295 {
1296     if (pkgName.empty() || credentialInfo.empty()) {
1297         LOGE("DeviceManagerServiceImpl::ImportCredential failed, pkgName is %{public}s, credentialInfo is %{public}s",
1298             pkgName.c_str(), GetAnonyString(credentialInfo).c_str());
1299         return ERR_DM_INPUT_PARA_INVALID;
1300     }
1301     if (credentialMgr_== nullptr) {
1302         LOGE("credentialMgr_ is nullptr");
1303         return ERR_DM_POINT_NULL;
1304     }
1305     isCredentialType_.store(true);
1306     return credentialMgr_->ImportCredential(pkgName, credentialInfo);
1307 }
1308 
DeleteCredential(const std::string & pkgName,const std::string & deleteInfo)1309 int32_t DeviceManagerServiceImpl::DeleteCredential(const std::string &pkgName, const std::string &deleteInfo)
1310 {
1311     if (pkgName.empty() || deleteInfo.empty()) {
1312         LOGE("DeviceManagerServiceImpl::DeleteCredential failed, pkgName is %{public}s, deleteInfo is %{public}s",
1313             pkgName.c_str(), GetAnonyString(deleteInfo).c_str());
1314         return ERR_DM_INPUT_PARA_INVALID;
1315     }
1316     if (credentialMgr_== nullptr) {
1317         LOGE("credentialMgr_ is nullptr");
1318         return ERR_DM_POINT_NULL;
1319     }
1320     isCredentialType_.store(false);
1321     return credentialMgr_->DeleteCredential(pkgName, deleteInfo);
1322 }
1323 
MineRequestCredential(const std::string & pkgName,std::string & returnJsonStr)1324 int32_t DeviceManagerServiceImpl::MineRequestCredential(const std::string &pkgName, std::string &returnJsonStr)
1325 {
1326     (void)pkgName;
1327     if (mineHiChainConnector_->RequestCredential(returnJsonStr) != DM_OK) {
1328         LOGE("failed to get device credential from hichain");
1329         return ERR_DM_HICHAIN_CREDENTIAL_REQUEST_FAILED;
1330     }
1331     return DM_OK;
1332 }
1333 
CheckCredential(const std::string & pkgName,const std::string & reqJsonStr,std::string & returnJsonStr)1334 int32_t DeviceManagerServiceImpl::CheckCredential(const std::string &pkgName, const std::string &reqJsonStr,
1335     std::string &returnJsonStr)
1336 {
1337     (void)pkgName;
1338     if (reqJsonStr.empty()) {
1339         LOGE("reqJsonStr is empty");
1340         return ERR_DM_INPUT_PARA_INVALID;
1341     }
1342     if (mineHiChainConnector_->CheckCredential(reqJsonStr, returnJsonStr) != DM_OK) {
1343         LOGE("failed to check devices credential status");
1344         return ERR_DM_HICHAIN_CREDENTIAL_CHECK_FAILED;
1345     }
1346     return DM_OK;
1347 }
1348 
ImportCredential(const std::string & pkgName,const std::string & reqJsonStr,std::string & returnJsonStr)1349 int32_t DeviceManagerServiceImpl::ImportCredential(const std::string &pkgName, const std::string &reqJsonStr,
1350     std::string &returnJsonStr)
1351 {
1352     (void)pkgName;
1353     if (reqJsonStr.empty()) {
1354         LOGE("reqJsonStr is empty");
1355         return ERR_DM_INPUT_PARA_INVALID;
1356     }
1357     if (mineHiChainConnector_->ImportCredential(reqJsonStr, returnJsonStr) != DM_OK) {
1358         LOGE("failed to import devices credential");
1359         return ERR_DM_HICHAIN_CREDENTIAL_IMPORT_FAILED;
1360     }
1361     isCredentialType_.store(true);
1362     return DM_OK;
1363 }
1364 
DeleteCredential(const std::string & pkgName,const std::string & reqJsonStr,std::string & returnJsonStr)1365 int32_t DeviceManagerServiceImpl::DeleteCredential(const std::string &pkgName, const std::string &reqJsonStr,
1366     std::string &returnJsonStr)
1367 {
1368     (void)pkgName;
1369     if (reqJsonStr.empty()) {
1370         LOGE("reqJsonStr is empty");
1371         return ERR_DM_INPUT_PARA_INVALID;
1372     }
1373     if (mineHiChainConnector_->DeleteCredential(reqJsonStr, returnJsonStr) != DM_OK) {
1374         LOGE("failed to delete devices credential");
1375         return ERR_DM_HICHAIN_CREDENTIAL_DELETE_FAILED;
1376     }
1377     isCredentialType_.store(false);
1378     return DM_OK;
1379 }
1380 
RegisterCredentialCallback(const std::string & pkgName)1381 int32_t DeviceManagerServiceImpl::RegisterCredentialCallback(const std::string &pkgName)
1382 {
1383     if (pkgName.empty()) {
1384         LOGE("RegisterCredentialCallback failed, pkgName is empty");
1385         return ERR_DM_INPUT_PARA_INVALID;
1386     }
1387     if (credentialMgr_ == nullptr) {
1388         LOGE("credentialMgr_ is nullptr");
1389         return ERR_DM_POINT_NULL;
1390     }
1391     return credentialMgr_->RegisterCredentialCallback(pkgName);
1392 }
1393 
UnRegisterCredentialCallback(const std::string & pkgName)1394 int32_t DeviceManagerServiceImpl::UnRegisterCredentialCallback(const std::string &pkgName)
1395 {
1396     if (pkgName.empty()) {
1397         LOGE("UnRegisterCredentialCallback failed, pkgName is empty");
1398         return ERR_DM_INPUT_PARA_INVALID;
1399     }
1400     if (credentialMgr_== nullptr) {
1401         LOGE("credentialMgr_ is nullptr");
1402         return ERR_DM_POINT_NULL;
1403     }
1404     return credentialMgr_->UnRegisterCredentialCallback(pkgName);
1405 }
1406 
RegisterUiStateCallback(const std::string & pkgName)1407 int32_t DeviceManagerServiceImpl::RegisterUiStateCallback(const std::string &pkgName)
1408 {
1409     if (pkgName.empty()) {
1410         LOGE("RegisterUiStateCallback failed, pkgName is empty");
1411         return ERR_DM_INPUT_PARA_INVALID;
1412     }
1413     auto authMgr = GetCurrentAuthMgr();
1414     if (authMgr == nullptr) {
1415         LOGE("authMgr is nullptr");
1416         return ERR_DM_POINT_NULL;
1417     }
1418     return authMgr->RegisterUiStateCallback(pkgName);
1419 }
1420 
UnRegisterUiStateCallback(const std::string & pkgName)1421 int32_t DeviceManagerServiceImpl::UnRegisterUiStateCallback(const std::string &pkgName)
1422 {
1423     if (pkgName.empty()) {
1424         LOGE("UnRegisterUiStateCallback failed, pkgName is empty");
1425         return ERR_DM_INPUT_PARA_INVALID;
1426     }
1427     auto authMgr = GetCurrentAuthMgr();
1428     if (authMgr == nullptr) {
1429         LOGE("authMgr is nullptr");
1430         return ERR_DM_POINT_NULL;
1431     }
1432     return authMgr->UnRegisterUiStateCallback(pkgName);
1433 }
1434 
PraseNotifyEventJson(const std::string & event,JsonObject & jsonObject)1435 int32_t DeviceManagerServiceImpl::PraseNotifyEventJson(const std::string &event, JsonObject &jsonObject)
1436 {
1437     jsonObject.Parse(event);
1438     if (jsonObject.IsDiscarded()) {
1439         LOGE("event prase error.");
1440         return ERR_DM_FAILED;
1441     }
1442     if ((!jsonObject.Contains("extra")) || (!jsonObject["extra"].IsObject())) {
1443         LOGE("extra error");
1444         return ERR_DM_FAILED;
1445     }
1446     if ((!jsonObject["extra"].Contains("deviceId")) || (!jsonObject["extra"]["deviceId"].IsString())) {
1447         LOGE("NotifyEvent deviceId invalid");
1448         return ERR_DM_FAILED;
1449     }
1450     return DM_OK;
1451 }
1452 
NotifyEvent(const std::string & pkgName,const int32_t eventId,const std::string & event)1453 int32_t DeviceManagerServiceImpl::NotifyEvent(const std::string &pkgName, const int32_t eventId,
1454     const std::string &event)
1455 {
1456     LOGI("NotifyEvent begin, pkgName : %{public}s, eventId : %{public}d", pkgName.c_str(), eventId);
1457     if ((eventId <= DM_NOTIFY_EVENT_START) || (eventId >= DM_NOTIFY_EVENT_BUTT)) {
1458         LOGE("NotifyEvent eventId invalid");
1459         return ERR_DM_INPUT_PARA_INVALID;
1460     }
1461     if (eventId == DM_NOTIFY_EVENT_ONDEVICEREADY) {
1462         JsonObject jsonObject;
1463         if (PraseNotifyEventJson(event, jsonObject) != DM_OK) {
1464             LOGE("NotifyEvent json invalid");
1465             return ERR_DM_INPUT_PARA_INVALID;
1466         }
1467         std::string deviceId;
1468         jsonObject["extra"]["deviceId"].GetTo(deviceId);
1469         if (deviceStateMgr_== nullptr) {
1470             LOGE("deviceStateMgr_ is nullptr");
1471             return ERR_DM_POINT_NULL;
1472         }
1473         if (deviceStateMgr_->ProcNotifyEvent(eventId, deviceId) != DM_OK) {
1474             LOGE("NotifyEvent failed");
1475             return ERR_DM_INPUT_PARA_INVALID;
1476         };
1477     }
1478     return DM_OK;
1479 }
1480 
GetGroupType(std::vector<DmDeviceInfo> & deviceList)1481 int32_t DeviceManagerServiceImpl::GetGroupType(std::vector<DmDeviceInfo> &deviceList)
1482 {
1483     LOGI("begin");
1484     if (softbusConnector_ == nullptr || hiChainConnector_ == nullptr) {
1485         LOGE("softbusConnector_ or hiChainConnector_ is nullptr");
1486         return ERR_DM_POINT_NULL;
1487     }
1488 
1489     for (auto it = deviceList.begin(); it != deviceList.end(); ++it) {
1490         std::string udid = "";
1491         int32_t ret = softbusConnector_->GetUdidByNetworkId(it->networkId, udid);
1492         if (ret != DM_OK) {
1493             LOGE("GetUdidByNetworkId failed ret: %{public}d", ret);
1494             return ret;
1495         }
1496         std::string deviceId = softbusConnector_->GetDeviceUdidHashByUdid(udid);
1497         if (memcpy_s(it->deviceId, DM_MAX_DEVICE_ID_LEN, deviceId.c_str(), deviceId.length()) != 0) {
1498             LOGE("get deviceId: %{public}s failed", GetAnonyString(deviceId).c_str());
1499             return ERR_DM_SECURITY_FUNC_FAILED;
1500         }
1501         it->authForm = hiChainConnector_->GetGroupType(udid);
1502     }
1503     return DM_OK;
1504 }
1505 
GetUdidHashByNetWorkId(const char * networkId,std::string & deviceId)1506 int32_t DeviceManagerServiceImpl::GetUdidHashByNetWorkId(const char *networkId, std::string &deviceId)
1507 {
1508     if (softbusConnector_ == nullptr || hiChainConnector_ == nullptr) {
1509         LOGE("softbusConnector_ or hiChainConnector_ is nullptr");
1510         return ERR_DM_POINT_NULL;
1511     }
1512     std::string udid = "";
1513     int32_t ret = softbusConnector_->GetUdidByNetworkId(networkId, udid);
1514     if (ret != DM_OK) {
1515         LOGE("GetUdidByNetworkId failed ret: %{public}d", ret);
1516         return ret;
1517     }
1518     deviceId = softbusConnector_->GetDeviceUdidHashByUdid(udid);
1519     return DM_OK;
1520 }
1521 
GetConfigByTokenId()1522 std::shared_ptr<Config> DeviceManagerServiceImpl::GetConfigByTokenId()
1523 {
1524     uint64_t tokenId = IPCSkeleton::GetCallingTokenID();
1525     std::lock_guard<std::mutex> configsLock(configsMapMutex_);
1526     if (configsMap_.find(tokenId) == configsMap_.end()) {
1527         configsMap_[tokenId] = std::make_shared<Config>();
1528     }
1529     return configsMap_[tokenId];
1530 }
1531 
ImportAuthCode(const std::string & pkgName,const std::string & authCode)1532 int32_t DeviceManagerServiceImpl::ImportAuthCode(const std::string &pkgName, const std::string &authCode)
1533 {
1534     if (pkgName.empty() || authCode.empty()) {
1535         LOGE("ImportAuthCode failed, pkgName or authCode is empty");
1536         return ERR_DM_INPUT_PARA_INVALID;
1537     }
1538 
1539     LOGI("pkgName is %{public}s, authCode is %{public}s",
1540         pkgName.c_str(), GetAnonyString(authCode).c_str());
1541     auto authMgr = GetAuthMgr();
1542     if (authMgr != nullptr) {
1543         authMgr->ImportAuthCode(pkgName, authCode);
1544     }
1545     auto config = GetConfigByTokenId();
1546     config->pkgName = pkgName;
1547     config->authCode = authCode;   // If registered multiple times, only the last one is kept
1548     return DM_OK;
1549 }
1550 
ExportAuthCode(std::string & authCode)1551 int32_t DeviceManagerServiceImpl::ExportAuthCode(std::string &authCode)
1552 {
1553     int32_t ret = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE);
1554     authCode = std::to_string(ret);
1555     LOGI("ExportAuthCode success, authCode: %{public}s.", GetAnonyString(authCode).c_str());
1556     return DM_OK;
1557 }
1558 
GetExtraJsonObject(const std::map<std::string,std::string> & bindParam)1559 static JsonObject GetExtraJsonObject(const std::map<std::string, std::string> &bindParam)
1560 {
1561     std::string extra;
1562     auto iter = bindParam.find(PARAM_KEY_BIND_EXTRA_DATA);
1563     if (iter != bindParam.end()) {
1564         extra = iter->second;
1565     } else {
1566         extra = ConvertMapToJsonString(bindParam);
1567     }
1568 
1569     return JsonObject(extra);
1570 }
1571 
GetHmlInfo(const JsonObject & jsonObject,bool & hmlEnable160M,int32_t & hmlActionId)1572 static int32_t GetHmlInfo(const JsonObject &jsonObject, bool &hmlEnable160M, int32_t &hmlActionId)
1573 {
1574     if (jsonObject[PARAM_KEY_HML_ENABLE_160M].IsBoolean()) {
1575         hmlEnable160M = jsonObject[PARAM_KEY_HML_ENABLE_160M].Get<bool>();
1576         LOGI("hmlEnable160M %{public}d", hmlEnable160M);
1577     }
1578     if (!IsString(jsonObject, PARAM_KEY_HML_ACTIONID)) {
1579         LOGE("PARAM_KEY_HML_ACTIONID is not string");
1580         return ERR_DM_INPUT_PARA_INVALID;
1581     }
1582     std::string actionIdStr = jsonObject[PARAM_KEY_HML_ACTIONID].Get<std::string>();
1583     if (!IsNumberString(actionIdStr)) {
1584         LOGE("PARAM_KEY_HML_ACTIONID is not number");
1585         return ERR_DM_INPUT_PARA_INVALID;
1586     }
1587     int32_t actionId = std::atoi(actionIdStr.c_str());
1588     if (actionId <= 0) {
1589         LOGE("PARAM_KEY_HML_ACTIONID is <= 0");
1590         return ERR_DM_INPUT_PARA_INVALID;
1591     }
1592     hmlActionId = actionId;
1593     return DM_OK;
1594 }
1595 
IsHmlSessionType(const JsonObject & jsonObject)1596 static bool IsHmlSessionType(const JsonObject &jsonObject)
1597 {
1598     std::string connSessionType;
1599     if (jsonObject[PARAM_KEY_CONN_SESSIONTYPE].IsString()) {
1600         connSessionType = jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get<std::string>();
1601         LOGI("connSessionType %{public}s", connSessionType.c_str());
1602     }
1603     return connSessionType == CONN_SESSION_TYPE_HML;
1604 }
1605 
OpenAuthSession(const std::string & deviceId,const std::map<std::string,std::string> & bindParam)1606 int DeviceManagerServiceImpl::OpenAuthSession(const std::string& deviceId,
1607     const std::map<std::string, std::string> &bindParam)
1608 {
1609     bool hmlEnable160M = false;
1610     int32_t hmlActionId = 0;
1611     int invalidSessionId = -1;
1612     JsonObject jsonObject = GetExtraJsonObject(bindParam);
1613     if (jsonObject.IsDiscarded()) {
1614         LOGE("extra string not a json type.");
1615         return invalidSessionId;
1616     }
1617     if (softbusConnector_ == nullptr) {
1618         return invalidSessionId;
1619     }
1620     if (IsHmlSessionType(jsonObject)) {
1621         auto ret = GetHmlInfo(jsonObject, hmlEnable160M, hmlActionId);
1622         if (ret != DM_OK) {
1623             LOGE("OpenAuthSession failed, GetHmlInfo failed.");
1624             return ret;
1625         }
1626         LOGI("hmlActionId %{public}d, hmlEnable160M %{public}d", hmlActionId, hmlEnable160M);
1627         CHECK_NULL_RETURN(listener_, ERR_DM_FAILED);
1628         return listener_->OpenAuthSessionWithPara(deviceId, hmlActionId, hmlEnable160M);
1629     } else {
1630         return softbusConnector_->GetSoftbusSession()->OpenAuthSession(deviceId);
1631     }
1632 }
1633 
GetOrCreateSession(const std::string & deviceId,const std::map<std::string,std::string> & bindParam,uint64_t tokenId)1634 std::shared_ptr<Session> DeviceManagerServiceImpl::GetOrCreateSession(const std::string& deviceId,
1635     const std::map<std::string, std::string> &bindParam, uint64_t tokenId)
1636 {
1637     std::shared_ptr<Session> instance;
1638     int sessionId = -1;
1639 
1640     // Check again whether the corresponding object already exists (because other threads may have created it during
1641     //  the lock acquisition in the previous step)
1642 
1643     std::lock_guard<std::mutex> lock(mapMutex_);
1644     if (deviceId2SessionIdMap_.find(deviceId) != deviceId2SessionIdMap_.end()) {
1645         sessionId = deviceId2SessionIdMap_[deviceId];
1646     }
1647     if (sessionsMap_.find(sessionId) != sessionsMap_.end()) {
1648         return sessionsMap_[sessionId];
1649     }
1650 
1651     sessionId = OpenAuthSession(deviceId, bindParam);
1652     if (sessionId < 0) {
1653         LOGE("OpenAuthSession failed, stop the authentication");
1654         return nullptr;
1655     }
1656 
1657     {
1658         std::lock_guard<std::mutex> lock(tokenIdSessionIdMapMtx_);
1659         tokenIdSessionIdMap_[tokenId] = sessionId;
1660     }
1661 
1662     std::unique_lock<std::mutex> cvLock(sessionEnableMutexMap_[sessionId]);
1663     sessionEnableCvReadyMap_[sessionId] = false;
1664     sessionStopMap_[sessionId] = false;
1665     sessionEnableMap_[sessionId] = false;
1666     if (!sessionEnableCvMap_[sessionId].wait_for(cvLock, std::chrono::milliseconds(OPEN_AUTH_SESSION_TIMEOUT),
1667         [&] { return sessionEnableCvReadyMap_[sessionId]; })) {
1668         LOGE("wait session enable timeout or enable fail, sessionId: %{public}d.", sessionId);
1669         return nullptr;
1670     }
1671     if (sessionStopMap_.find(sessionId) != sessionStopMap_.end() && sessionStopMap_[sessionId]) {
1672         LOGW("stop by caller, sessionId: %{public}d.", sessionId);
1673         return nullptr;
1674     }
1675     if (sessionEnableMap_.find(sessionId) != sessionEnableMap_.end() && !sessionEnableMap_[sessionId]) {
1676         LOGW("Open session failed, sessionId: %{public}d.", sessionId);
1677         return nullptr;
1678     }
1679     instance = std::make_shared<Session>(sessionId, deviceId);
1680     deviceId2SessionIdMap_[deviceId] = sessionId;
1681     sessionsMap_[sessionId] = instance;
1682 
1683     return instance;
1684 }
1685 
GetDeviceInfo(const PeerTargetId & targetId,std::string & addrType,std::string & deviceId,std::shared_ptr<DeviceInfo> deviceInfo,int32_t & index)1686 int32_t DeviceManagerServiceImpl::GetDeviceInfo(const PeerTargetId &targetId, std::string &addrType,
1687     std::string &deviceId, std::shared_ptr<DeviceInfo> deviceInfo, int32_t &index)
1688 {
1689     ConnectionAddr addr;
1690     if (!targetId.wifiIp.empty() && targetId.wifiIp.length() <= IP_STR_MAX_LEN) {
1691         LOGI("parse wifiIp: %{public}s.", GetAnonyString(targetId.wifiIp).c_str());
1692         if (!addrType.empty()) {
1693             addr.type = static_cast<ConnectionAddrType>(std::atoi(addrType.c_str()));
1694         } else {
1695             addr.type = ConnectionAddrType::CONNECTION_ADDR_WLAN;
1696         }
1697         if (memcpy_s(addr.info.ip.ip, IP_STR_MAX_LEN, targetId.wifiIp.c_str(), targetId.wifiIp.length()) != 0) {
1698             LOGE("get ip addr: %{public}s failed", GetAnonyString(targetId.wifiIp).c_str());
1699             return ERR_DM_SECURITY_FUNC_FAILED;
1700         }
1701         addr.info.ip.port = targetId.wifiPort;
1702         deviceInfo->addr[index] = addr;
1703         deviceId = targetId.wifiIp;
1704         index++;
1705     } else if (!targetId.brMac.empty() && targetId.brMac.length() <= BT_MAC_LEN) {
1706         LOGI("parse brMac: %{public}s.", GetAnonyString(targetId.brMac).c_str());
1707         addr.type = ConnectionAddrType::CONNECTION_ADDR_BR;
1708         if (memcpy_s(addr.info.br.brMac, BT_MAC_LEN, targetId.brMac.c_str(), targetId.brMac.length()) != 0) {
1709             LOGE("get brMac addr: %{public}s failed", GetAnonyString(targetId.brMac).c_str());
1710             return ERR_DM_SECURITY_FUNC_FAILED;
1711         }
1712         deviceInfo->addr[index] = addr;
1713         deviceId = targetId.brMac;
1714         index++;
1715     } else if (!targetId.bleMac.empty() && targetId.bleMac.length() <= BT_MAC_LEN) {
1716         LOGI("parse bleMac: %{public}s.", GetAnonyString(targetId.bleMac).c_str());
1717         addr.type = ConnectionAddrType::CONNECTION_ADDR_BLE;
1718         if (memcpy_s(addr.info.ble.bleMac, BT_MAC_LEN, targetId.bleMac.c_str(), targetId.bleMac.length()) != 0) {
1719             LOGE("get bleMac addr: %{public}s failed", GetAnonyString(targetId.bleMac).c_str());
1720             return ERR_DM_SECURITY_FUNC_FAILED;
1721         }
1722         if (!targetId.deviceId.empty()) {
1723             Crypto::ConvertHexStringToBytes(addr.info.ble.udidHash, UDID_HASH_LEN,
1724                 targetId.deviceId.c_str(), targetId.deviceId.length());
1725         }
1726         deviceInfo->addr[index] = addr;
1727         deviceId = targetId.bleMac;
1728         index++;
1729     } else {
1730         LOGE("DeviceManagerServiceImpl::GetDeviceInfo failed, not addr.");
1731         return ERR_DM_INPUT_PARA_INVALID;
1732     }
1733     return DM_OK;
1734 }
1735 
IsAuthNewVersion(int32_t bindLevel,std::string localUdid,std::string remoteUdid,int32_t tokenId,int32_t userId)1736 bool DeviceManagerServiceImpl::IsAuthNewVersion(int32_t bindLevel, std::string localUdid, std::string remoteUdid,
1737     int32_t tokenId, int32_t userId)
1738 {
1739     std::string extraInfo = DeviceProfileConnector::GetInstance().IsAuthNewVersion(
1740         bindLevel, localUdid, remoteUdid, tokenId, userId);
1741     JsonObject extraInfoJson(extraInfo);
1742     if (extraInfoJson.IsDiscarded()) {
1743         LOGE("IsAuthNewVersion extraInfoJson error");
1744         return false;
1745     }
1746     if (!extraInfoJson[TAG_DMVERSION].IsString()) {
1747         LOGE("IsAuthNewVersion PARAM_KEY_OS_VERSION error");
1748         return false;
1749     }
1750     std::string dmVersion = extraInfoJson[TAG_DMVERSION].Get<std::string>();
1751     if (CompareVersion(dmVersion, std::string(DM_VERSION_5_1_0)) || dmVersion == std::string(DM_VERSION_5_1_0)) {
1752         return true;
1753     }
1754     return false;
1755 }
1756 
ParseConnectAddr(const PeerTargetId & targetId,std::string & deviceId,const std::map<std::string,std::string> & bindParam)1757 int32_t DeviceManagerServiceImpl::ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId,
1758     const std::map<std::string, std::string> &bindParam)
1759 {
1760     std::string addrType;
1761     if (bindParam.count(PARAM_KEY_CONN_ADDR_TYPE) != 0) {
1762         addrType = bindParam.at(PARAM_KEY_CONN_ADDR_TYPE);
1763     }
1764     std::string isNeedJoinLnnStr;
1765     if (bindParam.find(IS_NEED_JOIN_LNN) != bindParam.end()) {
1766         isNeedJoinLnnStr = bindParam.at(IS_NEED_JOIN_LNN);
1767     }
1768     LOGI("isNeedJoinLnnStr: %{public}s.", isNeedJoinLnnStr.c_str());
1769     {
1770         std::lock_guard<std::mutex> lock(isNeedJoinLnnMtx_);
1771         if (isNeedJoinLnnStr == NEED_JOIN_LNN || isNeedJoinLnnStr == NO_NEED_JOIN_LNN) {
1772             isNeedJoinLnn_ = std::atoi(isNeedJoinLnnStr.c_str());
1773         }
1774     }
1775     std::shared_ptr<DeviceInfo> deviceInfo = std::make_shared<DeviceInfo>();
1776     int32_t index = 0;
1777     int32_t ret = GetDeviceInfo(targetId, addrType, deviceId, deviceInfo, index);
1778     if (ret != DM_OK) {
1779         LOGE("GetDeviceInfo failed, ret: %{public}d", ret);
1780     }
1781     deviceInfo->addrNum = static_cast<uint32_t>(index);
1782     if (softbusConnector_->AddMemberToDiscoverMap(deviceId, deviceInfo) != DM_OK) {
1783         LOGE("DeviceManagerServiceImpl::ParseConnectAddr failed, AddMemberToDiscoverMap failed.");
1784         return ERR_DM_INPUT_PARA_INVALID;
1785     }
1786     deviceInfo = nullptr;
1787     return DM_OK;
1788 }
1789 
SaveTokenIdAndSessionId(uint64_t & tokenId,int32_t & sessionId,uint64_t & logicalSessionId)1790 void DeviceManagerServiceImpl::SaveTokenIdAndSessionId(uint64_t &tokenId,
1791     int32_t &sessionId, uint64_t &logicalSessionId)
1792 {
1793     {
1794         std::lock_guard<std::mutex> tokenIdLock(logicalSessionId2TokenIdMapMtx_);
1795         logicalSessionId2TokenIdMap_[logicalSessionId] = tokenId;
1796     }
1797     {
1798         std::lock_guard<std::mutex> sessionIdLock(logicalSessionId2SessionIdMapMtx_);
1799         logicalSessionId2SessionIdMap_[logicalSessionId] = sessionId;
1800     }
1801 }
1802 
ParseConnectAddrAndSetProcessInfo(PeerTargetId & targetId,const std::map<std::string,std::string> & bindParam,ProcessInfo & processInfo,const std::string & pkgName,uint64_t tokenId)1803 bool DeviceManagerServiceImpl::ParseConnectAddrAndSetProcessInfo(PeerTargetId &targetId,
1804     const std::map<std::string, std::string> &bindParam, ProcessInfo &processInfo,
1805     const std::string &pkgName, uint64_t tokenId)
1806 {
1807     processInfo.pkgName = pkgName;
1808     if (bindParam.count(BIND_CALLER_USERID) != 0) {
1809         processInfo.userId = std::atoi(bindParam.at(BIND_CALLER_USERID).c_str());
1810     }
1811     std::string deviceId = "";
1812     if (ParseConnectAddr(targetId, deviceId, bindParam) == DM_OK) {
1813         targetId.deviceId = deviceId;
1814     } else {
1815         if (targetId.deviceId.empty()) {
1816             LOGE("DeviceManagerServiceImpl::BindTarget failed, ParseConnectAddr failed.");
1817             OnAuthResultAndOnBindResult(processInfo, targetId, "", ERR_DM_INPUT_PARA_INVALID, tokenId);
1818             return false;
1819         }
1820     }
1821     return true;
1822 }
1823 
OnAuthResultAndOnBindResult(const ProcessInfo & processInfo,const PeerTargetId & targetId,const std::string & deviceId,int32_t reason,uint64_t tokenId)1824 void DeviceManagerServiceImpl::OnAuthResultAndOnBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId,
1825     const std::string &deviceId, int32_t reason, uint64_t tokenId)
1826 {
1827     {
1828         std::lock_guard<std::mutex> lock(tokenIdSessionIdMapMtx_);
1829         auto iter = tokenIdSessionIdMap_.find(tokenId);
1830         if (iter != tokenIdSessionIdMap_.end()) {
1831             tokenIdSessionIdMap_.erase(iter);
1832         }
1833     }
1834     CHECK_NULL_VOID(listener_);
1835     listener_->OnAuthResult(processInfo, deviceId, "", DmAuthStatus::STATUS_DM_AUTH_DEFAULT, reason);
1836     listener_->OnBindResult(processInfo, targetId, reason, DmAuthStatus::STATUS_DM_AUTH_DEFAULT, "");
1837 }
1838 
BindTargetImpl(uint64_t tokenId,const std::string & pkgName,const PeerTargetId & targetId,const std::map<std::string,std::string> & bindParam)1839 void DeviceManagerServiceImpl::BindTargetImpl(uint64_t tokenId, const std::string &pkgName,
1840     const PeerTargetId &targetId, const std::map<std::string, std::string> &bindParam)
1841 {
1842     PeerTargetId targetIdTmp = const_cast<PeerTargetId&>(targetId);
1843     ProcessInfo processInfo;
1844     if (!ParseConnectAddrAndSetProcessInfo(targetIdTmp, bindParam, processInfo, pkgName, tokenId)) {
1845         return;
1846     }
1847     // Created only at the source end. The same target device will not be created repeatedly with the new protocol.
1848     std::shared_ptr<Session> curSession = GetOrCreateSession(targetIdTmp.deviceId, bindParam, tokenId);
1849     if (curSession == nullptr) {
1850         LOGE("create session failed. Target deviceId: %{public}s.", GetAnonyString(targetIdTmp.deviceId).c_str());
1851         OnAuthResultAndOnBindResult(processInfo, targetId, targetIdTmp.deviceId, ERR_DM_TIME_OUT, tokenId);
1852         return;
1853     }
1854 
1855     // Logical session random number
1856     int sessionId = curSession->sessionId_;
1857     uint64_t logicalSessionId = 0;
1858     if (curSession->version_ == "" || CompareVersion(curSession->version_, DM_VERSION_5_0_OLD_MAX)) {
1859         logicalSessionId = GenerateRandNum(sessionId);
1860         if (curSession->logicalSessionSet_.find(logicalSessionId) != curSession->logicalSessionSet_.end()) {
1861             LOGE("Failed to create the logical session.");
1862             CleanSessionMap(sessionId);
1863             OnAuthResultAndOnBindResult(processInfo, targetId, targetIdTmp.deviceId,
1864                 ERR_DM_INPUT_PARA_INVALID, tokenId);
1865             return;
1866         }
1867     }
1868 
1869     // Create on the src end.
1870     int32_t ret = InitAndRegisterAuthMgr(true, tokenId, curSession, logicalSessionId, "");
1871     if (ret != DM_OK) {
1872         LOGE("InitAndRegisterAuthMgr failed, ret %{public}d.", ret);
1873         CleanSessionMap(sessionId);
1874         OnAuthResultAndOnBindResult(processInfo, targetId, targetIdTmp.deviceId, ret, tokenId);
1875         return;
1876     }
1877     curSession->logicalSessionSet_.insert(logicalSessionId);
1878     curSession->logicalSessionCnt_.fetch_add(1);
1879     SaveTokenIdAndSessionId(tokenId, sessionId, logicalSessionId);
1880     auto authMgr = GetAuthMgrByTokenId(tokenId);
1881     if (authMgr == nullptr) {
1882         CleanAuthMgrByLogicalSessionId(logicalSessionId);
1883         OnAuthResultAndOnBindResult(processInfo, targetId, targetIdTmp.deviceId, ERR_DM_POINT_NULL, tokenId);
1884         return;
1885     }
1886     authMgr->SetBindTargetParams(targetId);
1887     if ((ret = authMgr->BindTarget(pkgName, targetIdTmp, bindParam, sessionId, logicalSessionId)) != DM_OK) {
1888         LOGE("authMgr BindTarget failed, ret %{public}d.", ret);
1889         CleanAuthMgrByLogicalSessionId(logicalSessionId);
1890         OnAuthResultAndOnBindResult(processInfo, targetId, targetIdTmp.deviceId, ret, tokenId);
1891     }
1892     LOGI("end, tokenId %{public}s.", GetAnonyInt32(tokenId).c_str());
1893     return;
1894 }
1895 
BindTarget(const std::string & pkgName,const PeerTargetId & targetId,const std::map<std::string,std::string> & bindParam)1896 int32_t DeviceManagerServiceImpl::BindTarget(const std::string &pkgName, const PeerTargetId &targetId,
1897     const std::map<std::string, std::string> &bindParam)
1898 {
1899     if (pkgName.empty()) {
1900         LOGE("BindTarget failed, pkgName is empty.");
1901         return ERR_DM_INPUT_PARA_INVALID;
1902     }
1903     DmBindCallerInfo bindCallerInfo;
1904     GetBindCallerInfo(bindCallerInfo, pkgName);
1905     std::map<std::string, std::string> bindParamTmp;
1906     SetBindCallerInfoToBindParam(bindParam, bindParamTmp, bindCallerInfo);
1907     uint64_t tokenId = IPCSkeleton::GetCallingTokenID();
1908     LOGI("DeviceManagerServiceImpl In, pkgName:%{public}s, tokenId:%{public}" PRIu64, pkgName.c_str(), tokenId);
1909     {
1910         std::lock_guard<std::mutex> lock(tokenIdSessionIdMapMtx_);
1911         if (tokenIdSessionIdMap_.find(tokenId) != tokenIdSessionIdMap_.end()) {
1912             LOGE("BindTarget failed, this device is being bound. please try again later,"
1913                 "pkgName:%{public}s, tokenId:%{public}" PRIu64, pkgName.c_str(), tokenId);
1914             return ERR_DM_AUTH_BUSINESS_BUSY;
1915         }
1916         if (tokenIdSessionIdMap_.size() >= MAX_NEW_PROC_SESSION_COUNT_TEMP) {
1917             LOGE("Other bind exist, can not start new one. size:%{public}zu", tokenIdSessionIdMap_.size());
1918             return ERR_DM_AUTH_BUSINESS_BUSY;
1919         }
1920         tokenIdSessionIdMap_[tokenId] = DEFAULT_SESSION_ID;
1921     }
1922     std::thread newThread(&DeviceManagerServiceImpl::BindTargetImpl, this, tokenId, pkgName, targetId, bindParamTmp);
1923     newThread.detach();
1924     return DM_OK;
1925 }
1926 
DpAclAdd(const std::string & udid)1927 int32_t DeviceManagerServiceImpl::DpAclAdd(const std::string &udid)
1928 {
1929     LOGI("start udid %{public}s.", GetAnonyString(udid).c_str());
1930     MultipleUserConnector::SetSwitchOldUserId(MultipleUserConnector::GetCurrentAccountUserID());
1931     MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId());
1932     if (deviceStateMgr_->CheckIsOnline(udid)) {
1933         LOGI("DeviceManagerServiceImpl DpAclAdd identical account and online");
1934         ProcessInfo processInfo;
1935         processInfo.pkgName = std::string(DM_PKG_NAME);
1936         processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId();
1937         softbusConnector_->SetProcessInfo(processInfo);
1938         deviceStateMgr_->OnDeviceOnline(udid, DmAuthForm::IDENTICAL_ACCOUNT);
1939     }
1940     return DM_OK;
1941 }
1942 
IsSameAccount(const std::string & udid)1943 int32_t DeviceManagerServiceImpl::IsSameAccount(const std::string &udid)
1944 {
1945     if (udid.empty()) {
1946         LOGE("DeviceManagerServiceImpl::IsSameAccount error: udid: %{public}s", GetAnonyString(udid).c_str());
1947         return ERR_DM_INPUT_PARA_INVALID;
1948     }
1949 
1950     return DeviceProfileConnector::GetInstance().IsSameAccount(udid);
1951 }
1952 
GetTokenIdByNameAndDeviceId(std::string extra,std::string requestDeviceId)1953 uint64_t DeviceManagerServiceImpl::GetTokenIdByNameAndDeviceId(std::string extra, std::string requestDeviceId)
1954 {
1955     if (extra.empty()) {
1956         LOGE("DeviceManagerServiceImpl::GetTokenIdByNameAndDeviceId error: extra.");
1957         return ERR_DM_INPUT_PARA_INVALID;
1958     }
1959 
1960     if (requestDeviceId.empty()) {
1961         LOGE("DeviceManagerServiceImpl::GetTokenIdByNameAndDeviceId error: requestDeviceId.");
1962         return ERR_DM_INPUT_PARA_INVALID;
1963     }
1964 
1965     return DeviceProfileConnector::GetInstance().GetTokenIdByNameAndDeviceId(extra, requestDeviceId);
1966 }
1967 
GetAppTrustDeviceIdList(std::string pkgname)1968 std::unordered_map<std::string, DmAuthForm> DeviceManagerServiceImpl::GetAppTrustDeviceIdList(
1969     std::string pkgname)
1970 {
1971     char localDeviceId[DEVICE_UUID_LENGTH];
1972     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
1973     std::string deviceId = reinterpret_cast<char *>(localDeviceId);
1974     return DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgname, deviceId);
1975 }
1976 
LoadHardwareFwkService()1977 void DeviceManagerServiceImpl::LoadHardwareFwkService()
1978 {
1979     DmDistributedHardwareLoad::GetInstance().LoadDistributedHardwareFwk();
1980 }
1981 
HandleIdentAccountLogout(const DMAclQuadInfo & info,const std::string & accountId)1982 void DeviceManagerServiceImpl::HandleIdentAccountLogout(const DMAclQuadInfo &info, const std::string &accountId)
1983 {
1984     LOGI("localUdid %{public}s, localUserId %{public}d, peerUdid %{public}s, peerUserId %{public}d.",
1985         GetAnonyString(info.localUdid).c_str(), info.localUserId, GetAnonyString(info.peerUdid).c_str(),
1986         info.peerUserId);
1987     DmOfflineParam offlineParam;
1988     bool notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(info, accountId,
1989         offlineParam);
1990     CHECK_NULL_VOID(hiChainConnector_);
1991     hiChainConnector_->DeleteAllGroup(info.localUserId);
1992     CHECK_NULL_VOID(hiChainAuthConnector_);
1993     {
1994         std::lock_guard lock(logoutMutex_);
1995         hiChainAuthConnector_->DeleteCredential(info.peerUdid, info.localUserId, info.peerUserId);
1996         DeleteSkCredAndAcl(offlineParam.needDelAclInfos);
1997     }
1998 
1999     std::set<std::string> pkgNameSet;
2000     GetBundleName(info, pkgNameSet);
2001     if (notifyOffline) {
2002         CHECK_NULL_VOID(softbusConnector_);
2003         softbusConnector_->SetProcessInfoVec(offlineParam.processVec);
2004         CHECK_NULL_VOID(listener_);
2005         listener_->SetExistPkgName(pkgNameSet);
2006         CHECK_NULL_VOID(deviceStateMgr_);
2007         deviceStateMgr_->OnDeviceOffline(info.peerUdid);
2008     }
2009 }
2010 
GetBundleName(const DMAclQuadInfo & info,std::set<std::string> & pkgNameSet)2011 void DeviceManagerServiceImpl::GetBundleName(const DMAclQuadInfo &info, std::set<std::string> &pkgNameSet)
2012 {
2013     std::vector<DistributedDeviceProfile::AccessControlProfile> profiles =
2014         DeviceProfileConnector::GetInstance().GetAllAclIncludeLnnAcl();
2015     for (auto &item : profiles) {
2016         std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId();
2017         std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId();
2018         int32_t accesserUserId = item.GetAccesser().GetAccesserUserId();
2019         int32_t accesseeUserId = item.GetAccessee().GetAccesseeUserId();
2020         std::string accesserPkgName = item.GetAccesser().GetAccesserBundleName();
2021         std::string accesseePkgName = item.GetAccessee().GetAccesseeBundleName();
2022         if (accesserUdid == info.localUdid && accesserUserId == info.localUserId &&
2023             accesseeUdid == info.peerUdid && accesseeUserId == info.peerUserId &&
2024             (!accesserPkgName.empty())) {
2025             pkgNameSet.insert(accesserPkgName);
2026             continue;
2027         }
2028         if (accesserUdid == info.peerUdid && accesserUserId == info.peerUserId &&
2029             accesseeUdid == info.localUdid && accesseeUserId == info.localUserId &&
2030             (!accesseePkgName.empty())) {
2031             pkgNameSet.insert(accesseePkgName);
2032             continue;
2033         }
2034     }
2035 }
2036 
HandleUserRemoved(std::vector<std::string> peerUdids,int32_t preUserId)2037 void DeviceManagerServiceImpl::HandleUserRemoved(std::vector<std::string> peerUdids, int32_t preUserId)
2038 {
2039     LOGI("PreUserId %{public}d.", preUserId);
2040     char localDeviceId[DEVICE_UUID_LENGTH];
2041     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
2042     std::string localUdid = reinterpret_cast<char *>(localDeviceId);
2043     std::multimap<std::string, int32_t> peerUserIdMap;     // key: peerUdid  value: peerUserId
2044     DmOfflineParam offlineParam;
2045     DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(localUdid, preUserId, peerUdids, peerUserIdMap,
2046         offlineParam);
2047     CHECK_NULL_VOID(hiChainConnector_);
2048     hiChainConnector_->DeleteAllGroup(preUserId);
2049 
2050     if (peerUserIdMap.empty()) {
2051         LOGE("peerUserIdMap is empty");
2052         return;
2053     }
2054     CHECK_NULL_VOID(hiChainAuthConnector_);
2055     for (const auto &item : peerUserIdMap) {
2056         hiChainAuthConnector_->DeleteCredential(item.first, preUserId, item.second);
2057     }
2058     DeleteSkCredAndAcl(offlineParam.needDelAclInfos);
2059 }
2060 
HandleRemoteUserRemoved(int32_t userId,const std::string & remoteUdid)2061 void DeviceManagerServiceImpl::HandleRemoteUserRemoved(int32_t userId, const std::string &remoteUdid)
2062 {
2063     LOGI("remoteUdid %{public}s, userId %{public}d", GetAnonyString(remoteUdid).c_str(), userId);
2064     std::vector<int32_t> localUserIds;
2065     DmOfflineParam offlineParam;
2066     DeviceProfileConnector::GetInstance().DeleteAclForRemoteUserRemoved(remoteUdid, userId, localUserIds, offlineParam);
2067     if (localUserIds.empty()) {
2068         return;
2069     }
2070     CHECK_NULL_VOID(hiChainAuthConnector_);
2071     std::vector<std::pair<int32_t, std::string>> delInfoVec;
2072     for (int32_t localUserId : localUserIds) {
2073         delInfoVec.push_back(std::pair<int32_t, std::string>(localUserId, remoteUdid));
2074         hiChainAuthConnector_->DeleteCredential(remoteUdid, localUserId, userId);
2075     }
2076     CHECK_NULL_VOID(hiChainConnector_);
2077     hiChainConnector_->DeleteGroupByACL(delInfoVec, localUserIds);
2078     DeleteSkCredAndAcl(offlineParam.needDelAclInfos);
2079 }
2080 
HandleUserSwitched(const std::vector<std::string> & deviceVec,int32_t currentUserId,int32_t beforeUserId)2081 void DeviceManagerServiceImpl::HandleUserSwitched(const std::vector<std::string> &deviceVec,
2082     int32_t currentUserId, int32_t beforeUserId)
2083 {
2084     LOGI("currentUserId: %{public}s, beforeUserId: %{public}s", GetAnonyInt32(currentUserId).c_str(),
2085         GetAnonyInt32(beforeUserId).c_str());
2086     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
2087     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
2088     std::string localUdid = static_cast<std::string>(localDeviceId);
2089     DeviceProfileConnector::GetInstance().HandleUserSwitched(localUdid, deviceVec, currentUserId, beforeUserId);
2090 }
2091 
ScreenCommonEventCallback(std::string commonEventType)2092 void DeviceManagerServiceImpl::ScreenCommonEventCallback(std::string commonEventType)
2093 {
2094     if (commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED) {
2095         LOGI("on screen locked.");
2096         std::lock_guard<std::mutex> lock(authMgrMapMtx_);
2097         for (auto& pair : authMgrMap_) {
2098             if (pair.second != nullptr) {
2099                 LOGI("tokenId: %{public}s.", GetAnonyInt32(pair.first).c_str());
2100                 pair.second->OnScreenLocked();
2101             }
2102         }
2103         return;
2104     }
2105     LOGI("error.");
2106 }
2107 
CheckIsSameAccount(const DmAccessCaller & caller,const std::string & srcUdid,const DmAccessCallee & callee,const std::string & sinkUdid)2108 bool DeviceManagerServiceImpl::CheckIsSameAccount(const DmAccessCaller &caller, const std::string &srcUdid,
2109     const DmAccessCallee &callee, const std::string &sinkUdid)
2110 {
2111     return DeviceProfileConnector::GetInstance().CheckIsSameAccount(caller, srcUdid, callee, sinkUdid);
2112 }
2113 
CheckAccessControl(const DmAccessCaller & caller,const std::string & srcUdid,const DmAccessCallee & callee,const std::string & sinkUdid)2114 bool DeviceManagerServiceImpl::CheckAccessControl(const DmAccessCaller &caller, const std::string &srcUdid,
2115     const DmAccessCallee &callee, const std::string &sinkUdid)
2116 {
2117     CHECK_NULL_RETURN(hiChainConnector_, ERR_DM_POINT_NULL);
2118     if (!hiChainConnector_->IsDevicesInP2PGroup(srcUdid, sinkUdid)) {
2119         return DeviceProfileConnector::GetInstance().CheckAccessControl(caller, srcUdid, callee, sinkUdid);
2120     } else {
2121         return true;
2122     }
2123 }
2124 
HandleDeviceNotTrust(const std::string & udid)2125 void DeviceManagerServiceImpl::HandleDeviceNotTrust(const std::string &udid)
2126 {
2127     LOGI("udid: %{public}s.", GetAnonyString(udid).c_str());
2128     if (udid.empty()) {
2129         LOGE("HandleDeviceNotTrust udid is empty.");
2130         return;
2131     }
2132     DeviceProfileConnector::GetInstance().DeleteAccessControlList(udid);
2133     CHECK_NULL_VOID(hiChainConnector_);
2134     hiChainConnector_->DeleteAllGroupByUdid(udid);
2135 }
2136 
GetBindLevel(const std::string & pkgName,const std::string & localUdid,const std::string & udid,uint64_t & tokenId)2137 int32_t DeviceManagerServiceImpl::GetBindLevel(const std::string &pkgName, const std::string &localUdid,
2138     const std::string &udid, uint64_t &tokenId)
2139 {
2140     return DeviceProfileConnector::GetInstance().GetBindLevel(pkgName, localUdid, udid, tokenId);
2141 }
2142 
GetDeviceIdAndBindLevel(int32_t userId)2143 std::map<std::string, int32_t> DeviceManagerServiceImpl::GetDeviceIdAndBindLevel(int32_t userId)
2144 {
2145     char localUdidTemp[DEVICE_UUID_LENGTH] = {0};
2146     GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH);
2147     std::string localUdid = std::string(localUdidTemp);
2148     std::vector<int32_t> userIds;
2149     userIds.push_back(userId);
2150     return DeviceProfileConnector::GetInstance().GetDeviceIdAndBindLevel(userIds, localUdid);
2151 }
2152 
GetDeviceIdByUserIdAndTokenId(int32_t userId,int32_t tokenId)2153 std::vector<std::string> DeviceManagerServiceImpl::GetDeviceIdByUserIdAndTokenId(int32_t userId,
2154     int32_t tokenId)
2155 {
2156     char localUdidTemp[DEVICE_UUID_LENGTH] = {0};
2157     GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH);
2158     std::string localUdid = std::string(localUdidTemp);
2159     std::vector<int32_t> userIds;
2160     userIds.push_back(userId);
2161     return DeviceProfileConnector::GetInstance().GetDeviceIdAndUdidListByTokenId(userIds, localUdid, tokenId);
2162 }
2163 
GetDeviceIdAndUserId(int32_t userId,const std::string & accountId)2164 std::multimap<std::string, int32_t> DeviceManagerServiceImpl::GetDeviceIdAndUserId(int32_t userId,
2165     const std::string &accountId)
2166 {
2167     char localUdidTemp[DEVICE_UUID_LENGTH] = {0};
2168     GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH);
2169     std::string localUdid = std::string(localUdidTemp);
2170     return DeviceProfileConnector::GetInstance().GetDeviceIdAndUserId(userId, accountId, localUdid);
2171 }
2172 
HandleAccountLogoutEvent(int32_t remoteUserId,const std::string & remoteAccountHash,const std::string & remoteUdid)2173 void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash,
2174     const std::string &remoteUdid)
2175 {
2176     char localUdidTemp[DEVICE_UUID_LENGTH] = {0};
2177     GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH);
2178     std::string localUdid = std::string(localUdidTemp);
2179     std::multimap<std::string, int32_t> devIdAndUserMap =
2180         DeviceProfileConnector::GetInstance().GetDevIdAndUserIdByActHash(localUdid, remoteUdid,
2181             remoteUserId, remoteAccountHash);
2182     CHECK_NULL_VOID(listener_);
2183     std::string uuid = "";
2184     SoftbusCache::GetInstance().GetUuidByUdid(remoteUdid, uuid);
2185     listener_->OnDeviceTrustChange(remoteUdid, uuid, DmAuthForm::IDENTICAL_ACCOUNT);
2186     for (const auto &item : devIdAndUserMap) {
2187         DmOfflineParam offlineParam;
2188         LOGI("remoteUdid %{public}s.", GetAnonyString(remoteUdid).c_str());
2189         DMAclQuadInfo info = {item.first, item.second, remoteUdid, remoteUserId};
2190         bool notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclByActhash(info,
2191             remoteAccountHash, offlineParam);
2192 
2193         CHECK_NULL_VOID(hiChainConnector_);
2194         hiChainConnector_->DeleteAllGroup(item.second);
2195         CHECK_NULL_VOID(hiChainAuthConnector_);
2196         {
2197             std::lock_guard lock(logoutMutex_);
2198             hiChainAuthConnector_->DeleteCredential(remoteUdid, item.second, remoteUserId);
2199             DeleteSkCredAndAcl(offlineParam.needDelAclInfos);
2200         }
2201 
2202         std::set<std::string> pkgNameSet;
2203         GetBundleName(info, pkgNameSet);
2204         if (notifyOffline) {
2205             CHECK_NULL_VOID(softbusConnector_);
2206             softbusConnector_->SetProcessInfoVec(offlineParam.processVec);
2207             CHECK_NULL_VOID(listener_);
2208             listener_->SetExistPkgName(pkgNameSet);
2209             CHECK_NULL_VOID(deviceStateMgr_);
2210             deviceStateMgr_->OnDeviceOffline(remoteUdid);
2211         }
2212     }
2213 }
2214 
ConvertBindTypeToAuthForm(int32_t bindType)2215 DmAuthForm DeviceManagerServiceImpl::ConvertBindTypeToAuthForm(int32_t bindType)
2216 {
2217     LOGI("BindType %{public}d.", bindType);
2218     DmAuthForm authForm = DmAuthForm::INVALID_TYPE;
2219     if (static_cast<uint32_t>(bindType) == DM_IDENTICAL_ACCOUNT) {
2220         authForm = IDENTICAL_ACCOUNT;
2221     } else if (static_cast<uint32_t>(bindType) == DM_POINT_TO_POINT) {
2222         authForm = PEER_TO_PEER;
2223     } else if (static_cast<uint32_t>(bindType) == DM_ACROSS_ACCOUNT) {
2224         authForm = ACROSS_ACCOUNT;
2225     } else {
2226         LOGE("Invalied bindType.");
2227     }
2228     return authForm;
2229 }
2230 
DeleteGroup(const std::string & pkgName,const std::string & deviceId)2231 int32_t DeviceManagerServiceImpl::DeleteGroup(const std::string &pkgName, const std::string &deviceId)
2232 {
2233     LOGI("start");
2234     if (pkgName.empty()) {
2235         LOGE("Invalid parameter, pkgName is empty.");
2236         return ERR_DM_FAILED;
2237     }
2238     std::vector<OHOS::DistributedHardware::GroupInfo> groupList;
2239     CHECK_NULL_RETURN(hiChainConnector_, ERR_DM_POINT_NULL);
2240     hiChainConnector_->GetRelatedGroups(deviceId, groupList);
2241     for (const auto &item : groupList) {
2242         std::string groupId = item.groupId;
2243         hiChainConnector_->DeleteGroup(groupId);
2244     }
2245     return DM_OK;
2246 }
2247 
HandleDevUnBindEvent(int32_t remoteUserId,const std::string & remoteUdid)2248 void DeviceManagerServiceImpl::HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid)
2249 {
2250     char localUdidTemp[DEVICE_UUID_LENGTH] = {0};
2251     GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH);
2252     std::string localUdid = std::string(localUdidTemp);
2253     DmOfflineParam offlineParam;
2254     int32_t bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(
2255         remoteUserId, remoteUdid, localUdid, offlineParam);
2256     if (static_cast<uint32_t>(bindType) == DM_INVALIED_TYPE) {
2257         LOGE("Invalied bindtype.");
2258         return;
2259     }
2260     DeleteGroup(DM_PKG_NAME, remoteUdid);
2261     DeleteSkCredAndAcl(offlineParam.needDelAclInfos);
2262 }
2263 
HandleAppUnBindEvent(int32_t remoteUserId,const std::string & remoteUdid,int32_t tokenId)2264 void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid,
2265     int32_t tokenId)
2266 {
2267     LOGI("tokenId = %{public}s.", GetAnonyInt32(tokenId).c_str());
2268     char localUdidTemp[DEVICE_UUID_LENGTH] = {0};
2269     GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH);
2270     std::string localUdid = std::string(localUdidTemp);
2271     DmOfflineParam offlineParam =
2272         DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid);
2273 
2274     DeleteSkCredAndAcl(offlineParam.needDelAclInfos);
2275 
2276     //first, not app/service/user/DM_IDENTICAL_ACCOUNT acl, determin if need clear lnn acl
2277     if (offlineParam.allLeftAppOrSvrAclInfos.empty() && offlineParam.allUserAclInfos.empty() &&
2278         !offlineParam.allLnnAclInfos.empty()) {
2279         LOGI("No acl exist, clear lnn acl");
2280         DeleteSkCredAndAcl(offlineParam.allLnnAclInfos);
2281     }
2282 
2283     //second, not user/DM_IDENTICAL_ACCOUNT acl, but app/service acl exist
2284     //determin if need report offline to unbind bundle
2285     if (!offlineParam.allLeftAppOrSvrAclInfos.empty() && offlineParam.allUserAclInfos.empty()) {
2286         LOGI("after clear target acl, No user acl exist, report offline");
2287         CHECK_NULL_VOID(softbusConnector_);
2288         softbusConnector_->SetProcessInfoVec(offlineParam.processVec);
2289         softbusConnector_->HandleDeviceOffline(remoteUdid);
2290     }
2291     //third, not lnn acl, determin if delete Credential
2292     if (offlineParam.allLnnAclInfos.empty()) {
2293         CHECK_NULL_VOID(hiChainAuthConnector_);
2294         hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(),
2295             remoteUserId);
2296     }
2297 }
2298 
HandleAppUnBindEvent(int32_t remoteUserId,const std::string & remoteUdid,int32_t tokenId,int32_t peerTokenId)2299 void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid,
2300     int32_t tokenId, int32_t peerTokenId)
2301 {
2302     LOGI("DeviceManagerServiceImpl::HandleAppUnBindEvent remoteUserId: %{public}s, remoteUdid: %{public}s,"
2303         "tokenId = %{public}s, peerTokenId = %{public}s.", GetAnonyInt32(remoteUserId).c_str(),
2304         GetAnonyString(remoteUdid).c_str(), GetAnonyInt32(tokenId).c_str(), GetAnonyInt32(peerTokenId).c_str());
2305     char localUdidTemp[DEVICE_UUID_LENGTH] = {0};
2306     GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH);
2307     std::string localUdid = std::string(localUdidTemp);
2308     DmOfflineParam offlineParam =
2309         DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid,
2310             tokenId, localUdid, peerTokenId);
2311 
2312     DeleteSkCredAndAcl(offlineParam.needDelAclInfos);
2313     //first, not app/service/user/DM_IDENTICAL_ACCOUNT acl, determin if need clear lnn acl
2314     if (offlineParam.allLeftAppOrSvrAclInfos.empty() && offlineParam.allUserAclInfos.empty() &&
2315         !offlineParam.allLnnAclInfos.empty()) {
2316         LOGI("No acl exist, clear lnn acl");
2317         DeleteSkCredAndAcl(offlineParam.allLnnAclInfos);
2318     }
2319 
2320     //second, not user/DM_IDENTICAL_ACCOUNT acl, but app/service acl exist
2321     //determin if need report offline to unbind bundle
2322     if (!offlineParam.allLeftAppOrSvrAclInfos.empty() && offlineParam.allUserAclInfos.empty()) {
2323         LOGI("after clear target acl, No user acl exist, report offline");
2324         CHECK_NULL_VOID(softbusConnector_);
2325         softbusConnector_->SetProcessInfoVec(offlineParam.processVec);
2326         softbusConnector_->HandleDeviceOffline(remoteUdid);
2327     }
2328     //third, not lnn acl, determin if delete Credential
2329     if (offlineParam.allLnnAclInfos.empty()) {
2330         CHECK_NULL_VOID(hiChainAuthConnector_);
2331         hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(),
2332             remoteUserId);
2333     }
2334 }
2335 
HandleServiceUnBindEvent(int32_t userId,const std::string & remoteUdid,int32_t remoteTokenId)2336 void DeviceManagerServiceImpl::HandleServiceUnBindEvent(int32_t userId, const std::string &remoteUdid,
2337     int32_t remoteTokenId)
2338 {
2339     LOGI("remoteTokenId = %{public}s, userId: %{public}d, remoteUdid: %{public}s.",
2340         GetAnonyInt32(remoteTokenId).c_str(), userId, GetAnonyString(remoteUdid).c_str());
2341     char localUdidTemp[DEVICE_UUID_LENGTH] = {0};
2342     GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH);
2343     std::string localUdid = std::string(localUdidTemp);
2344     DmOfflineParam offlineParam =
2345         DeviceProfileConnector::GetInstance().HandleServiceUnBindEvent(userId, remoteUdid, localUdid, remoteTokenId);
2346 
2347     //first, app/service acl exist, determin if need local acl
2348     DeleteSkCredAndAcl(offlineParam.needDelAclInfos);
2349     //second, not app/service/user/DM_IDENTICAL_ACCOUNT acl exist, determin if need clear lnn acl
2350     if (offlineParam.allLeftAppOrSvrAclInfos.empty() && offlineParam.allUserAclInfos.empty()) {
2351         LOGI("No acl exist, clear lnn acl");
2352         DeleteSkCredAndAcl(offlineParam.allLnnAclInfos);
2353     }
2354 
2355     //Third, not user/DM_IDENTICAL_ACCOUNT acl exist but app/service acl exist,
2356     //determin if need report offline to unbind bundle
2357     if (!offlineParam.allLeftAppOrSvrAclInfos.empty() && offlineParam.allUserAclInfos.empty()) {
2358         LOGI("after clear target acl, No user acl exist, report offline");
2359         softbusConnector_->SetProcessInfoVec(offlineParam.processVec);
2360         softbusConnector_->HandleDeviceOffline(remoteUdid);
2361     }
2362 }
2363 
HandleSyncUserIdEvent(const std::vector<uint32_t> & foregroundUserIds,const std::vector<uint32_t> & backgroundUserIds,const std::string & remoteUdid,bool isCheckUserStatus)2364 void DeviceManagerServiceImpl::HandleSyncUserIdEvent(const std::vector<uint32_t> &foregroundUserIds,
2365     const std::vector<uint32_t> &backgroundUserIds, const std::string &remoteUdid, bool isCheckUserStatus)
2366 {
2367     LOGI("remote udid: %{public}s, foregroundUserIds: %{public}s, backgroundUserIds: %{public}s",
2368         GetAnonyString(remoteUdid).c_str(), GetIntegerList<uint32_t>(foregroundUserIds).c_str(),
2369         GetIntegerList<uint32_t>(backgroundUserIds).c_str());
2370     char localUdidTemp[DEVICE_UUID_LENGTH] = {0};
2371     GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH);
2372     std::string localUdid = std::string(localUdidTemp);
2373     std::vector<int32_t> rmtFrontUserIdsTemp(foregroundUserIds.begin(), foregroundUserIds.end());
2374     std::vector<int32_t> rmtBackUserIdsTemp(backgroundUserIds.begin(), backgroundUserIds.end());
2375     std::vector<int32_t> localUserIds;
2376     int32_t ret = MultipleUserConnector::GetForegroundUserIds(localUserIds);
2377     if (ret != DM_OK) {
2378         LOGE("Get foreground userids failed, ret: %{public}d", ret);
2379         return;
2380     }
2381     if (isCheckUserStatus) {
2382         MultipleUserConnector::ClearLockedUser(localUserIds);
2383     }
2384     DmOfflineParam offlineParam;
2385     DeviceProfileConnector::GetInstance().UpdateACL(localUdid, localUserIds, remoteUdid,
2386         rmtFrontUserIdsTemp, rmtBackUserIdsTemp, offlineParam);
2387     DeleteSkCredAndAcl(offlineParam.needDelAclInfos);
2388     DeviceProfileConnector::GetInstance().HandleSyncBackgroundUserIdEvent(rmtBackUserIdsTemp, remoteUdid,
2389         localUserIds, localUdid);
2390     DeviceProfileConnector::GetInstance().HandleSyncForegroundUserIdEvent(rmtFrontUserIdsTemp, remoteUdid,
2391         localUserIds, localUdid);
2392 }
2393 
HandleDeviceScreenStatusChange(DmDeviceInfo & devInfo)2394 void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo)
2395 {
2396     LOGI("In");
2397     CHECK_NULL_VOID(deviceStateMgr_);
2398     CHECK_NULL_VOID(softbusConnector_);
2399     std::string trustDeviceId = "";
2400     if (softbusConnector_->GetUdidByNetworkId(devInfo.networkId, trustDeviceId) != DM_OK) {
2401         LOGE("get udid failed.");
2402         return;
2403     }
2404     std::string udidHash = softbusConnector_->GetDeviceUdidHashByUdid(trustDeviceId);
2405     if (memcpy_s(devInfo.deviceId, DM_MAX_DEVICE_ID_LEN, udidHash.c_str(), udidHash.length()) != 0) {
2406         LOGE("get deviceId: %{public}s failed", GetAnonyString(udidHash).c_str());
2407         return;
2408     }
2409     char localUdid[DEVICE_UUID_LENGTH] = {0};
2410     GetDevUdid(localUdid, DEVICE_UUID_LENGTH);
2411     std::string requestDeviceId = static_cast<std::string>(localUdid);
2412     uint32_t bindType = DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId);
2413     LOGI("bind type is %{public}d.", bindType);
2414     std::vector<ProcessInfo> processInfoVec;
2415     if (bindType == INVALIED_TYPE) {
2416         return;
2417     } else if (bindType == IDENTICAL_ACCOUNT_TYPE || bindType == DEVICE_PEER_TO_PEER_TYPE ||
2418         bindType == DEVICE_ACROSS_ACCOUNT_TYPE) {
2419         ProcessInfo processInfo;
2420         processInfo.pkgName = std::string(DM_PKG_NAME);
2421         processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId();
2422         processInfoVec.push_back(processInfo);
2423     } else if (bindType == APP_PEER_TO_PEER_TYPE || bindType == APP_ACROSS_ACCOUNT_TYPE) {
2424         processInfoVec = DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId,
2425             trustDeviceId, MultipleUserConnector::GetFirstForegroundUserId());
2426     }
2427     deviceStateMgr_->HandleDeviceScreenStatusChange(devInfo, processInfoVec);
2428 }
2429 
SyncLocalAclListProcess(const DevUserInfo & localDevUserInfo,const DevUserInfo & remoteDevUserInfo,std::string remoteAclList)2430 int32_t DeviceManagerServiceImpl::SyncLocalAclListProcess(const DevUserInfo &localDevUserInfo,
2431     const DevUserInfo &remoteDevUserInfo, std::string remoteAclList)
2432 {
2433     CHECK_NULL_RETURN(softbusConnector_, ERR_DM_POINT_NULL);
2434     return softbusConnector_->SyncLocalAclListProcess(localDevUserInfo, remoteDevUserInfo, remoteAclList);
2435 }
2436 
GetAclListHash(const DevUserInfo & localDevUserInfo,const DevUserInfo & remoteDevUserInfo,std::string & aclList)2437 int32_t DeviceManagerServiceImpl::GetAclListHash(const DevUserInfo &localDevUserInfo,
2438     const DevUserInfo &remoteDevUserInfo, std::string &aclList)
2439 {
2440     CHECK_NULL_RETURN(softbusConnector_, ERR_DM_POINT_NULL);
2441     return softbusConnector_->GetAclListHash(localDevUserInfo, remoteDevUserInfo, aclList);
2442 }
2443 
HandleCredentialAuthStatus(const std::string & deviceList,uint16_t deviceTypeId,int32_t errcode)2444 void DeviceManagerServiceImpl::HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId,
2445                                                           int32_t errcode)
2446 {
2447     CHECK_NULL_VOID(credentialMgr_);
2448     credentialMgr_->HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode);
2449 }
2450 
ProcessAppUnintall(const std::string & appId,int32_t accessTokenId)2451 int32_t DeviceManagerServiceImpl::ProcessAppUnintall(const std::string &appId, int32_t accessTokenId)
2452 {
2453     CHECK_NULL_RETURN(listener_, ERR_DM_POINT_NULL);
2454     std::vector<DistributedDeviceProfile::AccessControlProfile> profiles =
2455         DeviceProfileConnector::GetInstance().GetAllAclIncludeLnnAcl();
2456     LOGI("delete ACL size is %{public}zu, appId %{public}s", profiles.size(), GetAnonyString(appId).c_str());
2457     if (profiles.size() == 0) {
2458         return DM_OK;
2459     }
2460     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
2461     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
2462     std::string localUdid = std::string(localDeviceId);
2463     std::vector<std::pair<int32_t, std::string>> delACLInfoVec;
2464     std::vector<int32_t> userIdVec;
2465     std::map<int64_t, DistributedDeviceProfile::AccessControlProfile> delProfileMap;
2466     DeleteAclByTokenId(accessTokenId, profiles, delProfileMap, delACLInfoVec, userIdVec);
2467     for (auto item : delProfileMap) {
2468         DmOfflineParam lnnAclParam;
2469         bool isLastLnnAcl = false;
2470         for (auto it : profiles) {
2471             CheckIsLastLnnAcl(it, item.second, lnnAclParam, isLastLnnAcl, localUdid);
2472         }
2473         if (!isLastLnnAcl) {
2474             DeleteSkCredAndAcl(lnnAclParam.needDelAclInfos);
2475         }
2476     }
2477 
2478     if (delACLInfoVec.size() == 0) {
2479         return DM_OK;
2480     }
2481     if (userIdVec.size() == 0) {
2482         return DM_OK;
2483     }
2484     CHECK_NULL_RETURN(hiChainConnector_, ERR_DM_POINT_NULL);
2485     hiChainConnector_->DeleteGroupByACL(delACLInfoVec, userIdVec);
2486     return DM_OK;
2487 }
2488 
ProcessAppUninstall(int32_t userId,int32_t accessTokenId)2489 int32_t DeviceManagerServiceImpl::ProcessAppUninstall(int32_t userId, int32_t accessTokenId)
2490 {
2491     LOGE("DeviceManagerServiceImpl::ProcessAppUninstall userId = %{public}s, accessTokenId = %{public}s.",
2492         GetAnonyInt32(userId).c_str(), GetAnonyInt32(accessTokenId).c_str());
2493     CHECK_NULL_RETURN(listener_, ERR_DM_POINT_NULL);
2494     std::vector<DistributedDeviceProfile::AccessControlProfile> profiles =
2495         DeviceProfileConnector::GetInstance().GetAllAclIncludeLnnAcl();
2496     LOGI("delete ACL size is %{public}zu", profiles.size());
2497     if (profiles.size() == 0) {
2498         return DM_OK;
2499     }
2500     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
2501     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
2502     std::string localUdid = std::string(localDeviceId);
2503     std::vector<std::pair<int32_t, std::string>> delACLInfoVec;
2504     std::vector<int32_t> userIdVec;
2505     GetDelACLInfoVec(accessTokenId, profiles, delACLInfoVec, userIdVec, userId);
2506 
2507     if (delACLInfoVec.size() == 0 || userIdVec.size() == 0) {
2508         return DM_OK;
2509     }
2510 
2511     CHECK_NULL_RETURN(hiChainConnector_, ERR_DM_POINT_NULL);
2512     hiChainConnector_->DeleteGroupByACL(delACLInfoVec, userIdVec);
2513     return DM_OK;
2514 }
2515 
ProcessUnBindApp(int32_t userId,int32_t accessTokenId,const std::string & extra,const std::string & udid)2516 void DeviceManagerServiceImpl::ProcessUnBindApp(int32_t userId, int32_t accessTokenId,
2517     const std::string &extra, const std::string &udid)
2518 {
2519     LOGI("DeviceManagerServiceImpl::ProcessUnBindApp userId = %{public}s, accessTokenId = %{public}s,"
2520         "extra = %{public}s.", GetAnonyInt32(userId).c_str(), GetAnonyInt32(accessTokenId).c_str(),
2521         GetAnonyString(extra).c_str());
2522 
2523     JsonObject extraInfoJson(extra);
2524     if (extraInfoJson.IsDiscarded()) {
2525         LOGE("ParseExtra extraInfoJson error");
2526         HandleAppUnBindEvent(userId, udid, accessTokenId);
2527         return;
2528     }
2529     if (extraInfoJson.Contains(TAG_PEER_TOKENID) && extraInfoJson[TAG_PEER_TOKENID].IsNumberInteger()) {
2530         uint64_t peerTokenId = extraInfoJson[TAG_PEER_TOKENID].Get<uint64_t>();
2531         HandleAppUnBindEvent(userId, udid, accessTokenId, static_cast<int32_t>(peerTokenId));
2532     }
2533     return;
2534 }
2535 
CheckIsLastLnnAcl(DistributedDeviceProfile::AccessControlProfile profile,DistributedDeviceProfile::AccessControlProfile delProfile,DmOfflineParam & lnnAclParam,bool & isLastLnnAcl,const std::string & localUdid)2536 void DeviceManagerServiceImpl::CheckIsLastLnnAcl(DistributedDeviceProfile::AccessControlProfile profile,
2537     DistributedDeviceProfile::AccessControlProfile delProfile, DmOfflineParam &lnnAclParam, bool &isLastLnnAcl,
2538     const std::string &localUdid)
2539 {
2540     if (DeviceProfileConnector::GetInstance().IsLnnAcl(profile) && CheckLnnAcl(delProfile, profile)) {
2541         if (profile.GetAccesser().GetAccesserDeviceId() == localUdid) {
2542             DeviceProfileConnector::GetInstance().CacheAcerAclId(profile, lnnAclParam.needDelAclInfos);
2543         }
2544         if (profile.GetAccessee().GetAccesseeDeviceId() == localUdid) {
2545             DeviceProfileConnector::GetInstance().CacheAceeAclId(profile, lnnAclParam.needDelAclInfos);
2546         }
2547     }
2548     if (!DeviceProfileConnector::GetInstance().IsLnnAcl(profile) && CheckLnnAcl(delProfile, profile)) {
2549         isLastLnnAcl = true;
2550     }
2551 }
2552 
DeleteAclByTokenId(const int32_t accessTokenId,std::vector<DistributedDeviceProfile::AccessControlProfile> & profiles,std::map<int64_t,DistributedDeviceProfile::AccessControlProfile> & delProfileMap,std::vector<std::pair<int32_t,std::string>> & delACLInfoVec,std::vector<int32_t> & userIdVec)2553 void DeviceManagerServiceImpl::DeleteAclByTokenId(const int32_t accessTokenId,
2554     std::vector<DistributedDeviceProfile::AccessControlProfile> &profiles,
2555     std::map<int64_t, DistributedDeviceProfile::AccessControlProfile> &delProfileMap,
2556     std::vector<std::pair<int32_t, std::string>> &delACLInfoVec, std::vector<int32_t> &userIdVec)
2557 {
2558     for (auto &item : profiles) {
2559         int64_t accesssertokenId = item.GetAccesser().GetAccesserTokenId();
2560         int64_t accessseetokenId = item.GetAccessee().GetAccesseeTokenId();
2561         if (accessTokenId != static_cast<int32_t>(accesssertokenId) &&
2562             accessTokenId != static_cast<int32_t>(accessseetokenId)) {
2563             continue;
2564         }
2565         if (accessTokenId == static_cast<int32_t>(accesssertokenId)) {
2566             DmOfflineParam offlineParam;
2567             delProfileMap[item.GetAccessControlId()] = item;
2568             DeviceProfileConnector::GetInstance().CacheAcerAclId(item, offlineParam.needDelAclInfos);
2569             DeleteSkCredAndAcl(offlineParam.needDelAclInfos);
2570             listener_->OnAppUnintall(item.GetAccesser().GetAccesserBundleName());
2571             if (item.GetBindLevel() == USER) {
2572                 userIdVec.push_back(item.GetAccesser().GetAccesserUserId());
2573                 delACLInfoVec.push_back(std::pair<int32_t, std::string>(item.GetAccesser().GetAccesserUserId(),
2574                     item.GetAccessee().GetAccesseeDeviceId()));
2575             }
2576         }
2577         if (accessTokenId == static_cast<int32_t>(accessseetokenId)) {
2578             DmOfflineParam offlineParam;
2579             DeviceProfileConnector::GetInstance().CacheAceeAclId(item, offlineParam.needDelAclInfos);
2580             delProfileMap[item.GetAccessControlId()] = item;
2581             DeleteSkCredAndAcl(offlineParam.needDelAclInfos);
2582             listener_->OnAppUnintall(item.GetAccessee().GetAccesseeBundleName());
2583             if (item.GetBindLevel() == USER) {
2584                 userIdVec.push_back(item.GetAccessee().GetAccesseeUserId());
2585                 delACLInfoVec.push_back(std::pair<int32_t, std::string>(item.GetAccessee().GetAccesseeUserId(),
2586                     item.GetAccesser().GetAccesserDeviceId()));
2587             }
2588         }
2589     }
2590     for (auto item : delProfileMap) {
2591         for (auto it = profiles.begin(); it != profiles.end();) {
2592             if (item.first == it->GetAccessControlId()) {
2593                 it = profiles.erase(it);
2594             } else {
2595                 it++;
2596             }
2597         }
2598     }
2599 }
2600 
GetDelACLInfoVec(const int32_t & accessTokenId,std::vector<DistributedDeviceProfile::AccessControlProfile> & profiles,std::vector<std::pair<int32_t,std::string>> & delACLInfoVec,std::vector<int32_t> & userIdVec,const uint32_t & userId)2601 void DeviceManagerServiceImpl::GetDelACLInfoVec(const int32_t &accessTokenId,
2602     std::vector<DistributedDeviceProfile::AccessControlProfile> &profiles,
2603     std::vector<std::pair<int32_t, std::string>> &delACLInfoVec, std::vector<int32_t> &userIdVec,
2604     const uint32_t &userId)
2605 {
2606     std::map<int64_t, DistributedDeviceProfile::AccessControlProfile> delProfileMap;
2607     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
2608     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
2609     std::string localUdid = std::string(localDeviceId);
2610     for (auto &item : profiles) {
2611         int64_t accesssertokenId = item.GetAccesser().GetAccesserTokenId();
2612         int64_t accessseetokenId = item.GetAccessee().GetAccesseeTokenId();
2613         if (accessTokenId != static_cast<int32_t>(accesssertokenId) &&
2614             accessTokenId != static_cast<int32_t>(accessseetokenId)) {
2615             continue;
2616         }
2617         if (accessTokenId == static_cast<int32_t>(accesssertokenId) &&
2618             userId == item.GetAccesser().GetAccesserUserId() &&
2619             localUdid == item.GetAccessee().GetAccesseeDeviceId()) {
2620             DmOfflineParam offlineParam;
2621             delProfileMap[item.GetAccessControlId()] = item;
2622             DeviceProfileConnector::GetInstance().CacheAcerAclId(item, offlineParam.needDelAclInfos);
2623             DeleteSkCredAndAcl(offlineParam.needDelAclInfos);
2624             if (item.GetBindLevel() == USER) {
2625                 userIdVec.push_back(item.GetAccessee().GetAccesseeUserId());
2626                 delACLInfoVec.push_back(std::pair<int32_t, std::string>(item.GetAccessee().GetAccesseeUserId(),
2627                     item.GetAccesser().GetAccesserDeviceId()));
2628             }
2629         }
2630         if (accessTokenId == static_cast<int32_t>(accessseetokenId) &&
2631             userId == item.GetAccessee().GetAccesseeUserId() &&
2632             localUdid == item.GetAccesser().GetAccesserDeviceId()) {
2633             DmOfflineParam offlineParam;
2634             DeviceProfileConnector::GetInstance().CacheAceeAclId(item, offlineParam.needDelAclInfos);
2635             delProfileMap[item.GetAccessControlId()] = item;
2636             DeleteSkCredAndAcl(offlineParam.needDelAclInfos);
2637             if (item.GetBindLevel() == USER) {
2638                 userIdVec.push_back(item.GetAccesser().GetAccesserUserId());
2639                 delACLInfoVec.push_back(std::pair<int32_t, std::string>(item.GetAccesser().GetAccesserUserId(),
2640                     item.GetAccessee().GetAccesseeDeviceId()));
2641             }
2642         }
2643     }
2644     DeleteAclByDelProfileMap(delProfileMap, profiles, localUdid);
2645 }
2646 
DeleteAclByDelProfileMap(const std::map<int64_t,DistributedDeviceProfile::AccessControlProfile> & delProfileMap,std::vector<DistributedDeviceProfile::AccessControlProfile> & profiles,const std::string & localUdid)2647 void DeviceManagerServiceImpl::DeleteAclByDelProfileMap(
2648     const std::map<int64_t, DistributedDeviceProfile::AccessControlProfile> &delProfileMap,
2649     std::vector<DistributedDeviceProfile::AccessControlProfile> &profiles, const std::string &localUdid)
2650 {
2651     for (auto item : delProfileMap) {
2652         for (auto it = profiles.begin(); it != profiles.end();) {
2653             if (item.first == it->GetAccessControlId()) {
2654                 it = profiles.erase(it);
2655             } else {
2656                 it++;
2657             }
2658         }
2659     }
2660     for (auto item : delProfileMap) {
2661         DmOfflineParam lnnAclParam;
2662         bool isLastLnnAcl = false;
2663         for (auto it : profiles) {
2664             CheckIsLastLnnAcl(it, item.second, lnnAclParam, isLastLnnAcl, localUdid);
2665         }
2666         if (!isLastLnnAcl) {
2667             DeleteSkCredAndAcl(lnnAclParam.needDelAclInfos);
2668         }
2669     }
2670 }
2671 
CheckLnnAcl(DistributedDeviceProfile::AccessControlProfile delProfile,DistributedDeviceProfile::AccessControlProfile lastprofile)2672 bool DeviceManagerServiceImpl::CheckLnnAcl(DistributedDeviceProfile::AccessControlProfile delProfile,
2673     DistributedDeviceProfile::AccessControlProfile lastprofile)
2674 {
2675     if ((delProfile.GetAccesser().GetAccesserDeviceId() == lastprofile.GetAccesser().GetAccesserDeviceId() &&
2676         delProfile.GetAccesser().GetAccesserUserId() == lastprofile.GetAccesser().GetAccesserUserId() &&
2677         delProfile.GetAccessee().GetAccesseeDeviceId() == lastprofile.GetAccessee().GetAccesseeDeviceId() &&
2678         delProfile.GetAccessee().GetAccesseeUserId() == lastprofile.GetAccessee().GetAccesseeUserId()) ||
2679         (delProfile.GetAccesser().GetAccesserDeviceId() == lastprofile.GetAccessee().GetAccesseeDeviceId() &&
2680         delProfile.GetAccesser().GetAccesserUserId() == lastprofile.GetAccessee().GetAccesseeUserId() &&
2681         delProfile.GetAccessee().GetAccesseeDeviceId() == lastprofile.GetAccesser().GetAccesserDeviceId() &&
2682         delProfile.GetAccessee().GetAccesseeUserId() == lastprofile.GetAccesser().GetAccesserUserId())) {
2683         return true;
2684     }
2685     return false;
2686 }
2687 
GetDeviceIdAndUserId(int32_t localUserId)2688 std::multimap<std::string, int32_t> DeviceManagerServiceImpl::GetDeviceIdAndUserId(int32_t localUserId)
2689 {
2690     LOGI("localUserId %{public}d.", localUserId);
2691     char localdeviceId[DEVICE_UUID_LENGTH] = {0};
2692     GetDevUdid(localdeviceId, DEVICE_UUID_LENGTH);
2693     std::string localUdid = std::string(localdeviceId);
2694     return DeviceProfileConnector::GetInstance().GetDeviceIdAndUserId(localUdid, localUserId);
2695 }
2696 
SaveOnlineDeviceInfo(const std::vector<DmDeviceInfo> & deviceList)2697 int32_t DeviceManagerServiceImpl::SaveOnlineDeviceInfo(const std::vector<DmDeviceInfo> &deviceList)
2698 {
2699     CHECK_NULL_RETURN(deviceStateMgr_, ERR_DM_POINT_NULL);
2700     for (auto item : deviceList) {
2701         deviceStateMgr_->SaveOnlineDeviceInfo(item);
2702     }
2703     return DM_OK;
2704 }
2705 
HandleDeviceUnBind(int32_t bindType,const std::string & peerUdid,const std::string & localUdid,int32_t localUserId,const std::string & localAccountId)2706 void DeviceManagerServiceImpl::HandleDeviceUnBind(int32_t bindType, const std::string &peerUdid,
2707     const std::string &localUdid, int32_t localUserId, const std::string &localAccountId)
2708 {
2709     return DeviceProfileConnector::GetInstance().HandleDeviceUnBind(bindType, peerUdid,
2710         localUdid, localUserId, localAccountId);
2711 }
2712 
RegisterAuthenticationType(int32_t authenticationType)2713 int32_t DeviceManagerServiceImpl::RegisterAuthenticationType(int32_t authenticationType)
2714 {
2715     if (authenticationType != USER_OPERATION_TYPE_ALLOW_AUTH &&
2716         authenticationType != USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) {
2717         LOGE("Invalid parameter.");
2718         return ERR_DM_INPUT_PARA_INVALID;
2719     }
2720     auto authMgr = GetAuthMgr();
2721     if (authMgr == nullptr) {
2722         auto config = GetConfigByTokenId();
2723         config->authenticationType = authenticationType;   // only the last registration is retained
2724         return DM_OK;
2725     }
2726     return authMgr->RegisterAuthenticationType(authenticationType);
2727 }
2728 
DeleteAlwaysAllowTimeOut()2729 void DeviceManagerServiceImpl::DeleteAlwaysAllowTimeOut()
2730 {
2731     LOGI("Start");
2732     std::vector<DistributedDeviceProfile::AccessControlProfile> profiles =
2733         DeviceProfileConnector::GetInstance().GetAllAccessControlProfile();
2734     std::string remoteUdid = "";
2735     int32_t remoteUserId = -1;
2736     int64_t currentTime =
2737         std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
2738     int32_t currentUserId = MultipleUserConnector::GetCurrentAccountUserID();
2739     char localDeviceId[DEVICE_UUID_LENGTH] = {0};
2740     GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
2741     std::string localUdid = std::string(localDeviceId);
2742     for (auto &item : profiles) {
2743         if (item.GetBindType() == DM_IDENTICAL_ACCOUNT) {
2744             continue;
2745         }
2746         if ((currentTime - item.GetLastAuthTime()) > MAX_ALWAYS_ALLOW_SECONDS && item.GetLastAuthTime() > 0) {
2747             DeviceProfileConnector::GetInstance().DeleteAccessControlById(item.GetAccessControlId());
2748             if (item.GetAccesser().GetAccesserUserId() == currentUserId &&
2749                 item.GetAccesser().GetAccesserDeviceId() == localUdid) {
2750                 remoteUserId = item.GetAccessee().GetAccesseeUserId();
2751             }
2752             if (item.GetAccessee().GetAccesseeUserId() == currentUserId &&
2753                 item.GetAccessee().GetAccesseeDeviceId() == localUdid) {
2754                 remoteUserId = item.GetAccesser().GetAccesserUserId();
2755             }
2756             remoteUdid = item.GetTrustDeviceId();
2757             CheckDeleteCredential(remoteUdid, remoteUserId);
2758         }
2759     }
2760 }
2761 
CheckDeleteCredential(const std::string & remoteUdid,int32_t remoteUserId)2762 void DeviceManagerServiceImpl::CheckDeleteCredential(const std::string &remoteUdid, int32_t remoteUserId)
2763 {
2764     std::vector<DistributedDeviceProfile::AccessControlProfile> profiles =
2765         DeviceProfileConnector::GetInstance().GetAllAccessControlProfile();
2766     bool leftAcl = false;
2767     for (auto &item : profiles) {
2768         if (item.GetTrustDeviceId() == remoteUdid) {
2769             leftAcl = true;
2770         }
2771     }
2772     if (!leftAcl) {
2773         LOGI("CheckDeleteCredential delete credential");
2774         hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(),
2775             remoteUserId);
2776     }
2777 }
2778 
HandleCredentialDeleted(const char * credId,const char * credInfo,const std::string & localUdid,std::string & remoteUdid,bool & isSendBroadCast)2779 void DeviceManagerServiceImpl::HandleCredentialDeleted(const char *credId, const char *credInfo,
2780     const std::string &localUdid, std::string &remoteUdid, bool &isSendBroadCast)
2781 {
2782     std::vector<DistributedDeviceProfile::AccessControlProfile> profiles;
2783     {
2784         std::lock_guard lock(logoutMutex_);
2785         profiles = DeviceProfileConnector::GetInstance().GetAccessControlProfile();
2786     }
2787 
2788     JsonObject jsonObject;
2789     jsonObject.Parse(std::string(credInfo));
2790     if (jsonObject.IsDiscarded()) {
2791         LOGE("credInfo prase error.");
2792         return;
2793     }
2794     std::string deviceIdTag = "deviceId";
2795     std::string userIdTag = "osAccountId";
2796     int32_t localUserId = MultipleUserConnector::GetCurrentAccountUserID();
2797     int32_t userId = 0;
2798     if (IsString(jsonObject, deviceIdTag)) {
2799         remoteUdid = jsonObject[deviceIdTag].Get<std::string>();
2800     }
2801     if (IsInt32(jsonObject, userIdTag)) {
2802         userId = jsonObject[userIdTag].Get<int32_t>();
2803     }
2804 
2805     for (const auto &item : profiles) {
2806         if (item.GetBindType() != DM_SHARE) {
2807             continue;
2808         }
2809         if ((item.GetAccesser().GetAccesserCredentialIdStr() == credId &&
2810             item.GetAccesser().GetAccesserDeviceId() == localUdid &&
2811             item.GetAccesser().GetAccesserUserId() == localUserId &&
2812             item.GetAccessee().GetAccesseeUserId() == userId &&
2813             item.GetAccessee().GetAccesseeDeviceId() == remoteUdid) ||
2814             (item.GetAccessee().GetAccesseeCredentialIdStr() == credId &&
2815             item.GetAccessee().GetAccesseeDeviceId() == localUdid &&
2816             item.GetAccessee().GetAccesseeUserId() == localUserId &&
2817             item.GetAccesser().GetAccesserUserId() == userId &&
2818             item.GetAccesser().GetAccesserDeviceId() == remoteUdid)) {
2819             isSendBroadCast = true;
2820             DeleteSessionKey(userId, item);
2821             DeviceProfileConnector::GetInstance().DeleteAccessControlById(item.GetAccessControlId());
2822         }
2823     }
2824 }
2825 
HandleShareUnbindBroadCast(const std::string & credId,const int32_t & userId,const std::string & localUdid)2826 void DeviceManagerServiceImpl::HandleShareUnbindBroadCast(const std::string &credId, const int32_t &userId,
2827     const std::string &localUdid)
2828 {
2829     std::vector<DistributedDeviceProfile::AccessControlProfile> profiles;
2830     {
2831         std::lock_guard lock(logoutMutex_);
2832         profiles = DeviceProfileConnector::GetInstance().GetAccessControlProfile();
2833     }
2834     int32_t localUserId = MultipleUserConnector::GetCurrentAccountUserID();
2835     for (const auto &item : profiles) {
2836         if (item.GetBindType() != DM_SHARE) {
2837             continue;
2838         }
2839         std::string accesserCredId = "";
2840         std::string accesseeCredId = "";
2841         for (int32_t i = 0; i < BROADCAST_CREDID_LENGTH; i++) {
2842             accesserCredId += item.GetAccesser().GetAccesserCredentialIdStr()[i];
2843             accesseeCredId += item.GetAccessee().GetAccesseeCredentialIdStr()[i];
2844         }
2845         if (accesserCredId == credId && item.GetAccessee().GetAccesseeDeviceId() == localUdid &&
2846             item.GetAccessee().GetAccesseeUserId() == localUserId &&
2847             item.GetAccesser().GetAccesserUserId() == userId) {
2848             DeleteSessionKey(userId, item);
2849             DeviceProfileConnector::GetInstance().DeleteAccessControlById(item.GetAccessControlId());
2850         }
2851         if (accesseeCredId == credId && item.GetAccesser().GetAccesserDeviceId() == localUdid &&
2852             item.GetAccesser().GetAccesserUserId() == localUserId &&
2853             item.GetAccessee().GetAccesseeUserId() == userId) {
2854             DeleteSessionKey(userId, item);
2855             DeviceProfileConnector::GetInstance().DeleteAccessControlById(item.GetAccessControlId());
2856         }
2857     }
2858 }
2859 
CheckDeviceInfoPermission(const std::string & localUdid,const std::string & peerDeviceId)2860 int32_t DeviceManagerServiceImpl::CheckDeviceInfoPermission(const std::string &localUdid,
2861     const std::string &peerDeviceId)
2862 {
2863     int32_t ret = DeviceProfileConnector::GetInstance().CheckDeviceInfoPermission(localUdid, peerDeviceId);
2864     if (ret != DM_OK) {
2865         LOGE("CheckDeviceInfoPermission failed, ret: %{public}d", ret);
2866         return ret;
2867     }
2868     return DM_OK;
2869 }
2870 
DeleteAcl(const std::string & pkgName,const std::string & localUdid,const std::string & remoteUdid,int32_t bindLevel,const std::string & extra)2871 int32_t DeviceManagerServiceImpl::DeleteAcl(const std::string &pkgName, const std::string &localUdid,
2872     const std::string &remoteUdid, int32_t bindLevel, const std::string &extra)
2873 {
2874     LOGI("pkgName %{public}s, localUdid %{public}s, remoteUdid %{public}s, bindLevel %{public}d.",
2875         pkgName.c_str(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str(), bindLevel);
2876     if (static_cast<uint32_t>(bindLevel) == USER) {
2877         DeleteGroup(pkgName, remoteUdid);
2878     }
2879     DmOfflineParam offlineParam =
2880         DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localUdid, remoteUdid, bindLevel, extra);
2881     if (offlineParam.bindType == INVALIED_TYPE) {
2882         LOGE("Acl not contain the pkgname bind data.");
2883         return ERR_DM_FAILED;
2884     }
2885     CHECK_NULL_RETURN(softbusConnector_, ERR_DM_POINT_NULL);
2886     CHECK_NULL_RETURN(hiChainAuthConnector_, ERR_DM_POINT_NULL);
2887     if (static_cast<uint32_t>(bindLevel) == APP) {
2888         ProcessInfo processInfo;
2889         processInfo.pkgName = pkgName;
2890         processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId();
2891         if (offlineParam.leftAclNumber != 0) {
2892             LOGI("The pkgName unbind app-level type leftAclNumber not zero.");
2893             softbusConnector_->SetProcessInfoVec(offlineParam.processVec);
2894             softbusConnector_->HandleDeviceOffline(remoteUdid);
2895             return DM_OK;
2896         }
2897         if (offlineParam.leftAclNumber == 0) {
2898             LOGI("The pkgName unbind app-level type leftAclNumber is zero.");
2899             softbusConnector_->SetProcessInfoVec(offlineParam.processVec);
2900             hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(),
2901                 offlineParam.peerUserId);
2902             return DM_OK;
2903         }
2904     }
2905     if (static_cast<uint32_t>(bindLevel) == USER && offlineParam.leftAclNumber != 0) {
2906         LOGI("Unbind deivce-level, retain identical account bind type.");
2907         return DM_OK;
2908     }
2909     if (static_cast<uint32_t>(bindLevel) == USER && offlineParam.leftAclNumber == 0) {
2910         LOGI("Unbind deivce-level, retain null.");
2911         hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID(),
2912             offlineParam.peerUserId);
2913         return DM_OK;
2914     }
2915     return ERR_DM_FAILED;
2916 }
2917 
DeleteCredential(DmAclIdParam & acl)2918 void DeviceManagerServiceImpl::DeleteCredential(DmAclIdParam &acl)
2919 {
2920     CHECK_NULL_VOID(hiChainAuthConnector_);
2921     JsonObject credJson;
2922     int32_t ret = hiChainAuthConnector_->QueryCredInfoByCredId(acl.userId, acl.credId, credJson);
2923     if (ret != DM_OK || !credJson.Contains(acl.credId)) {
2924         LOGE("DeleteCredential err, ret:%{public}d", ret);
2925         return;
2926     }
2927     if (!credJson[acl.credId].Contains(FILED_AUTHORIZED_APP_LIST)) {
2928         ret = hiChainAuthConnector_->DeleteCredential(acl.userId, acl.credId);
2929         if (ret != DM_OK) {
2930             LOGE("DeletecredId err, ret:%{public}d", ret);
2931         }
2932         return;
2933     }
2934     DistributedDeviceProfile::AccessControlProfile profile =
2935         DeviceProfileConnector::GetInstance().GetAccessControlProfileByAccessControlId(acl.accessControlId);
2936     if (profile.GetAccessControlId() != acl.accessControlId) {
2937         LOGE("DeleteCredential, no found profile");
2938         return;
2939     }
2940     std::vector<std::string> appList;
2941     credJson[acl.credId][FILED_AUTHORIZED_APP_LIST].Get(appList);
2942     auto erIt = std::find(appList.begin(), appList.end(), std::to_string(profile.GetAccesser().GetAccesserTokenId()));
2943     if (erIt != appList.end()) {
2944         appList.erase(erIt);
2945     }
2946     auto eeIt = std::find(appList.begin(), appList.end(), std::to_string(profile.GetAccessee().GetAccesseeTokenId()));
2947     if (eeIt != appList.end()) {
2948         appList.erase(eeIt);
2949     }
2950     if (appList.size() == 0) {
2951         ret = hiChainAuthConnector_->DeleteCredential(acl.userId, acl.credId);
2952         if (ret != DM_OK) {
2953             LOGE("DeletecredId err, ret:%{public}d", ret);
2954         }
2955         return;
2956     }
2957     hiChainAuthConnector_->UpdateCredential(acl.credId, acl.userId, appList);
2958 }
2959 
DeleteSkCredAndAcl(const std::vector<DmAclIdParam> & acls)2960 int32_t DeviceManagerServiceImpl::DeleteSkCredAndAcl(const std::vector<DmAclIdParam> &acls)
2961 {
2962     LOGI("start.");
2963     int32_t ret = DM_OK;
2964     if (acls.empty()) {
2965         return ret;
2966     }
2967     CHECK_NULL_RETURN(hiChainAuthConnector_, ERR_DM_POINT_NULL);
2968     for (auto item : acls) {
2969         LOGI("DeleteSkCredAndAcl, userId:%{public}d, skId:%{public}d, credId:%{public}s",
2970             item.userId, item.skId, GetAnonyString(item.credId).c_str());
2971         ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(item.userId, item.skId);
2972         if (ret != DM_OK) {
2973             LOGE("DeleteSessionKey err, ret:%{public}d", ret);
2974         }
2975         DeleteCredential(item);
2976         DeviceProfileConnector::GetInstance().DeleteAccessControlById(item.accessControlId);
2977     }
2978     return ret;
2979 }
2980 
DeleteAclForProcV2(const std::string & localUdid,uint32_t localTokenId,const std::string & remoteUdid,int32_t bindLevel,const std::string & extra,int32_t userId)2981 int32_t DeviceManagerServiceImpl::DeleteAclForProcV2(const std::string &localUdid, uint32_t localTokenId,
2982     const std::string &remoteUdid, int32_t bindLevel, const std::string &extra, int32_t userId)
2983 {
2984     DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().FilterNeedDeleteACL(
2985         localUdid, localTokenId, remoteUdid, extra);
2986 
2987     //first, clear the unbind sk/cred/acl
2988     DeleteSkCredAndAcl(offlineParam.needDelAclInfos);
2989 
2990     //second, not app/service/user/DM_IDENTICAL_ACCOUNT acl exist, determin if need clear lnn acl
2991     if (offlineParam.allLeftAppOrSvrAclInfos.empty() && offlineParam.allUserAclInfos.empty()) {
2992         LOGI("No acl exist, clear lnn acl");
2993         DeleteSkCredAndAcl(offlineParam.allLnnAclInfos);
2994     }
2995 
2996     //third, not user/DM_IDENTICAL_ACCOUNT acl exist but app/service acl exist
2997     //determin if need report offline to unbind bundle
2998     if (offlineParam.allUserAclInfos.empty() && !offlineParam.allLeftAppOrSvrAclInfos.empty()) {
2999         LOGI("after clear target acl, No user acl exist, report offline");
3000         softbusConnector_->SetProcessInfoVec(offlineParam.processVec);
3001         softbusConnector_->HandleDeviceOffline(remoteUdid);
3002     }
3003     return DM_OK;
3004 }
3005 
IsProxyUnbind(const std::string & extra)3006 bool DeviceManagerServiceImpl::IsProxyUnbind(const std::string &extra)
3007 {
3008     if (extra.empty()) {
3009         return false;
3010     }
3011     JsonObject jsonObject;
3012     jsonObject.Parse(extra);
3013     if (jsonObject.IsDiscarded()) {
3014         return false;
3015     }
3016     if (IsString(jsonObject, PARAM_KEY_IS_PROXY_UNBIND) &&
3017         jsonObject[PARAM_KEY_IS_PROXY_UNBIND].Get<std::string>() == DM_VAL_TRUE) {
3018         return true;
3019     }
3020     return false;
3021 }
3022 
DeleteAclV2(const std::string & pkgName,const std::string & localUdid,const std::string & remoteUdid,int32_t bindLevel,const std::string & extra)3023 int32_t DeviceManagerServiceImpl::DeleteAclV2(const std::string &pkgName, const std::string &localUdid,
3024     const std::string &remoteUdid, int32_t bindLevel, const std::string &extra)
3025 {
3026     LOGI("pkgName %{public}s, localUdid %{public}s, remoteUdid %{public}s, bindLevel %{public}d.",
3027         pkgName.c_str(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str(), bindLevel);
3028     int64_t tokenId = 0;
3029     int32_t userId = MultipleUserConnector::GetCurrentAccountUserID();
3030     if (IsProxyUnbind(extra) != true) {
3031         uint32_t callingTokenId = 0;
3032         MultipleUserConnector::GetTokenId(callingTokenId);
3033         tokenId = static_cast<int64_t>(callingTokenId);
3034     } else {
3035         std::string bundleName = pkgName;
3036         AppManager::GetInstance().GetTokenIdByBundleName(userId, bundleName, tokenId);
3037     }
3038     bool isNewVersion = IsAuthNewVersion(bindLevel, localUdid, remoteUdid, tokenId, userId);
3039     if (!isNewVersion) {
3040         return DeleteAcl(pkgName, localUdid, remoteUdid, bindLevel, extra);
3041     }
3042     return DeleteAclForProcV2(localUdid, tokenId, remoteUdid, bindLevel, extra, userId);
3043 }
3044 
HandleCommonEventBroadCast(const std::vector<uint32_t> & foregroundUserIds,const std::vector<uint32_t> & backgroundUserIds,const std::string & remoteUdid)3045 void DeviceManagerServiceImpl::HandleCommonEventBroadCast(const std::vector<uint32_t> &foregroundUserIds,
3046     const std::vector<uint32_t> &backgroundUserIds, const std::string &remoteUdid)
3047 {
3048     LOGI("remote udid: %{public}s, foregroundUserIds: %{public}s, backgroundUserIds: %{public}s",
3049         GetAnonyString(remoteUdid).c_str(), GetIntegerList<uint32_t>(foregroundUserIds).c_str(),
3050         GetIntegerList<uint32_t>(backgroundUserIds).c_str());
3051     std::vector<int32_t> rmtFrontUserIdsTemp(foregroundUserIds.begin(), foregroundUserIds.end());
3052     std::vector<int32_t> rmtBackUserIdsTemp(backgroundUserIds.begin(), backgroundUserIds.end());
3053     std::vector<int32_t> localUserIds;
3054     int32_t ret = MultipleUserConnector::GetForegroundUserIds(localUserIds);
3055     if (ret != DM_OK) {
3056         LOGE("Get foreground userids failed, ret: %{public}d", ret);
3057         return;
3058     }
3059     char localUdidTemp[DEVICE_UUID_LENGTH] = {0};
3060     GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH);
3061     std::string localUdid = std::string(localUdidTemp);
3062     MultipleUserConnector::ClearLockedUser(localUserIds);
3063     DmOfflineParam offlineParam;
3064     DeviceProfileConnector::GetInstance().UpdateACL(localUdid, localUserIds, remoteUdid,
3065         rmtFrontUserIdsTemp, rmtBackUserIdsTemp, offlineParam);
3066     DeleteSkCredAndAcl(offlineParam.needDelAclInfos);
3067     DeviceProfileConnector::GetInstance().HandleSyncBackgroundUserIdEvent(rmtBackUserIdsTemp, remoteUdid,
3068         localUserIds, localUdid);
3069     DeviceProfileConnector::GetInstance().HandleSyncForegroundUserIdEvent(rmtFrontUserIdsTemp, remoteUdid,
3070         localUserIds, localUdid);
3071 }
3072 
GetBindCallerInfo(DmBindCallerInfo & bindCallerInfo,const std::string & pkgName)3073 void DeviceManagerServiceImpl::GetBindCallerInfo(DmBindCallerInfo &bindCallerInfo, const std::string &pkgName)
3074 {
3075     int32_t userId = -1;
3076     MultipleUserConnector::GetCallerUserId(userId);
3077     uint32_t callingTokenId = 0;
3078     MultipleUserConnector::GetCallingTokenId(callingTokenId);
3079     bool isSystemSA = false;
3080     std::string bundleName = "";
3081     AppManager::GetInstance().GetCallerName(isSystemSA, bundleName);
3082     std::string processName = "";
3083     AppManager::GetInstance().GetCallerProcessName(processName);
3084     int32_t bindLevel = static_cast<int32_t>(DmRole::DM_ROLE_FA);
3085     if (AppManager::GetInstance().IsSystemApp()) {
3086         bindLevel = static_cast<int32_t>(DmRole::DM_ROLE_FA);
3087     }
3088     if (AppManager::GetInstance().IsSystemSA()) {
3089         isSystemSA = true;
3090         bindLevel = static_cast<int32_t>(DmRole::DM_ROLE_SA);
3091     }
3092     if (AuthManagerBase::CheckProcessNameInWhiteList(bundleName)) {
3093         bindLevel = static_cast<int32_t>(DmRole::DM_ROLE_USER);
3094     }
3095     std::string hostPkgLabel = GetBundleLable(pkgName);
3096     bindCallerInfo.userId = userId;
3097     bindCallerInfo.tokenId = static_cast<int32_t>(callingTokenId);
3098     bindCallerInfo.bindLevel = bindLevel;
3099     bindCallerInfo.bundleName = bundleName;
3100     bindCallerInfo.hostPkgLabel  = hostPkgLabel;
3101     bindCallerInfo.processName = processName;
3102     bindCallerInfo.isSystemSA = isSystemSA;
3103     LOGI("userId %{public}d, tokenId %{public}s, bindLevel %{public}d, bundleName %{public}s, hostPkgLabel  %{public}s,"
3104         "processName %{public}s, isSystemSA %{public}d", userId, GetAnonyInt32(callingTokenId).c_str(), bindLevel,
3105         GetAnonyString(bundleName).c_str(), GetAnonyString(hostPkgLabel).c_str(), GetAnonyString(processName).c_str(),
3106         isSystemSA);
3107 }
3108 
GetBundleLable(const std::string & bundleName)3109 std::string DeviceManagerServiceImpl::GetBundleLable(const std::string &bundleName)
3110 {
3111     auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
3112     if (samgr == nullptr) {
3113         LOGE("Get ability manager failed");
3114         return bundleName;
3115     }
3116 
3117     sptr<IRemoteObject> object = samgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
3118     if (object == nullptr) {
3119         LOGE("object is NULL.");
3120         return bundleName;
3121     }
3122 
3123     sptr<OHOS::AppExecFwk::IBundleMgr> bms = iface_cast<OHOS::AppExecFwk::IBundleMgr>(object);
3124     if (bms == nullptr) {
3125         LOGE("bundle manager service is NULL.");
3126         return bundleName;
3127     }
3128 
3129     auto bundleResourceProxy = bms->GetBundleResourceProxy();
3130     if (bundleResourceProxy == nullptr) {
3131         LOGE("GetBundleResourceProxy fail");
3132         return bundleName;
3133     }
3134     AppExecFwk::BundleResourceInfo resourceInfo;
3135     auto result = bundleResourceProxy->GetBundleResourceInfo(bundleName,
3136         static_cast<uint32_t>(OHOS::AppExecFwk::ResourceFlag::GET_RESOURCE_INFO_ALL), resourceInfo);
3137     if (result != ERR_OK) {
3138         LOGE("GetBundleResourceInfo failed");
3139         return bundleName;
3140     }
3141     LOGI("bundle resource label is %{public}s ", (resourceInfo.label).c_str());
3142     return resourceInfo.label;
3143 }
3144 
SetBindCallerInfoToBindParam(const std::map<std::string,std::string> & bindParam,std::map<std::string,std::string> & bindParamTmp,const DmBindCallerInfo & bindCallerInfo)3145 void DeviceManagerServiceImpl::SetBindCallerInfoToBindParam(const std::map<std::string, std::string> &bindParam,
3146     std::map<std::string, std::string> &bindParamTmp, const DmBindCallerInfo &bindCallerInfo)
3147 {
3148     bindParamTmp = const_cast<std::map<std::string, std::string> &>(bindParam);
3149     bindParamTmp["bindCallerUserId"] = std::to_string(bindCallerInfo.userId);
3150     bindParamTmp["bindCallerTokenId"] = std::to_string(bindCallerInfo.tokenId);
3151     bindParamTmp["bindCallerBindLevel"] = std::to_string(bindCallerInfo.bindLevel);
3152     bindParamTmp["bindCallerBundleName"] = bindCallerInfo.bundleName;
3153     bindParamTmp["bindCallerHostPkgLabel"] = bindCallerInfo.hostPkgLabel;
3154     bindParamTmp["bindCallerProcessName"] = bindCallerInfo.processName;
3155     bindParamTmp["bindCallerIsSystemSA"] = bindCallerInfo.isSystemSA;
3156 }
3157 
CheckSrcAccessControl(const DmAccessCaller & caller,const std::string & srcUdid,const DmAccessCallee & callee,const std::string & sinkUdid)3158 bool DeviceManagerServiceImpl::CheckSrcAccessControl(const DmAccessCaller &caller, const std::string &srcUdid,
3159     const DmAccessCallee &callee, const std::string &sinkUdid)
3160 {
3161     return DeviceProfileConnector::GetInstance().CheckSrcAccessControl(caller, srcUdid, callee, sinkUdid);
3162 }
3163 
CheckSinkAccessControl(const DmAccessCaller & caller,const std::string & srcUdid,const DmAccessCallee & callee,const std::string & sinkUdid)3164 bool DeviceManagerServiceImpl::CheckSinkAccessControl(const DmAccessCaller &caller, const std::string &srcUdid,
3165     const DmAccessCallee &callee, const std::string &sinkUdid)
3166 {
3167     return DeviceProfileConnector::GetInstance().CheckSinkAccessControl(caller, srcUdid, callee, sinkUdid);
3168 }
3169 
CheckSrcIsSameAccount(const DmAccessCaller & caller,const std::string & srcUdid,const DmAccessCallee & callee,const std::string & sinkUdid)3170 bool DeviceManagerServiceImpl::CheckSrcIsSameAccount(const DmAccessCaller &caller, const std::string &srcUdid,
3171     const DmAccessCallee &callee, const std::string &sinkUdid)
3172 {
3173     return DeviceProfileConnector::GetInstance().CheckSrcIsSameAccount(caller, srcUdid, callee, sinkUdid);
3174 }
3175 
CheckSinkIsSameAccount(const DmAccessCaller & caller,const std::string & srcUdid,const DmAccessCallee & callee,const std::string & sinkUdid)3176 bool DeviceManagerServiceImpl::CheckSinkIsSameAccount(const DmAccessCaller &caller, const std::string &srcUdid,
3177     const DmAccessCallee &callee, const std::string &sinkUdid)
3178 {
3179     return DeviceProfileConnector::GetInstance().CheckSinkIsSameAccount(caller, srcUdid, callee, sinkUdid);
3180 }
3181 
DeleteHoDevice(const std::string & peerUdid,const std::vector<int32_t> & foreGroundUserIds,const std::vector<int32_t> & backGroundUserIds)3182 void DeviceManagerServiceImpl::DeleteHoDevice(const std::string &peerUdid,
3183     const std::vector<int32_t> &foreGroundUserIds, const std::vector<int32_t> &backGroundUserIds)
3184 {
3185     LOGI("peerudid %{public}s, foreGroundUserIds %{public}s, backGroundUserIds %{public}s.",
3186         GetAnonyString(peerUdid).c_str(), GetIntegerList(foreGroundUserIds).c_str(),
3187         GetIntegerList(backGroundUserIds).c_str());
3188     //delete acl
3189     DeviceProfileConnector::GetInstance().DeleteHoDevice(peerUdid, foreGroundUserIds, backGroundUserIds);
3190     //delete group
3191     hiChainConnector_->DeleteHoDevice(peerUdid, foreGroundUserIds, backGroundUserIds);
3192     return;
3193 }
3194 
DeleteSessionKey(int32_t userId,const DistributedDeviceProfile::AccessControlProfile & profile)3195 void DeviceManagerServiceImpl::DeleteSessionKey(int32_t userId,
3196     const DistributedDeviceProfile::AccessControlProfile &profile)
3197 {
3198     int32_t skId = profile.GetAccesser().GetAccesserSessionKeyId();
3199     DeviceProfileConnector::GetInstance().DeleteSessionKey(userId, skId);
3200     skId = profile.GetAccessee().GetAccesseeSessionKeyId();
3201     DeviceProfileConnector::GetInstance().DeleteSessionKey(userId, skId);
3202 }
3203 
CreateDMServiceObject(void)3204 extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void)
3205 {
3206     return new DeviceManagerServiceImpl;
3207 }
3208 } // namespace DistributedHardware
3209 } // namespace OHOS
3210