1 /*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "device_profile_manager.h"
17
18 #include <algorithm>
19 #include <dlfcn.h>
20 #include <list>
21 #include <thread>
22
23 #include "datetime_ex.h"
24 #include "dm_constants.h"
25
26 #include "content_sensor_manager_utils.h"
27 #include "distributed_device_profile_errors.h"
28 #include "distributed_device_profile_enums.h"
29 #include "distributed_device_profile_log.h"
30 #include "event_handler_factory.h"
31 #include "i_sync_completed_callback.h"
32 #include "kv_adapter.h"
33 #include "multi_user_manager.h"
34 #include "permission_manager.h"
35 #include "profile_cache.h"
36 #include "profile_control_utils.h"
37 #include "profile_utils.h"
38 #include "static_profile_manager.h"
39 #include "trust_profile_manager.h"
40
41 namespace OHOS {
42 namespace DistributedDeviceProfile {
43 constexpr const char *LIB_DP_ADAPTER_NAME = "libdeviceprofileadapter.z.so";
44 IMPLEMENT_SINGLE_INSTANCE(DeviceProfileManager);
45 namespace {
46 const std::string APP_ID = "distributed_device_profile_service";
47 const std::string STORE_ID = "dp_kv_store";
48 const std::string TAG = "DeviceProfileManager";
49 const std::unordered_set<std::string> NON_OHBASE_NEED_CLEAR_SVR_NAMES {
50 "collaborationFwk", "Nfc_Publish_Br_Mac_Address" };
51 }
52
Init()53 int32_t DeviceProfileManager::Init()
54 {
55 HILOGI("call!");
56 int32_t initResult = DP_MANAGER_INIT_FAIL;
57 {
58 std::lock_guard<std::mutex> lock(dynamicStoreMutex_);
59 deviceProfileStore_ = std::make_shared<KVAdapter>(APP_ID, STORE_ID,
60 std::make_shared<KvDataChangeListener>(STORE_ID),
61 std::make_shared<KvSyncCompletedListener>(STORE_ID), std::make_shared<KvDeathRecipient>(STORE_ID),
62 DistributedKv::TYPE_DYNAMICAL);
63 initResult = deviceProfileStore_->Init();
64 if (initResult != DP_SUCCESS) {
65 HILOGE("deviceProfileStore init failed");
66 return initResult;
67 }
68 std::string localDeviceId = ContentSensorManagerUtils::GetInstance().ObtainLocalUdid();
69 std::string dbKeyPrefix = ProfileUtils::GenerateDeviceProfileKey(localDeviceId);
70 std::map<std::string, std::string> values;
71 int32_t status = deviceProfileStore_->GetByPrefix(dbKeyPrefix, values);
72 if (status == DP_SUCCESS) {
73 isFirst_.store(values.empty());
74 }
75 }
76 LoadDpSyncAdapter();
77 HILOGI("Init finish, res: %{public}d", initResult);
78 return initResult;
79 }
80
UnInit()81 int32_t DeviceProfileManager::UnInit()
82 {
83 HILOGI("call!");
84 {
85 std::lock_guard<std::mutex> lock(dynamicStoreMutex_);
86 if (deviceProfileStore_ == nullptr) {
87 HILOGE("deviceProfileStore_ is nullptr");
88 return DP_KV_DB_PTR_NULL;
89 }
90 deviceProfileStore_->UnInit();
91 deviceProfileStore_ = nullptr;
92 }
93 {
94 std::lock_guard<std::mutex> lock(putTempCacheMutex_);
95 putTempCache_.clear();
96 }
97 UnloadDpSyncAdapter();
98 return DP_SUCCESS;
99 }
100
ReInit()101 int32_t DeviceProfileManager::ReInit()
102 {
103 HILOGI("call!");
104 UnInit();
105 return Init();
106 }
107
PutDeviceProfile(const DeviceProfile & deviceProfile)108 int32_t DeviceProfileManager::PutDeviceProfile(const DeviceProfile& deviceProfile)
109 {
110 HILOGI("deviceProfile: %{public}s", deviceProfile.AnnoymizeDump().c_str());
111 if (!ProfileUtils::IsDevProfileValid(deviceProfile)) {
112 HILOGE("the profile is invalid! deviceProfile: %{public}s", deviceProfile.AnnoymizeDump().c_str());
113 return DP_INVALID_PARAMS;
114 }
115 std::map<std::string, std::string> entries;
116 if (deviceProfile.IsMultiUser()) {
117 ProfileUtils::DeviceProfileToEntries(deviceProfile, entries, true);
118 if (MultiUserManager::GetInstance().GetCurrentForegroundUserID() == deviceProfile.GetUserId()) {
119 ProfileUtils::DeviceProfileToEntries(deviceProfile, entries);
120 } else {
121 HILOGI("the profile does not belong to the current user.");
122 }
123 } else {
124 ProfileUtils::DeviceProfileToEntries(deviceProfile, entries);
125 }
126 if (isFirst_.load()) {
127 AddToPutTempCache(entries);
128 return DP_SUCCESS;
129 }
130 {
131 std::lock_guard<std::mutex> lock(dynamicStoreMutex_);
132 if (deviceProfileStore_ == nullptr) {
133 HILOGE("deviceProfileStore is nullptr!");
134 return DP_KV_DB_PTR_NULL;
135 }
136 if (deviceProfileStore_->PutBatch(entries) != DP_SUCCESS) {
137 HILOGE("PutDeviceProfile fail! deviceProfile: %{public}s", deviceProfile.AnnoymizeDump().c_str());
138 return DP_PUT_KV_DB_FAIL;
139 }
140 }
141 HILOGD("PutDeviceProfile success");
142 return DP_SUCCESS;
143 }
144
PutServiceProfile(const ServiceProfile & serviceProfile)145 int32_t DeviceProfileManager::PutServiceProfile(const ServiceProfile& serviceProfile)
146 {
147 HILOGI("serviceProfile: %{public}s", serviceProfile.dump().c_str());
148 if (!ProfileUtils::IsSvrProfileValid(serviceProfile)) {
149 HILOGE("the profile is invalid!");
150 return DP_INVALID_PARAMS;
151 }
152 std::map<std::string, std::string> entries;
153 if (serviceProfile.IsMultiUser()) {
154 ProfileUtils::ServiceProfileToEntries(serviceProfile, entries, true);
155 if (MultiUserManager::GetInstance().GetCurrentForegroundUserID() == serviceProfile.GetUserId()) {
156 ProfileUtils::ServiceProfileToEntries(serviceProfile, entries);
157 } else {
158 HILOGI("the profile does not belong to the current user.");
159 }
160 } else {
161 ProfileUtils::ServiceProfileToEntries(serviceProfile, entries);
162 }
163 if (isFirst_.load()) {
164 AddToPutTempCache(entries);
165 return DP_SUCCESS;
166 }
167 {
168 std::lock_guard<std::mutex> lock(dynamicStoreMutex_);
169 if (deviceProfileStore_ == nullptr) {
170 HILOGE("deviceProfileStore is nullptr!");
171 return DP_KV_DB_PTR_NULL;
172 }
173 if (deviceProfileStore_->PutBatch(entries) != DP_SUCCESS) {
174 HILOGE("PutServiceProfile fail! serviceProfile: %{public}s", serviceProfile.dump().c_str());
175 return DP_PUT_KV_DB_FAIL;
176 }
177 }
178 HILOGD("PutServiceProfile success");
179 return DP_SUCCESS;
180 }
181
PutServiceProfileBatch(const std::vector<ServiceProfile> & serviceProfiles)182 int32_t DeviceProfileManager::PutServiceProfileBatch(const std::vector<ServiceProfile>& serviceProfiles)
183 {
184 HILOGD("call!");
185 std::map<std::string, std::string> entries;
186 for (const auto& serviceProfile : serviceProfiles) {
187 if (!ProfileUtils::IsSvrProfileValid(serviceProfile)) {
188 HILOGE("the profile is invalid! serviceProfile:%{public}s", serviceProfile.dump().c_str());
189 continue;
190 }
191 if (serviceProfile.IsMultiUser()) {
192 ProfileUtils::ServiceProfileToEntries(serviceProfile, entries, true);
193 if (MultiUserManager::GetInstance().GetCurrentForegroundUserID() == serviceProfile.GetUserId()) {
194 ProfileUtils::ServiceProfileToEntries(serviceProfile, entries);
195 } else {
196 HILOGI("the profile does not belong to the current user.");
197 }
198 } else {
199 ProfileUtils::ServiceProfileToEntries(serviceProfile, entries);
200 }
201 }
202 if (isFirst_.load()) {
203 AddToPutTempCache(entries);
204 return DP_SUCCESS;
205 }
206 {
207 std::lock_guard<std::mutex> lock(dynamicStoreMutex_);
208 if (deviceProfileStore_ == nullptr) {
209 HILOGE("deviceProfileStore is nullptr!");
210 return DP_KV_DB_PTR_NULL;
211 }
212 if (deviceProfileStore_->PutBatch(entries) != DP_SUCCESS) {
213 HILOGE("PutServiceProfileBatch fail!");
214 return DP_PUT_KV_DB_FAIL;
215 }
216 }
217 HILOGD("PutServiceProfileBatch success");
218 return DP_SUCCESS;
219 }
220
PutCharacteristicProfile(const CharacteristicProfile & charProfile)221 int32_t DeviceProfileManager::PutCharacteristicProfile(const CharacteristicProfile& charProfile)
222 {
223 HILOGI("charProfile: %{public}s", charProfile.dump().c_str());
224 if (!ProfileUtils::IsCharProfileValid(charProfile)) {
225 HILOGE("the profile is invalid!");
226 return DP_INVALID_PARAMS;
227 }
228 std::map<std::string, std::string> entries;
229 if (charProfile.IsMultiUser()) {
230 ProfileUtils::CharacteristicProfileToEntries(charProfile, entries, true);
231 if (MultiUserManager::GetInstance().GetCurrentForegroundUserID() == charProfile.GetUserId()) {
232 ProfileUtils::CharacteristicProfileToEntries(charProfile, entries);
233 } else {
234 HILOGI("the profile does not belong to the current user.");
235 }
236 } else {
237 ProfileUtils::CharacteristicProfileToEntries(charProfile, entries);
238 }
239 if (isFirst_.load()) {
240 AddToPutTempCache(entries);
241 return DP_SUCCESS;
242 }
243 {
244 std::lock_guard<std::mutex> lock(dynamicStoreMutex_);
245 if (deviceProfileStore_ == nullptr) {
246 HILOGE("deviceProfileStore is nullptr!");
247 return DP_KV_DB_PTR_NULL;
248 }
249 if (deviceProfileStore_->PutBatch(entries) != DP_SUCCESS) {
250 HILOGE("PutCharacteristicProfile fail! charProfile: %{public}s", charProfile.dump().c_str());
251 return DP_PUT_KV_DB_FAIL;
252 }
253 }
254 HILOGD("PutCharacteristicProfile success");
255 return DP_SUCCESS;
256 }
257
PutCharacteristicProfileBatch(const std::vector<CharacteristicProfile> & charProfiles)258 int32_t DeviceProfileManager::PutCharacteristicProfileBatch(const std::vector<CharacteristicProfile>& charProfiles)
259 {
260 HILOGD("call!");
261 std::map<std::string, std::string> entries;
262 for (const auto& charProfile : charProfiles) {
263 if (!ProfileUtils::IsCharProfileValid(charProfile)) {
264 HILOGE("the profile is invalid! charProfile:%{public}s", charProfile.dump().c_str());
265 continue;
266 }
267 if (charProfile.IsMultiUser()) {
268 ProfileUtils::CharacteristicProfileToEntries(charProfile, entries, true);
269 if (MultiUserManager::GetInstance().GetCurrentForegroundUserID() == charProfile.GetUserId()) {
270 ProfileUtils::CharacteristicProfileToEntries(charProfile, entries);
271 } else {
272 HILOGI("the profile does not belong to the current user.");
273 }
274 } else {
275 ProfileUtils::CharacteristicProfileToEntries(charProfile, entries);
276 }
277 }
278 if (isFirst_.load()) {
279 AddToPutTempCache(entries);
280 return DP_SUCCESS;
281 }
282 {
283 std::lock_guard<std::mutex> lock(dynamicStoreMutex_);
284 if (deviceProfileStore_ == nullptr) {
285 HILOGE("deviceProfileStore is nullptr!");
286 return DP_KV_DB_PTR_NULL;
287 }
288 if (deviceProfileStore_->PutBatch(entries) != DP_SUCCESS) {
289 HILOGE("PutCharacteristicProfileBatch fail!");
290 return DP_PUT_KV_DB_FAIL;
291 }
292 }
293 HILOGD("PutCharacteristicProfileBatch success");
294 return DP_SUCCESS;
295 }
296
GetDeviceProfile(const std::string & deviceId,DeviceProfile & deviceProfile)297 int32_t DeviceProfileManager::GetDeviceProfile(const std::string& deviceId, DeviceProfile& deviceProfile)
298 {
299 deviceProfile.SetDeviceId(deviceId);
300 int32_t res = IsMultiUserValid(deviceProfile);
301 if (res != DP_SUCCESS) {
302 HILOGE("GetDeviceProfile IsMultiUserValid failed, res: %{public}d", res);
303 return res;
304 }
305 {
306 std::lock_guard<std::mutex> lock(dynamicStoreMutex_);
307 res = ProfileControlUtils::GetDeviceProfile(deviceProfileStore_, deviceId, deviceProfile);
308 }
309 if (res != DP_SUCCESS) {
310 HILOGE("GetDeviceProfile fail, reason: %{public}d!", res);
311 return res;
312 }
313 HILOGD("GetDeviceProfile success");
314 return DP_SUCCESS;
315 }
316
GetServiceProfile(const std::string & deviceId,const std::string & serviceName,ServiceProfile & serviceProfile)317 int32_t DeviceProfileManager::GetServiceProfile(const std::string& deviceId, const std::string& serviceName,
318 ServiceProfile& serviceProfile)
319 {
320 serviceProfile.SetDeviceId(deviceId);
321 int32_t res = IsMultiUserValid(serviceProfile);
322 if (res != DP_SUCCESS) {
323 HILOGE("GetServiceProfile IsMultiUserValid failed, res: %{public}d", res);
324 return res;
325 }
326 {
327 std::lock_guard<std::mutex> lock(dynamicStoreMutex_);
328 res = ProfileControlUtils::GetServiceProfile(deviceProfileStore_, deviceId, serviceName,
329 serviceProfile);
330 }
331 if (res != DP_SUCCESS) {
332 HILOGE("GetServiceProfile fail, reason: %{public}d!", res);
333 return res;
334 }
335 HILOGD("GetServiceProfile success");
336 return DP_SUCCESS;
337 }
338
GetCharacteristicProfile(const std::string & deviceId,const std::string & serviceName,const std::string & characteristicKey,CharacteristicProfile & charProfile)339 int32_t DeviceProfileManager::GetCharacteristicProfile(const std::string& deviceId, const std::string& serviceName,
340 const std::string& characteristicKey, CharacteristicProfile& charProfile)
341 {
342 charProfile.SetDeviceId(deviceId);
343 int32_t res = IsMultiUserValid(charProfile);
344 if (res != DP_SUCCESS) {
345 HILOGE("IsMultiUserValid fail, res:%{public}d, devId:%{public}s, svrName:%{public}s, charKey:%{public}s!",
346 res, ProfileUtils::GetAnonyString(deviceId).c_str(), serviceName.c_str(), characteristicKey.c_str());
347 return res;
348 }
349 {
350 std::lock_guard<std::mutex> lock(dynamicStoreMutex_);
351 res = ProfileControlUtils::GetCharacteristicProfile(deviceProfileStore_, deviceId, serviceName,
352 characteristicKey, charProfile);
353 }
354 if (res != DP_SUCCESS) {
355 HILOGE("fail, reason: %{public}d! devId:%{public}s, svrName:%{public}s, charKey:%{public}s!",
356 res, ProfileUtils::GetAnonyString(deviceId).c_str(), serviceName.c_str(), characteristicKey.c_str());
357 return res;
358 }
359 HILOGD("GetCharacteristicProfile success");
360 return DP_SUCCESS;
361 }
362
DeleteServiceProfile(const std::string & deviceId,const std::string & serviceName,bool isMultiUser,int32_t userId)363 int32_t DeviceProfileManager::DeleteServiceProfile(const std::string& deviceId, const std::string& serviceName,
364 bool isMultiUser, int32_t userId)
365 {
366 HILOGD("call!");
367 int32_t res = 0;
368 {
369 std::lock_guard<std::mutex> lock(dynamicStoreMutex_);
370 res = ProfileControlUtils::DeleteServiceProfile(deviceProfileStore_, deviceId, serviceName, isMultiUser,
371 userId);
372 }
373 if (res != DP_SUCCESS) {
374 HILOGE("DeleteServiceProfile fail, reason: %{public}d!", res);
375 return res;
376 }
377 HILOGD("DeleteServiceProfile success");
378 return DP_SUCCESS;
379 }
380
DeleteCharacteristicProfile(const std::string & deviceId,const std::string & serviceName,const std::string & characteristicKey,bool isMultiUser,int32_t userId)381 int32_t DeviceProfileManager::DeleteCharacteristicProfile(const std::string& deviceId, const std::string& serviceName,
382 const std::string& characteristicKey, bool isMultiUser, int32_t userId)
383 {
384 HILOGD("call!");
385 int32_t res = 0;
386 {
387 std::lock_guard<std::mutex> lock(dynamicStoreMutex_);
388 res = ProfileControlUtils::DeleteCharacteristicProfile(deviceProfileStore_, deviceId, serviceName,
389 characteristicKey, isMultiUser, userId);
390 }
391 if (res != DP_SUCCESS) {
392 HILOGE("DeleteCharacteristicProfile fail, reason: %{public}d!", res);
393 return res;
394 }
395 HILOGD("DeleteCharacteristicProfile success");
396 return DP_SUCCESS;
397 }
398
DeleteRemovedUserData(int32_t userId)399 int32_t DeviceProfileManager::DeleteRemovedUserData(int32_t userId)
400 {
401 if (userId < MIN_USER_ID || userId > MAX_USER_ID) {
402 HILOGE("Invalid userId: %{public}d", userId);
403 return DP_INVALID_PARAM;
404 }
405 std::map<std::string, std::string> allLocalEntries;
406 std::vector<std::string> keysToDelete;
407 std::string localDeviceId = ProfileCache::GetInstance().GetLocalUdid();
408 if (localDeviceId.empty()) {
409 HILOGE("GetLocalUdid fail");
410 return DP_GET_LOCAL_UDID_FAILED;
411 }
412 int32_t getRet = GetProfilesByKeyPrefix(localDeviceId, allLocalEntries);
413 if (getRet != DP_SUCCESS) {
414 HILOGE("GetLocalProfile fail,deviceId: %{public}s,reason: %{public}d!",
415 ProfileUtils::GetAnonyString(localDeviceId).c_str(), getRet);
416 return getRet;
417 }
418 for (const auto& pair : allLocalEntries) {
419 if (userId == ProfileUtils::GetUserIdFromDbKey(pair.first)) {
420 keysToDelete.emplace_back(pair.first);
421 }
422 }
423 if (keysToDelete.empty()) {
424 HILOGI("userId:%{public}d has no multi-user data.", userId);
425 return DP_SUCCESS;
426 }
427 std::lock_guard<std::mutex> lock(dynamicStoreMutex_);
428 if (deviceProfileStore_ == nullptr) {
429 HILOGE("dynamicProfileStore is nullptr!");
430 return DP_KV_DB_PTR_NULL;
431 }
432 int32_t delRet = deviceProfileStore_->DeleteBatch(keysToDelete);
433 if (delRet != DP_SUCCESS) {
434 HILOGE("DeleteBatch fail, reason: %{public}d!", delRet);
435 return delRet;
436 }
437 return DP_SUCCESS;
438 }
439
GetAllDeviceProfile(std::vector<DeviceProfile> & deviceProfiles)440 int32_t DeviceProfileManager::GetAllDeviceProfile(std::vector<DeviceProfile>& deviceProfiles)
441 {
442 HILOGD("call!");
443 int32_t res = 0;
444 {
445 std::lock_guard<std::mutex> lock(dynamicStoreMutex_);
446 res = ProfileControlUtils::GetAllDeviceProfile(deviceProfileStore_, deviceProfiles);
447 }
448 if (res != DP_SUCCESS) {
449 HILOGE("GetAllDeviceProfile fail, reason: %{public}d!", res);
450 return res;
451 }
452 HILOGD("GetAllDeviceProfile success");
453 return DP_SUCCESS;
454 }
455
GetAllServiceProfile(std::vector<ServiceProfile> & serviceProfiles)456 int32_t DeviceProfileManager::GetAllServiceProfile(std::vector<ServiceProfile>& serviceProfiles)
457 {
458 HILOGD("call!");
459 int32_t res = 0;
460 {
461 std::lock_guard<std::mutex> lock(dynamicStoreMutex_);
462 res = ProfileControlUtils::GetAllServiceProfile(deviceProfileStore_, serviceProfiles);
463 }
464 if (res != DP_SUCCESS) {
465 HILOGE("serviceProfiles fail, reason: %{public}d!", res);
466 return res;
467 }
468 HILOGD("serviceProfiles success");
469 return DP_SUCCESS;
470 }
471
GetAllCharacteristicProfile(std::vector<CharacteristicProfile> & charProfiles)472 int32_t DeviceProfileManager::GetAllCharacteristicProfile(std::vector<CharacteristicProfile>& charProfiles)
473 {
474 HILOGD("call!");
475 int32_t res = 0;
476 {
477 std::lock_guard<std::mutex> lock(dynamicStoreMutex_);
478 res = ProfileControlUtils::GetAllCharacteristicProfile(deviceProfileStore_, charProfiles);
479 }
480 if (res != DP_SUCCESS) {
481 HILOGE("GetAllCharacteristicProfile fail, reason: %{public}d!", res);
482 return res;
483 }
484 HILOGD("GetAllCharacteristicProfile success");
485 return DP_SUCCESS;
486 }
487
SyncDeviceProfile(const DistributedDeviceProfile::DpSyncOptions & syncOptions,sptr<IRemoteObject> syncCompletedCallback)488 int32_t DeviceProfileManager::SyncDeviceProfile(const DistributedDeviceProfile::DpSyncOptions& syncOptions,
489 sptr<IRemoteObject> syncCompletedCallback)
490 {
491 HILOGI("call!");
492 if (syncCompletedCallback == nullptr) {
493 HILOGE("Params is invalid!");
494 return DP_INVALID_PARAMS;
495 }
496 std::vector<std::string> ohBasedDevices;
497 std::vector<std::string> notOHBasedDevices;
498 ProfileCache::GetInstance().FilterAndGroupOnlineDevices(syncOptions.GetDeviceList(),
499 ohBasedDevices, notOHBasedDevices);
500 if (ohBasedDevices.empty() && notOHBasedDevices.empty()) {
501 HILOGE("Params is invalid!");
502 return DP_INVALID_PARAMS;
503 }
504 std::string callerDescriptor = PermissionManager::GetInstance().GetCallerProcName();
505 if (!ohBasedDevices.empty()) {
506 ProfileCache::GetInstance().AddSyncListener(callerDescriptor, syncCompletedCallback);
507 {
508 std::lock_guard<std::mutex> lock(dynamicStoreMutex_);
509 if (deviceProfileStore_ == nullptr) {
510 HILOGE("deviceProfileStore is nullptr");
511 return DP_SYNC_DEVICE_FAIL;
512 }
513 int32_t syncResult = deviceProfileStore_->Sync(ohBasedDevices, syncOptions.GetSyncMode());
514 if (syncResult != DP_SUCCESS) {
515 HILOGE("SyncDeviceProfile fail, res: %{public}d!", syncResult);
516 return DP_SYNC_DEVICE_FAIL;
517 }
518 }
519 }
520 if (!notOHBasedDevices.empty()) {
521 auto syncTask = [this, notOHBasedDevices, callerDescriptor, syncCompletedCallback]() {
522 SyncWithNotOHBasedDevice(notOHBasedDevices, callerDescriptor, syncCompletedCallback);
523 };
524 std::thread(syncTask).detach();
525 }
526 HILOGI("SyncDeviceProfile success, caller: %{public}s!", callerDescriptor.c_str());
527 return DP_SUCCESS;
528 }
529
LoadDpSyncAdapter()530 bool DeviceProfileManager::LoadDpSyncAdapter()
531 {
532 HILOGI("start.");
533 std::lock_guard<std::mutex> lock(isAdapterLoadLock_);
534 if (isAdapterSoLoaded_ && (dpSyncAdapter_ != nullptr)) {
535 return true;
536 }
537 int64_t beginTime = GetTickCount();
538 std::string soName = std::string(LIB_DP_ADAPTER_NAME);
539 if ((soName.length() == 0) || (soName.length() > PATH_MAX)) {
540 HILOGE("File %{public}s canonicalization failed", soName.c_str());
541 return false;
542 }
543 void *so_handle = dlopen(soName.c_str(), RTLD_NOW | RTLD_NOLOAD);
544 if (so_handle == nullptr) {
545 so_handle = dlopen(soName.c_str(), RTLD_NOW);
546 }
547 if (so_handle == nullptr) {
548 HILOGE("load dp sync adapter so %{public}s failed", soName.c_str());
549 return false;
550 }
551 dlerror();
552 auto func = (CreateDPSyncAdapterFuncPtr)dlsym(so_handle, "CreateDPSyncAdaptertObject");
553 if (dlerror() != nullptr || func == nullptr) {
554 dlclose(so_handle);
555 HILOGE("Create object function is not exist.");
556 return false;
557 }
558 auto adapter = func();
559 if (adapter == nullptr) {
560 dlclose(so_handle);
561 HILOGE("adapter is nullptr");
562 return false;
563 }
564 dpSyncAdapter_ = std::shared_ptr<IDPSyncAdapter>(adapter);
565 if (dpSyncAdapter_->Initialize() != DP_SUCCESS) {
566 dpSyncAdapter_->Release();
567 dpSyncAdapter_ = nullptr;
568 isAdapterSoLoaded_ = false;
569 HILOGE("dp sync adapter init failed");
570 return false;
571 }
572 isAdapterSoLoaded_ = true;
573 int64_t endTime = GetTickCount();
574 HILOGI("sucess. spend %{public}" PRId64 " ms", endTime - beginTime);
575 return true;
576 }
577
UnloadDpSyncAdapter()578 void DeviceProfileManager::UnloadDpSyncAdapter()
579 {
580 HILOGD("start.");
581 std::lock_guard<std::mutex> lock(isAdapterLoadLock_);
582 if (dpSyncAdapter_ != nullptr) {
583 dpSyncAdapter_->Release();
584 }
585 dpSyncAdapter_ = nullptr;
586 std::string soPathName = std::string(LIB_DP_ADAPTER_NAME);
587 if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX)) {
588 HILOGE("File %{public}s canonicalization failed", soPathName.c_str());
589 return;
590 }
591 void *so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NOLOAD);
592 if (so_handle != nullptr) {
593 HILOGI("dp sync adapter so_handle is not nullptr.");
594 dlclose(so_handle);
595 isAdapterSoLoaded_ = false;
596 }
597 }
598
SyncWithNotOHBasedDevice(const std::vector<std::string> & notOHBasedDevices,const std::string & callerDescriptor,sptr<IRemoteObject> syncCompletedCallback)599 int32_t DeviceProfileManager::SyncWithNotOHBasedDevice(const std::vector<std::string>& notOHBasedDevices,
600 const std::string& callerDescriptor, sptr<IRemoteObject> syncCompletedCallback)
601 {
602 if (!LoadDpSyncAdapter()) {
603 HILOGE("dp service adapter load failed.");
604 SyncWithNotOHBasedDeviceFailed(notOHBasedDevices, syncCompletedCallback);
605 return DP_LOAD_SYNC_ADAPTER_FAILED;
606 }
607 for (const auto& deviceId : notOHBasedDevices) {
608 if (RunloadedFunction(deviceId, syncCompletedCallback) != DP_SUCCESS) {
609 HILOGE("Sync With NotOHBasedDevice Failed. deviceId:%{public}s",
610 ProfileUtils::GetAnonyString(deviceId).c_str());
611 SyncWithNotOHBasedDeviceFailed({deviceId}, syncCompletedCallback);
612 }
613 }
614 return DP_SUCCESS;
615 }
616
SyncWithNotOHBasedDeviceFailed(const std::vector<std::string> & notOHBasedDevices,sptr<IRemoteObject> syncCompletedCallback)617 void DeviceProfileManager::SyncWithNotOHBasedDeviceFailed(const std::vector<std::string>& notOHBasedDevices,
618 sptr<IRemoteObject> syncCompletedCallback)
619 {
620 std::map<std::string, SyncStatus> syncResults;
621 for (const auto& deviceId : notOHBasedDevices) {
622 syncResults[deviceId] = SyncStatus::FAILED;
623 }
624 sptr<ISyncCompletedCallback> syncListenerProxy = iface_cast<ISyncCompletedCallback>(syncCompletedCallback);
625 if (syncListenerProxy == nullptr) {
626 HILOGE("Cast to ISyncCompletedCallback failed");
627 return;
628 }
629 syncListenerProxy->OnSyncCompleted(syncResults);
630 }
631
RunloadedFunction(const std::string & deviceId,sptr<IRemoteObject> syncCompletedCallback)632 int32_t DeviceProfileManager::RunloadedFunction(const std::string& deviceId, sptr<IRemoteObject> syncCompletedCallback)
633 {
634 std::lock_guard<std::mutex> lock(isAdapterLoadLock_);
635 if (dpSyncAdapter_ == nullptr) {
636 HILOGE("dpSyncAdapter is nullptr.");
637 return DP_LOAD_SYNC_ADAPTER_FAILED;
638 }
639 if (dpSyncAdapter_->DetectRemoteDPVersion(deviceId) != DP_SUCCESS) {
640 HILOGE("dp service adapter detect remote version failed.");
641 return DP_LOAD_SYNC_ADAPTER_FAILED;
642 }
643 const std::list<std::string> deviceIdList = { deviceId };
644 if (dpSyncAdapter_->SyncProfile(deviceIdList, syncCompletedCallback) != DP_SUCCESS) {
645 HILOGE("dp service adapter sync profile failed.");
646 return DP_LOAD_SYNC_ADAPTER_FAILED;
647 }
648 HILOGD("dp service adapter sync profile success.");
649 return DP_SUCCESS;
650 }
651
GetEntriesByKeys(const std::vector<std::string> & keys)652 std::vector<DistributedKv::Entry> DeviceProfileManager::GetEntriesByKeys(const std::vector<std::string>& keys)
653 {
654 HILOGD("call!");
655 std::vector<DistributedKv::Entry> entries;
656 if (keys.empty()) {
657 HILOGE("keys empty.");
658 return entries;
659 }
660 {
661 std::lock_guard<std::mutex> lock(dynamicStoreMutex_);
662 if (deviceProfileStore_ == nullptr) {
663 HILOGE("dynamicProfileStore is nullptr!");
664 return entries;
665 }
666 for (const auto& key : keys) {
667 std::string value;
668 if (deviceProfileStore_->Get(key, value) != DP_SUCCESS) {
669 continue;
670 }
671 DistributedKv::Entry entry;
672 DistributedKv::Key kvKey(key);
673 entry.key = kvKey;
674 entry.value = value;
675 entries.emplace_back(entry);
676 }
677 }
678 return entries;
679 }
680
AddToPutTempCache(const std::map<std::string,std::string> & values)681 void DeviceProfileManager::AddToPutTempCache(const std::map<std::string, std::string>& values)
682 {
683 if (values.empty()) {
684 HILOGW("values empty!");
685 return;
686 }
687 HILOGI("values.size : %{public}zu", values.size());
688 {
689 std::lock_guard<std::mutex> lock(putTempCacheMutex_);
690 for (const auto& [key, value] : values) {
691 putTempCache_[key] = value;
692 }
693 }
694 }
695
SavePutTempCache(std::map<std::string,std::string> & entries)696 int32_t DeviceProfileManager::SavePutTempCache(std::map<std::string, std::string>& entries)
697 {
698 HILOGI("business entries.size : %{public}zu", entries.size());
699 {
700 std::lock_guard<std::mutex> lock(putTempCacheMutex_);
701 if (!putTempCache_.empty()) {
702 for (const auto& [key, value] : putTempCache_) {
703 entries[key] = value;
704 }
705 }
706 }
707 if (entries.empty()) {
708 HILOGW("all entries empty!");
709 isFirst_.store(false);
710 {
711 std::lock_guard<std::mutex> lock(putTempCacheMutex_);
712 putTempCache_.clear();
713 }
714 return DP_SUCCESS;
715 }
716 HILOGI("all entries.size : %{public}zu", entries.size());
717 int32_t ret = DP_SUCCESS;
718 {
719 std::lock_guard<std::mutex> lock(dynamicStoreMutex_);
720 if (deviceProfileStore_ == nullptr) {
721 HILOGE("deviceProfileStore is nullptr!");
722 return DP_GET_KV_DB_FAIL;
723 }
724 ret = deviceProfileStore_->PutBatch(entries);
725 if (ret != DP_SUCCESS) {
726 HILOGE("PutBatch fail! ret:%{public}d", ret);
727 return ret;
728 }
729 }
730 isFirst_.store(false);
731 {
732 std::lock_guard<std::mutex> lock(putTempCacheMutex_);
733 putTempCache_.clear();
734 }
735 HILOGI("put all entries success");
736 return ret;
737 }
738
IsFirstInitDB()739 bool DeviceProfileManager::IsFirstInitDB()
740 {
741 return isFirst_.load();
742 }
743
ResetFirst()744 void DeviceProfileManager::ResetFirst()
745 {
746 isFirst_.store(false);
747 }
748
OnDeviceOnline(const TrustedDeviceInfo & deviceInfo)749 void DeviceProfileManager::OnDeviceOnline(const TrustedDeviceInfo& deviceInfo)
750 {
751 FixDataOnDeviceOnline(deviceInfo);
752 NotifyNotOHBaseOnline(deviceInfo);
753 if (ContentSensorManagerUtils::GetInstance().IsDeviceE2ESync()) {
754 HILOGI("need E2ESync, deviceInfo:%{public}s", deviceInfo.dump().c_str());
755 E2ESyncDynamicProfile(deviceInfo);
756 StaticProfileManager::GetInstance().E2ESyncStaticProfile(deviceInfo);
757 }
758 }
759
FixDataOnDeviceOnline(const TrustedDeviceInfo & deviceInfo)760 void DeviceProfileManager::FixDataOnDeviceOnline(const TrustedDeviceInfo& deviceInfo)
761 {
762 HILOGI("deviceInfo=%{public}s", deviceInfo.dump().c_str());
763 if (deviceInfo.GetNetworkId().empty()) {
764 HILOGE("networkId is empty!");
765 return;
766 }
767 auto task = [this, deviceInfo]() {
768 std::string localUdid = ProfileCache::GetInstance().GetLocalUdid();
769 std::string localUuid = ProfileCache::GetInstance().GetLocalUuid();
770 if (localUdid.empty() || localUuid.empty()) {
771 HILOGE("Get local udid fail.");
772 return;
773 }
774 std::map<std::string, std::string> localDataByOwner;
775 if (GetProfilesByOwner(localUuid, localDataByOwner) != DP_SUCCESS) {
776 HILOGE("GetProfilesByOwner fail, localUuid=%{public}s", ProfileUtils::GetAnonyString(localUuid).c_str());
777 return;
778 }
779 FixLocalData(localUdid, localDataByOwner);
780 if (deviceInfo.GetUdid().empty()) {
781 HILOGE("remoteUdid empty. remoteNetworkId=%{public}s",
782 ProfileUtils::GetAnonyString(deviceInfo.GetNetworkId()).c_str());
783 return;
784 }
785 if (deviceInfo.GetOsType() != OHOS_TYPE) {
786 FixRemoteDataWhenPeerIsNonOH(deviceInfo.GetUdid());
787 return;
788 }
789 FixRemoteDataWhenPeerIsOHBase(deviceInfo.GetUdid(), localDataByOwner);
790 };
791 auto handler = EventHandlerFactory::GetInstance().GetEventHandler();
792 if (handler == nullptr || !handler->PostTask(task)) {
793 HILOGE("Post FixDataOnDeviceOnline task faild");
794 return;
795 }
796 }
797
DeleteBatchByKeys(const std::vector<std::string> & delKeys)798 int32_t DeviceProfileManager::DeleteBatchByKeys(const std::vector<std::string>& delKeys)
799 {
800 HILOGD("delKeys.size:%{public}zu", delKeys.size());
801 if (delKeys.empty()) {
802 HILOGW("delKeys is empty");
803 return DP_SUCCESS;
804 }
805 std::lock_guard<std::mutex> lock(dynamicStoreMutex_);
806 if (deviceProfileStore_ == nullptr) {
807 HILOGE("dynamicProfileStore is nullptr!");
808 return DP_KV_DB_PTR_NULL;
809 }
810 if (deviceProfileStore_->DeleteBatch(delKeys) != DP_SUCCESS) {
811 HILOGE("DeleteBatch fail");
812 return DP_DEL_KV_DB_FAIL;
813 }
814 return DP_SUCCESS;
815 }
816
GetProfilesByOwner(const std::string & uuid,std::map<std::string,std::string> & values)817 int32_t DeviceProfileManager::GetProfilesByOwner(const std::string& uuid, std::map<std::string, std::string>& values)
818 {
819 HILOGD("uuid:%{public}s", ProfileUtils::GetAnonyString(uuid).c_str());
820 if (uuid.empty()) {
821 HILOGW("uuid is empty");
822 return DP_INVALID_PARAM;
823 }
824 std::lock_guard<std::mutex> lock(dynamicStoreMutex_);
825 if (deviceProfileStore_ == nullptr) {
826 HILOGE("dynamicProfileStore is nullptr!");
827 return DP_KV_DB_PTR_NULL;
828 }
829 if (deviceProfileStore_->GetDeviceEntries(uuid, values) != DP_SUCCESS) {
830 HILOGE("GetDeviceEntries fail, uuid=%{public}s", ProfileUtils::GetAnonyString(uuid).c_str());
831 return DP_GET_DEVICE_ENTRIES_FAIL;
832 }
833 return DP_SUCCESS;
834 }
835
GetProfilesByKeyPrefix(const std::string & udid,std::map<std::string,std::string> & values)836 int32_t DeviceProfileManager::GetProfilesByKeyPrefix(const std::string& udid,
837 std::map<std::string, std::string>& values)
838 {
839 HILOGD("udid:%{public}s", ProfileUtils::GetAnonyString(udid).c_str());
840 if (udid.empty()) {
841 HILOGW("udid is empty");
842 return DP_INVALID_PARAM;
843 }
844 std::lock_guard<std::mutex> lock(dynamicStoreMutex_);
845 if (deviceProfileStore_ == nullptr) {
846 HILOGE("dynamicProfileStore is nullptr!");
847 return DP_KV_DB_PTR_NULL;
848 }
849 if (deviceProfileStore_->GetByPrefix(DEV_PREFIX + SEPARATOR + udid, values) != DP_SUCCESS) {
850 HILOGE("Get dev profile by prefix fail, udid=%{public}s", ProfileUtils::GetAnonyString(udid).c_str());
851 return DP_GET_KV_DB_FAIL;
852 }
853 if (deviceProfileStore_->GetByPrefix(SVR_PREFIX + SEPARATOR + udid, values) != DP_SUCCESS) {
854 HILOGE("Get svr profile by prefix fail, udid=%{public}s", ProfileUtils::GetAnonyString(udid).c_str());
855 return DP_GET_KV_DB_FAIL;
856 }
857 if (deviceProfileStore_->GetByPrefix(CHAR_PREFIX + SEPARATOR + udid, values) != DP_SUCCESS) {
858 HILOGE("Get char profile by prefix fail, udid=%{public}s", ProfileUtils::GetAnonyString(udid).c_str());
859 return DP_GET_KV_DB_FAIL;
860 }
861 return DP_SUCCESS;
862 }
863
NotifyNotOHBaseOnline(const TrustedDeviceInfo & deviceInfo)864 void DeviceProfileManager::NotifyNotOHBaseOnline(const TrustedDeviceInfo& deviceInfo)
865 {
866 HILOGI("deviceInfo:%{public}s", deviceInfo.dump().c_str());
867 if (deviceInfo.GetNetworkId().empty()) {
868 HILOGE("networkId is empty!");
869 return;
870 }
871 if (deviceInfo.GetOsType() == OHOS_TYPE) {
872 HILOGD("device is ohbase. networkId=%{public}s",
873 ProfileUtils::GetAnonyString(deviceInfo.GetNetworkId()).c_str());
874 return;
875 }
876 if (!ProfileUtils::IsP2p(deviceInfo.GetAuthForm())) {
877 HILOGD("is not point 2 point. remoteNetworkId=%{public}s",
878 ProfileUtils::GetAnonyString(deviceInfo.GetNetworkId()).c_str());
879 return;
880 }
881 auto task = [this, deviceInfo]() {
882 if (deviceInfo.GetUdid().empty()) {
883 HILOGE("remoteUdid empty. remoteNetworkId=%{public}s",
884 ProfileUtils::GetAnonyString(deviceInfo.GetNetworkId()).c_str());
885 return;
886 }
887 std::lock_guard<std::mutex> lock(isAdapterLoadLock_);
888 if (dpSyncAdapter_ == nullptr) {
889 HILOGE("dpSyncAdapter is nullptr.");
890 return;
891 }
892 int32_t ret = dpSyncAdapter_->NotOHBaseDeviceOnline(deviceInfo.GetUdid(), deviceInfo.GetNetworkId(),
893 ProfileUtils::IsP2p(deviceInfo.GetAuthForm()));
894 if (ret != DP_SUCCESS) {
895 HILOGE("NotOHBaseDeviceOnline fail. ret=%{public}d, remoteNetworkId=%{public}s, authForm=%{public}d",
896 ret, ProfileUtils::GetAnonyString(deviceInfo.GetNetworkId()).c_str(), deviceInfo.GetAuthForm());
897 return;
898 }
899 };
900 auto handler = EventHandlerFactory::GetInstance().GetEventHandler();
901 if (handler == nullptr || !handler->PostTask(task)) {
902 HILOGE("Post NotifyNotOHBaseOnline task faild");
903 return;
904 }
905 }
906
E2ESyncDynamicProfile(const TrustedDeviceInfo & deviceInfo)907 void DeviceProfileManager::E2ESyncDynamicProfile(const TrustedDeviceInfo& deviceInfo)
908 {
909 HILOGI("deviceInfo:%{public}s", deviceInfo.dump().c_str());
910 auto task = [this, deviceInfo]() {
911 HILOGD("networkId:%{public}s", ProfileUtils::GetAnonyString(deviceInfo.GetNetworkId()).c_str());
912 if (deviceInfo.GetNetworkId().empty()) {
913 HILOGE("networkId or extraData is empty!");
914 return;
915 }
916 if (deviceInfo.GetOsType() != OHOS_TYPE) {
917 HILOGI("device is not ohbase. remoteNetworkId=%{public}s",
918 ProfileUtils::GetAnonyString(deviceInfo.GetNetworkId()).c_str());
919 return;
920 }
921 std::lock_guard<std::mutex> lock(dynamicStoreMutex_);
922 if (deviceProfileStore_ == nullptr) {
923 HILOGE("deviceProfileStore is nullptr");
924 return;
925 }
926 int32_t syncResult = deviceProfileStore_->Sync({deviceInfo.GetNetworkId()}, SyncMode::PUSH_PULL);
927 if (syncResult != DP_SUCCESS) {
928 HILOGE("E2ESyncDynamicProfile fail, res: %{public}d!", syncResult);
929 return;
930 }
931 HILOGI("E2ESyncDynamicProfile success!");
932 };
933 auto handler = EventHandlerFactory::GetInstance().GetEventHandler();
934 if (handler == nullptr || !handler->PostTask(task)) {
935 HILOGE("Post E2ESyncDynamicProfile task fail!");
936 return;
937 }
938 }
939
940 // Clean data that does not belong to the local.
FixLocalData(const std::string & localUdid,const std::map<std::string,std::string> & localDataByOwner)941 void DeviceProfileManager::FixLocalData(const std::string& localUdid,
942 const std::map<std::string, std::string>& localDataByOwner)
943 {
944 HILOGD("localUdid:%{public}s,localDataByOwner.size:%{public}zu",
945 ProfileUtils::GetAnonyString(localUdid).c_str(), localDataByOwner.size());
946 if (localDataByOwner.empty()) { return; }
947 std::map<std::string, std::string> localDataByKeyPrefix;
948 if (GetProfilesByKeyPrefix(localUdid, localDataByKeyPrefix) != DP_SUCCESS) {
949 HILOGE("GetProfilesByKeyPrefix fail, localUdid=%{public}s", ProfileUtils::GetAnonyString(localUdid).c_str());
950 return;
951 }
952 HILOGD("localDataByKeyPrefix.size:%{public}zu", localDataByKeyPrefix.size());
953 if (localDataByKeyPrefix.empty()) { return; }
954 std::vector<std::string> delKeys;
955 // cloud has local data, but the data is not written by local
956 for (const auto& [key, _] : localDataByKeyPrefix) {
957 if (localDataByOwner.find(key) == localDataByOwner.end()) {
958 HILOGI("delKey: %{public}s", ProfileUtils::GetDbKeyAnonyString(key).c_str());
959 delKeys.emplace_back(key);
960 }
961 }
962 HILOGD("delKeys.size:%{public}zu", delKeys.size());
963 if (delKeys.empty()) { return; }
964 if (DeleteBatchByKeys(delKeys) != DP_SUCCESS) {
965 HILOGE("DeleteBatchByKeys fail, localUdid=%{public}s", ProfileUtils::GetAnonyString(localUdid).c_str());
966 return;
967 }
968 }
969
970 // Clean ohbase data when the peer is non-ohbase
FixRemoteDataWhenPeerIsNonOH(const std::string & remoteUdid)971 void DeviceProfileManager::FixRemoteDataWhenPeerIsNonOH(const std::string& remoteUdid)
972 {
973 HILOGD("remoteUdid:%{public}s", ProfileUtils::GetAnonyString(remoteUdid).c_str());
974 std::map<std::string, std::string> remoteDataByKeyPrefix;
975 if (GetProfilesByKeyPrefix(remoteUdid, remoteDataByKeyPrefix) != DP_SUCCESS) {
976 HILOGE("GetProfilesByKeyPrefix fail, remoteUdid=%{public}s", ProfileUtils::GetAnonyString(remoteUdid).c_str());
977 return;
978 }
979 std::vector<std::string> delKeys;
980 for (const auto& [key, _] : remoteDataByKeyPrefix) {
981 std::vector<std::string> res;
982 if (ProfileUtils::SplitString(key, SEPARATOR, res) != DP_SUCCESS || res.size() < NUM_3) {
983 HILOGW("SplitString fail, key: %{public}s", ProfileUtils::GetDbKeyAnonyString(key).c_str());
984 continue;
985 }
986 if (ProfileUtils::EndsWith(res[NUM_2], OH_PROFILE_SUFFIX)) {
987 HILOGI("delKey: %{public}s", ProfileUtils::GetDbKeyAnonyString(key).c_str());
988 delKeys.emplace_back(key);
989 continue;
990 }
991 if ((res[0] == SVR_PREFIX || res[0] == CHAR_PREFIX) &&
992 NON_OHBASE_NEED_CLEAR_SVR_NAMES.find(res[NUM_2]) != NON_OHBASE_NEED_CLEAR_SVR_NAMES.end()) {
993 HILOGI("delKey: %{public}s", ProfileUtils::GetDbKeyAnonyString(key).c_str());
994 delKeys.emplace_back(key);
995 continue;
996 }
997 }
998 HILOGD("delKeys.size:%{public}zu", delKeys.size());
999 if (delKeys.empty()) { return; }
1000 if (DeleteBatchByKeys(delKeys) != DP_SUCCESS) {
1001 HILOGE("DeleteBatchByKeys fail, remoteUdid=%{public}s", ProfileUtils::GetAnonyString(remoteUdid).c_str());
1002 return;
1003 }
1004 }
1005
1006 // Clean non-ohbase data when the peer is ohbase
FixRemoteDataWhenPeerIsOHBase(const std::string & remoteUdid,const std::map<std::string,std::string> & localDataByOwner)1007 void DeviceProfileManager::FixRemoteDataWhenPeerIsOHBase(const std::string& remoteUdid,
1008 const std::map<std::string, std::string>& localDataByOwner)
1009 {
1010 HILOGD("remoteUdid:%{public}s", ProfileUtils::GetAnonyString(remoteUdid).c_str());
1011 std::vector<std::string> delKeys;
1012 // local has remote data, and the data is written by local
1013 for (const auto& [key, _] : localDataByOwner) {
1014 if (key.find(remoteUdid) != std::string::npos) {
1015 HILOGI("delKey: %{public}s", ProfileUtils::GetDbKeyAnonyString(key).c_str());
1016 delKeys.emplace_back(key);
1017 }
1018 }
1019 HILOGD("delKeys.size:%{public}zu", delKeys.size());
1020 if (delKeys.empty()) { return; }
1021 if (deviceProfileStore_->DeleteBatch(delKeys) != DP_SUCCESS) {
1022 HILOGE("DeleteBatch failed, remoteUdid=%{public}s", ProfileUtils::GetAnonyString(remoteUdid).c_str());
1023 return;
1024 }
1025 }
1026
FixDiffProfiles()1027 void DeviceProfileManager::FixDiffProfiles()
1028 {
1029 HILOGI("call");
1030 std::lock_guard<std::mutex> lock(isAdapterLoadLock_);
1031 if (dpSyncAdapter_ == nullptr) {
1032 HILOGE("dpSyncAdapter is nullptr!");
1033 return;
1034 }
1035 int32_t ret = dpSyncAdapter_->FixDiffProfiles({});
1036 if (ret!= DP_SUCCESS) {
1037 HILOGE("FixDiffProfiles fail! ret=%{public}d", ret);
1038 return;
1039 }
1040 return;
1041 }
1042
OnUserChange(int32_t lastUserId,int32_t curUserId)1043 void DeviceProfileManager::OnUserChange(int32_t lastUserId, int32_t curUserId)
1044 {
1045 HILOGI("lastUserId:%{public}d,curUserId:%{public}d", lastUserId, curUserId);
1046 if (lastUserId == curUserId) {
1047 HILOGW("user not change");
1048 return;
1049 }
1050 std::string localUdid = ProfileCache::GetInstance().GetLocalUdid();
1051 if (localUdid.empty()) {
1052 HILOGE("GetLocalUdid fail");
1053 return;
1054 }
1055 std::map<std::string, std::string> profileMap;
1056 if (GetProfilesByKeyPrefix(localUdid, profileMap) != DP_SUCCESS || profileMap.empty()) {
1057 HILOGE("Get All Local Profiles fail");
1058 return;
1059 }
1060 std::unordered_set<std::string> lastUserDbKeysWithoutUID;
1061 std::map<std::string, std::string> curUserProfiles;
1062 for (const auto& [key, value] : profileMap) {
1063 int32_t userId = ProfileUtils::GetUserIdFromDbKey(key);
1064 if (userId != DEFAULT_USER_ID && userId == lastUserId) {
1065 std::string dbKeyWithoutUID = ProfileUtils::RemoveUserIdFromDbKey(key);
1066 if (!dbKeyWithoutUID.empty()) {
1067 lastUserDbKeysWithoutUID.insert(dbKeyWithoutUID);
1068 }
1069 }
1070 if (userId != DEFAULT_USER_ID && userId == curUserId) {
1071 curUserProfiles[key] = value;
1072 }
1073 }
1074 std::map<std::string, std::string> curUserProfilesWithoutUID;
1075 for (const auto& [key, value] : curUserProfiles) {
1076 std::string dbKeyWithoutUID = ProfileUtils::RemoveUserIdFromDbKey(key);
1077 if (!dbKeyWithoutUID.empty()) {
1078 lastUserDbKeysWithoutUID.erase(dbKeyWithoutUID);
1079 curUserProfilesWithoutUID[dbKeyWithoutUID] = value;
1080 }
1081 }
1082 int32_t ret = SaveBatchByKeys(curUserProfilesWithoutUID);
1083 if (ret != DP_SUCCESS) {
1084 HILOGE("SaveBatchByKeys fail ret=%{public}d", ret);
1085 return;
1086 }
1087 std::vector<std::string> delKeys{lastUserDbKeysWithoutUID.begin(), lastUserDbKeysWithoutUID.end()};
1088 ret = DeleteBatchByKeys(delKeys);
1089 if (ret != DP_SUCCESS) {
1090 HILOGE("DeleteBatchByKeys fail ret=%{public}d", ret);
1091 return;
1092 }
1093 }
1094
SaveBatchByKeys(const std::map<std::string,std::string> & entries)1095 int32_t DeviceProfileManager::SaveBatchByKeys(const std::map<std::string, std::string>& entries)
1096 {
1097 HILOGD("entries.size:%{public}zu", entries.size());
1098 if (entries.empty()) {
1099 HILOGW("entries is empty");
1100 return DP_SUCCESS;
1101 }
1102 std::lock_guard<std::mutex> lock(dynamicStoreMutex_);
1103 if (deviceProfileStore_ == nullptr) {
1104 HILOGE("deviceProfileStore is nullptr!");
1105 return DP_GET_KV_DB_FAIL;
1106 }
1107 int32_t ret = deviceProfileStore_->PutBatch(entries);
1108 if (ret != DP_SUCCESS) {
1109 HILOGE("PutBatch fail! ret:%{public}d", ret);
1110 return ret;
1111 }
1112 return DP_SUCCESS;
1113 }
1114
1115 template <typename T>
IsMultiUserValid(const T & profile)1116 int32_t DeviceProfileManager::IsMultiUserValid(const T& profile)
1117 {
1118 if (profile.GetDeviceId().empty() || (profile.IsMultiUser() && profile.GetUserId() <= 0) ||
1119 (!profile.IsMultiUser() && profile.GetUserId() != DEFAULT_USER_ID)) {
1120 HILOGE("multi-user params are invalid, isMultiUser: %{public}d, userId: %{public}d",
1121 profile.IsMultiUser(), profile.GetUserId());
1122 return DP_GET_MULTI_USER_PROFILE_PARAMS_INVALID;
1123 }
1124 if (profile.IsMultiUser() && (profile.GetDeviceId() == ProfileCache::GetInstance().GetLocalUdid()) &&
1125 (profile.GetUserId() != MultiUserManager::GetInstance().GetCurrentForegroundUserID())) {
1126 HILOGE("this userId is not foregroundUserId, userId: %{public}d, foregroundId: %{public}d",
1127 profile.GetUserId(), MultiUserManager::GetInstance().GetCurrentForegroundUserID());
1128 return DP_GET_LOCAL_PROFILE_IS_NOT_FOREGROUND_ID;
1129 }
1130 return DP_SUCCESS;
1131 }
1132
1133 template int32_t DeviceProfileManager::IsMultiUserValid<DeviceProfile>(const DeviceProfile& profile);
1134 template int32_t DeviceProfileManager::IsMultiUserValid<ServiceProfile>(const ServiceProfile& profile);
1135 template int32_t DeviceProfileManager::IsMultiUserValid<CharacteristicProfile>(const CharacteristicProfile& profile);
1136
IsSameAccount(const std::string deviceId,const int32_t userId)1137 bool DeviceProfileManager::IsSameAccount(const std::string deviceId, const int32_t userId)
1138 {
1139 (void)userId;
1140 if (deviceId.empty()) {
1141 HILOGE("param is invalid");
1142 return false;
1143 }
1144
1145 std::map<std::string, std::string> params = {
1146 {BUNDLENAME, EMPTY_STRING},
1147 {BIND_TYPE, std::to_string(static_cast<int32_t>(BindType::SAME_ACCOUNT))},
1148 {STATUS, std::to_string(static_cast<int32_t>(Status::ACTIVE))}
1149 };
1150 std::vector<AccessControlProfile> profile;
1151 int32_t res = TrustProfileManager::GetInstance().GetAccessControlProfile(params, profile);
1152 if (res != DP_SUCCESS || profile.empty()) {
1153 HILOGE("GetAccessControlProfile failed, res: %{public}d", res);
1154 return false;
1155 }
1156 for (auto& item : profile) {
1157 if (item.GetTrustDeviceId() == deviceId) {
1158 HILOGI("profile has the same account");
1159 return true;
1160 }
1161 }
1162 return false;
1163 }
1164
HasTrustP2PRelation(const std::string deviceId,const int32_t userId)1165 bool DeviceProfileManager::HasTrustP2PRelation(const std::string deviceId, const int32_t userId)
1166 {
1167 (void)userId;
1168 if (deviceId.empty()) {
1169 HILOGE("param is invalid");
1170 return false;
1171 }
1172
1173 std::map<std::string, std::string> params = {
1174 {BUNDLENAME, EMPTY_STRING},
1175 {BIND_TYPE, std::to_string(static_cast<int32_t>(BindType::POINT_TO_POINT))},
1176 {STATUS, std::to_string(static_cast<int32_t>(Status::ACTIVE))}
1177 };
1178 std::vector<AccessControlProfile> profile;
1179 int32_t res = TrustProfileManager::GetInstance().GetAccessControlProfile(params, profile);
1180 if (res != DP_SUCCESS || profile.empty()) {
1181 HILOGE("HasTrustP2PRelation failed, res: %{public}d", res);
1182 return false;
1183 }
1184 for (auto& item : profile) {
1185 if (item.GetTrustDeviceId() == deviceId) {
1186 HILOGI("profile has the trust p2p relationship");
1187 return true;
1188 }
1189 }
1190 return false;
1191 }
1192
1193 } // namespace DeviceProfile
1194 } // namespace OHOS
1195