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 "group_data_manager.h"
17
18 #include "broadcast_manager.h"
19 #include "common_defs.h"
20 #include "device_auth.h"
21 #include "device_auth_defines.h"
22 #include "hc_dev_info.h"
23 #include "hc_file.h"
24 #include "hc_log.h"
25 #include "hc_mutex.h"
26 #include "hc_string_vector.h"
27 #include "hc_types.h"
28 #include "key_manager.h"
29 #include "securec.h"
30 #include "hidump_adapter.h"
31 #include "os_account_adapter.h"
32 #include "pseudonym_manager.h"
33 #include "security_label_adapter.h"
34 #include "account_task_manager.h"
35 #include "string_util.h"
36
37 typedef struct {
38 DECLARE_TLV_STRUCT(10)
39 TlvString name;
40 TlvString id;
41 TlvUint32 type;
42 TlvInt32 visibility;
43 TlvInt32 expireTime;
44 TlvString userId;
45 TlvString sharedUserId;
46 TlvBuffer managers;
47 TlvBuffer friends;
48 TlvUint8 upgradeFlag;
49 } TlvGroupElement;
50 DECLEAR_INIT_FUNC(TlvGroupElement)
51 DECLARE_TLV_VECTOR(TlvGroupVec, TlvGroupElement)
52
53 typedef struct {
54 uint8_t credential;
55 uint8_t devType;
56 uint8_t source;
57 int64_t userId;
58 uint64_t lastTm;
59 } DevAuthFixedLenInfo;
60 DECLARE_TLV_FIX_LENGTH_TYPE(TlvDevAuthFixedLenInfo, DevAuthFixedLenInfo)
61 DECLEAR_INIT_FUNC(TlvDevAuthFixedLenInfo)
62
63 typedef struct {
64 DECLARE_TLV_STRUCT(8)
65 TlvString groupId;
66 TlvString udid;
67 TlvString authId;
68 TlvString userId;
69 TlvString serviceType;
70 TlvBuffer ext;
71 TlvDevAuthFixedLenInfo info;
72 TlvUint8 upgradeFlag;
73 } TlvDeviceElement;
74 DECLEAR_INIT_FUNC(TlvDeviceElement)
75 DECLARE_TLV_VECTOR(TlvDeviceVec, TlvDeviceElement)
76
77 typedef struct {
78 DECLARE_TLV_STRUCT(3)
79 TlvInt32 version;
80 TlvGroupVec groups;
81 TlvDeviceVec devices;
82 } HCDataBaseV1;
83 DECLEAR_INIT_FUNC(HCDataBaseV1)
84
85 DEFINE_TLV_FIX_LENGTH_TYPE(TlvDevAuthFixedLenInfo, NO_REVERT)
86
87 BEGIN_TLV_STRUCT_DEFINE(TlvGroupElement, 0x0001)
88 TLV_MEMBER(TlvString, name, 0x4001)
89 TLV_MEMBER(TlvString, id, 0x4002)
90 TLV_MEMBER(TlvUint32, type, 0x4003)
91 TLV_MEMBER(TlvInt32, visibility, 0x4004)
92 TLV_MEMBER(TlvInt32, expireTime, 0x4005)
93 TLV_MEMBER(TlvString, userId, 0x4006)
94 TLV_MEMBER(TlvString, sharedUserId, 0x4007)
95 TLV_MEMBER(TlvBuffer, managers, 0x4008)
96 TLV_MEMBER(TlvBuffer, friends, 0x4009)
97 TLV_MEMBER(TlvUint8, upgradeFlag, 0x400A)
98 END_TLV_STRUCT_DEFINE()
99 IMPLEMENT_TLV_VECTOR(TlvGroupVec, TlvGroupElement, 1)
100
101 BEGIN_TLV_STRUCT_DEFINE(TlvDeviceElement, 0x0002)
102 TLV_MEMBER(TlvString, groupId, 0x4101)
103 TLV_MEMBER(TlvString, udid, 0x4102)
104 TLV_MEMBER(TlvString, authId, 0x4103)
105 TLV_MEMBER(TlvString, userId, 0x4107)
106 TLV_MEMBER(TlvString, serviceType, 0x4104)
107 TLV_MEMBER(TlvBuffer, ext, 0x4105)
108 TLV_MEMBER(TlvDevAuthFixedLenInfo, info, 0x4106)
109 TLV_MEMBER(TlvUint8, upgradeFlag, 0x4108)
110 END_TLV_STRUCT_DEFINE()
111 IMPLEMENT_TLV_VECTOR(TlvDeviceVec, TlvDeviceElement, 1)
112
113 BEGIN_TLV_STRUCT_DEFINE(HCDataBaseV1, 0x0001)
114 TLV_MEMBER(TlvInt32, version, 0x6001)
115 TLV_MEMBER(TlvGroupVec, groups, 0x6002)
116 TLV_MEMBER(TlvDeviceVec, devices, 0x6003)
117 END_TLV_STRUCT_DEFINE()
118
119 IMPLEMENT_HC_VECTOR(GroupEntryVec, TrustedGroupEntry*, 1)
120 IMPLEMENT_HC_VECTOR(DeviceEntryVec, TrustedDeviceEntry*, 1)
121
122 typedef struct {
123 int32_t osAccountId;
124 GroupEntryVec groups;
125 DeviceEntryVec devices;
126 } OsAccountTrustedInfo;
127
128 DECLARE_HC_VECTOR(DeviceAuthDb, OsAccountTrustedInfo)
129 IMPLEMENT_HC_VECTOR(DeviceAuthDb, OsAccountTrustedInfo, 1)
130
131 #define MAX_DB_PATH_LEN 256
132
133 static HcMutex *g_databaseMutex = NULL;
134 static DeviceAuthDb g_deviceauthDb;
135 static const int UPGRADE_OS_ACCOUNT_ID = 100;
136
EndWithZero(HcParcel * parcel)137 static bool EndWithZero(HcParcel *parcel)
138 {
139 const char *p = GetParcelLastChar(parcel);
140 if (p == NULL) {
141 return false;
142 }
143 return (*p == '\0');
144 }
145
LoadStringVectorFromParcel(StringVector * vec,HcParcel * parcel)146 static bool LoadStringVectorFromParcel(StringVector *vec, HcParcel *parcel)
147 {
148 uint32_t strLen = 0;
149 do {
150 if (!ParcelReadUint32(parcel, &strLen)) {
151 return true;
152 }
153 if ((strLen == 0) || (strLen > MAX_STRING_LEN)) {
154 LOGE("strlen invalid.");
155 return false;
156 }
157 HcString str = CreateString();
158 ClearParcel(&str.parcel);
159 if (!ParcelReadParcel(parcel, &str.parcel, strLen, false) ||
160 !EndWithZero(&str.parcel)) {
161 DeleteString(&str);
162 return false;
163 } else {
164 if (vec->pushBack(vec, &str) == NULL) {
165 DeleteString(&str);
166 LOGE("vec pushBack failed.");
167 return false;
168 }
169 }
170 } while (1);
171 }
172
SaveStringVectorToParcel(const StringVector * vec,HcParcel * parcel)173 static bool SaveStringVectorToParcel(const StringVector *vec, HcParcel *parcel)
174 {
175 uint32_t index;
176 HcString *str = NULL;
177 FOR_EACH_HC_VECTOR(*vec, index, str) {
178 uint32_t len = StringLength(str) + sizeof(char);
179 if (!ParcelWriteUint32(parcel, len)) {
180 LOGE("Parcel write failed.");
181 return false;
182 }
183 if (!ParcelWrite(parcel, GetParcelData(&str->parcel), GetParcelDataSize(&str->parcel))) {
184 LOGE("Parcel write failed.");
185 return false;
186 }
187 }
188 return true;
189 }
190
GetOsAccountInfoPathCe(int32_t osAccountId,char * infoPath,uint32_t pathBufferLen)191 static bool GetOsAccountInfoPathCe(int32_t osAccountId, char *infoPath, uint32_t pathBufferLen)
192 {
193 const char *beginPath = GetStorageDirPathCe();
194 if (beginPath == NULL) {
195 LOGE("[DB]: Failed to get the storage path!");
196 return false;
197 }
198 if (sprintf_s(infoPath, pathBufferLen, "%s/%d/deviceauth/hcgroup.dat", beginPath, osAccountId) <= 0) {
199 LOGE("[DB]: Failed to generate db file path!");
200 return false;
201 }
202 return true;
203 }
204
GetOsAccountInfoPathDe(int32_t osAccountId,char * infoPath,uint32_t pathBufferLen)205 static bool GetOsAccountInfoPathDe(int32_t osAccountId, char *infoPath, uint32_t pathBufferLen)
206 {
207 const char *beginPath = GetStorageDirPath();
208 if (beginPath == NULL) {
209 LOGE("[DB]: Failed to get the storage path dir!");
210 return false;
211 }
212 int32_t writeByteNum;
213 if (osAccountId == DEFAULT_OS_ACCOUNT) {
214 writeByteNum = sprintf_s(infoPath, pathBufferLen, "%s/hcgroup.dat", beginPath);
215 } else {
216 writeByteNum = sprintf_s(infoPath, pathBufferLen, "%s/hcgroup%d.dat", beginPath, osAccountId);
217 }
218 if (writeByteNum <= 0) {
219 LOGE("[DB]: sprintf_s fail!");
220 return false;
221 }
222 return true;
223 }
224
GetOsAccountInfoPath(int32_t osAccountId,char * infoPath,uint32_t pathBufferLen)225 static bool GetOsAccountInfoPath(int32_t osAccountId, char *infoPath, uint32_t pathBufferLen)
226 {
227 if (IsOsAccountSupported()) {
228 return GetOsAccountInfoPathCe(osAccountId, infoPath, pathBufferLen);
229 } else {
230 return GetOsAccountInfoPathDe(osAccountId, infoPath, pathBufferLen);
231 }
232 }
233
GenerateGroupEntryFromEntry(const TrustedGroupEntry * entry,TrustedGroupEntry * returnEntry)234 bool GenerateGroupEntryFromEntry(const TrustedGroupEntry *entry, TrustedGroupEntry *returnEntry)
235 {
236 if (HC_VECTOR_SIZE(&entry->managers) <= 0) {
237 LOGE("[DB]: The group owner is lost!");
238 return false;
239 }
240 HcString entryOwner = HC_VECTOR_GET(&entry->managers, 0);
241 if (!StringSet(&returnEntry->name, entry->name)) {
242 LOGE("[DB]: Failed to copy groupName!");
243 return false;
244 }
245 if (!StringSet(&returnEntry->id, entry->id)) {
246 LOGE("[DB]: Failed to copy groupId!");
247 return false;
248 }
249 if (!StringSet(&returnEntry->userId, entry->userId)) {
250 LOGE("[DB]: Failed to copy userId!");
251 return false;
252 }
253 if (!StringSet(&returnEntry->sharedUserId, entry->sharedUserId)) {
254 LOGE("[DB]: Failed to copy sharedUserId!");
255 return false;
256 }
257 returnEntry->type = entry->type;
258 returnEntry->visibility = entry->visibility;
259 returnEntry->upgradeFlag = entry->upgradeFlag;
260 returnEntry->expireTime = entry->expireTime;
261 HcString ownerName = CreateString();
262 if (!StringSet(&ownerName, entryOwner)) {
263 LOGE("[DB]: Failed to copy groupOwner!");
264 DeleteString(&ownerName);
265 return false;
266 }
267 if (returnEntry->managers.pushBack(&returnEntry->managers, &ownerName) == NULL) {
268 LOGE("[DB]: Failed to push groupOwner to managers!");
269 DeleteString(&ownerName);
270 return false;
271 }
272 return true;
273 }
274
GenerateDeviceEntryFromEntry(const TrustedDeviceEntry * entry,TrustedDeviceEntry * returnEntry)275 bool GenerateDeviceEntryFromEntry(const TrustedDeviceEntry *entry, TrustedDeviceEntry *returnEntry)
276 {
277 returnEntry->groupEntry = NULL;
278 if (!StringSet(&returnEntry->groupId, entry->groupId)) {
279 LOGE("[DB]: Failed to copy udid!");
280 return false;
281 }
282 if (!StringSet(&returnEntry->udid, entry->udid)) {
283 LOGE("[DB]: Failed to copy udid!");
284 return false;
285 }
286 if (!StringSet(&returnEntry->authId, entry->authId)) {
287 LOGE("[DB]: Failed to copy authId!");
288 return false;
289 }
290 if (!StringSet(&returnEntry->userId, entry->userId)) {
291 LOGE("[DB]: Failed to copy userId!");
292 return false;
293 }
294 if (!StringSet(&returnEntry->serviceType, entry->serviceType)) {
295 LOGE("[DB]: Failed to copy serviceType!");
296 return false;
297 }
298 returnEntry->credential = entry->credential;
299 returnEntry->devType = entry->devType;
300 returnEntry->upgradeFlag = entry->upgradeFlag;
301 returnEntry->source = entry->source;
302 returnEntry->lastTm = entry->lastTm;
303 return true;
304 }
305
GenerateGroupEntryFromTlv(TlvGroupElement * group,TrustedGroupEntry * entry)306 static bool GenerateGroupEntryFromTlv(TlvGroupElement *group, TrustedGroupEntry *entry)
307 {
308 if (!StringSet(&entry->name, group->name.data)) {
309 LOGE("[DB]: Failed to load groupName from tlv!");
310 return false;
311 }
312 if (!StringSet(&entry->id, group->id.data)) {
313 LOGE("[DB]: Failed to load groupId from tlv!");
314 return false;
315 }
316 if (!StringSet(&entry->userId, group->userId.data)) {
317 LOGE("[DB]: Failed to load userId from tlv!");
318 return false;
319 }
320 if (!StringSet(&entry->sharedUserId, group->sharedUserId.data)) {
321 LOGE("[DB]: Failed to load sharedUserId from tlv!");
322 return false;
323 }
324 if (!LoadStringVectorFromParcel(&entry->managers, &group->managers.data)) {
325 LOGE("[DB]: Failed to load managers from tlv!");
326 return false;
327 }
328 if (!LoadStringVectorFromParcel(&entry->friends, &group->friends.data)) {
329 LOGE("[DB]: Failed to load friends from tlv!");
330 return false;
331 }
332 entry->type = group->type.data;
333 entry->visibility = group->visibility.data;
334 entry->upgradeFlag = group->upgradeFlag.data;
335 entry->expireTime = group->expireTime.data;
336 return true;
337 }
338
GenerateDeviceEntryFromTlv(TlvDeviceElement * device,TrustedDeviceEntry * deviceEntry)339 static bool GenerateDeviceEntryFromTlv(TlvDeviceElement *device, TrustedDeviceEntry *deviceEntry)
340 {
341 deviceEntry->groupEntry = NULL;
342 if (!StringSet(&deviceEntry->groupId, device->groupId.data)) {
343 LOGE("[DB]: Failed to load groupId from tlv!");
344 return false;
345 }
346 if (!StringSet(&deviceEntry->udid, device->udid.data)) {
347 LOGE("[DB]: Failed to load udid from tlv!");
348 return false;
349 }
350 if (!StringSet(&deviceEntry->authId, device->authId.data)) {
351 LOGE("[DB]: Failed to load authId from tlv!");
352 return false;
353 }
354 if (!StringSet(&deviceEntry->userId, device->userId.data)) {
355 LOGE("[DB]: Failed to load userId from tlv!");
356 return false;
357 }
358 if (!StringSet(&deviceEntry->serviceType, device->serviceType.data)) {
359 LOGE("[DB]: Failed to load serviceType from tlv!");
360 return false;
361 }
362 if (!ParcelCopy(&device->ext.data, &deviceEntry->ext)) {
363 LOGE("[DB]: Failed to load external data from tlv!");
364 return false;
365 }
366 deviceEntry->credential = device->info.data.credential;
367 deviceEntry->devType = device->info.data.devType;
368 deviceEntry->upgradeFlag = device->upgradeFlag.data;
369 deviceEntry->source = device->info.data.source;
370 deviceEntry->lastTm = device->info.data.lastTm;
371 return true;
372 }
373
LoadGroups(HCDataBaseV1 * db,GroupEntryVec * vec)374 static bool LoadGroups(HCDataBaseV1 *db, GroupEntryVec *vec)
375 {
376 uint32_t index;
377 TlvGroupElement *group = NULL;
378 FOR_EACH_HC_VECTOR(db->groups.data, index, group) {
379 if (group == NULL) {
380 continue;
381 }
382 TrustedGroupEntry *entry = CreateGroupEntry();
383 if (entry == NULL) {
384 LOGE("[DB]: Failed to allocate entry memory!");
385 ClearGroupEntryVec(vec);
386 return false;
387 }
388 if (!GenerateGroupEntryFromTlv(group, entry)) {
389 DestroyGroupEntry(entry);
390 ClearGroupEntryVec(vec);
391 return false;
392 }
393 if (vec->pushBackT(vec, entry) == NULL) {
394 LOGE("[DB]: Failed to push entry to vec!");
395 DestroyGroupEntry(entry);
396 ClearGroupEntryVec(vec);
397 return false;
398 }
399 }
400 return true;
401 }
402
LoadDevices(HCDataBaseV1 * db,DeviceEntryVec * vec)403 static bool LoadDevices(HCDataBaseV1 *db, DeviceEntryVec *vec)
404 {
405 uint32_t index;
406 TlvDeviceElement *device = NULL;
407 FOR_EACH_HC_VECTOR(db->devices.data, index, device) {
408 if (device == NULL) {
409 continue;
410 }
411 TrustedDeviceEntry *entry = CreateDeviceEntry();
412 if (entry == NULL) {
413 LOGE("[DB]: Failed to allocate entry memory!");
414 ClearDeviceEntryVec(vec);
415 return false;
416 }
417 if (!GenerateDeviceEntryFromTlv(device, entry)) {
418 DestroyDeviceEntry(entry);
419 ClearDeviceEntryVec(vec);
420 return false;
421 }
422 if (vec->pushBackT(vec, entry) == NULL) {
423 LOGE("[DB]: Failed to push entry to vec!");
424 DestroyDeviceEntry(entry);
425 ClearDeviceEntryVec(vec);
426 return false;
427 }
428 }
429 return true;
430 }
431
ReadInfoFromParcel(HcParcel * parcel,OsAccountTrustedInfo * info)432 static bool ReadInfoFromParcel(HcParcel *parcel, OsAccountTrustedInfo *info)
433 {
434 bool ret = false;
435 HCDataBaseV1 dbv1;
436 TLV_INIT(HCDataBaseV1, &dbv1)
437 if (DecodeTlvMessage((TlvBase *)&dbv1, parcel, false)) {
438 if (!LoadGroups(&dbv1, &info->groups)) {
439 TLV_DEINIT(dbv1)
440 return false;
441 }
442 if (!LoadDevices(&dbv1, &info->devices)) {
443 ClearGroupEntryVec(&info->groups);
444 TLV_DEINIT(dbv1)
445 return false;
446 }
447 ret = true;
448 } else {
449 LOGE("[DB]: Decode Tlv Message Failed!");
450 }
451 TLV_DEINIT(dbv1)
452 return ret;
453 }
454
ReadParcelFromFile(const char * filePath,HcParcel * parcel)455 static bool ReadParcelFromFile(const char *filePath, HcParcel *parcel)
456 {
457 FileHandle file;
458 int ret = HcFileOpen(filePath, MODE_FILE_READ, &file);
459 if (ret != 0) {
460 LOGE("[DB]: Failed to open database file!");
461 return false;
462 }
463 SetSecurityLabel(filePath, SECURITY_LABEL_S2);
464 int fileSize = HcFileSize(file);
465 if (fileSize <= 0) {
466 LOGE("[DB]: The database file size is invalid!");
467 HcFileClose(file);
468 return false;
469 }
470 char *fileData = (char *)HcMalloc(fileSize, 0);
471 if (fileData == NULL) {
472 LOGE("[DB]: Failed to allocate fileData memory!");
473 HcFileClose(file);
474 return false;
475 }
476 if (HcFileRead(file, fileData, fileSize) != fileSize) {
477 LOGE("[DB]: Read file error!");
478 HcFileClose(file);
479 HcFree(fileData);
480 return false;
481 }
482 HcFileClose(file);
483 if (!ParcelWrite(parcel, fileData, fileSize)) {
484 HcFree(fileData);
485 LOGE("[DB]: parcel write error!");
486 return false;
487 }
488 HcFree(fileData);
489 return true;
490 }
491
SaveParcelToFile(const char * filePath,HcParcel * parcel)492 static bool SaveParcelToFile(const char *filePath, HcParcel *parcel)
493 {
494 FileHandle file;
495 int ret = HcFileOpen(filePath, MODE_FILE_WRITE, &file);
496 if (ret != HC_SUCCESS) {
497 LOGE("[DB]: Failed to open database file!");
498 return false;
499 }
500 SetSecurityLabel(filePath, SECURITY_LABEL_S2);
501 int fileSize = (int)GetParcelDataSize(parcel);
502 const char *fileData = GetParcelData(parcel);
503 int writeSize = HcFileWrite(file, fileData, fileSize);
504 HcFileClose(file);
505 if (writeSize == fileSize) {
506 return true;
507 } else {
508 LOGE("[DB]: write file error!");
509 return false;
510 }
511 }
512
LoadOsAccountDb(int32_t osAccountId)513 static void LoadOsAccountDb(int32_t osAccountId)
514 {
515 char filePath[MAX_DB_PATH_LEN] = { 0 };
516 if (!GetOsAccountInfoPath(osAccountId, filePath, MAX_DB_PATH_LEN)) {
517 LOGE("[DB]: Failed to get os account info path!");
518 return;
519 }
520 HcParcel parcel = CreateParcel(0, 0);
521 if (!ReadParcelFromFile(filePath, &parcel)) {
522 DeleteParcel(&parcel);
523 return;
524 }
525 OsAccountTrustedInfo info;
526 info.osAccountId = osAccountId;
527 info.groups = CreateGroupEntryVec();
528 info.devices = CreateDeviceEntryVec();
529 if (!ReadInfoFromParcel(&parcel, &info)) {
530 DestroyGroupEntryVec(&info.groups);
531 DestroyDeviceEntryVec(&info.devices);
532 DeleteParcel(&parcel);
533 return;
534 }
535 DeleteParcel(&parcel);
536 if (g_deviceauthDb.pushBackT(&g_deviceauthDb, info) == NULL) {
537 LOGE("[DB]: Failed to push osAccountInfo to database!");
538 ClearGroupEntryVec(&info.groups);
539 ClearDeviceEntryVec(&info.devices);
540 return;
541 }
542 LOGI("[DB]: Load os account db successfully! [Id]: %" LOG_PUB "d", osAccountId);
543 }
544
TryMoveDeDataToCe(int32_t osAccountId)545 static void TryMoveDeDataToCe(int32_t osAccountId)
546 {
547 char ceFilePath[MAX_DB_PATH_LEN] = { 0 };
548 if (!GetOsAccountInfoPathCe(osAccountId, ceFilePath, MAX_DB_PATH_LEN)) {
549 LOGE("[DB]: Failed to get ce database file path!");
550 return;
551 }
552 HcParcel parcelCe = CreateParcel(0, 0);
553 if (ReadParcelFromFile(ceFilePath, &parcelCe)) {
554 LOGI("[DB]: ce data exists, no need to move.");
555 DeleteParcel(&parcelCe);
556 return;
557 }
558 DeleteParcel(&parcelCe);
559 char deFilePath[MAX_DB_PATH_LEN] = { 0 };
560 if (!GetOsAccountInfoPathDe(osAccountId, deFilePath, MAX_DB_PATH_LEN)) {
561 LOGE("[DB]: Failed to get de database file path!");
562 return;
563 }
564 HcParcel parcelDe = CreateParcel(0, 0);
565 if (!ReadParcelFromFile(deFilePath, &parcelDe)) {
566 LOGI("[DB]: no data in de file, no need to move!");
567 DeleteParcel(&parcelDe);
568 return;
569 }
570 if (!SaveParcelToFile(ceFilePath, &parcelDe)) {
571 LOGE("[DB]: save de parcel to ce file failed!");
572 DeleteParcel(&parcelDe);
573 return;
574 }
575 DeleteParcel(&parcelDe);
576 parcelCe = CreateParcel(0, 0);
577 if (!ReadParcelFromFile(ceFilePath, &parcelCe)) {
578 LOGE("[DB]: Failed to read ce file data!");
579 DeleteParcel(&parcelCe);
580 return;
581 }
582 DeleteParcel(&parcelCe);
583 LOGI("[DB]: move de data to ce successfully, remove de file!");
584 HcFileRemove(deFilePath);
585 }
586
RemoveOsAccountTrustedInfo(int32_t osAccountId)587 static void RemoveOsAccountTrustedInfo(int32_t osAccountId)
588 {
589 uint32_t index = 0;
590 OsAccountTrustedInfo *info = NULL;
591 FOR_EACH_HC_VECTOR(g_deviceauthDb, index, info) {
592 if (info->osAccountId == osAccountId) {
593 OsAccountTrustedInfo deleteInfo;
594 HC_VECTOR_POPELEMENT(&g_deviceauthDb, &deleteInfo, index);
595 ClearGroupEntryVec(&deleteInfo.groups);
596 ClearDeviceEntryVec(&deleteInfo.devices);
597 return;
598 }
599 }
600 }
601
LoadOsAccountDbCe(int32_t osAccountId)602 static void LoadOsAccountDbCe(int32_t osAccountId)
603 {
604 TryMoveDeDataToCe(osAccountId);
605 RemoveOsAccountTrustedInfo(osAccountId);
606 LoadOsAccountDb(osAccountId);
607 }
608
DelGroupFromDbInner(int32_t osAccountId,const char * groupId)609 static int32_t DelGroupFromDbInner(int32_t osAccountId, const char *groupId)
610 {
611 if (groupId == NULL) {
612 LOGE("The input groupId is NULL!");
613 return HC_ERR_NULL_PTR;
614 }
615 QueryGroupParams queryGroupParams = InitQueryGroupParams();
616 QueryDeviceParams queryDeviceParams = InitQueryDeviceParams();
617 queryGroupParams.groupId = groupId;
618 queryDeviceParams.groupId = groupId;
619 int32_t result = HC_SUCCESS;
620 if (DelTrustedDevice(osAccountId, &queryDeviceParams) != HC_SUCCESS) {
621 result = HC_ERR_DEL_GROUP;
622 }
623 if (DelGroup(osAccountId, &queryGroupParams) != HC_SUCCESS) {
624 result = HC_ERR_DEL_GROUP;
625 }
626 if (SaveOsAccountDb(osAccountId) != HC_SUCCESS) {
627 result = HC_ERR_DEL_GROUP;
628 }
629 return result;
630 }
631
CheckAndRemoveUpgradeGroupEntry(const TrustedGroupEntry * groupEntry)632 static void CheckAndRemoveUpgradeGroupEntry(const TrustedGroupEntry *groupEntry)
633 {
634 if (groupEntry->upgradeFlag != IS_UPGRADE) {
635 LOGW("Group is not upgrade group, not need to remove!");
636 return;
637 }
638 const char *groupId = StringGet(&(groupEntry->id));
639
640 HcString entryManager = HC_VECTOR_GET(&groupEntry->managers, 0);
641 const char *groupOwner = StringGet(&entryManager);
642 if (groupId == NULL || groupOwner == NULL) {
643 LOGW("groupId or groupOwner is null, not need to remove!");
644 return;
645 }
646 CJson *upgradeJson = CreateJson();
647 if (upgradeJson == NULL) {
648 LOGE("Failed to create upgradeIdentity json.");
649 return;
650 }
651 if (AddStringToJson(upgradeJson, FIELD_APP_ID, groupOwner) != HC_SUCCESS) {
652 FreeJson(upgradeJson);
653 LOGE("Failed to add groupOwner.");
654 return;
655 }
656 int32_t res = ExecuteAccountAuthCmd(UPGRADE_OS_ACCOUNT_ID, CHECK_UPGRADE_DATA, upgradeJson, NULL);
657 FreeJson(upgradeJson);
658 if (res == HC_SUCCESS) {
659 LOGI("GroupOwner is in trustedlist, not need to remove!");
660 return;
661 }
662 if (DelGroupFromDbInner(UPGRADE_OS_ACCOUNT_ID, groupId) != HC_SUCCESS) {
663 LOGW("Delete group from db failed!");
664 return;
665 }
666 LOGI("Delete group from db successfully!");
667 }
668
CheckAndRemoveUpgradeData(int32_t osAccountId)669 static void CheckAndRemoveUpgradeData(int32_t osAccountId)
670 {
671 if (osAccountId != UPGRADE_OS_ACCOUNT_ID) {
672 LOGI("Current os accountId is %" LOG_PUB "d, no need to check and remove.", osAccountId);
673 return;
674 }
675 QueryGroupParams queryParams = InitQueryGroupParams();
676 GroupEntryVec groupEntryVec = CreateGroupEntryVec();
677 int32_t ret = QueryGroups(UPGRADE_OS_ACCOUNT_ID, &queryParams, &groupEntryVec);
678 if (ret != HC_SUCCESS) {
679 LOGE("Failed to query groups!");
680 ClearGroupEntryVec(&groupEntryVec);
681 return;
682 }
683 uint32_t index;
684 TrustedGroupEntry **ptr = NULL;
685 FOR_EACH_HC_VECTOR(groupEntryVec, index, ptr) {
686 if (ptr == NULL || *ptr == NULL) {
687 continue;
688 }
689 const TrustedGroupEntry *groupEntry = (const TrustedGroupEntry *)(*ptr);
690 CheckAndRemoveUpgradeGroupEntry(groupEntry);
691 }
692 ClearGroupEntryVec(&groupEntryVec);
693 }
694
OnOsAccountUnlocked(int32_t osAccountId)695 static void OnOsAccountUnlocked(int32_t osAccountId)
696 {
697 (void)LockHcMutex(g_databaseMutex);
698 LoadOsAccountDbCe(osAccountId);
699 UnlockHcMutex(g_databaseMutex);
700 CheckAndRemoveUpgradeData(osAccountId);
701 }
702
OnOsAccountRemoved(int32_t osAccountId)703 static void OnOsAccountRemoved(int32_t osAccountId)
704 {
705 LOGI("[DB]: os account is removed, osAccountId: %" LOG_PUB "d", osAccountId);
706 (void)LockHcMutex(g_databaseMutex);
707 RemoveOsAccountTrustedInfo(osAccountId);
708 UnlockHcMutex(g_databaseMutex);
709 }
710
IsOsAccountGroupDataLoaded(int32_t osAccountId)711 static bool IsOsAccountGroupDataLoaded(int32_t osAccountId)
712 {
713 uint32_t index = 0;
714 OsAccountTrustedInfo *info = NULL;
715 FOR_EACH_HC_VECTOR(g_deviceauthDb, index, info) {
716 if (info->osAccountId == osAccountId) {
717 return true;
718 }
719 }
720 return false;
721 }
722
LoadDataIfNotLoaded(int32_t osAccountId)723 static void LoadDataIfNotLoaded(int32_t osAccountId)
724 {
725 if (IsOsAccountGroupDataLoaded(osAccountId)) {
726 return;
727 }
728 LOGI("[DB]: data has not been loaded, load it, osAccountId: %" LOG_PUB "d", osAccountId);
729 LoadOsAccountDbCe(osAccountId);
730 }
731
GetTrustedInfoByOsAccountId(int32_t osAccountId)732 static OsAccountTrustedInfo *GetTrustedInfoByOsAccountId(int32_t osAccountId)
733 {
734 if (IsOsAccountSupported()) {
735 LoadDataIfNotLoaded(osAccountId);
736 }
737 uint32_t index = 0;
738 OsAccountTrustedInfo *info = NULL;
739 FOR_EACH_HC_VECTOR(g_deviceauthDb, index, info) {
740 if (info->osAccountId == osAccountId) {
741 return info;
742 }
743 }
744 LOGI("[DB]: Create a new os account database cache! [Id]: %" LOG_PUB "d", osAccountId);
745 OsAccountTrustedInfo newInfo;
746 newInfo.osAccountId = osAccountId;
747 newInfo.groups = CreateGroupEntryVec();
748 newInfo.devices = CreateDeviceEntryVec();
749 OsAccountTrustedInfo *returnInfo = g_deviceauthDb.pushBackT(&g_deviceauthDb, newInfo);
750 if (returnInfo == NULL) {
751 LOGE("[DB]: Failed to push osAccountInfo to database!");
752 DestroyGroupEntryVec(&newInfo.groups);
753 DestroyDeviceEntryVec(&newInfo.devices);
754 }
755 return returnInfo;
756 }
757
LoadDeviceAuthDb(void)758 static void LoadDeviceAuthDb(void)
759 {
760 if (IsOsAccountSupported()) {
761 return;
762 }
763 (void)LockHcMutex(g_databaseMutex);
764 StringVector osAccountDbNameVec = CreateStrVector();
765 HcFileGetSubFileName(GetStorageDirPath(), &osAccountDbNameVec);
766 HcString *dbName;
767 uint32_t index;
768 FOR_EACH_HC_VECTOR(osAccountDbNameVec, index, dbName) {
769 int32_t osAccountId;
770 const char *osAccountIdStr = StringGet(dbName);
771 if (osAccountIdStr == NULL) {
772 LOGW("[DB]: Invalid osAccountIdStr!");
773 continue;
774 }
775 if (IsStrEqual(osAccountIdStr, "hcgroup.dat")) {
776 LoadOsAccountDb(DEFAULT_OS_ACCOUNT);
777 } else if (sscanf_s(osAccountIdStr, "hcgroup%d.dat", &osAccountId) == 1) {
778 LoadOsAccountDb(osAccountId);
779 }
780 }
781 DestroyStrVector(&osAccountDbNameVec);
782 UnlockHcMutex(g_databaseMutex);
783 }
784
SetGroupElement(TlvGroupElement * element,TrustedGroupEntry * entry)785 static bool SetGroupElement(TlvGroupElement *element, TrustedGroupEntry *entry)
786 {
787 if (!StringSet(&element->name.data, entry->name)) {
788 LOGE("[DB]: Failed to copy groupName!");
789 return false;
790 }
791 if (!StringSet(&element->id.data, entry->id)) {
792 LOGE("[DB]: Failed to copy groupId!");
793 return false;
794 }
795 if (!StringSet(&element->userId.data, entry->userId)) {
796 LOGE("[DB]: Failed to copy userId!");
797 return false;
798 }
799 if (!StringSet(&element->sharedUserId.data, entry->sharedUserId)) {
800 LOGE("[DB]: Failed to copy sharedUserId!");
801 return false;
802 }
803 element->type.data = entry->type;
804 element->visibility.data = entry->visibility;
805 element->upgradeFlag.data = entry->upgradeFlag;
806 element->expireTime.data = entry->expireTime;
807 if (!SaveStringVectorToParcel(&entry->managers, &element->managers.data)) {
808 LOGE("[DB]: Failed to copy managers!");
809 return false;
810 }
811 if (!SaveStringVectorToParcel(&entry->friends, &element->friends.data)) {
812 LOGE("[DB]: Failed to copy friends!");
813 return false;
814 }
815 return true;
816 }
817
SetDeviceElement(TlvDeviceElement * element,TrustedDeviceEntry * entry)818 static bool SetDeviceElement(TlvDeviceElement *element, TrustedDeviceEntry *entry)
819 {
820 if (!StringSet(&element->groupId.data, entry->groupId)) {
821 LOGE("[DB]: Failed to copy groupId!");
822 return false;
823 }
824 if (!StringSet(&element->udid.data, entry->udid)) {
825 LOGE("[DB]: Failed to copy udid!");
826 return false;
827 }
828 if (!StringSet(&element->authId.data, entry->authId)) {
829 LOGE("[DB]: Failed to copy authId!");
830 return false;
831 }
832 if (!StringSet(&element->userId.data, entry->userId)) {
833 LOGE("[DB]: Failed to copy userId!");
834 return false;
835 }
836 if (!StringSet(&element->serviceType.data, entry->serviceType)) {
837 LOGE("[DB]: Failed to copy serviceType!");
838 return false;
839 }
840 if (!ParcelCopy(&element->ext.data, &entry->ext)) {
841 LOGE("[DB]: Failed to copy external data!");
842 return false;
843 }
844 element->info.data.credential = entry->credential;
845 element->info.data.devType = entry->devType;
846 element->upgradeFlag.data = entry->upgradeFlag;
847 element->info.data.source = entry->source;
848 element->info.data.lastTm = entry->lastTm;
849 return true;
850 }
851
SaveGroups(const GroupEntryVec * vec,HCDataBaseV1 * db)852 static bool SaveGroups(const GroupEntryVec *vec, HCDataBaseV1 *db)
853 {
854 uint32_t index;
855 TrustedGroupEntry **entry;
856 FOR_EACH_HC_VECTOR(*vec, index, entry) {
857 TlvGroupElement tmp;
858 TlvGroupElement *element = db->groups.data.pushBack(&db->groups.data, &tmp);
859 if (element == NULL) {
860 return false;
861 }
862 TLV_INIT(TlvGroupElement, element);
863 if (!SetGroupElement(element, *entry)) {
864 TLV_DEINIT((*element));
865 return false;
866 }
867 }
868 return true;
869 }
870
SaveDevices(const DeviceEntryVec * vec,HCDataBaseV1 * db)871 static bool SaveDevices(const DeviceEntryVec *vec, HCDataBaseV1 *db)
872 {
873 uint32_t index;
874 TrustedDeviceEntry **entry;
875 FOR_EACH_HC_VECTOR(*vec, index, entry) {
876 TlvDeviceElement tmp;
877 TlvDeviceElement *element = db->devices.data.pushBack(&db->devices.data, &tmp);
878 if (element == NULL) {
879 return false;
880 }
881 TLV_INIT(TlvDeviceElement, element);
882 if (!SetDeviceElement(element, *entry)) {
883 TLV_DEINIT((*element));
884 return false;
885 }
886 }
887 return true;
888 }
889
SaveInfoToParcel(const OsAccountTrustedInfo * info,HcParcel * parcel)890 static bool SaveInfoToParcel(const OsAccountTrustedInfo *info, HcParcel *parcel)
891 {
892 int32_t ret = false;
893 HCDataBaseV1 dbv1;
894 TLV_INIT(HCDataBaseV1, &dbv1)
895 dbv1.version.data = 1;
896 do {
897 if (!SaveGroups(&info->groups, &dbv1)) {
898 break;
899 }
900 if (!SaveDevices(&info->devices, &dbv1)) {
901 break;
902 }
903 if (!EncodeTlvMessage((TlvBase *)&dbv1, parcel)) {
904 LOGE("[DB]: Encode Tlv Message failed!");
905 break;
906 }
907 ret = true;
908 } while (0);
909 TLV_DEINIT(dbv1)
910 return ret;
911 }
912
CompareQueryGroupParams(const QueryGroupParams * params,const TrustedGroupEntry * entry)913 static bool CompareQueryGroupParams(const QueryGroupParams *params, const TrustedGroupEntry *entry)
914 {
915 if ((params->groupId != NULL) && (!IsStrEqual(params->groupId, StringGet(&entry->id)))) {
916 return false;
917 }
918 if ((params->groupName != NULL) && (!IsStrEqual(params->groupName, StringGet(&entry->name)))) {
919 return false;
920 }
921 if ((params->userId != NULL) && (!IsStrEqual(params->userId, StringGet(&entry->userId)))) {
922 return false;
923 }
924 if ((params->sharedUserId != NULL) && (!IsStrEqual(params->sharedUserId, StringGet(&entry->sharedUserId)))) {
925 return false;
926 }
927 if ((params->groupType != ALL_GROUP) && (params->groupType != entry->type)) {
928 return false;
929 }
930 if ((params->groupVisibility != ALL_GROUP_VISIBILITY) && (params->groupVisibility != entry->visibility)) {
931 return false;
932 }
933 if (params->ownerName != NULL) {
934 HcString entryOwner = HC_VECTOR_GET(&entry->managers, 0);
935 if (!IsStrEqual(params->ownerName, StringGet(&entryOwner))) {
936 return false;
937 }
938 }
939 return true;
940 }
941
CompareQueryDeviceParams(const QueryDeviceParams * params,const TrustedDeviceEntry * entry)942 static bool CompareQueryDeviceParams(const QueryDeviceParams *params, const TrustedDeviceEntry *entry)
943 {
944 if ((params->groupId != NULL) && (!IsStrEqual(params->groupId, StringGet(&entry->groupId)))) {
945 return false;
946 }
947 if ((params->udid != NULL) && (!IsStrEqual(params->udid, StringGet(&entry->udid)))) {
948 return false;
949 }
950 if ((params->authId != NULL) && (!IsStrEqual(params->authId, StringGet(&entry->authId)))) {
951 return false;
952 }
953 if ((params->userId != NULL) && (!IsStrEqual(params->userId, StringGet(&entry->userId)))) {
954 return false;
955 }
956 return true;
957 }
958
QueryGroupEntryPtrIfMatch(const GroupEntryVec * vec,const QueryGroupParams * params)959 static TrustedGroupEntry **QueryGroupEntryPtrIfMatch(const GroupEntryVec *vec, const QueryGroupParams *params)
960 {
961 uint32_t index;
962 TrustedGroupEntry **entry;
963 FOR_EACH_HC_VECTOR(*vec, index, entry) {
964 if (CompareQueryGroupParams(params, *entry)) {
965 return entry;
966 }
967 }
968 return NULL;
969 }
970
QueryDeviceEntryPtrIfMatch(const DeviceEntryVec * vec,const QueryDeviceParams * params)971 static TrustedDeviceEntry **QueryDeviceEntryPtrIfMatch(const DeviceEntryVec *vec, const QueryDeviceParams *params)
972 {
973 uint32_t index;
974 TrustedDeviceEntry **entry;
975 FOR_EACH_HC_VECTOR(*vec, index, entry) {
976 if (CompareQueryDeviceParams(params, *entry)) {
977 return entry;
978 }
979 }
980 return NULL;
981 }
982
AddGroupNameToReturn(const TrustedGroupEntry * groupInfo,CJson * json)983 static int32_t AddGroupNameToReturn(const TrustedGroupEntry *groupInfo, CJson *json)
984 {
985 const char *groupName = StringGet(&groupInfo->name);
986 if (groupName == NULL) {
987 LOGE("Failed to get groupName from groupInfo!");
988 return HC_ERR_NULL_PTR;
989 }
990 if (AddStringToJson(json, FIELD_GROUP_NAME, groupName) != HC_SUCCESS) {
991 LOGE("Failed to add groupName to json!");
992 return HC_ERR_JSON_FAIL;
993 }
994 return HC_SUCCESS;
995 }
996
AddGroupIdToReturn(const TrustedGroupEntry * groupInfo,CJson * json)997 static int32_t AddGroupIdToReturn(const TrustedGroupEntry *groupInfo, CJson *json)
998 {
999 const char *groupId = StringGet(&groupInfo->id);
1000 if (groupId == NULL) {
1001 LOGE("Failed to get groupId from groupInfo!");
1002 return HC_ERR_NULL_PTR;
1003 }
1004 if (AddStringToJson(json, FIELD_GROUP_ID, groupId) != HC_SUCCESS) {
1005 LOGE("Failed to add groupId to json!");
1006 return HC_ERR_JSON_FAIL;
1007 }
1008 return HC_SUCCESS;
1009 }
1010
AddGroupOwnerToReturn(const TrustedGroupEntry * groupInfo,CJson * json)1011 static int32_t AddGroupOwnerToReturn(const TrustedGroupEntry *groupInfo, CJson *json)
1012 {
1013 HcString entryManager = HC_VECTOR_GET(&groupInfo->managers, 0);
1014 const char *groupOwner = StringGet(&entryManager);
1015 if (groupOwner == NULL) {
1016 LOGE("Failed to get groupOwner from groupInfo!");
1017 return HC_ERR_NULL_PTR;
1018 }
1019 if (AddStringToJson(json, FIELD_GROUP_OWNER, groupOwner) != HC_SUCCESS) {
1020 LOGE("Failed to add groupOwner to json!");
1021 return HC_ERR_JSON_FAIL;
1022 }
1023 return HC_SUCCESS;
1024 }
1025
AddGroupTypeToReturn(const TrustedGroupEntry * groupInfo,CJson * json)1026 static int32_t AddGroupTypeToReturn(const TrustedGroupEntry *groupInfo, CJson *json)
1027 {
1028 int32_t groupType = groupInfo->type;
1029 if (AddIntToJson(json, FIELD_GROUP_TYPE, groupType) != HC_SUCCESS) {
1030 LOGE("Failed to add groupType to json!");
1031 return HC_ERR_JSON_FAIL;
1032 }
1033 return HC_SUCCESS;
1034 }
1035
AddGroupVisibilityToReturn(const TrustedGroupEntry * groupInfo,CJson * json)1036 static int32_t AddGroupVisibilityToReturn(const TrustedGroupEntry *groupInfo, CJson *json)
1037 {
1038 int groupVisibility = groupInfo->visibility;
1039 if (AddIntToJson(json, FIELD_GROUP_VISIBILITY, groupVisibility) != HC_SUCCESS) {
1040 LOGE("Failed to add groupType to json!");
1041 return HC_ERR_JSON_FAIL;
1042 }
1043 return HC_SUCCESS;
1044 }
1045
AddUserIdToReturnIfAccountGroup(const TrustedGroupEntry * groupInfo,CJson * json)1046 static int32_t AddUserIdToReturnIfAccountGroup(const TrustedGroupEntry *groupInfo, CJson *json)
1047 {
1048 if ((groupInfo->type != ACROSS_ACCOUNT_AUTHORIZE_GROUP) && (groupInfo->type != IDENTICAL_ACCOUNT_GROUP)) {
1049 return HC_SUCCESS;
1050 }
1051 const char *userId = StringGet(&groupInfo->userId);
1052 if (userId == NULL) {
1053 LOGE("Failed to get userId from groupInfo!");
1054 return HC_ERR_NULL_PTR;
1055 }
1056 if (AddStringToJson(json, FIELD_USER_ID, userId) != HC_SUCCESS) {
1057 LOGE("Failed to add userId to json!");
1058 return HC_ERR_JSON_FAIL;
1059 }
1060 return HC_SUCCESS;
1061 }
1062
AddSharedUserIdToReturnIfAcrossAccountGroup(const TrustedGroupEntry * groupInfo,CJson * json)1063 static int32_t AddSharedUserIdToReturnIfAcrossAccountGroup(const TrustedGroupEntry *groupInfo, CJson *json)
1064 {
1065 if (groupInfo->type != ACROSS_ACCOUNT_AUTHORIZE_GROUP) {
1066 return HC_SUCCESS;
1067 }
1068 const char *sharedUserId = StringGet(&groupInfo->sharedUserId);
1069 if (sharedUserId == NULL) {
1070 LOGE("Failed to get sharedUserId from groupInfo!");
1071 return HC_ERR_NULL_PTR;
1072 }
1073 if (AddStringToJson(json, FIELD_SHARED_USER_ID, sharedUserId) != HC_SUCCESS) {
1074 LOGE("Failed to add sharedUserId to json!");
1075 return HC_ERR_JSON_FAIL;
1076 }
1077 return HC_SUCCESS;
1078 }
1079
AddAuthIdToReturn(const TrustedDeviceEntry * deviceInfo,CJson * json)1080 static int32_t AddAuthIdToReturn(const TrustedDeviceEntry *deviceInfo, CJson *json)
1081 {
1082 const char *authId = StringGet(&deviceInfo->authId);
1083 if (authId == NULL) {
1084 LOGE("Failed to get authId from deviceInfo!");
1085 return HC_ERR_NULL_PTR;
1086 }
1087 if (AddStringToJson(json, FIELD_AUTH_ID, authId) != HC_SUCCESS) {
1088 LOGE("Failed to add authId to json!");
1089 return HC_ERR_JSON_FAIL;
1090 }
1091 return HC_SUCCESS;
1092 }
1093
AddCredentialTypeToReturn(const TrustedDeviceEntry * deviceInfo,CJson * json)1094 static int32_t AddCredentialTypeToReturn(const TrustedDeviceEntry *deviceInfo, CJson *json)
1095 {
1096 int credentialType = deviceInfo->credential;
1097 if (AddIntToJson(json, FIELD_CREDENTIAL_TYPE, credentialType) != HC_SUCCESS) {
1098 LOGE("Failed to add credentialType to json!");
1099 return HC_ERR_JSON_FAIL;
1100 }
1101 return HC_SUCCESS;
1102 }
1103
AddUserTypeToReturn(const TrustedDeviceEntry * deviceInfo,CJson * json)1104 static int32_t AddUserTypeToReturn(const TrustedDeviceEntry *deviceInfo, CJson *json)
1105 {
1106 int userType = deviceInfo->devType;
1107 if (AddIntToJson(json, FIELD_USER_TYPE, userType) != HC_SUCCESS) {
1108 LOGE("Failed to add userType to json!");
1109 return HC_ERR_JSON_FAIL;
1110 }
1111 return HC_SUCCESS;
1112 }
1113
GenerateMessage(const TrustedGroupEntry * groupEntry,char ** returnGroupInfo)1114 static int32_t GenerateMessage(const TrustedGroupEntry *groupEntry, char **returnGroupInfo)
1115 {
1116 if (groupEntry == NULL) {
1117 LOGE("Input param groupEntry is null!");
1118 return HC_ERR_NULL_PTR;
1119 }
1120 CJson *message = CreateJson();
1121 if (message == NULL) {
1122 LOGE("Failed to allocate message memory!");
1123 return HC_ERR_ALLOC_MEMORY;
1124 }
1125 int32_t result = GenerateReturnGroupInfo(groupEntry, message);
1126 if (result != HC_SUCCESS) {
1127 FreeJson(message);
1128 return result;
1129 }
1130 char *messageStr = PackJsonToString(message);
1131 FreeJson(message);
1132 if (messageStr == NULL) {
1133 LOGE("Failed to convert json to string!");
1134 return HC_ERR_JSON_FAIL;
1135 }
1136 *returnGroupInfo = messageStr;
1137 return HC_SUCCESS;
1138 }
1139
PostGroupCreatedMsg(const TrustedGroupEntry * groupEntry)1140 static void PostGroupCreatedMsg(const TrustedGroupEntry *groupEntry)
1141 {
1142 if (!IsBroadcastSupported()) {
1143 return;
1144 }
1145 char *messageStr = NULL;
1146 if (GenerateMessage(groupEntry, &messageStr) != HC_SUCCESS) {
1147 return;
1148 }
1149 GetBroadcaster()->postOnGroupCreated(messageStr);
1150 FreeJsonString(messageStr);
1151 }
1152
PostGroupDeletedMsg(const TrustedGroupEntry * groupEntry)1153 static void PostGroupDeletedMsg(const TrustedGroupEntry *groupEntry)
1154 {
1155 if (!IsBroadcastSupported()) {
1156 return;
1157 }
1158 char *messageStr = NULL;
1159 if (GenerateMessage(groupEntry, &messageStr) != HC_SUCCESS) {
1160 return;
1161 }
1162 GetBroadcaster()->postOnGroupDeleted(messageStr);
1163 FreeJsonString(messageStr);
1164 }
1165
PostDeviceBoundMsg(OsAccountTrustedInfo * info,const TrustedDeviceEntry * deviceEntry)1166 static void PostDeviceBoundMsg(OsAccountTrustedInfo *info, const TrustedDeviceEntry *deviceEntry)
1167 {
1168 if (!IsBroadcastSupported()) {
1169 return;
1170 }
1171 QueryGroupParams groupParams = InitQueryGroupParams();
1172 groupParams.groupId = StringGet(&deviceEntry->groupId);
1173 TrustedGroupEntry **groupEntryPtr = QueryGroupEntryPtrIfMatch(&info->groups, &groupParams);
1174 if (groupEntryPtr != NULL) {
1175 char *messageStr = NULL;
1176 if (GenerateMessage(*groupEntryPtr, &messageStr) != HC_SUCCESS) {
1177 return;
1178 }
1179 GetBroadcaster()->postOnDeviceBound(StringGet(&deviceEntry->udid), messageStr);
1180 FreeJsonString(messageStr);
1181 }
1182 }
1183
IsSelfDeviceEntry(const TrustedDeviceEntry * deviceEntry)1184 static bool IsSelfDeviceEntry(const TrustedDeviceEntry *deviceEntry)
1185 {
1186 char selfUdid[INPUT_UDID_LEN] = { 0 };
1187 int32_t res = HcGetUdid((uint8_t *)selfUdid, INPUT_UDID_LEN);
1188 if (res != HC_SUCCESS) {
1189 LOGE("Failed to get local udid! res: %" LOG_PUB "d", res);
1190 return false;
1191 }
1192 const char *entryUdid = StringGet(&deviceEntry->udid);
1193 if (entryUdid == NULL) {
1194 LOGE("The entryUdid is NULL!");
1195 return false;
1196 }
1197 return IsStrEqual(selfUdid, entryUdid);
1198 }
1199
GenerateMessageWithOsAccount(const TrustedGroupEntry * groupEntry,int32_t osAccountId,char ** returnMessageStr)1200 static int32_t GenerateMessageWithOsAccount(const TrustedGroupEntry *groupEntry, int32_t osAccountId,
1201 char **returnMessageStr)
1202 {
1203 if (groupEntry == NULL) {
1204 LOGE("groupEntry is null!");
1205 return HC_ERR_NULL_PTR;
1206 }
1207 CJson *message = CreateJson();
1208 if (message == NULL) {
1209 LOGE("Failed to create message json!");
1210 return HC_ERR_ALLOC_MEMORY;
1211 }
1212 int32_t result = GenerateReturnGroupInfo(groupEntry, message);
1213 if (result != HC_SUCCESS) {
1214 FreeJson(message);
1215 return result;
1216 }
1217 if (AddIntToJson(message, FIELD_OS_ACCOUNT_ID, osAccountId) != HC_SUCCESS) {
1218 FreeJson(message);
1219 return HC_ERR_JSON_ADD;
1220 }
1221 char *messageStr = PackJsonToString(message);
1222 FreeJson(message);
1223 if (messageStr == NULL) {
1224 LOGE("Failed to convert json to string!");
1225 return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL;
1226 }
1227 *returnMessageStr = messageStr;
1228 return HC_SUCCESS;
1229 }
1230
PostDeviceUnBoundMsg(OsAccountTrustedInfo * info,const TrustedDeviceEntry * deviceEntry)1231 static void PostDeviceUnBoundMsg(OsAccountTrustedInfo *info, const TrustedDeviceEntry *deviceEntry)
1232 {
1233 if (!IsBroadcastSupported()) {
1234 return;
1235 }
1236 const char *groupId = StringGet(&deviceEntry->groupId);
1237 const char *udid = StringGet(&deviceEntry->udid);
1238 QueryGroupParams groupParams = InitQueryGroupParams();
1239 groupParams.groupId = groupId;
1240 TrustedGroupEntry **groupEntryPtr = QueryGroupEntryPtrIfMatch(&info->groups, &groupParams);
1241 if (groupEntryPtr != NULL) {
1242 char *messageStr = NULL;
1243 if (GenerateMessageWithOsAccount(*groupEntryPtr, info->osAccountId, &messageStr) != HC_SUCCESS) {
1244 return;
1245 }
1246 GetBroadcaster()->postOnDeviceUnBound(udid, messageStr);
1247 FreeJsonString(messageStr);
1248 }
1249 QueryDeviceParams deviceParams = InitQueryDeviceParams();
1250 deviceParams.udid = udid;
1251 if (QueryDeviceEntryPtrIfMatch(&info->devices, &deviceParams) == NULL) {
1252 GetBroadcaster()->postOnDeviceNotTrusted(udid);
1253 if (!IsSelfDeviceEntry(deviceEntry)) {
1254 (void)DeleteMk(info->osAccountId, udid);
1255 (void)DeletePseudonymPsk(info->osAccountId, udid);
1256 }
1257 }
1258 }
1259
DeletePdidByDeviceEntry(int32_t osAccountId,const TrustedDeviceEntry * deviceEntry)1260 static void DeletePdidByDeviceEntry(int32_t osAccountId, const TrustedDeviceEntry *deviceEntry)
1261 {
1262 if (IsSelfDeviceEntry(deviceEntry)) {
1263 return;
1264 }
1265 const char *userId = StringGet(&deviceEntry->userId);
1266 if (userId == NULL) {
1267 LOGW("userId is null!");
1268 return;
1269 }
1270 if (deviceEntry->credential != ASYMMETRIC_CRED) {
1271 LOGW("credential type is not asymmetric!");
1272 return;
1273 }
1274 PseudonymManager *manager = GetPseudonymInstance();
1275 if (manager == NULL) {
1276 LOGE("Pseudonym manager is null!");
1277 return;
1278 }
1279 int32_t res = manager->deletePseudonymId(osAccountId, userId);
1280 if (res != HC_SUCCESS) {
1281 LOGE("Failed to delete pdid!");
1282 } else {
1283 LOGI("Delete pdid successfully!");
1284 }
1285 }
1286
InitQueryGroupParams(void)1287 QueryGroupParams InitQueryGroupParams(void)
1288 {
1289 QueryGroupParams params = {
1290 .groupId = NULL,
1291 .groupName = NULL,
1292 .ownerName = NULL,
1293 .userId = NULL,
1294 .groupType = ALL_GROUP,
1295 .groupVisibility = ALL_GROUP_VISIBILITY
1296 };
1297 return params;
1298 }
1299
InitQueryDeviceParams(void)1300 QueryDeviceParams InitQueryDeviceParams(void)
1301 {
1302 QueryDeviceParams params = {
1303 .groupId = NULL,
1304 .udid = NULL,
1305 .authId = NULL,
1306 .userId = NULL
1307 };
1308 return params;
1309 }
1310
CreateGroupEntry(void)1311 TrustedGroupEntry *CreateGroupEntry(void)
1312 {
1313 TrustedGroupEntry *ptr = (TrustedGroupEntry *)HcMalloc(sizeof(TrustedGroupEntry), 0);
1314 if (ptr == NULL) {
1315 LOGE("[DB]: Failed to allocate groupEntry memory!");
1316 return NULL;
1317 }
1318 ptr->name = CreateString();
1319 ptr->id = CreateString();
1320 ptr->userId = CreateString();
1321 ptr->sharedUserId = CreateString();
1322 ptr->managers = CreateStrVector();
1323 ptr->friends = CreateStrVector();
1324 return ptr;
1325 }
1326
DestroyGroupEntry(TrustedGroupEntry * groupEntry)1327 void DestroyGroupEntry(TrustedGroupEntry *groupEntry)
1328 {
1329 if (groupEntry == NULL) {
1330 return;
1331 }
1332 DeleteString(&groupEntry->name);
1333 DeleteString(&groupEntry->id);
1334 DeleteString(&groupEntry->userId);
1335 DeleteString(&groupEntry->sharedUserId);
1336 DestroyStrVector(&groupEntry->managers);
1337 DestroyStrVector(&groupEntry->friends);
1338 HcFree(groupEntry);
1339 }
1340
DeepCopyGroupEntry(const TrustedGroupEntry * entry)1341 TrustedGroupEntry *DeepCopyGroupEntry(const TrustedGroupEntry *entry)
1342 {
1343 TrustedGroupEntry *returnEntry = CreateGroupEntry();
1344 if (returnEntry == NULL) {
1345 return NULL;
1346 }
1347 if (!GenerateGroupEntryFromEntry(entry, returnEntry)) {
1348 DestroyGroupEntry(returnEntry);
1349 return NULL;
1350 }
1351 return returnEntry;
1352 }
1353
CreateDeviceEntry(void)1354 TrustedDeviceEntry *CreateDeviceEntry(void)
1355 {
1356 TrustedDeviceEntry *ptr = (TrustedDeviceEntry *)HcMalloc(sizeof(TrustedDeviceEntry), 0);
1357 if (ptr == NULL) {
1358 LOGE("[DB]: Failed to allocate deviceEntry memory!");
1359 return NULL;
1360 }
1361 ptr->groupId = CreateString();
1362 ptr->udid = CreateString();
1363 ptr->authId = CreateString();
1364 ptr->userId = CreateString();
1365 ptr->serviceType = CreateString();
1366 ptr->ext = CreateParcel(0, 0);
1367 return ptr;
1368 }
1369
DestroyDeviceEntry(TrustedDeviceEntry * deviceEntry)1370 void DestroyDeviceEntry(TrustedDeviceEntry *deviceEntry)
1371 {
1372 if (deviceEntry == NULL) {
1373 return;
1374 }
1375 DeleteString(&deviceEntry->groupId);
1376 DeleteString(&deviceEntry->udid);
1377 DeleteString(&deviceEntry->authId);
1378 DeleteString(&deviceEntry->userId);
1379 DeleteString(&deviceEntry->serviceType);
1380 DeleteParcel(&deviceEntry->ext);
1381 HcFree(deviceEntry);
1382 }
1383
DeepCopyDeviceEntry(const TrustedDeviceEntry * entry)1384 TrustedDeviceEntry *DeepCopyDeviceEntry(const TrustedDeviceEntry *entry)
1385 {
1386 if (entry == NULL) {
1387 return NULL;
1388 }
1389 TrustedDeviceEntry *returnEntry = CreateDeviceEntry();
1390 if (returnEntry == NULL) {
1391 return NULL;
1392 }
1393 if (!GenerateDeviceEntryFromEntry(entry, returnEntry)) {
1394 DestroyDeviceEntry(returnEntry);
1395 return NULL;
1396 }
1397 return returnEntry;
1398 }
1399
ClearGroupEntryVec(GroupEntryVec * vec)1400 void ClearGroupEntryVec(GroupEntryVec *vec)
1401 {
1402 uint32_t index;
1403 TrustedGroupEntry **entry;
1404 FOR_EACH_HC_VECTOR(*vec, index, entry) {
1405 DestroyGroupEntry(*entry);
1406 }
1407 DESTROY_HC_VECTOR(GroupEntryVec, vec);
1408 }
1409
ClearDeviceEntryVec(DeviceEntryVec * vec)1410 void ClearDeviceEntryVec(DeviceEntryVec *vec)
1411 {
1412 uint32_t index;
1413 TrustedDeviceEntry **entry;
1414 FOR_EACH_HC_VECTOR(*vec, index, entry) {
1415 DestroyDeviceEntry(*entry);
1416 }
1417 DESTROY_HC_VECTOR(DeviceEntryVec, vec);
1418 }
1419
GenerateReturnGroupInfo(const TrustedGroupEntry * groupEntry,CJson * returnJson)1420 int32_t GenerateReturnGroupInfo(const TrustedGroupEntry *groupEntry, CJson *returnJson)
1421 {
1422 int32_t result;
1423 if (((result = AddGroupNameToReturn(groupEntry, returnJson)) != HC_SUCCESS) ||
1424 ((result = AddGroupIdToReturn(groupEntry, returnJson)) != HC_SUCCESS) ||
1425 ((result = AddGroupOwnerToReturn(groupEntry, returnJson)) != HC_SUCCESS) ||
1426 ((result = AddGroupTypeToReturn(groupEntry, returnJson)) != HC_SUCCESS) ||
1427 ((result = AddGroupVisibilityToReturn(groupEntry, returnJson)) != HC_SUCCESS) ||
1428 ((result = AddUserIdToReturnIfAccountGroup(groupEntry, returnJson)) != HC_SUCCESS) ||
1429 ((result = AddSharedUserIdToReturnIfAcrossAccountGroup(groupEntry, returnJson)) != HC_SUCCESS)) {
1430 return result;
1431 }
1432 return HC_SUCCESS;
1433 }
1434
GenerateReturnDevInfo(const TrustedDeviceEntry * deviceEntry,CJson * returnJson)1435 int32_t GenerateReturnDevInfo(const TrustedDeviceEntry *deviceEntry, CJson *returnJson)
1436 {
1437 int32_t result;
1438 if (((result = AddAuthIdToReturn(deviceEntry, returnJson)) != HC_SUCCESS) ||
1439 ((result = AddCredentialTypeToReturn(deviceEntry, returnJson)) != HC_SUCCESS) ||
1440 ((result = AddUserTypeToReturn(deviceEntry, returnJson)) != HC_SUCCESS)) {
1441 return result;
1442 }
1443 return HC_SUCCESS;
1444 }
1445
AddGroup(int32_t osAccountId,const TrustedGroupEntry * groupEntry)1446 int32_t AddGroup(int32_t osAccountId, const TrustedGroupEntry *groupEntry)
1447 {
1448 LOGI("[DB]: Start to add a group to database! [OsAccountId]: %" LOG_PUB "d", osAccountId);
1449 if (groupEntry == NULL) {
1450 LOGE("[DB]: The input groupEntry is NULL!");
1451 return HC_ERR_NULL_PTR;
1452 }
1453 (void)LockHcMutex(g_databaseMutex);
1454 OsAccountTrustedInfo *info = GetTrustedInfoByOsAccountId(osAccountId);
1455 if (info == NULL) {
1456 UnlockHcMutex(g_databaseMutex);
1457 return HC_ERR_INVALID_PARAMS;
1458 }
1459 TrustedGroupEntry *newEntry = DeepCopyGroupEntry(groupEntry);
1460 if (newEntry == NULL) {
1461 UnlockHcMutex(g_databaseMutex);
1462 return HC_ERR_MEMORY_COPY;
1463 }
1464 QueryGroupParams params = InitQueryGroupParams();
1465 params.groupId = StringGet(&groupEntry->id);
1466 TrustedGroupEntry **oldEntryPtr = QueryGroupEntryPtrIfMatch(&info->groups, ¶ms);
1467 if (oldEntryPtr != NULL) {
1468 DestroyGroupEntry(*oldEntryPtr);
1469 *oldEntryPtr = newEntry;
1470 PostGroupCreatedMsg(newEntry);
1471 UnlockHcMutex(g_databaseMutex);
1472 LOGI("[DB]: Replace an old group successfully! [GroupType]: %" LOG_PUB "u", groupEntry->type);
1473 return HC_SUCCESS;
1474 }
1475 if (info->groups.pushBackT(&info->groups, newEntry) == NULL) {
1476 DestroyGroupEntry(newEntry);
1477 UnlockHcMutex(g_databaseMutex);
1478 LOGE("[DB]: Failed to push groupEntry to vec!");
1479 return HC_ERR_MEMORY_COPY;
1480 }
1481 PostGroupCreatedMsg(newEntry);
1482 UnlockHcMutex(g_databaseMutex);
1483 LOGI("[DB]: Add a group to database successfully! [GroupType]: %" LOG_PUB "u", groupEntry->type);
1484 return HC_SUCCESS;
1485 }
1486
AddTrustedDevice(int32_t osAccountId,const TrustedDeviceEntry * deviceEntry)1487 int32_t AddTrustedDevice(int32_t osAccountId, const TrustedDeviceEntry *deviceEntry)
1488 {
1489 LOGI("[DB]: Start to add a trusted device to database! [OsAccountId]: %" LOG_PUB "d", osAccountId);
1490 if (deviceEntry == NULL) {
1491 LOGE("[DB]: The input deviceEntry is NULL!");
1492 return HC_ERR_NULL_PTR;
1493 }
1494 (void)LockHcMutex(g_databaseMutex);
1495 OsAccountTrustedInfo *info = GetTrustedInfoByOsAccountId(osAccountId);
1496 if (info == NULL) {
1497 UnlockHcMutex(g_databaseMutex);
1498 return HC_ERR_INVALID_PARAMS;
1499 }
1500 TrustedDeviceEntry *newEntry = DeepCopyDeviceEntry(deviceEntry);
1501 if (newEntry == NULL) {
1502 UnlockHcMutex(g_databaseMutex);
1503 return HC_ERR_MEMORY_COPY;
1504 }
1505 QueryDeviceParams params = InitQueryDeviceParams();
1506 params.udid = StringGet(&deviceEntry->udid);
1507 params.groupId = StringGet(&deviceEntry->groupId);
1508 TrustedDeviceEntry **oldEntryPtr = QueryDeviceEntryPtrIfMatch(&info->devices, ¶ms);
1509 if (oldEntryPtr != NULL) {
1510 DestroyDeviceEntry(*oldEntryPtr);
1511 *oldEntryPtr = newEntry;
1512 PostDeviceBoundMsg(info, newEntry);
1513 UnlockHcMutex(g_databaseMutex);
1514 LOGI("[DB]: Replace an old trusted device successfully!");
1515 return HC_SUCCESS;
1516 }
1517 if (info->devices.pushBackT(&info->devices, newEntry) == NULL) {
1518 DestroyDeviceEntry(newEntry);
1519 UnlockHcMutex(g_databaseMutex);
1520 LOGE("[DB]: Failed to push deviceEntry to vec!");
1521 return HC_ERR_MEMORY_COPY;
1522 }
1523 PostDeviceBoundMsg(info, newEntry);
1524 UnlockHcMutex(g_databaseMutex);
1525 LOGI("[DB]: Add a trusted device to database successfully!");
1526 return HC_SUCCESS;
1527 }
1528
DelGroup(int32_t osAccountId,const QueryGroupParams * params)1529 int32_t DelGroup(int32_t osAccountId, const QueryGroupParams *params)
1530 {
1531 LOGI("[DB]: Start to delete groups from database! [OsAccountId]: %" LOG_PUB "d", osAccountId);
1532 if (params == NULL) {
1533 LOGE("[DB]: The input params is NULL!");
1534 return HC_ERR_NULL_PTR;
1535 }
1536 (void)LockHcMutex(g_databaseMutex);
1537 OsAccountTrustedInfo *info = GetTrustedInfoByOsAccountId(osAccountId);
1538 if (info == NULL) {
1539 UnlockHcMutex(g_databaseMutex);
1540 LOGE("[DB]: GetTrustedInfoByOsAccountId occurred error!");
1541 return HC_ERR_INVALID_PARAMS;
1542 }
1543 int32_t count = 0;
1544 uint32_t index = 0;
1545 TrustedGroupEntry **entry = NULL;
1546 while (index < HC_VECTOR_SIZE(&info->groups)) {
1547 entry = info->groups.getp(&info->groups, index);
1548 if ((entry == NULL) || (*entry == NULL) || (!CompareQueryGroupParams(params, *entry))) {
1549 index++;
1550 continue;
1551 }
1552 TrustedGroupEntry *popEntry;
1553 HC_VECTOR_POPELEMENT(&info->groups, &popEntry, index);
1554 PostGroupDeletedMsg(popEntry);
1555 LOGI("[DB]: Delete a group from database successfully! [GroupType]: %" LOG_PUB "u", popEntry->type);
1556 DestroyGroupEntry(popEntry);
1557 count++;
1558 }
1559 UnlockHcMutex(g_databaseMutex);
1560 LOGI("[DB]: Number of groups deleted: %" LOG_PUB "d", count);
1561 return HC_SUCCESS;
1562 }
1563
DelTrustedDevice(int32_t osAccountId,const QueryDeviceParams * params)1564 int32_t DelTrustedDevice(int32_t osAccountId, const QueryDeviceParams *params)
1565 {
1566 LOGI("[DB]: Start to delete devices from database! [OsAccountId]: %" LOG_PUB "d", osAccountId);
1567 if (params == NULL) {
1568 LOGE("[DB]: The input params is NULL!");
1569 return HC_ERR_NULL_PTR;
1570 }
1571 (void)LockHcMutex(g_databaseMutex);
1572 OsAccountTrustedInfo *info = GetTrustedInfoByOsAccountId(osAccountId);
1573 if (info == NULL) {
1574 UnlockHcMutex(g_databaseMutex);
1575 return HC_ERR_INVALID_PARAMS;
1576 }
1577 int32_t count = 0;
1578 uint32_t index = 0;
1579 TrustedDeviceEntry **entry = NULL;
1580 while (index < HC_VECTOR_SIZE(&info->devices)) {
1581 entry = info->devices.getp(&info->devices, index);
1582 if ((entry == NULL) || (*entry == NULL) || (!CompareQueryDeviceParams(params, *entry))) {
1583 index++;
1584 continue;
1585 }
1586 TrustedDeviceEntry *popEntry;
1587 HC_VECTOR_POPELEMENT(&info->devices, &popEntry, index);
1588 PostDeviceUnBoundMsg(info, popEntry);
1589 DeletePdidByDeviceEntry(osAccountId, popEntry);
1590 LOGI("[DB]: Delete a trusted device from database successfully!");
1591 DestroyDeviceEntry(popEntry);
1592 count++;
1593 }
1594 UnlockHcMutex(g_databaseMutex);
1595 LOGI("[DB]: Number of trusted devices deleted: %" LOG_PUB "d", count);
1596 return HC_SUCCESS;
1597 }
1598
QueryGroups(int32_t osAccountId,const QueryGroupParams * params,GroupEntryVec * vec)1599 int32_t QueryGroups(int32_t osAccountId, const QueryGroupParams *params, GroupEntryVec *vec)
1600 {
1601 if ((params == NULL) || (vec == NULL)) {
1602 LOGE("[DB]: Error occurs, the input params or vec is NULL!");
1603 return HC_ERR_NULL_PTR;
1604 }
1605 (void)LockHcMutex(g_databaseMutex);
1606 OsAccountTrustedInfo *info = GetTrustedInfoByOsAccountId(osAccountId);
1607 if (info == NULL) {
1608 UnlockHcMutex(g_databaseMutex);
1609 return HC_ERR_INVALID_PARAMS;
1610 }
1611 uint32_t index;
1612 TrustedGroupEntry **entry;
1613 FOR_EACH_HC_VECTOR(info->groups, index, entry) {
1614 if (!CompareQueryGroupParams(params, *entry)) {
1615 continue;
1616 }
1617 TrustedGroupEntry *newEntry = DeepCopyGroupEntry(*entry);
1618 if (newEntry == NULL) {
1619 continue;
1620 }
1621 if (vec->pushBackT(vec, newEntry) == NULL) {
1622 LOGE("[DB]: Failed to push entry to vec!");
1623 DestroyGroupEntry(newEntry);
1624 }
1625 }
1626 UnlockHcMutex(g_databaseMutex);
1627 return HC_SUCCESS;
1628 }
1629
QueryDevices(int32_t osAccountId,const QueryDeviceParams * params,DeviceEntryVec * vec)1630 int32_t QueryDevices(int32_t osAccountId, const QueryDeviceParams *params, DeviceEntryVec *vec)
1631 {
1632 if ((params == NULL) || (vec == NULL)) {
1633 LOGE("[DB]: The input query devices params or vec is NULL!");
1634 return HC_ERR_NULL_PTR;
1635 }
1636 (void)LockHcMutex(g_databaseMutex);
1637 OsAccountTrustedInfo *info = GetTrustedInfoByOsAccountId(osAccountId);
1638 if (info == NULL) {
1639 UnlockHcMutex(g_databaseMutex);
1640 return HC_ERR_INVALID_PARAMS;
1641 }
1642 uint32_t index;
1643 TrustedDeviceEntry **entry;
1644 FOR_EACH_HC_VECTOR(info->devices, index, entry) {
1645 if (!CompareQueryDeviceParams(params, *entry)) {
1646 continue;
1647 }
1648 TrustedDeviceEntry *newEntry = DeepCopyDeviceEntry(*entry);
1649 if (newEntry == NULL) {
1650 continue;
1651 }
1652 if (vec->pushBackT(vec, newEntry) == NULL) {
1653 LOGE("[DB]: Failed to push entry to vec!");
1654 DestroyDeviceEntry(newEntry);
1655 }
1656 }
1657 UnlockHcMutex(g_databaseMutex);
1658 return HC_SUCCESS;
1659 }
1660
SaveOsAccountDb(int32_t osAccountId)1661 int32_t SaveOsAccountDb(int32_t osAccountId)
1662 {
1663 (void)LockHcMutex(g_databaseMutex);
1664 OsAccountTrustedInfo *info = GetTrustedInfoByOsAccountId(osAccountId);
1665 if (info == NULL) {
1666 UnlockHcMutex(g_databaseMutex);
1667 return HC_ERR_INVALID_PARAMS;
1668 }
1669 HcParcel parcel = CreateParcel(0, 0);
1670 if (!SaveInfoToParcel(info, &parcel)) {
1671 DeleteParcel(&parcel);
1672 UnlockHcMutex(g_databaseMutex);
1673 return HC_ERR_MEMORY_COPY;
1674 }
1675 char filePath[MAX_DB_PATH_LEN] = { 0 };
1676 if (!GetOsAccountInfoPath(osAccountId, filePath, MAX_DB_PATH_LEN)) {
1677 DeleteParcel(&parcel);
1678 UnlockHcMutex(g_databaseMutex);
1679 return HC_ERROR;
1680 }
1681 if (!SaveParcelToFile(filePath, &parcel)) {
1682 DeleteParcel(&parcel);
1683 UnlockHcMutex(g_databaseMutex);
1684 return HC_ERR_MEMORY_COPY;
1685 }
1686 DeleteParcel(&parcel);
1687 UnlockHcMutex(g_databaseMutex);
1688 LOGI("[DB]: Save an os account database successfully! [Id]: %" LOG_PUB "d", osAccountId);
1689 return HC_SUCCESS;
1690 }
1691
ReloadOsAccountDb(int32_t osAccountId)1692 void ReloadOsAccountDb(int32_t osAccountId)
1693 {
1694 if (g_databaseMutex == NULL) {
1695 LOGE("[DB]: not initialized!");
1696 return;
1697 }
1698 (void)LockHcMutex(g_databaseMutex);
1699 LoadOsAccountDbCe(osAccountId);
1700 UnlockHcMutex(g_databaseMutex);
1701 }
1702
1703 #ifdef DEV_AUTH_HIVIEW_ENABLE
DumpGroup(int fd,const TrustedGroupEntry * group)1704 static void DumpGroup(int fd, const TrustedGroupEntry *group)
1705 {
1706 dprintf(fd, "||----------------------------Group----------------------------| |\n");
1707 dprintf(fd, "||%-12s = %-46.8s| |\n", "name", StringGet(&group->name));
1708 dprintf(fd, "||%-12s = %-46.8s| |\n", "id", StringGet(&group->id));
1709 dprintf(fd, "||%-12s = %-46d| |\n", "type", group->type);
1710 dprintf(fd, "||%-12s = %-46d| |\n", "visibility", group->visibility);
1711 dprintf(fd, "||%-12s = %-46d| |\n", "upgradeFlag", group->upgradeFlag);
1712 dprintf(fd, "||%-12s = %-46d| |\n", "expireTime", group->expireTime);
1713 HcString entryOwner = HC_VECTOR_GET(&group->managers, 0);
1714 dprintf(fd, "||%-12s = %-46.8s| |\n", "ownerName", StringGet(&entryOwner));
1715 dprintf(fd, "||%-12s = %-46.8s| |\n", "userId", StringGet(&group->userId));
1716 dprintf(fd, "||%-12s = %-46.8s| |\n", "sharedUserId", StringGet(&group->sharedUserId));
1717 dprintf(fd, "||----------------------------Group----------------------------| |\n");
1718 }
1719
DumpDevice(int fd,const TrustedDeviceEntry * device)1720 static void DumpDevice(int fd, const TrustedDeviceEntry *device)
1721 {
1722 dprintf(fd, "|||--------------------DEV--------------------| |\n");
1723 dprintf(fd, "|||%-12s = %-28.8s| |\n", "groupId", StringGet(&device->groupId));
1724 dprintf(fd, "|||%-12s = %-28.8s| |\n", "udid", StringGet(&device->udid));
1725 dprintf(fd, "|||%-12s = %-28.8s| |\n", "authId", StringGet(&device->authId));
1726 dprintf(fd, "|||%-12s = %-28.8s| |\n", "userId", StringGet(&device->userId));
1727 dprintf(fd, "|||%-12s = %-28.8s| |\n", "serviceType",
1728 StringGet(&device->serviceType));
1729 dprintf(fd, "|||%-12s = %-28d| |\n", "credential", device->credential);
1730 dprintf(fd, "|||%-12s = %-28d| |\n", "devType", device->devType);
1731 dprintf(fd, "|||%-12s = %-28d| |\n", "upgradeFlag", device->upgradeFlag);
1732 dprintf(fd, "|||%-12s = %-28d| |\n", "credSource", device->source);
1733 dprintf(fd, "|||--------------------DEV--------------------| |\n");
1734 }
1735
DumpDb(int fd,const OsAccountTrustedInfo * db)1736 static void DumpDb(int fd, const OsAccountTrustedInfo *db)
1737 {
1738 const GroupEntryVec *groups = &db->groups;
1739 const DeviceEntryVec *devices = &db->devices;
1740 dprintf(fd, "|-------------------------------------DataBase-------------------------------------|\n");
1741 dprintf(fd, "|%-12s = %-67d|\n", "osAccountId", db->osAccountId);
1742 dprintf(fd, "|%-12s = %-67d|\n", "groupNum", groups->size(groups));
1743 dprintf(fd, "|%-12s = %-67d|\n", "deviceNum", devices->size(devices));
1744 uint32_t index;
1745 TrustedGroupEntry **groupEntry;
1746 FOR_EACH_HC_VECTOR(*groups, index, groupEntry) {
1747 DumpGroup(fd, *groupEntry);
1748 }
1749 TrustedDeviceEntry **deviceEntry;
1750 FOR_EACH_HC_VECTOR(*devices, index, deviceEntry) {
1751 DumpDevice(fd, *deviceEntry);
1752 }
1753 dprintf(fd, "|-------------------------------------DataBase-------------------------------------|\n");
1754 }
1755
LoadAllAccountsData(void)1756 static void LoadAllAccountsData(void)
1757 {
1758 int32_t *accountIds = NULL;
1759 uint32_t size = 0;
1760 int32_t ret = GetAllOsAccountIds(&accountIds, &size);
1761 if (ret != HC_SUCCESS) {
1762 LOGE("[DB]: Failed to get all os account ids, [res]: %" LOG_PUB "d", ret);
1763 return;
1764 }
1765 for (uint32_t index = 0; index < size; index++) {
1766 LoadDataIfNotLoaded(accountIds[index]);
1767 }
1768 HcFree(accountIds);
1769 }
1770
DevAuthDataBaseDump(int fd)1771 static void DevAuthDataBaseDump(int fd)
1772 {
1773 if (g_databaseMutex == NULL) {
1774 LOGE("[DB]: Init mutex failed");
1775 return;
1776 }
1777 (void)LockHcMutex(g_databaseMutex);
1778 if (IsOsAccountSupported()) {
1779 LoadAllAccountsData();
1780 }
1781 uint32_t index;
1782 OsAccountTrustedInfo *info;
1783 FOR_EACH_HC_VECTOR(g_deviceauthDb, index, info) {
1784 DumpDb(fd, info);
1785 }
1786 UnlockHcMutex(g_databaseMutex);
1787 }
1788 #endif
1789
InitDatabase(void)1790 int32_t InitDatabase(void)
1791 {
1792 if (g_databaseMutex == NULL) {
1793 g_databaseMutex = (HcMutex *)HcMalloc(sizeof(HcMutex), 0);
1794 if (g_databaseMutex == NULL) {
1795 LOGE("[DB]: Alloc databaseMutex failed");
1796 return HC_ERR_ALLOC_MEMORY;
1797 }
1798 if (InitHcMutex(g_databaseMutex, false) != HC_SUCCESS) {
1799 LOGE("[DB]: Init mutex failed");
1800 HcFree(g_databaseMutex);
1801 g_databaseMutex = NULL;
1802 return HC_ERROR;
1803 }
1804 }
1805 g_deviceauthDb = CREATE_HC_VECTOR(DeviceAuthDb);
1806 AddOsAccountEventCallback(GROUP_DATA_CALLBACK, OnOsAccountUnlocked, OnOsAccountRemoved);
1807 LoadDeviceAuthDb();
1808 DEV_AUTH_REG_DUMP_FUNC(DevAuthDataBaseDump);
1809 return HC_SUCCESS;
1810 }
1811
DestroyDatabase(void)1812 void DestroyDatabase(void)
1813 {
1814 RemoveOsAccountEventCallback(GROUP_DATA_CALLBACK);
1815 (void)LockHcMutex(g_databaseMutex);
1816 uint32_t index;
1817 OsAccountTrustedInfo *info;
1818 FOR_EACH_HC_VECTOR(g_deviceauthDb, index, info) {
1819 ClearGroupEntryVec(&info->groups);
1820 ClearDeviceEntryVec(&info->devices);
1821 }
1822 DESTROY_HC_VECTOR(DeviceAuthDb, &g_deviceauthDb);
1823 UnlockHcMutex(g_databaseMutex);
1824 DestroyHcMutex(g_databaseMutex);
1825 HcFree(g_databaseMutex);
1826 g_databaseMutex = NULL;
1827 }