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 "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_auth_plugin_proxy.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]: %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 = ExcuteCredMgrCmd(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(void)664 static void CheckAndRemoveUpgradeData(void)
665 {
666     QueryGroupParams queryParams = InitQueryGroupParams();
667     GroupEntryVec groupEntryVec = CreateGroupEntryVec();
668     int32_t ret = QueryGroups(UPGRADE_OS_ACCOUNT_ID, &queryParams, &groupEntryVec);
669     if (ret != HC_SUCCESS) {
670         LOGE("Failed to query groups!");
671         ClearGroupEntryVec(&groupEntryVec);
672         return;
673     }
674     uint32_t index;
675     TrustedGroupEntry **ptr = NULL;
676     FOR_EACH_HC_VECTOR(groupEntryVec, index, ptr) {
677         if (ptr == NULL || *ptr == NULL) {
678             continue;
679         }
680         const TrustedGroupEntry *groupEntry = (const TrustedGroupEntry *)(*ptr);
681         CheckAndRemoveUpgradeGroupEntry(groupEntry);
682     }
683     ClearGroupEntryVec(&groupEntryVec);
684 }
685 
OnOsAccountUnlocked(int32_t osAccountId)686 static void OnOsAccountUnlocked(int32_t osAccountId)
687 {
688     g_databaseMutex->lock(g_databaseMutex);
689     LoadOsAccountDbCe(osAccountId);
690     g_databaseMutex->unlock(g_databaseMutex);
691     CheckAndRemoveUpgradeData();
692 }
693 
OnOsAccountRemoved(int32_t osAccountId)694 static void OnOsAccountRemoved(int32_t osAccountId)
695 {
696     LOGI("[DB]: os account is removed, osAccountId: %d", osAccountId);
697     g_databaseMutex->lock(g_databaseMutex);
698     RemoveOsAccountTrustedInfo(osAccountId);
699     g_databaseMutex->unlock(g_databaseMutex);
700 }
701 
IsOsAccountDataLoaded(int32_t osAccountId)702 static bool IsOsAccountDataLoaded(int32_t osAccountId)
703 {
704     uint32_t index = 0;
705     OsAccountTrustedInfo *info = NULL;
706     FOR_EACH_HC_VECTOR(g_deviceauthDb, index, info) {
707         if (info->osAccountId == osAccountId) {
708             return true;
709         }
710     }
711     return false;
712 }
713 
LoadDataIfNotLoaded(int32_t osAccountId)714 static void LoadDataIfNotLoaded(int32_t osAccountId)
715 {
716     if (IsOsAccountDataLoaded(osAccountId)) {
717         return;
718     }
719     LOGI("[DB]: data has not been loaded, load it, osAccountId: %d", osAccountId);
720     LoadOsAccountDbCe(osAccountId);
721 }
722 
GetTrustedInfoByOsAccountId(int32_t osAccountId)723 static OsAccountTrustedInfo *GetTrustedInfoByOsAccountId(int32_t osAccountId)
724 {
725     if (IsOsAccountSupported()) {
726         LoadDataIfNotLoaded(osAccountId);
727     }
728     uint32_t index = 0;
729     OsAccountTrustedInfo *info = NULL;
730     FOR_EACH_HC_VECTOR(g_deviceauthDb, index, info) {
731         if (info->osAccountId == osAccountId) {
732             return info;
733         }
734     }
735     LOGI("[DB]: Create a new os account database cache! [Id]: %d", osAccountId);
736     OsAccountTrustedInfo newInfo;
737     newInfo.osAccountId = osAccountId;
738     newInfo.groups = CreateGroupEntryVec();
739     newInfo.devices = CreateDeviceEntryVec();
740     OsAccountTrustedInfo *returnInfo = g_deviceauthDb.pushBackT(&g_deviceauthDb, newInfo);
741     if (returnInfo == NULL) {
742         LOGE("[DB]: Failed to push osAccountInfo to database!");
743         DestroyGroupEntryVec(&newInfo.groups);
744         DestroyDeviceEntryVec(&newInfo.devices);
745     }
746     return returnInfo;
747 }
748 
LoadDeviceAuthDb(void)749 static void LoadDeviceAuthDb(void)
750 {
751     if (IsOsAccountSupported()) {
752         return;
753     }
754     g_databaseMutex->lock(g_databaseMutex);
755     StringVector osAccountDbNameVec = CreateStrVector();
756     HcFileGetSubFileName(GetStorageDirPath(), &osAccountDbNameVec);
757     uint32_t index;
758     HcString *dbName;
759     FOR_EACH_HC_VECTOR(osAccountDbNameVec, index, dbName) {
760         int32_t osAccountId;
761         const char *osAccountIdStr = StringGet(dbName);
762         if (osAccountIdStr == NULL) {
763             continue;
764         }
765         if (strcmp(osAccountIdStr, "hcgroup.dat") == 0) {
766             LoadOsAccountDb(DEFAULT_OS_ACCOUNT);
767         } else if (sscanf_s(osAccountIdStr, "hcgroup%d.dat", &osAccountId) == 1) {
768             LoadOsAccountDb(osAccountId);
769         }
770     }
771     DestroyStrVector(&osAccountDbNameVec);
772     g_databaseMutex->unlock(g_databaseMutex);
773 }
774 
SetGroupElement(TlvGroupElement * element,TrustedGroupEntry * entry)775 static bool SetGroupElement(TlvGroupElement *element, TrustedGroupEntry *entry)
776 {
777     if (!StringSet(&element->name.data, entry->name)) {
778         LOGE("[DB]: Failed to copy groupName!");
779         return false;
780     }
781     if (!StringSet(&element->id.data, entry->id)) {
782         LOGE("[DB]: Failed to copy groupId!");
783         return false;
784     }
785     if (!StringSet(&element->userId.data, entry->userId)) {
786         LOGE("[DB]: Failed to copy userId!");
787         return false;
788     }
789     if (!StringSet(&element->sharedUserId.data, entry->sharedUserId)) {
790         LOGE("[DB]: Failed to copy sharedUserId!");
791         return false;
792     }
793     element->type.data = entry->type;
794     element->visibility.data = entry->visibility;
795     element->upgradeFlag.data = entry->upgradeFlag;
796     element->expireTime.data = entry->expireTime;
797     if (!SaveStringVectorToParcel(&entry->managers, &element->managers.data)) {
798         LOGE("[DB]: Failed to copy managers!");
799         return false;
800     }
801     if (!SaveStringVectorToParcel(&entry->friends, &element->friends.data)) {
802         LOGE("[DB]: Failed to copy friends!");
803         return false;
804     }
805     return true;
806 }
807 
SetDeviceElement(TlvDeviceElement * element,TrustedDeviceEntry * entry)808 static bool SetDeviceElement(TlvDeviceElement *element, TrustedDeviceEntry *entry)
809 {
810     if (!StringSet(&element->groupId.data, entry->groupId)) {
811         LOGE("[DB]: Failed to copy groupId!");
812         return false;
813     }
814     if (!StringSet(&element->udid.data, entry->udid)) {
815         LOGE("[DB]: Failed to copy udid!");
816         return false;
817     }
818     if (!StringSet(&element->authId.data, entry->authId)) {
819         LOGE("[DB]: Failed to copy authId!");
820         return false;
821     }
822     if (!StringSet(&element->userId.data, entry->userId)) {
823         LOGE("[DB]: Failed to copy userId!");
824         return false;
825     }
826     if (!StringSet(&element->serviceType.data, entry->serviceType)) {
827         LOGE("[DB]: Failed to copy serviceType!");
828         return false;
829     }
830     if (!ParcelCopy(&element->ext.data, &entry->ext)) {
831         LOGE("[DB]: Failed to copy external data!");
832         return false;
833     }
834     element->info.data.credential = entry->credential;
835     element->info.data.devType = entry->devType;
836     element->upgradeFlag.data = entry->upgradeFlag;
837     element->info.data.source = entry->source;
838     element->info.data.lastTm = entry->lastTm;
839     return true;
840 }
841 
SaveGroups(const GroupEntryVec * vec,HCDataBaseV1 * db)842 static bool SaveGroups(const GroupEntryVec *vec, HCDataBaseV1 *db)
843 {
844     uint32_t index;
845     TrustedGroupEntry **entry;
846     FOR_EACH_HC_VECTOR(*vec, index, entry) {
847         TlvGroupElement tmp;
848         TlvGroupElement *element = db->groups.data.pushBack(&db->groups.data, &tmp);
849         if (element == NULL) {
850             return false;
851         }
852         TLV_INIT(TlvGroupElement, element);
853         if (!SetGroupElement(element, *entry)) {
854             TLV_DEINIT((*element));
855             return false;
856         }
857     }
858     return true;
859 }
860 
SaveDevices(const DeviceEntryVec * vec,HCDataBaseV1 * db)861 static bool SaveDevices(const DeviceEntryVec *vec, HCDataBaseV1 *db)
862 {
863     uint32_t index;
864     TrustedDeviceEntry **entry;
865     FOR_EACH_HC_VECTOR(*vec, index, entry) {
866         TlvDeviceElement tmp;
867         TlvDeviceElement *element = db->devices.data.pushBack(&db->devices.data, &tmp);
868         if (element == NULL) {
869             return false;
870         }
871         TLV_INIT(TlvDeviceElement, element);
872         if (!SetDeviceElement(element, *entry)) {
873             TLV_DEINIT((*element));
874             return false;
875         }
876     }
877     return true;
878 }
879 
SaveInfoToParcel(const OsAccountTrustedInfo * info,HcParcel * parcel)880 static bool SaveInfoToParcel(const OsAccountTrustedInfo *info, HcParcel *parcel)
881 {
882     int32_t ret = false;
883     HCDataBaseV1 dbv1;
884     TLV_INIT(HCDataBaseV1, &dbv1)
885     dbv1.version.data = 1;
886     do {
887         if (!SaveGroups(&info->groups, &dbv1)) {
888             break;
889         }
890         if (!SaveDevices(&info->devices, &dbv1)) {
891             break;
892         }
893         if (!EncodeTlvMessage((TlvBase *)&dbv1, parcel)) {
894             LOGE("[DB]: Encode Tlv Message failed!");
895             break;
896         }
897         ret = true;
898     } while (0);
899     TLV_DEINIT(dbv1)
900     return ret;
901 }
902 
CompareQueryGroupParams(const QueryGroupParams * params,const TrustedGroupEntry * entry)903 static bool CompareQueryGroupParams(const QueryGroupParams *params, const TrustedGroupEntry *entry)
904 {
905     if ((params->groupId != NULL) && (strcmp(params->groupId, StringGet(&entry->id)) != 0)) {
906         return false;
907     }
908     if ((params->groupName != NULL) && (strcmp(params->groupName, StringGet(&entry->name)) != 0)) {
909         return false;
910     }
911     if ((params->userId != NULL) && (strcmp(params->userId, StringGet(&entry->userId)) != 0)) {
912         return false;
913     }
914     if ((params->sharedUserId != NULL) && (strcmp(params->sharedUserId, StringGet(&entry->sharedUserId)) != 0)) {
915         return false;
916     }
917     if ((params->groupType != ALL_GROUP) && (params->groupType != entry->type)) {
918         return false;
919     }
920     if ((params->groupVisibility != ALL_GROUP_VISIBILITY) && (params->groupVisibility != entry->visibility)) {
921         return false;
922     }
923     if (params->ownerName != NULL) {
924         HcString entryOwner = HC_VECTOR_GET(&entry->managers, 0);
925         if (strcmp(params->ownerName, StringGet(&entryOwner)) != 0) {
926             return false;
927         }
928     }
929     return true;
930 }
931 
CompareQueryDeviceParams(const QueryDeviceParams * params,const TrustedDeviceEntry * entry)932 static bool CompareQueryDeviceParams(const QueryDeviceParams *params, const TrustedDeviceEntry *entry)
933 {
934     if ((params->groupId != NULL) && (strcmp(params->groupId, StringGet(&entry->groupId)) != 0)) {
935         return false;
936     }
937     if ((params->udid != NULL) && (strcmp(params->udid, StringGet(&entry->udid)) != 0)) {
938         return false;
939     }
940     if ((params->authId != NULL) && (strcmp(params->authId, StringGet(&entry->authId)) != 0)) {
941         return false;
942     }
943     if ((params->userId != NULL) && (strcmp(params->userId, StringGet(&entry->userId)) != 0)) {
944         return false;
945     }
946     return true;
947 }
948 
QueryGroupEntryPtrIfMatch(const GroupEntryVec * vec,const QueryGroupParams * params)949 static TrustedGroupEntry **QueryGroupEntryPtrIfMatch(const GroupEntryVec *vec, const QueryGroupParams *params)
950 {
951     uint32_t index;
952     TrustedGroupEntry **entry;
953     FOR_EACH_HC_VECTOR(*vec, index, entry) {
954         if (CompareQueryGroupParams(params, *entry)) {
955             return entry;
956         }
957     }
958     return NULL;
959 }
960 
QueryDeviceEntryPtrIfMatch(const DeviceEntryVec * vec,const QueryDeviceParams * params)961 static TrustedDeviceEntry **QueryDeviceEntryPtrIfMatch(const DeviceEntryVec *vec, const QueryDeviceParams *params)
962 {
963     uint32_t index;
964     TrustedDeviceEntry **entry;
965     FOR_EACH_HC_VECTOR(*vec, index, entry) {
966         if (CompareQueryDeviceParams(params, *entry)) {
967             return entry;
968         }
969     }
970     return NULL;
971 }
972 
AddGroupNameToReturn(const TrustedGroupEntry * groupInfo,CJson * json)973 static int32_t AddGroupNameToReturn(const TrustedGroupEntry *groupInfo, CJson *json)
974 {
975     const char *groupName = StringGet(&groupInfo->name);
976     if (groupName == NULL) {
977         LOGE("Failed to get groupName from groupInfo!");
978         return HC_ERR_NULL_PTR;
979     }
980     if (AddStringToJson(json, FIELD_GROUP_NAME, groupName) != HC_SUCCESS) {
981         LOGE("Failed to add groupName to json!");
982         return HC_ERR_JSON_FAIL;
983     }
984     return HC_SUCCESS;
985 }
986 
AddGroupIdToReturn(const TrustedGroupEntry * groupInfo,CJson * json)987 static int32_t AddGroupIdToReturn(const TrustedGroupEntry *groupInfo, CJson *json)
988 {
989     const char *groupId = StringGet(&groupInfo->id);
990     if (groupId == NULL) {
991         LOGE("Failed to get groupId from groupInfo!");
992         return HC_ERR_NULL_PTR;
993     }
994     if (AddStringToJson(json, FIELD_GROUP_ID, groupId) != HC_SUCCESS) {
995         LOGE("Failed to add groupId to json!");
996         return HC_ERR_JSON_FAIL;
997     }
998     return HC_SUCCESS;
999 }
1000 
AddGroupOwnerToReturn(const TrustedGroupEntry * groupInfo,CJson * json)1001 static int32_t AddGroupOwnerToReturn(const TrustedGroupEntry *groupInfo, CJson *json)
1002 {
1003     HcString entryManager = HC_VECTOR_GET(&groupInfo->managers, 0);
1004     const char *groupOwner = StringGet(&entryManager);
1005     if (groupOwner == NULL) {
1006         LOGE("Failed to get groupOwner from groupInfo!");
1007         return HC_ERR_NULL_PTR;
1008     }
1009     if (AddStringToJson(json, FIELD_GROUP_OWNER, groupOwner) != HC_SUCCESS) {
1010         LOGE("Failed to add groupOwner to json!");
1011         return HC_ERR_JSON_FAIL;
1012     }
1013     return HC_SUCCESS;
1014 }
1015 
AddGroupTypeToReturn(const TrustedGroupEntry * groupInfo,CJson * json)1016 static int32_t AddGroupTypeToReturn(const TrustedGroupEntry *groupInfo, CJson *json)
1017 {
1018     int32_t groupType = groupInfo->type;
1019     if (AddIntToJson(json, FIELD_GROUP_TYPE, groupType) != HC_SUCCESS) {
1020         LOGE("Failed to add groupType to json!");
1021         return HC_ERR_JSON_FAIL;
1022     }
1023     return HC_SUCCESS;
1024 }
1025 
AddGroupVisibilityToReturn(const TrustedGroupEntry * groupInfo,CJson * json)1026 static int32_t AddGroupVisibilityToReturn(const TrustedGroupEntry *groupInfo, CJson *json)
1027 {
1028     int groupVisibility = groupInfo->visibility;
1029     if (AddIntToJson(json, FIELD_GROUP_VISIBILITY, groupVisibility) != HC_SUCCESS) {
1030         LOGE("Failed to add groupType to json!");
1031         return HC_ERR_JSON_FAIL;
1032     }
1033     return HC_SUCCESS;
1034 }
1035 
AddUserIdToReturnIfAccountGroup(const TrustedGroupEntry * groupInfo,CJson * json)1036 static int32_t AddUserIdToReturnIfAccountGroup(const TrustedGroupEntry *groupInfo, CJson *json)
1037 {
1038     if ((groupInfo->type != ACROSS_ACCOUNT_AUTHORIZE_GROUP) && (groupInfo->type != IDENTICAL_ACCOUNT_GROUP)) {
1039         return HC_SUCCESS;
1040     }
1041     const char *userId = StringGet(&groupInfo->userId);
1042     if (userId == NULL) {
1043         LOGE("Failed to get userId from groupInfo!");
1044         return HC_ERR_NULL_PTR;
1045     }
1046     if (AddStringToJson(json, FIELD_USER_ID, userId) != HC_SUCCESS) {
1047         LOGE("Failed to add userId to json!");
1048         return HC_ERR_JSON_FAIL;
1049     }
1050     return HC_SUCCESS;
1051 }
1052 
AddSharedUserIdToReturnIfAcrossAccountGroup(const TrustedGroupEntry * groupInfo,CJson * json)1053 static int32_t AddSharedUserIdToReturnIfAcrossAccountGroup(const TrustedGroupEntry *groupInfo, CJson *json)
1054 {
1055     if (groupInfo->type != ACROSS_ACCOUNT_AUTHORIZE_GROUP) {
1056         return HC_SUCCESS;
1057     }
1058     const char *sharedUserId = StringGet(&groupInfo->sharedUserId);
1059     if (sharedUserId == NULL) {
1060         LOGE("Failed to get sharedUserId from groupInfo!");
1061         return HC_ERR_NULL_PTR;
1062     }
1063     if (AddStringToJson(json, FIELD_SHARED_USER_ID, sharedUserId) != HC_SUCCESS) {
1064         LOGE("Failed to add sharedUserId to json!");
1065         return HC_ERR_JSON_FAIL;
1066     }
1067     return HC_SUCCESS;
1068 }
1069 
AddAuthIdToReturn(const TrustedDeviceEntry * deviceInfo,CJson * json)1070 static int32_t AddAuthIdToReturn(const TrustedDeviceEntry *deviceInfo, CJson *json)
1071 {
1072     const char *authId = StringGet(&deviceInfo->authId);
1073     if (authId == NULL) {
1074         LOGE("Failed to get authId from deviceInfo!");
1075         return HC_ERR_NULL_PTR;
1076     }
1077     if (AddStringToJson(json, FIELD_AUTH_ID, authId) != HC_SUCCESS) {
1078         LOGE("Failed to add authId to json!");
1079         return HC_ERR_JSON_FAIL;
1080     }
1081     return HC_SUCCESS;
1082 }
1083 
AddCredentialTypeToReturn(const TrustedDeviceEntry * deviceInfo,CJson * json)1084 static int32_t AddCredentialTypeToReturn(const TrustedDeviceEntry *deviceInfo, CJson *json)
1085 {
1086     int credentialType = deviceInfo->credential;
1087     if (AddIntToJson(json, FIELD_CREDENTIAL_TYPE, credentialType) != HC_SUCCESS) {
1088         LOGE("Failed to add credentialType to json!");
1089         return HC_ERR_JSON_FAIL;
1090     }
1091     return HC_SUCCESS;
1092 }
1093 
AddUserTypeToReturn(const TrustedDeviceEntry * deviceInfo,CJson * json)1094 static int32_t AddUserTypeToReturn(const TrustedDeviceEntry *deviceInfo, CJson *json)
1095 {
1096     int userType = deviceInfo->devType;
1097     if (AddIntToJson(json, FIELD_USER_TYPE, userType) != HC_SUCCESS) {
1098         LOGE("Failed to add userType to json!");
1099         return HC_ERR_JSON_FAIL;
1100     }
1101     return HC_SUCCESS;
1102 }
1103 
GenerateMessage(const TrustedGroupEntry * groupEntry,char ** returnGroupInfo)1104 static int32_t GenerateMessage(const TrustedGroupEntry *groupEntry, char **returnGroupInfo)
1105 {
1106     if (groupEntry == NULL) {
1107         LOGE("groupEntry is null!");
1108         return HC_ERR_NULL_PTR;
1109     }
1110     CJson *message = CreateJson();
1111     if (message == NULL) {
1112         LOGE("Failed to allocate message memory!");
1113         return HC_ERR_ALLOC_MEMORY;
1114     }
1115     int32_t result = GenerateReturnGroupInfo(groupEntry, message);
1116     if (result != HC_SUCCESS) {
1117         FreeJson(message);
1118         return result;
1119     }
1120     char *messageStr = PackJsonToString(message);
1121     FreeJson(message);
1122     if (messageStr == NULL) {
1123         LOGE("Failed to convert json to string!");
1124         return HC_ERR_JSON_FAIL;
1125     }
1126     *returnGroupInfo = messageStr;
1127     return HC_SUCCESS;
1128 }
1129 
PostGroupCreatedMsg(const TrustedGroupEntry * groupEntry)1130 static void PostGroupCreatedMsg(const TrustedGroupEntry *groupEntry)
1131 {
1132     if (!IsBroadcastSupported()) {
1133         return;
1134     }
1135     char *messageStr = NULL;
1136     if (GenerateMessage(groupEntry, &messageStr) != HC_SUCCESS) {
1137         return;
1138     }
1139     GetBroadcaster()->postOnGroupCreated(messageStr);
1140     FreeJsonString(messageStr);
1141 }
1142 
PostGroupDeletedMsg(const TrustedGroupEntry * groupEntry)1143 static void PostGroupDeletedMsg(const TrustedGroupEntry *groupEntry)
1144 {
1145     if (!IsBroadcastSupported()) {
1146         return;
1147     }
1148     char *messageStr = NULL;
1149     if (GenerateMessage(groupEntry, &messageStr) != HC_SUCCESS) {
1150         return;
1151     }
1152     GetBroadcaster()->postOnGroupDeleted(messageStr);
1153     FreeJsonString(messageStr);
1154 }
1155 
PostDeviceBoundMsg(OsAccountTrustedInfo * info,const TrustedDeviceEntry * deviceEntry)1156 static void PostDeviceBoundMsg(OsAccountTrustedInfo *info, const TrustedDeviceEntry *deviceEntry)
1157 {
1158     if (!IsBroadcastSupported()) {
1159         return;
1160     }
1161     QueryGroupParams groupParams = InitQueryGroupParams();
1162     groupParams.groupId = StringGet(&deviceEntry->groupId);
1163     TrustedGroupEntry **groupEntryPtr = QueryGroupEntryPtrIfMatch(&info->groups, &groupParams);
1164     if (groupEntryPtr != NULL) {
1165         char *messageStr = NULL;
1166         if (GenerateMessage(*groupEntryPtr, &messageStr) != HC_SUCCESS) {
1167             return;
1168         }
1169         GetBroadcaster()->postOnDeviceBound(StringGet(&deviceEntry->udid), messageStr);
1170         FreeJsonString(messageStr);
1171     }
1172 }
1173 
IsSelfDeviceEntry(const TrustedDeviceEntry * deviceEntry)1174 static bool IsSelfDeviceEntry(const TrustedDeviceEntry *deviceEntry)
1175 {
1176     char selfUdid[INPUT_UDID_LEN] = { 0 };
1177     int32_t res = HcGetUdid((uint8_t *)selfUdid, INPUT_UDID_LEN);
1178     if (res != HC_SUCCESS) {
1179         LOGE("Failed to get local udid! res: %d", res);
1180         return false;
1181     }
1182     const char *entryUdid = StringGet(&deviceEntry->udid);
1183     return strcmp(selfUdid, entryUdid) == 0;
1184 }
1185 
PostDeviceUnBoundMsg(OsAccountTrustedInfo * info,const TrustedDeviceEntry * deviceEntry)1186 static void PostDeviceUnBoundMsg(OsAccountTrustedInfo *info, const TrustedDeviceEntry *deviceEntry)
1187 {
1188     if (!IsBroadcastSupported()) {
1189         return;
1190     }
1191     const char *groupId = StringGet(&deviceEntry->groupId);
1192     const char *udid = StringGet(&deviceEntry->udid);
1193     QueryGroupParams groupParams = InitQueryGroupParams();
1194     groupParams.groupId = groupId;
1195     TrustedGroupEntry **groupEntryPtr = QueryGroupEntryPtrIfMatch(&info->groups, &groupParams);
1196     if (groupEntryPtr != NULL) {
1197         char *messageStr = NULL;
1198         if (GenerateMessage(*groupEntryPtr, &messageStr) != HC_SUCCESS) {
1199             return;
1200         }
1201         GetBroadcaster()->postOnDeviceUnBound(udid, messageStr);
1202         FreeJsonString(messageStr);
1203     }
1204     QueryDeviceParams deviceParams = InitQueryDeviceParams();
1205     deviceParams.udid = udid;
1206     if (QueryDeviceEntryPtrIfMatch(&info->devices, &deviceParams) == NULL) {
1207         GetBroadcaster()->postOnDeviceNotTrusted(udid);
1208         if (!IsSelfDeviceEntry(deviceEntry)) {
1209             (void)DeleteMk(info->osAccountId, udid);
1210             (void)DeletePseudonymPsk(info->osAccountId, udid);
1211         }
1212     }
1213 }
1214 
DeletePdidByDeviceEntry(int32_t osAccountId,const TrustedDeviceEntry * deviceEntry)1215 static void DeletePdidByDeviceEntry(int32_t osAccountId, const TrustedDeviceEntry *deviceEntry)
1216 {
1217     if (IsSelfDeviceEntry(deviceEntry)) {
1218         return;
1219     }
1220     const char *userId = StringGet(&deviceEntry->userId);
1221     if (userId == NULL) {
1222         LOGW("userId is null!");
1223         return;
1224     }
1225     if (deviceEntry->credential != ASYMMETRIC_CRED) {
1226         LOGW("credential type is not asymmetric!");
1227         return;
1228     }
1229     PseudonymManager *manager = GetPseudonymInstance();
1230     if (manager == NULL) {
1231         LOGE("Pseudonym manager is null!");
1232         return;
1233     }
1234     int32_t res = manager->deletePseudonymId(osAccountId, userId);
1235     if (res != HC_SUCCESS) {
1236         LOGE("Failed to delete pdid!");
1237     } else {
1238         LOGI("Delete pdid successfully!");
1239     }
1240 }
1241 
InitQueryGroupParams(void)1242 QueryGroupParams InitQueryGroupParams(void)
1243 {
1244     QueryGroupParams params = {
1245         .groupId = NULL,
1246         .groupName = NULL,
1247         .ownerName = NULL,
1248         .userId = NULL,
1249         .groupType = ALL_GROUP,
1250         .groupVisibility = ALL_GROUP_VISIBILITY
1251     };
1252     return params;
1253 }
1254 
InitQueryDeviceParams(void)1255 QueryDeviceParams InitQueryDeviceParams(void)
1256 {
1257     QueryDeviceParams params = {
1258         .groupId = NULL,
1259         .udid = NULL,
1260         .authId = NULL,
1261         .userId = NULL
1262     };
1263     return params;
1264 }
1265 
CreateGroupEntry(void)1266 TrustedGroupEntry *CreateGroupEntry(void)
1267 {
1268     TrustedGroupEntry *ptr = (TrustedGroupEntry *)HcMalloc(sizeof(TrustedGroupEntry), 0);
1269     if (ptr == NULL) {
1270         LOGE("[DB]: Failed to allocate groupEntry memory!");
1271         return NULL;
1272     }
1273     ptr->name = CreateString();
1274     ptr->id = CreateString();
1275     ptr->userId = CreateString();
1276     ptr->sharedUserId = CreateString();
1277     ptr->managers = CreateStrVector();
1278     ptr->friends = CreateStrVector();
1279     return ptr;
1280 }
1281 
DestroyGroupEntry(TrustedGroupEntry * groupEntry)1282 void DestroyGroupEntry(TrustedGroupEntry *groupEntry)
1283 {
1284     if (groupEntry == NULL) {
1285         return;
1286     }
1287     DeleteString(&groupEntry->name);
1288     DeleteString(&groupEntry->id);
1289     DeleteString(&groupEntry->userId);
1290     DeleteString(&groupEntry->sharedUserId);
1291     DestroyStrVector(&groupEntry->managers);
1292     DestroyStrVector(&groupEntry->friends);
1293     HcFree(groupEntry);
1294 }
1295 
DeepCopyGroupEntry(const TrustedGroupEntry * entry)1296 TrustedGroupEntry *DeepCopyGroupEntry(const TrustedGroupEntry *entry)
1297 {
1298     TrustedGroupEntry *returnEntry = CreateGroupEntry();
1299     if (returnEntry == NULL) {
1300         return NULL;
1301     }
1302     if (!GenerateGroupEntryFromEntry(entry, returnEntry)) {
1303         DestroyGroupEntry(returnEntry);
1304         return NULL;
1305     }
1306     return returnEntry;
1307 }
1308 
CreateDeviceEntry(void)1309 TrustedDeviceEntry *CreateDeviceEntry(void)
1310 {
1311     TrustedDeviceEntry *ptr = (TrustedDeviceEntry *)HcMalloc(sizeof(TrustedDeviceEntry), 0);
1312     if (ptr == NULL) {
1313         LOGE("[DB]: Failed to allocate deviceEntry memory!");
1314         return NULL;
1315     }
1316     ptr->groupId = CreateString();
1317     ptr->udid = CreateString();
1318     ptr->authId = CreateString();
1319     ptr->userId = CreateString();
1320     ptr->serviceType = CreateString();
1321     ptr->ext = CreateParcel(0, 0);
1322     return ptr;
1323 }
1324 
DestroyDeviceEntry(TrustedDeviceEntry * deviceEntry)1325 void DestroyDeviceEntry(TrustedDeviceEntry *deviceEntry)
1326 {
1327     if (deviceEntry == NULL) {
1328         return;
1329     }
1330     DeleteString(&deviceEntry->groupId);
1331     DeleteString(&deviceEntry->udid);
1332     DeleteString(&deviceEntry->authId);
1333     DeleteString(&deviceEntry->userId);
1334     DeleteString(&deviceEntry->serviceType);
1335     DeleteParcel(&deviceEntry->ext);
1336     HcFree(deviceEntry);
1337 }
1338 
DeepCopyDeviceEntry(const TrustedDeviceEntry * entry)1339 TrustedDeviceEntry *DeepCopyDeviceEntry(const TrustedDeviceEntry *entry)
1340 {
1341     if (entry == NULL) {
1342         return NULL;
1343     }
1344     TrustedDeviceEntry *returnEntry = CreateDeviceEntry();
1345     if (returnEntry == NULL) {
1346         return NULL;
1347     }
1348     if (!GenerateDeviceEntryFromEntry(entry, returnEntry)) {
1349         DestroyDeviceEntry(returnEntry);
1350         return NULL;
1351     }
1352     return returnEntry;
1353 }
1354 
ClearGroupEntryVec(GroupEntryVec * vec)1355 void ClearGroupEntryVec(GroupEntryVec *vec)
1356 {
1357     uint32_t index;
1358     TrustedGroupEntry **entry;
1359     FOR_EACH_HC_VECTOR(*vec, index, entry) {
1360         DestroyGroupEntry(*entry);
1361     }
1362     DESTROY_HC_VECTOR(GroupEntryVec, vec);
1363 }
1364 
ClearDeviceEntryVec(DeviceEntryVec * vec)1365 void ClearDeviceEntryVec(DeviceEntryVec *vec)
1366 {
1367     uint32_t index;
1368     TrustedDeviceEntry **entry;
1369     FOR_EACH_HC_VECTOR(*vec, index, entry) {
1370         DestroyDeviceEntry(*entry);
1371     }
1372     DESTROY_HC_VECTOR(DeviceEntryVec, vec);
1373 }
1374 
GenerateReturnGroupInfo(const TrustedGroupEntry * groupEntry,CJson * returnJson)1375 int32_t GenerateReturnGroupInfo(const TrustedGroupEntry *groupEntry, CJson *returnJson)
1376 {
1377     int32_t result;
1378     if (((result = AddGroupNameToReturn(groupEntry, returnJson)) != HC_SUCCESS) ||
1379         ((result = AddGroupIdToReturn(groupEntry, returnJson)) != HC_SUCCESS) ||
1380         ((result = AddGroupOwnerToReturn(groupEntry, returnJson)) != HC_SUCCESS) ||
1381         ((result = AddGroupTypeToReturn(groupEntry, returnJson)) != HC_SUCCESS) ||
1382         ((result = AddGroupVisibilityToReturn(groupEntry, returnJson)) != HC_SUCCESS) ||
1383         ((result = AddUserIdToReturnIfAccountGroup(groupEntry, returnJson)) != HC_SUCCESS) ||
1384         ((result = AddSharedUserIdToReturnIfAcrossAccountGroup(groupEntry, returnJson)) != HC_SUCCESS)) {
1385         return result;
1386     }
1387     return HC_SUCCESS;
1388 }
1389 
GenerateReturnDevInfo(const TrustedDeviceEntry * deviceEntry,CJson * returnJson)1390 int32_t GenerateReturnDevInfo(const TrustedDeviceEntry *deviceEntry, CJson *returnJson)
1391 {
1392     int32_t result;
1393     if (((result = AddAuthIdToReturn(deviceEntry, returnJson)) != HC_SUCCESS) ||
1394         ((result = AddCredentialTypeToReturn(deviceEntry, returnJson)) != HC_SUCCESS) ||
1395         ((result = AddUserTypeToReturn(deviceEntry, returnJson)) != HC_SUCCESS)) {
1396         return result;
1397     }
1398     return HC_SUCCESS;
1399 }
1400 
AddGroup(int32_t osAccountId,const TrustedGroupEntry * groupEntry)1401 int32_t AddGroup(int32_t osAccountId, const TrustedGroupEntry *groupEntry)
1402 {
1403     LOGI("[DB]: Start to add a group to database! [OsAccountId]: %d", osAccountId);
1404     if (groupEntry == NULL) {
1405         LOGE("[DB]: The input groupEntry is NULL!");
1406         return HC_ERR_NULL_PTR;
1407     }
1408     g_databaseMutex->lock(g_databaseMutex);
1409     OsAccountTrustedInfo *info = GetTrustedInfoByOsAccountId(osAccountId);
1410     if (info == NULL) {
1411         g_databaseMutex->unlock(g_databaseMutex);
1412         return HC_ERR_INVALID_PARAMS;
1413     }
1414     TrustedGroupEntry *newEntry = DeepCopyGroupEntry(groupEntry);
1415     if (newEntry == NULL) {
1416         g_databaseMutex->unlock(g_databaseMutex);
1417         return HC_ERR_MEMORY_COPY;
1418     }
1419     QueryGroupParams params = InitQueryGroupParams();
1420     params.groupId = StringGet(&groupEntry->id);
1421     TrustedGroupEntry **oldEntryPtr = QueryGroupEntryPtrIfMatch(&info->groups, &params);
1422     if (oldEntryPtr != NULL) {
1423         DestroyGroupEntry(*oldEntryPtr);
1424         *oldEntryPtr = newEntry;
1425         PostGroupCreatedMsg(newEntry);
1426         g_databaseMutex->unlock(g_databaseMutex);
1427         LOGI("[DB]: Replace an old group successfully! [GroupType]: %u", groupEntry->type);
1428         return HC_SUCCESS;
1429     }
1430     if (info->groups.pushBackT(&info->groups, newEntry) == NULL) {
1431         DestroyGroupEntry(newEntry);
1432         g_databaseMutex->unlock(g_databaseMutex);
1433         LOGE("[DB]: Failed to push groupEntry to vec!");
1434         return HC_ERR_MEMORY_COPY;
1435     }
1436     PostGroupCreatedMsg(newEntry);
1437     g_databaseMutex->unlock(g_databaseMutex);
1438     LOGI("[DB]: Add a group to database successfully! [GroupType]: %u", groupEntry->type);
1439     return HC_SUCCESS;
1440 }
1441 
AddTrustedDevice(int32_t osAccountId,const TrustedDeviceEntry * deviceEntry)1442 int32_t AddTrustedDevice(int32_t osAccountId, const TrustedDeviceEntry *deviceEntry)
1443 {
1444     LOGI("[DB]: Start to add a trusted device to database! [OsAccountId]: %d", osAccountId);
1445     if (deviceEntry == NULL) {
1446         LOGE("[DB]: The input deviceEntry is NULL!");
1447         return HC_ERR_NULL_PTR;
1448     }
1449     g_databaseMutex->lock(g_databaseMutex);
1450     OsAccountTrustedInfo *info = GetTrustedInfoByOsAccountId(osAccountId);
1451     if (info == NULL) {
1452         g_databaseMutex->unlock(g_databaseMutex);
1453         return HC_ERR_INVALID_PARAMS;
1454     }
1455     TrustedDeviceEntry *newEntry = DeepCopyDeviceEntry(deviceEntry);
1456     if (newEntry == NULL) {
1457         g_databaseMutex->unlock(g_databaseMutex);
1458         return HC_ERR_MEMORY_COPY;
1459     }
1460     QueryDeviceParams params = InitQueryDeviceParams();
1461     params.udid = StringGet(&deviceEntry->udid);
1462     params.groupId = StringGet(&deviceEntry->groupId);
1463     TrustedDeviceEntry **oldEntryPtr = QueryDeviceEntryPtrIfMatch(&info->devices, &params);
1464     if (oldEntryPtr != NULL) {
1465         DestroyDeviceEntry(*oldEntryPtr);
1466         *oldEntryPtr = newEntry;
1467         PostDeviceBoundMsg(info, newEntry);
1468         g_databaseMutex->unlock(g_databaseMutex);
1469         LOGI("[DB]: Replace an old trusted device successfully!");
1470         return HC_SUCCESS;
1471     }
1472     if (info->devices.pushBackT(&info->devices, newEntry) == NULL) {
1473         DestroyDeviceEntry(newEntry);
1474         g_databaseMutex->unlock(g_databaseMutex);
1475         LOGE("[DB]: Failed to push deviceEntry to vec!");
1476         return HC_ERR_MEMORY_COPY;
1477     }
1478     PostDeviceBoundMsg(info, newEntry);
1479     g_databaseMutex->unlock(g_databaseMutex);
1480     LOGI("[DB]: Add a trusted device to database successfully!");
1481     return HC_SUCCESS;
1482 }
1483 
DelGroup(int32_t osAccountId,const QueryGroupParams * params)1484 int32_t DelGroup(int32_t osAccountId, const QueryGroupParams *params)
1485 {
1486     LOGI("[DB]: Start to delete groups from database! [OsAccountId]: %d", osAccountId);
1487     if (params == NULL) {
1488         LOGE("[DB]: The input params is NULL!");
1489         return HC_ERR_NULL_PTR;
1490     }
1491     g_databaseMutex->lock(g_databaseMutex);
1492     OsAccountTrustedInfo *info = GetTrustedInfoByOsAccountId(osAccountId);
1493     if (info == NULL) {
1494         g_databaseMutex->unlock(g_databaseMutex);
1495         return HC_ERR_INVALID_PARAMS;
1496     }
1497     int32_t count = 0;
1498     uint32_t index = 0;
1499     TrustedGroupEntry **entry = NULL;
1500     while (index < HC_VECTOR_SIZE(&info->groups)) {
1501         entry = info->groups.getp(&info->groups, index);
1502         if ((entry == NULL) || (*entry == NULL) || (!CompareQueryGroupParams(params, *entry))) {
1503             index++;
1504             continue;
1505         }
1506         TrustedGroupEntry *popEntry;
1507         HC_VECTOR_POPELEMENT(&info->groups, &popEntry, index);
1508         PostGroupDeletedMsg(popEntry);
1509         LOGI("[DB]: Delete a group from database successfully! [GroupType]: %u", popEntry->type);
1510         DestroyGroupEntry(popEntry);
1511         count++;
1512     }
1513     g_databaseMutex->unlock(g_databaseMutex);
1514     LOGI("[DB]: Number of groups deleted: %d", count);
1515     return HC_SUCCESS;
1516 }
1517 
DelTrustedDevice(int32_t osAccountId,const QueryDeviceParams * params)1518 int32_t DelTrustedDevice(int32_t osAccountId, const QueryDeviceParams *params)
1519 {
1520     LOGI("[DB]: Start to delete devices from database! [OsAccountId]: %d", osAccountId);
1521     if (params == NULL) {
1522         LOGE("[DB]: The input params is NULL!");
1523         return HC_ERR_NULL_PTR;
1524     }
1525     g_databaseMutex->lock(g_databaseMutex);
1526     OsAccountTrustedInfo *info = GetTrustedInfoByOsAccountId(osAccountId);
1527     if (info == NULL) {
1528         g_databaseMutex->unlock(g_databaseMutex);
1529         return HC_ERR_INVALID_PARAMS;
1530     }
1531     int32_t count = 0;
1532     uint32_t index = 0;
1533     TrustedDeviceEntry **entry = NULL;
1534     while (index < HC_VECTOR_SIZE(&info->devices)) {
1535         entry = info->devices.getp(&info->devices, index);
1536         if ((entry == NULL) || (*entry == NULL) || (!CompareQueryDeviceParams(params, *entry))) {
1537             index++;
1538             continue;
1539         }
1540         TrustedDeviceEntry *popEntry;
1541         HC_VECTOR_POPELEMENT(&info->devices, &popEntry, index);
1542         PostDeviceUnBoundMsg(info, popEntry);
1543         DeletePdidByDeviceEntry(osAccountId, popEntry);
1544         LOGI("[DB]: Delete a trusted device from database successfully!");
1545         DestroyDeviceEntry(popEntry);
1546         count++;
1547     }
1548     g_databaseMutex->unlock(g_databaseMutex);
1549     LOGI("[DB]: Number of trusted devices deleted: %d", count);
1550     return HC_SUCCESS;
1551 }
1552 
QueryGroups(int32_t osAccountId,const QueryGroupParams * params,GroupEntryVec * vec)1553 int32_t QueryGroups(int32_t osAccountId, const QueryGroupParams *params, GroupEntryVec *vec)
1554 {
1555     if ((params == NULL) || (vec == NULL)) {
1556         LOGE("[DB]: The input params or vec is NULL!");
1557         return HC_ERR_NULL_PTR;
1558     }
1559     g_databaseMutex->lock(g_databaseMutex);
1560     OsAccountTrustedInfo *info = GetTrustedInfoByOsAccountId(osAccountId);
1561     if (info == NULL) {
1562         g_databaseMutex->unlock(g_databaseMutex);
1563         return HC_ERR_INVALID_PARAMS;
1564     }
1565     uint32_t index;
1566     TrustedGroupEntry **entry;
1567     FOR_EACH_HC_VECTOR(info->groups, index, entry) {
1568         if (!CompareQueryGroupParams(params, *entry)) {
1569             continue;
1570         }
1571         TrustedGroupEntry *newEntry = DeepCopyGroupEntry(*entry);
1572         if (newEntry == NULL) {
1573             continue;
1574         }
1575         if (vec->pushBackT(vec, newEntry) == NULL) {
1576             LOGE("[DB]: Failed to push entry to vec!");
1577             DestroyGroupEntry(newEntry);
1578         }
1579     }
1580     g_databaseMutex->unlock(g_databaseMutex);
1581     return HC_SUCCESS;
1582 }
1583 
QueryDevices(int32_t osAccountId,const QueryDeviceParams * params,DeviceEntryVec * vec)1584 int32_t QueryDevices(int32_t osAccountId, const QueryDeviceParams *params, DeviceEntryVec *vec)
1585 {
1586     if ((params == NULL) || (vec == NULL)) {
1587         LOGE("[DB]: The input params or vec is NULL!");
1588         return HC_ERR_NULL_PTR;
1589     }
1590     g_databaseMutex->lock(g_databaseMutex);
1591     OsAccountTrustedInfo *info = GetTrustedInfoByOsAccountId(osAccountId);
1592     if (info == NULL) {
1593         g_databaseMutex->unlock(g_databaseMutex);
1594         return HC_ERR_INVALID_PARAMS;
1595     }
1596     uint32_t index;
1597     TrustedDeviceEntry **entry;
1598     FOR_EACH_HC_VECTOR(info->devices, index, entry) {
1599         if (!CompareQueryDeviceParams(params, *entry)) {
1600             continue;
1601         }
1602         TrustedDeviceEntry *newEntry = DeepCopyDeviceEntry(*entry);
1603         if (newEntry == NULL) {
1604             continue;
1605         }
1606         if (vec->pushBackT(vec, newEntry) == NULL) {
1607             LOGE("[DB]: Failed to push entry to vec!");
1608             DestroyDeviceEntry(newEntry);
1609         }
1610     }
1611     g_databaseMutex->unlock(g_databaseMutex);
1612     return HC_SUCCESS;
1613 }
1614 
SaveOsAccountDb(int32_t osAccountId)1615 int32_t SaveOsAccountDb(int32_t osAccountId)
1616 {
1617     g_databaseMutex->lock(g_databaseMutex);
1618     OsAccountTrustedInfo *info = GetTrustedInfoByOsAccountId(osAccountId);
1619     if (info == NULL) {
1620         g_databaseMutex->unlock(g_databaseMutex);
1621         return HC_ERR_INVALID_PARAMS;
1622     }
1623     HcParcel parcel = CreateParcel(0, 0);
1624     if (!SaveInfoToParcel(info, &parcel)) {
1625         DeleteParcel(&parcel);
1626         g_databaseMutex->unlock(g_databaseMutex);
1627         return HC_ERR_MEMORY_COPY;
1628     }
1629     char filePath[MAX_DB_PATH_LEN] = { 0 };
1630     if (!GetOsAccountInfoPath(osAccountId, filePath, MAX_DB_PATH_LEN)) {
1631         DeleteParcel(&parcel);
1632         g_databaseMutex->unlock(g_databaseMutex);
1633         return HC_ERROR;
1634     }
1635     if (!SaveParcelToFile(filePath, &parcel)) {
1636         DeleteParcel(&parcel);
1637         g_databaseMutex->unlock(g_databaseMutex);
1638         return HC_ERR_MEMORY_COPY;
1639     }
1640     DeleteParcel(&parcel);
1641     g_databaseMutex->unlock(g_databaseMutex);
1642     LOGI("[DB]: Save an os account database successfully! [Id]: %d", osAccountId);
1643     return HC_SUCCESS;
1644 }
1645 
ReloadOsAccountDb(int32_t osAccountId)1646 void ReloadOsAccountDb(int32_t osAccountId)
1647 {
1648     if (g_databaseMutex == NULL) {
1649         LOGE("[DB]: not initialized!");
1650         return;
1651     }
1652     g_databaseMutex->lock(g_databaseMutex);
1653     LoadOsAccountDbCe(osAccountId);
1654     g_databaseMutex->unlock(g_databaseMutex);
1655 }
1656 
1657 #ifdef DEV_AUTH_HIVIEW_ENABLE
DumpGroup(int fd,const TrustedGroupEntry * group)1658 static void DumpGroup(int fd, const TrustedGroupEntry *group)
1659 {
1660     dprintf(fd, "||----------------------------Group----------------------------|                   |\n");
1661     dprintf(fd, "||%-12s = %-46.8s|                   |\n", "name", StringGet(&group->name));
1662     dprintf(fd, "||%-12s = %-46.8s|                   |\n", "id", StringGet(&group->id));
1663     dprintf(fd, "||%-12s = %-46d|                   |\n", "type", group->type);
1664     dprintf(fd, "||%-12s = %-46d|                   |\n", "visibility", group->visibility);
1665     dprintf(fd, "||%-12s = %-46d|                   |\n", "upgradeFlag", group->upgradeFlag);
1666     dprintf(fd, "||%-12s = %-46d|                   |\n", "expireTime", group->expireTime);
1667     HcString entryOwner = HC_VECTOR_GET(&group->managers, 0);
1668     dprintf(fd, "||%-12s = %-46.8s|                   |\n", "ownerName", StringGet(&entryOwner));
1669     dprintf(fd, "||%-12s = %-46.8s|                   |\n", "userId", StringGet(&group->userId));
1670     dprintf(fd, "||%-12s = %-46.8s|                   |\n", "sharedUserId", StringGet(&group->sharedUserId));
1671     dprintf(fd, "||----------------------------Group----------------------------|                   |\n");
1672 }
1673 
DumpDevice(int fd,const TrustedDeviceEntry * device)1674 static void DumpDevice(int fd, const TrustedDeviceEntry *device)
1675 {
1676     dprintf(fd, "|||--------------------DEV--------------------|                                    |\n");
1677     dprintf(fd, "|||%-12s = %-28.8s|                                    |\n", "groupId", StringGet(&device->groupId));
1678     dprintf(fd, "|||%-12s = %-28.8s|                                    |\n", "udid", StringGet(&device->udid));
1679     dprintf(fd, "|||%-12s = %-28.8s|                                    |\n", "authId", StringGet(&device->authId));
1680     dprintf(fd, "|||%-12s = %-28.8s|                                    |\n", "userId", StringGet(&device->userId));
1681     dprintf(fd, "|||%-12s = %-28.8s|                                    |\n", "serviceType",
1682         StringGet(&device->serviceType));
1683     dprintf(fd, "|||%-12s = %-28d|                                    |\n", "credential", device->credential);
1684     dprintf(fd, "|||%-12s = %-28d|                                    |\n", "devType", device->devType);
1685     dprintf(fd, "|||%-12s = %-28d|                                    |\n", "upgradeFlag", device->upgradeFlag);
1686     dprintf(fd, "|||%-12s = %-28d|                                    |\n", "credSource", device->source);
1687     dprintf(fd, "|||--------------------DEV--------------------|                                    |\n");
1688 }
1689 
DumpDb(int fd,const OsAccountTrustedInfo * db)1690 static void DumpDb(int fd, const OsAccountTrustedInfo *db)
1691 {
1692     const GroupEntryVec *groups = &db->groups;
1693     const DeviceEntryVec *devices = &db->devices;
1694     dprintf(fd, "|-------------------------------------DataBase-------------------------------------|\n");
1695     dprintf(fd, "|%-12s = %-67d|\n", "osAccountId", db->osAccountId);
1696     dprintf(fd, "|%-12s = %-67d|\n", "groupNum", groups->size(groups));
1697     dprintf(fd, "|%-12s = %-67d|\n", "deviceNum", devices->size(devices));
1698     uint32_t index;
1699     TrustedGroupEntry **groupEntry;
1700     FOR_EACH_HC_VECTOR(*groups, index, groupEntry) {
1701         DumpGroup(fd, *groupEntry);
1702     }
1703     TrustedDeviceEntry **deviceEntry;
1704     FOR_EACH_HC_VECTOR(*devices, index, deviceEntry) {
1705         DumpDevice(fd, *deviceEntry);
1706     }
1707     dprintf(fd, "|-------------------------------------DataBase-------------------------------------|\n");
1708 }
1709 
LoadAllAccountsData(void)1710 static void LoadAllAccountsData(void)
1711 {
1712     int32_t *accountIds = NULL;
1713     uint32_t size = 0;
1714     int32_t ret = GetAllOsAccountIds(&accountIds, &size);
1715     if (ret != HC_SUCCESS) {
1716         LOGE("[DB]: Failed to get all os account ids, [res]: %d", ret);
1717         return;
1718     }
1719     for (uint32_t index = 0; index < size; index++) {
1720         LoadDataIfNotLoaded(accountIds[index]);
1721     }
1722     HcFree(accountIds);
1723 }
1724 
DevAuthDataBaseDump(int fd)1725 static void DevAuthDataBaseDump(int fd)
1726 {
1727     if (g_databaseMutex == NULL) {
1728         LOGE("[DB]: Init mutex failed");
1729         return;
1730     }
1731     g_databaseMutex->lock(g_databaseMutex);
1732     if (IsOsAccountSupported()) {
1733         LoadAllAccountsData();
1734     }
1735     uint32_t index;
1736     OsAccountTrustedInfo *info;
1737     FOR_EACH_HC_VECTOR(g_deviceauthDb, index, info) {
1738         DumpDb(fd, info);
1739     }
1740     g_databaseMutex->unlock(g_databaseMutex);
1741 }
1742 #endif
1743 
InitDatabase(void)1744 int32_t InitDatabase(void)
1745 {
1746     if (g_databaseMutex == NULL) {
1747         g_databaseMutex = (HcMutex *)HcMalloc(sizeof(HcMutex), 0);
1748         if (g_databaseMutex == NULL) {
1749             LOGE("[DB]: Alloc databaseMutex failed");
1750             return HC_ERR_ALLOC_MEMORY;
1751         }
1752         if (InitHcMutex(g_databaseMutex) != HC_SUCCESS) {
1753             LOGE("[DB]: Init mutex failed");
1754             HcFree(g_databaseMutex);
1755             g_databaseMutex = NULL;
1756             return HC_ERROR;
1757         }
1758     }
1759     g_deviceauthDb = CREATE_HC_VECTOR(DeviceAuthDb);
1760     AddOsAccountEventCallback(GROUP_DATA_CALLBACK, OnOsAccountUnlocked, OnOsAccountRemoved);
1761     LoadDeviceAuthDb();
1762     DEV_AUTH_REG_DUMP_FUNC(DevAuthDataBaseDump);
1763     return HC_SUCCESS;
1764 }
1765 
DestroyDatabase(void)1766 void DestroyDatabase(void)
1767 {
1768     RemoveOsAccountEventCallback(GROUP_DATA_CALLBACK);
1769     g_databaseMutex->lock(g_databaseMutex);
1770     uint32_t index;
1771     OsAccountTrustedInfo *info;
1772     FOR_EACH_HC_VECTOR(g_deviceauthDb, index, info) {
1773         ClearGroupEntryVec(&info->groups);
1774         ClearDeviceEntryVec(&info->devices);
1775     }
1776     DESTROY_HC_VECTOR(DeviceAuthDb, &g_deviceauthDb);
1777     g_databaseMutex->unlock(g_databaseMutex);
1778     DestroyHcMutex(g_databaseMutex);
1779     HcFree(g_databaseMutex);
1780     g_databaseMutex = NULL;
1781 }