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