• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2025 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *    http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "credential_data_manager.h"
17 
18 #include "common_defs.h"
19 #include "device_auth_defines.h"
20 #include "hc_dev_info.h"
21 #include "hc_file.h"
22 #include "hc_log.h"
23 #include "hc_mutex.h"
24 #include "hc_types.h"
25 #include "securec.h"
26 #include "hidump_adapter.h"
27 #include "os_account_adapter.h"
28 #include "security_label_adapter.h"
29 #include "account_task_manager.h"
30 #include "cred_listener.h"
31 #include "cred_tlv_parser.h"
32 
33 typedef struct {
34     DECLARE_CRED_TLV_STRUCT(17)
35     CredTlvString credId;
36     CredTlvString deviceId;
37     CredTlvString peerUserSpaceId;
38     CredTlvUint8 subject;
39     CredTlvString userId;
40     CredTlvUint8 issuer;
41     CredTlvUint8 credType;
42     CredTlvUint8 keyFormat;
43     CredTlvUint8 algorithmType;
44     CredTlvUint8 proofType;
45     CredTlvBuffer authorizedAccountList;
46     CredTlvBuffer authorizedAppList;
47     CredTlvBuffer authorizedDeviceList;
48     CredTlvUint8 authorizedScope;
49     CredTlvString credOwner;
50     CredTlvInt32 ownerUid;
51     CredTlvString extendInfo;
52 } TlvCredentialElement;
53 DECLEAR_CRED_INIT_FUNC(TlvCredentialElement)
54 DECLARE_CRED_TLV_VECTOR(TlvCredentialVec, TlvCredentialElement)
55 
56 typedef struct {
57     DECLARE_CRED_TLV_STRUCT(2)
58     CredTlvInt32 version;
59     TlvCredentialVec credentials;
60 } HCCredDataBaseV1;
61 DECLEAR_CRED_INIT_FUNC(HCCredDataBaseV1)
62 
63 BEGIN_CRED_TLV_STRUCT_DEFINE(TlvCredentialElement, 0x0001)
64     CRED_TLV_MEMBER(CredTlvString, credId, 0x4001)
65     CRED_TLV_MEMBER(CredTlvString, deviceId, 0x4002)
66     CRED_TLV_MEMBER(CredTlvString, peerUserSpaceId, 0x4003)
67     CRED_TLV_MEMBER(CredTlvUint8, subject, 0x4004)
68     CRED_TLV_MEMBER(CredTlvString, userId, 0x4005)
69     CRED_TLV_MEMBER(CredTlvUint8, issuer, 0x4006)
70     CRED_TLV_MEMBER(CredTlvUint8, credType, 0x4007)
71     CRED_TLV_MEMBER(CredTlvUint8, keyFormat, 0x4008)
72     CRED_TLV_MEMBER(CredTlvUint8, algorithmType, 0x4009)
73     CRED_TLV_MEMBER(CredTlvUint8, proofType, 0x400A)
74     CRED_TLV_MEMBER(CredTlvBuffer, authorizedAccountList, 0x400B)
75     CRED_TLV_MEMBER(CredTlvBuffer, authorizedAppList, 0x400C)
76     CRED_TLV_MEMBER(CredTlvBuffer, authorizedDeviceList, 0x400D)
77     CRED_TLV_MEMBER(CredTlvUint8, authorizedScope, 0x400E)
78     CRED_TLV_MEMBER(CredTlvString, credOwner, 0x400F)
79     CRED_TLV_MEMBER(CredTlvInt32, ownerUid, 0x4010)
80     CRED_TLV_MEMBER(CredTlvString, extendInfo, 0x4011)
81 END_CRED_TLV_STRUCT_DEFINE()
82 IMPLEMENT_CRED_TLV_VECTOR(TlvCredentialVec, TlvCredentialElement, 1)
83 
84 BEGIN_CRED_TLV_STRUCT_DEFINE(HCCredDataBaseV1, 0x0001)
85     CRED_TLV_MEMBER(CredTlvInt32, version, 0x6001)
86     CRED_TLV_MEMBER(TlvCredentialVec, credentials, 0x6002)
87 END_CRED_TLV_STRUCT_DEFINE()
88 
89 IMPLEMENT_HC_VECTOR(CredentialVec, Credential*, 1)
90 
91 typedef struct {
92     int32_t osAccountId;
93     CredentialVec credentials;
94 } OsAccountCredInfo;
95 
96 DECLARE_HC_VECTOR(DevAuthCredDb, OsAccountCredInfo)
97 IMPLEMENT_HC_VECTOR(DevAuthCredDb, OsAccountCredInfo, 1)
98 
99 #define MAX_DB_PATH_LEN 256
100 
101 static HcMutex *g_credMutex = NULL;
102 static DevAuthCredDb g_devauthCredDb;
103 const uint8_t DEFAULT_CRED_PARAM_VAL = 0;
104 
EndWithZero(HcParcel * parcel)105 static bool EndWithZero(HcParcel *parcel)
106 {
107     const char *p = GetParcelLastChar(parcel);
108     if (p == NULL) {
109         return false;
110     }
111     return (*p == '\0');
112 }
113 
LoadStringVectorFromParcel(StringVector * vec,HcParcel * parcel)114 static bool LoadStringVectorFromParcel(StringVector *vec, HcParcel *parcel)
115 {
116     uint32_t strLen = 0;
117     do {
118         if (!ParcelReadUint32(parcel, &strLen)) {
119             return true;
120         }
121         if ((strLen == 0) || (strLen > MAX_STRING_LEN)) {
122             return false;
123         }
124         HcString str = CreateString();
125         ClearParcel(&str.parcel);
126         if (!ParcelReadParcel(parcel, &str.parcel, strLen, false) ||
127             !EndWithZero(&str.parcel)) {
128             DeleteString(&str);
129             return false;
130         } else {
131             if (vec->pushBack(vec, &str) == NULL) {
132                 DeleteString(&str);
133                 return false;
134             }
135         }
136     } while (1);
137 }
138 
SaveStringVectorToParcel(const StringVector * vec,HcParcel * parcel)139 static bool SaveStringVectorToParcel(const StringVector *vec, HcParcel *parcel)
140 {
141     uint32_t index;
142     HcString *str = NULL;
143     FOR_EACH_HC_VECTOR(*vec, index, str) {
144         uint32_t len = StringLength(str) + sizeof(char);
145         if (!ParcelWriteUint32(parcel, len)) {
146             return false;
147         }
148         if (!ParcelWrite(parcel, GetParcelData(&str->parcel), GetParcelDataSize(&str->parcel))) {
149             return false;
150         }
151     }
152     return true;
153 }
154 
GetOsAccountCredInfoPathCe(int32_t osAccountId,char * infoPath,uint32_t pathBufferLen)155 static bool GetOsAccountCredInfoPathCe(int32_t osAccountId, char *infoPath, uint32_t pathBufferLen)
156 {
157     const char *beginPath = GetStorageDirPathCe();
158     if (beginPath == NULL) {
159         LOGE("[CRED#DB]: Failed to get the storage path!");
160         return false;
161     }
162     if (sprintf_s(infoPath, pathBufferLen, "%s/%d/deviceauth/hccredential.dat", beginPath, osAccountId) <= 0) {
163         LOGE("[CRED#DB]: Failed to generate db file path!");
164         return false;
165     }
166     return true;
167 }
168 
GetOsAccountCredInfoPathDe(int32_t osAccountId,char * infoPath,uint32_t pathBufferLen)169 static bool GetOsAccountCredInfoPathDe(int32_t osAccountId, char *infoPath, uint32_t pathBufferLen)
170 {
171     const char *beginPath = GetStorageDirPath();
172     if (beginPath == NULL) {
173         LOGE("[CRED#DB]: Failed to get the storage path dir!");
174         return false;
175     }
176     int32_t writeByteNum;
177     if (osAccountId == DEFAULT_OS_ACCOUNT) {
178         writeByteNum = sprintf_s(infoPath, pathBufferLen, "%s/hccredential.dat", beginPath);
179     } else {
180         writeByteNum = sprintf_s(infoPath, pathBufferLen, "%s/hccredential%d.dat", beginPath, osAccountId);
181     }
182     if (writeByteNum <= 0) {
183         LOGE("[CRED#DB]: sprintf_s fail!");
184         return false;
185     }
186     return true;
187 }
188 
GetOsAccountCredInfoPath(int32_t osAccountId,char * infoPath,uint32_t pathBufferLen)189 static bool GetOsAccountCredInfoPath(int32_t osAccountId, char *infoPath, uint32_t pathBufferLen)
190 {
191     if (IsOsAccountSupported())  {
192         return GetOsAccountCredInfoPathCe(osAccountId, infoPath, pathBufferLen);
193     } else {
194         return GetOsAccountCredInfoPathDe(osAccountId, infoPath, pathBufferLen);
195     }
196 }
197 
GenerateAuthorizedAppList(const Credential * entry,Credential * returnEntry)198 static bool GenerateAuthorizedAppList(const Credential *entry, Credential *returnEntry)
199 {
200     uint32_t index = 0;
201     HcString *authorizedApp = NULL;
202     FOR_EACH_HC_VECTOR(entry->authorizedAppList, index, authorizedApp) {
203         if (authorizedApp == NULL) {
204             continue;
205         }
206         HcString returnAuthorizedApp = CreateString();
207         if (!StringSet(&returnAuthorizedApp, *authorizedApp)) {
208             DeleteString(&returnAuthorizedApp);
209             LOGE("[CRED#DB]: Failed to copy authorizedApp!");
210             return false;
211         }
212         if (returnEntry->authorizedAppList.pushBack(&returnEntry->authorizedAppList, &returnAuthorizedApp)
213             == NULL) {
214             LOGE("[CRED#DB]: Failed to push authorizedApp to list!");
215             DeleteString(&returnAuthorizedApp);
216             return false;
217         }
218     }
219     return true;
220 }
221 
GenerateCredFromCred(const Credential * entry,Credential * returnEntry)222 bool GenerateCredFromCred(const Credential *entry, Credential *returnEntry)
223 {
224     if (!StringSet(&returnEntry->credId, entry->credId)) {
225         LOGE("[CRED#DB]: Failed to copy credId!");
226         return false;
227     }
228     if (!StringSet(&returnEntry->deviceId, entry->deviceId)) {
229         LOGE("[CRED#DB]: Failed to copy deviceId!");
230         return false;
231     }
232     if (!StringSet(&returnEntry->peerUserSpaceId, entry->peerUserSpaceId)) {
233         LOGE("[CRED#DB]: Failed to copy peerUserSpaceId!");
234         return false;
235     }
236     if (!StringSet(&returnEntry->userId, entry->userId)) {
237         LOGE("[CRED#DB]: Failed to copy userId!");
238         return false;
239     }
240     if (!StringSet(&returnEntry->credOwner, entry->credOwner)) {
241         LOGE("[CRED#DB]: Failed to copy credOwner!");
242         return false;
243     }
244     if (!GenerateAuthorizedAppList(entry, returnEntry)) {
245         return false;
246     }
247     if (!StringSet(&returnEntry->extendInfo, entry->extendInfo)) {
248         LOGE("[CRED#DB]: Failed to copy extendInfo!");
249         return false;
250     }
251     returnEntry->subject = entry->subject;
252     returnEntry->authorizedScope = entry->authorizedScope;
253     returnEntry->credType = entry->credType;
254     returnEntry->issuer = entry->issuer;
255     returnEntry->keyFormat = entry->keyFormat;
256     returnEntry->algorithmType = entry->algorithmType;
257     returnEntry->proofType = entry->proofType;
258     returnEntry->ownerUid = entry->ownerUid;
259     return true;
260 }
261 
GenerateCredentialFromTlv(TlvCredentialElement * credential,Credential * entry)262 static bool GenerateCredentialFromTlv(TlvCredentialElement *credential, Credential *entry)
263 {
264     if (!StringSet(&entry->credId, credential->credId.data)) {
265         LOGE("[CRED#DB]: Failed to load credId from tlv!");
266         return false;
267     }
268     if (!StringSet(&entry->deviceId, credential->deviceId.data)) {
269         LOGE("[CRED#DB]: Failed to load deviceId from tlv!");
270         return false;
271     }
272     if (!StringSet(&entry->peerUserSpaceId, credential->peerUserSpaceId.data)) {
273         LOGE("[CRED#DB]: Failed to load peerUserSpaceId from tlv!");
274         return false;
275     }
276     if (!StringSet(&entry->userId, credential->userId.data)) {
277         LOGE("[CRED#DB]: Failed to load userId from tlv!");
278         return false;
279     }
280     if (!StringSet(&entry->credOwner, credential->credOwner.data)) {
281         LOGE("[CRED#DB]: Failed to load credOwner from tlv!");
282         return false;
283     }
284     if (!LoadStringVectorFromParcel(&entry->authorizedAccountList, &credential->authorizedAccountList.data)) {
285         LOGE("[CRED#DB]: Failed to load authorizedAccountList from tlv!");
286         return false;
287     }
288     if (!LoadStringVectorFromParcel(&entry->authorizedDeviceList, &credential->authorizedDeviceList.data)) {
289         LOGE("[CRED#DB]: Failed to load authorizedDeviceList from tlv!");
290         return false;
291     }
292     if (!LoadStringVectorFromParcel(&entry->authorizedAppList, &credential->authorizedAppList.data)) {
293         LOGE("[CRED#DB]: Failed to load authorizedAppList from tlv!");
294         return false;
295     }
296     if (!StringSet(&entry->extendInfo, credential->extendInfo.data)) {
297         LOGE("[CRED#DB]: Failed to load extendInfo from tlv!");
298         return false;
299     }
300     entry->subject = credential->subject.data;
301     entry->authorizedScope = credential->authorizedScope.data;
302     entry->issuer = credential->issuer.data;
303     entry->credType = credential->credType.data;
304     entry->keyFormat = credential->keyFormat.data;
305     entry->algorithmType = credential->algorithmType.data;
306     entry->proofType = credential->proofType.data;
307     entry->ownerUid = credential->ownerUid.data;
308     return true;
309 }
310 
LoadCredentials(HCCredDataBaseV1 * db,CredentialVec * vec)311 static bool LoadCredentials(HCCredDataBaseV1 *db, CredentialVec *vec)
312 {
313     uint32_t index;
314     TlvCredentialElement *credentialTlv = NULL;
315     FOR_EACH_HC_VECTOR(db->credentials.data, index, credentialTlv) {
316         if (credentialTlv == NULL) {
317             continue;
318         }
319         Credential *entry = CreateCredential();
320         if (entry == NULL) {
321             LOGE("[CRED#DB]: Failed to allocate entry memory!");
322             ClearCredentialVec(vec);
323             return false;
324         }
325         if (!GenerateCredentialFromTlv(credentialTlv, entry)) {
326             DestroyCredential(entry);
327             ClearCredentialVec(vec);
328             return false;
329         }
330         if (vec->pushBackT(vec, entry) == NULL) {
331             LOGE("[CRED#DB]: Failed to push entry to vec!");
332             DestroyCredential(entry);
333             ClearCredentialVec(vec);
334             return false;
335         }
336     }
337     return true;
338 }
339 
ReadCredInfoFromParcel(HcParcel * parcel,OsAccountCredInfo * info)340 static bool ReadCredInfoFromParcel(HcParcel *parcel, OsAccountCredInfo *info)
341 {
342     bool ret = false;
343     HCCredDataBaseV1 dbv1;
344     CRED_TLV_INIT(HCCredDataBaseV1, &dbv1)
345     if (DecodeCredTlvMessage((CredTlvBase *)&dbv1, parcel, false)) {
346         if (!LoadCredentials(&dbv1, &info->credentials)) {
347             CRED_TLV_DEINIT(dbv1)
348             return false;
349         }
350         ret = true;
351     } else {
352         LOGE("[CRED#DB]: Decode Tlv Message Failed!");
353     }
354     CRED_TLV_DEINIT(dbv1)
355     return ret;
356 }
357 
ReadParcelFromFile(const char * filePath,HcParcel * parcel)358 static bool ReadParcelFromFile(const char *filePath, HcParcel *parcel)
359 {
360     FileHandle file;
361     int ret = HcFileOpen(filePath, MODE_FILE_READ, &file);
362     if (ret != 0) {
363         LOGE("[CRED#DB]: Failed to open database file!");
364         return false;
365     }
366     SetSecurityLabel(filePath, SECURITY_LABEL_S2);
367     int fileSize = HcFileSize(file);
368     if (fileSize <= 0) {
369         LOGE("[CRED#DB]: The database file size is invalid!");
370         HcFileClose(file);
371         return false;
372     }
373     char *fileData = (char *)HcMalloc(fileSize, 0);
374     if (fileData == NULL) {
375         LOGE("[CRED#DB]: Failed to allocate fileData memory!");
376         HcFileClose(file);
377         return false;
378     }
379     if (HcFileRead(file, fileData, fileSize) != fileSize) {
380         LOGE("[CRED#DB]: Read file error!");
381         HcFileClose(file);
382         HcFree(fileData);
383         return false;
384     }
385     HcFileClose(file);
386     if (!ParcelWrite(parcel, fileData, fileSize)) {
387         LOGE("[CRED#DB]: parcel write error!");
388         HcFree(fileData);
389         return false;
390     }
391     HcFree(fileData);
392     return true;
393 }
394 
SaveParcelToFile(const char * filePath,HcParcel * parcel)395 static bool SaveParcelToFile(const char *filePath, HcParcel *parcel)
396 {
397     FileHandle file;
398     int ret = HcFileOpen(filePath, MODE_FILE_WRITE, &file);
399     if (ret != IS_SUCCESS) {
400         LOGE("[CRED#DB]: Failed to open database file!");
401         return false;
402     }
403     SetSecurityLabel(filePath, SECURITY_LABEL_S2);
404     int fileSize = (int)GetParcelDataSize(parcel);
405     const char *fileData = GetParcelData(parcel);
406     int writeSize = HcFileWrite(file, fileData, fileSize);
407     HcFileClose(file);
408     if (writeSize == fileSize) {
409         return true;
410     } else {
411         LOGE("[CRED#DB]: write file error!");
412         return false;
413     }
414 }
415 
LoadOsAccountCredDb(int32_t osAccountId)416 static void LoadOsAccountCredDb(int32_t osAccountId)
417 {
418     char filePath[MAX_DB_PATH_LEN] = { 0 };
419     if (!GetOsAccountCredInfoPath(osAccountId, filePath, MAX_DB_PATH_LEN)) {
420         LOGE("[CRED#DB]: Failed to get os account info path!");
421         return;
422     }
423     HcParcel parcel = CreateParcel(0, 0);
424     if (!ReadParcelFromFile(filePath, &parcel)) {
425         DeleteParcel(&parcel);
426         return;
427     }
428     OsAccountCredInfo info;
429     info.osAccountId = osAccountId;
430     info.credentials = CreateCredentialVec();
431     if (!ReadCredInfoFromParcel(&parcel, &info)) {
432         DestroyCredentialVec(&info.credentials);
433         DeleteParcel(&parcel);
434         return;
435     }
436     DeleteParcel(&parcel);
437     if (g_devauthCredDb.pushBackT(&g_devauthCredDb, info) == NULL) {
438         LOGE("[CRED#DB]: Failed to push osAccountCredInfo to cred database!");
439         ClearCredentialVec(&info.credentials);
440         return;
441     }
442     LOGI("[CRED#DB]: Load os account cred db successfully! [Id]: %" LOG_PUB "d", osAccountId);
443 }
444 
RemoveOsAccountCredInfo(int32_t osAccountId)445 static void RemoveOsAccountCredInfo(int32_t osAccountId)
446 {
447     uint32_t index = 0;
448     OsAccountCredInfo *info = NULL;
449     FOR_EACH_HC_VECTOR(g_devauthCredDb, index, info) {
450         if (info != NULL && info->osAccountId == osAccountId) {
451             OsAccountCredInfo deleteInfo;
452             HC_VECTOR_POPELEMENT(&g_devauthCredDb, &deleteInfo, index);
453             ClearCredentialVec(&deleteInfo.credentials);
454             return;
455         }
456     }
457 }
458 
OnOsAccountUnlocked(int32_t osAccountId)459 static void OnOsAccountUnlocked(int32_t osAccountId)
460 {
461     (void)LockHcMutex(g_credMutex);
462     RemoveOsAccountCredInfo(osAccountId);
463     LoadOsAccountCredDb(osAccountId);
464     UnlockHcMutex(g_credMutex);
465 }
466 
OnOsAccountRemoved(int32_t osAccountId)467 static void OnOsAccountRemoved(int32_t osAccountId)
468 {
469     LOGI("[CRED#DB]: os account is removed, osAccountId: %" LOG_PUB "d", osAccountId);
470     (void)LockHcMutex(g_credMutex);
471     RemoveOsAccountCredInfo(osAccountId);
472     UnlockHcMutex(g_credMutex);
473 }
474 
IsOsAccountDataLoaded(int32_t osAccountId)475 static bool IsOsAccountDataLoaded(int32_t osAccountId)
476 {
477     uint32_t index = 0;
478     OsAccountCredInfo *info = NULL;
479     FOR_EACH_HC_VECTOR(g_devauthCredDb, index, info) {
480         if (info != NULL && info->osAccountId == osAccountId) {
481             return true;
482         }
483     }
484     return false;
485 }
486 
LoadDataIfNotLoaded(int32_t osAccountId)487 static void LoadDataIfNotLoaded(int32_t osAccountId)
488 {
489     if (IsOsAccountDataLoaded(osAccountId)) {
490         return;
491     }
492     LOGI("[CRED#DB]: data has not been loaded, load it, osAccountId: %" LOG_PUB "d", osAccountId);
493     LoadOsAccountCredDb(osAccountId);
494 }
495 
GetCredInfoByOsAccountId(int32_t osAccountId)496 static OsAccountCredInfo *GetCredInfoByOsAccountId(int32_t osAccountId)
497 {
498     if (IsOsAccountSupported()) {
499         LoadDataIfNotLoaded(osAccountId);
500     }
501     uint32_t index = 0;
502     OsAccountCredInfo *info = NULL;
503     FOR_EACH_HC_VECTOR(g_devauthCredDb, index, info) {
504         if (info != NULL && info->osAccountId == osAccountId) {
505             return info;
506         }
507     }
508     LOGI("[CRED#DB]: Create a new os account database cache! [Id]: %" LOG_PUB "d", osAccountId);
509     OsAccountCredInfo newInfo;
510     newInfo.osAccountId = osAccountId;
511     newInfo.credentials = CreateCredentialVec();
512     OsAccountCredInfo *returnInfo = g_devauthCredDb.pushBackT(&g_devauthCredDb, newInfo);
513     if (returnInfo == NULL) {
514         LOGE("[CRED#DB]: Failed to push osAccountInfo to database!");
515         DestroyCredentialVec(&newInfo.credentials);
516     }
517     return returnInfo;
518 }
519 
LoadDevAuthCredDb(void)520 static void LoadDevAuthCredDb(void)
521 {
522     if (IsOsAccountSupported()) {
523         return;
524     }
525     (void)LockHcMutex(g_credMutex);
526     StringVector osAccountDbNameVec = CreateStrVector();
527     HcFileGetSubFileName(GetStorageDirPath(), &osAccountDbNameVec);
528     uint32_t index;
529     HcString *dbName;
530     FOR_EACH_HC_VECTOR(osAccountDbNameVec, index, dbName) {
531         int32_t osAccountId;
532         const char *osAccountIdStr = StringGet(dbName);
533         if (osAccountIdStr == NULL) {
534             continue;
535         }
536         if (strcmp(osAccountIdStr, "hccredential.dat") == 0) {
537             LoadOsAccountCredDb(DEFAULT_OS_ACCOUNT);
538         } else if (sscanf_s(osAccountIdStr, "hccredential%d.dat", &osAccountId) == 1) {
539             LoadOsAccountCredDb(osAccountId);
540         }
541     }
542     DestroyStrVector(&osAccountDbNameVec);
543     UnlockHcMutex(g_credMutex);
544 }
545 
SetCredentialElement(TlvCredentialElement * element,Credential * entry)546 static bool SetCredentialElement(TlvCredentialElement *element, Credential *entry)
547 {
548     if (!StringSet(&element->credId.data, entry->credId)) {
549         LOGE("[CRED#DB]: Failed to copy credId!");
550         return false;
551     }
552     if (!StringSet(&element->deviceId.data, entry->deviceId)) {
553         LOGE("[CRED#DB]: Failed to copy deviceId!");
554         return false;
555     }
556     if (!StringSet(&element->peerUserSpaceId.data, entry->peerUserSpaceId)) {
557         LOGE("[CRED#DB]: Failed to copy peerUserSpaceId!");
558         return false;
559     }
560     if (!StringSet(&element->userId.data, entry->userId)) {
561         LOGE("[CRED#DB]: Failed to copy userId!");
562         return false;
563     }
564     if (!StringSet(&element->credOwner.data, entry->credOwner)) {
565         LOGE("[CRED#DB]: Failed to copy credOwner!");
566         return false;
567     }
568     if (!SaveStringVectorToParcel(&entry->authorizedAccountList, &element->authorizedAccountList.data)) {
569         LOGE("[CRED#DB]: Failed to copy authorizedAccountList!");
570         return false;
571     }
572     if (!SaveStringVectorToParcel(&entry->authorizedDeviceList, &element->authorizedDeviceList.data)) {
573         LOGE("[CRED#DB]: Failed to copy authorizedDeviceList!");
574         return false;
575     }
576     if (!SaveStringVectorToParcel(&entry->authorizedAppList, &element->authorizedAppList.data)) {
577         LOGE("[CRED#DB]: Failed to copy authorizedAppList!");
578         return false;
579     }
580     if (!StringSet(&element->extendInfo.data, entry->extendInfo)) {
581         LOGE("[CRED#DB]: Failed to copy extendInfo!");
582         return false;
583     }
584     element->subject.data = entry->subject;
585     element->authorizedScope.data = entry->authorizedScope;
586     element->issuer.data = entry->issuer;
587     element->credType.data = entry->credType;
588     element->keyFormat.data = entry->keyFormat;
589     element->algorithmType.data = entry->algorithmType;
590     element->proofType.data = entry->proofType;
591     element->ownerUid.data = entry->ownerUid;
592     return true;
593 }
594 
SaveCredentials(const CredentialVec * vec,HCCredDataBaseV1 * db)595 static bool SaveCredentials(const CredentialVec *vec, HCCredDataBaseV1 *db)
596 {
597     uint32_t index;
598     Credential **entry;
599     FOR_EACH_HC_VECTOR(*vec, index, entry) {
600         if (entry == NULL || *entry == NULL) {
601             continue;
602         }
603         TlvCredentialElement tmp;
604         TlvCredentialElement *element = db->credentials.data.pushBack(&db->credentials.data, &tmp);
605         if (element == NULL) {
606             return false;
607         }
608         CRED_TLV_INIT(TlvCredentialElement, element);
609         if (!SetCredentialElement(element, *entry)) {
610             CRED_TLV_DEINIT((*element));
611             return false;
612         }
613     }
614     return true;
615 }
616 
SaveCredInfoToParcel(const OsAccountCredInfo * info,HcParcel * parcel)617 static bool SaveCredInfoToParcel(const OsAccountCredInfo *info, HcParcel *parcel)
618 {
619     int32_t ret = false;
620     HCCredDataBaseV1 dbv1;
621     CRED_TLV_INIT(HCCredDataBaseV1, &dbv1)
622     dbv1.version.data = 1;
623     do {
624         if (!SaveCredentials(&info->credentials, &dbv1)) {
625             break;
626         }
627         if (!EncodeCredTlvMessage((CredTlvBase *)&dbv1, parcel)) {
628             LOGE("[CRED#DB]: Encode Tlv Message failed!");
629             break;
630         }
631         ret = true;
632     } while (0);
633     CRED_TLV_DEINIT(dbv1)
634     return ret;
635 }
636 
CompareQueryCredentialParams(const QueryCredentialParams * params,const Credential * entry)637 static bool CompareQueryCredentialParams(const QueryCredentialParams *params, const Credential *entry)
638 {
639     if ((params->deviceId != NULL) && (strcmp(params->deviceId, StringGet(&entry->deviceId)) != 0)) {
640         return false;
641     }
642     if ((params->credOwner != NULL) && (strcmp(params->credOwner, StringGet(&entry->credOwner)) != 0)) {
643         return false;
644     }
645     if ((params->userId != NULL) && (strcmp(params->userId, StringGet(&entry->userId)) != 0)) {
646         return false;
647     }
648     if ((params->credId != NULL) && (strcmp(params->credId, StringGet(&entry->credId)) != 0)) {
649         return false;
650     }
651     if ((params->credType != DEFAULT_CRED_PARAM_VAL) && (params->credType != entry->credType)) {
652         return false;
653     }
654     if ((params->subject != DEFAULT_CRED_PARAM_VAL) && (params->subject != entry->subject)) {
655         return false;
656     }
657     if ((params->issuer != DEFAULT_CRED_PARAM_VAL) && (params->issuer != entry->issuer)) {
658         return false;
659     }
660     if ((params->ownerUid != DEFAULT_CRED_PARAM_VAL) && (params->ownerUid != entry->ownerUid)) {
661         return false;
662     }
663     return true;
664 }
665 
QueryCredentialPtrIfMatch(const CredentialVec * vec,const QueryCredentialParams * params)666 static Credential **QueryCredentialPtrIfMatch(const CredentialVec *vec, const QueryCredentialParams *params)
667 {
668     uint32_t index;
669     Credential **entry;
670     FOR_EACH_HC_VECTOR(*vec, index, entry) {
671         if (entry != NULL && *entry != NULL && CompareQueryCredentialParams(params, *entry)) {
672             return entry;
673         }
674     }
675     return NULL;
676 }
677 
InitQueryCredentialParams(void)678 QueryCredentialParams InitQueryCredentialParams(void)
679 {
680     QueryCredentialParams params = {
681         .deviceId = NULL,
682         .credOwner = NULL,
683         .credId = NULL,
684         .userId = NULL,
685         .credType = DEFAULT_CRED_PARAM_VAL,
686         .ownerUid = DEFAULT_CRED_PARAM_VAL,
687         .subject = DEFAULT_CRED_PARAM_VAL,
688         .issuer = DEFAULT_CRED_PARAM_VAL,
689     };
690     return params;
691 }
692 
CreateCredential(void)693 Credential *CreateCredential(void)
694 {
695     Credential *ptr = (Credential *)HcMalloc(sizeof(Credential), 0);
696     if (ptr == NULL) {
697         LOGE("[CRED#DB]: Failed to allocate Credential memory!");
698         return NULL;
699     }
700     ptr->credId = CreateString();
701     ptr->deviceId = CreateString();
702     ptr->peerUserSpaceId = CreateString();
703     ptr->userId = CreateString();
704     ptr->credOwner = CreateString();
705     ptr->authorizedAccountList = CreateStrVector();
706     ptr->authorizedAppList = CreateStrVector();
707     ptr->authorizedDeviceList = CreateStrVector();
708     ptr->extendInfo = CreateString();
709     return ptr;
710 }
711 
DestroyCredential(Credential * credential)712 void DestroyCredential(Credential *credential)
713 {
714     if (credential == NULL) {
715         return;
716     }
717     DeleteString(&credential->credId);
718     DeleteString(&credential->deviceId);
719     DeleteString(&credential->peerUserSpaceId);
720     DeleteString(&credential->userId);
721     DeleteString(&credential->credOwner);
722     DestroyStrVector(&credential->authorizedAccountList);
723     DestroyStrVector(&credential->authorizedAppList);
724     DestroyStrVector(&credential->authorizedDeviceList);
725     DeleteString(&credential->extendInfo);
726     HcFree(credential);
727 }
728 
DeepCopyCredential(const Credential * entry)729 Credential *DeepCopyCredential(const Credential *entry)
730 {
731     Credential *returnEntry = CreateCredential();
732     if (returnEntry == NULL) {
733         return NULL;
734     }
735     if (!GenerateCredFromCred(entry, returnEntry)) {
736         DestroyCredential(returnEntry);
737         return NULL;
738     }
739     return returnEntry;
740 }
741 
ClearCredentialVec(CredentialVec * vec)742 void ClearCredentialVec(CredentialVec *vec)
743 {
744     uint32_t index;
745     Credential **entry;
746     FOR_EACH_HC_VECTOR(*vec, index, entry) {
747         if (entry == NULL || *entry == NULL) {
748             continue;
749         }
750         DestroyCredential(*entry);
751     }
752     DESTROY_HC_VECTOR(CredentialVec, vec);
753 }
754 
AddCredIdToReturn(const Credential * credInfo,CJson * json)755 static int32_t AddCredIdToReturn(const Credential *credInfo, CJson *json)
756 {
757     const char *credId = StringGet(&credInfo->credId);
758     if (credId == NULL) {
759         LOGE("[CRED#DB]: Failed to get credId from credInfo!");
760         return IS_ERR_NULL_PTR;
761     }
762     if (AddStringToJson(json, FIELD_CRED_ID, credId) != IS_SUCCESS) {
763         LOGE("[CRED#DB]: Failed to add credId to json!");
764         return IS_ERR_JSON_ADD;
765     }
766     return IS_SUCCESS;
767 }
768 
AddCredTypeToReturn(const Credential * credInfo,CJson * json)769 static int32_t AddCredTypeToReturn(const Credential *credInfo, CJson *json)
770 {
771     uint8_t credType = credInfo->credType;
772     if (AddIntToJson(json, FIELD_CRED_TYPE, credType) != IS_SUCCESS) {
773         LOGE("[CRED#DB]: Failed to add credType to json!");
774         return IS_ERR_JSON_ADD;
775     }
776     return IS_SUCCESS;
777 }
778 
AddUserIdToReturn(const Credential * credInfo,CJson * json)779 static int32_t AddUserIdToReturn(const Credential *credInfo, CJson *json)
780 {
781     const char *userId = StringGet(&credInfo->userId);
782     if (userId == NULL) {
783         LOGE("[CRED#DB]: Failed to get userId from credInfo!");
784         return IS_ERR_NULL_PTR;
785     }
786     if (AddStringToJson(json, FIELD_USER_ID, userId) != IS_SUCCESS) {
787         LOGE("[CRED#DB]: Failed to add userId to json!");
788         return IS_ERR_JSON_ADD;
789     }
790     return IS_SUCCESS;
791 }
792 
AddSubjectToReturn(const Credential * credInfo,CJson * json)793 static int32_t AddSubjectToReturn(const Credential *credInfo, CJson *json)
794 {
795     uint8_t subject = credInfo->subject;
796     if (AddIntToJson(json, FIELD_SUBJECT, subject) != IS_SUCCESS) {
797         LOGE("[CRED#DB]: Failed to add subject to json!");
798         return IS_ERR_JSON_ADD;
799     }
800     return IS_SUCCESS;
801 }
802 
AddIssuerToReturn(const Credential * credInfo,CJson * json)803 static int32_t AddIssuerToReturn(const Credential *credInfo, CJson *json)
804 {
805     uint8_t issuer = credInfo->issuer;
806     if (AddIntToJson(json, FIELD_ISSUER, issuer) != IS_SUCCESS) {
807         LOGE("[CRED#DB]: Failed to add issuer to json!");
808         return IS_ERR_JSON_ADD;
809     }
810     return IS_SUCCESS;
811 }
812 
AddKeyFormatToReturn(const Credential * credInfo,CJson * json)813 static int32_t AddKeyFormatToReturn(const Credential *credInfo, CJson *json)
814 {
815     uint8_t keyFormat = credInfo->keyFormat;
816     if (AddIntToJson(json, FIELD_KEY_FORMAT, keyFormat) != IS_SUCCESS) {
817         LOGE("[CRED#DB]: Failed to add keyFormat to json!");
818         return IS_ERR_JSON_ADD;
819     }
820     return IS_SUCCESS;
821 }
822 
AddProofTypeToReturn(const Credential * credInfo,CJson * json)823 static int32_t AddProofTypeToReturn(const Credential *credInfo, CJson *json)
824 {
825     uint8_t proofType = credInfo->proofType;
826     if (AddIntToJson(json, FIELD_PROOF_TYPE, proofType) != IS_SUCCESS) {
827         LOGE("[CRED#DB]: Failed to add proofType to json!");
828         return IS_ERR_JSON_ADD;
829     }
830     return IS_SUCCESS;
831 }
832 
AddAlgorithmTypeToReturn(const Credential * credInfo,CJson * json)833 static int32_t AddAlgorithmTypeToReturn(const Credential *credInfo, CJson *json)
834 {
835     uint8_t algorithmType = credInfo->algorithmType;
836     if (AddIntToJson(json, FIELD_ALGORITHM_TYPE, algorithmType) != IS_SUCCESS) {
837         LOGE("[CRED#DB]: Failed to add algorithmType to json!");
838         return IS_ERR_JSON_ADD;
839     }
840     return IS_SUCCESS;
841 }
842 
AddDeviceIdToReturn(const Credential * credInfo,CJson * json)843 static int32_t AddDeviceIdToReturn(const Credential *credInfo, CJson *json)
844 {
845     const char *deviceId = StringGet(&credInfo->deviceId);
846     if (deviceId == NULL) {
847         LOGE("[CRED#DB]: Failed to get deviceId from credInfo!");
848         return IS_ERR_NULL_PTR;
849     }
850     if (AddStringToJson(json, FIELD_DEVICE_ID, deviceId) != IS_SUCCESS) {
851         LOGE("[CRED#DB]: Failed to add deviceId to json!");
852         return IS_ERR_JSON_ADD;
853     }
854     return IS_SUCCESS;
855 }
856 
AddCredOwnerToReturn(const Credential * credInfo,CJson * json)857 static int32_t AddCredOwnerToReturn(const Credential *credInfo, CJson *json)
858 {
859     const char *credOwner = StringGet(&credInfo->credOwner);
860     if (credOwner == NULL) {
861         LOGE("[CRED#DB]: Failed to get credOwner from credInfo!");
862         return IS_ERR_NULL_PTR;
863     }
864     if (AddStringToJson(json, FIELD_CRED_OWNER, credOwner) != IS_SUCCESS) {
865         LOGE("[CRED#DB]: Failed to add credOwner to json!");
866         return IS_ERR_JSON_ADD;
867     }
868     return IS_SUCCESS;
869 }
870 
AddExtendInfoToReturn(const Credential * credInfo,CJson * json)871 static int32_t AddExtendInfoToReturn(const Credential *credInfo, CJson *json)
872 {
873     const char *extendInfo = StringGet(&credInfo->extendInfo);
874     if (extendInfo == NULL) {
875         LOGE("[CRED#DB]: Failed to get extendInfo from credInfo!");
876         return IS_ERR_NULL_PTR;
877     }
878     if (AddStringToJson(json, FIELD_EXTEND_INFO, extendInfo) != IS_SUCCESS) {
879         LOGE("[CRED#DB]: Failed to add extendInfo to json!");
880         return IS_ERR_JSON_ADD;
881     }
882     return IS_SUCCESS;
883 }
884 
AddPeerUserSpaceIdToReturn(const Credential * credInfo,CJson * json)885 static int32_t AddPeerUserSpaceIdToReturn(const Credential *credInfo, CJson *json)
886 {
887     const char *peerUserSpaceId = StringGet(&credInfo->peerUserSpaceId);
888     if (peerUserSpaceId == NULL) {
889         LOGE("[CRED#DB]: Failed to get peerUserSpaceId from credInfo!");
890         return IS_ERR_NULL_PTR;
891     }
892     if (AddStringToJson(json, FIELD_PEER_USER_SPACE_ID, peerUserSpaceId) != IS_SUCCESS) {
893         LOGE("[CRED#DB]: Failed to add peerUserSpaceId to json!");
894         return IS_ERR_JSON_ADD;
895     }
896     return IS_SUCCESS;
897 }
898 
AddAuthorizedAppListToReturn(const Credential * credInfo,CJson * json)899 static int32_t AddAuthorizedAppListToReturn(const Credential *credInfo, CJson *json)
900 {
901     CJson *arr = CreateJsonArray();
902     if (arr == NULL) {
903         LOGE("Failed to allocate json memory!");
904         return IS_ERR_JSON_CREATE;
905     }
906     uint32_t index = 0;
907     HcString *authorizedApp = NULL;
908     FOR_EACH_HC_VECTOR(credInfo->authorizedAppList, index, authorizedApp) {
909         if (authorizedApp == NULL) {
910             continue;
911         }
912         if (AddStringToArray(arr, StringGet(authorizedApp)) != IS_SUCCESS) {
913             FreeJson(arr);
914             LOGE("[CRED#DB]: Failed to add authorizedApp to json!");
915             return IS_ERR_JSON_ADD;
916         }
917     }
918     if (AddObjToJson(json, FIELD_AUTHORIZED_APP_LIST, arr) != IS_SUCCESS) {
919         FreeJson(arr);
920         LOGE("[CRED#DB]: Failed to add authorizedApp to json!");
921         return IS_ERR_JSON_ADD;
922     }
923     FreeJson(arr);
924     return IS_SUCCESS;
925 }
926 
GenerateReturnCredInfo(const Credential * credential,CJson * returnJson)927 int32_t GenerateReturnCredInfo(const Credential *credential, CJson *returnJson)
928 {
929     int32_t result;
930     if (((result = AddCredIdToReturn(credential, returnJson)) != IS_SUCCESS) ||
931         ((result = AddDeviceIdToReturn(credential, returnJson)) != IS_SUCCESS) ||
932         ((result = AddPeerUserSpaceIdToReturn(credential, returnJson)) != IS_SUCCESS) ||
933         ((result = AddSubjectToReturn(credential, returnJson)) != IS_SUCCESS) ||
934         ((result = AddUserIdToReturn(credential, returnJson)) != IS_SUCCESS) ||
935         ((result = AddIssuerToReturn(credential, returnJson)) != IS_SUCCESS) ||
936         ((result = AddCredTypeToReturn(credential, returnJson)) != IS_SUCCESS) ||
937         ((result = AddKeyFormatToReturn(credential, returnJson)) != IS_SUCCESS) ||
938         ((result = AddAlgorithmTypeToReturn(credential, returnJson)) != IS_SUCCESS) ||
939         ((result = AddProofTypeToReturn(credential, returnJson)) != IS_SUCCESS) ||
940         ((result = AddCredOwnerToReturn(credential, returnJson)) != IS_SUCCESS) ||
941         ((result = AddAuthorizedAppListToReturn(credential, returnJson)) != IS_SUCCESS) ||
942         ((result = AddExtendInfoToReturn(credential, returnJson)) != IS_SUCCESS)) {
943         return result;
944     }
945     return IS_SUCCESS;
946 }
947 
GenerateCredChangedInfo(const Credential * entry,char ** returnCredInfo)948 static int32_t GenerateCredChangedInfo(const Credential *entry, char **returnCredInfo)
949 {
950     CJson *credInfo = CreateJson();
951     if (AddCredTypeToReturn(entry, credInfo) != IS_SUCCESS) {
952         LOGE("add cretype to json failed.");
953         FreeJson(credInfo);
954         return IS_ERR_JSON_ADD;
955     }
956     if (AddDeviceIdToReturn(entry, credInfo) != IS_SUCCESS) {
957         LOGE("add deviceId to json failed.");
958         FreeJson(credInfo);
959         return IS_ERR_JSON_ADD;
960     }
961     if (AddUserIdToReturn(entry, credInfo) != IS_SUCCESS) {
962         LOGE("add userId to json failed.");
963         FreeJson(credInfo);
964         return IS_ERR_JSON_ADD;
965     }
966     if (AddSubjectToReturn(entry, credInfo) != IS_SUCCESS) {
967         LOGE("add userId to json failed.");
968         FreeJson(credInfo);
969         return IS_ERR_JSON_ADD;
970     }
971     char *credInfoJsonStr = PackJsonToString(credInfo);
972     FreeJson(credInfo);
973     if (credInfoJsonStr == NULL) {
974         LOGE("pack json to string failed.");
975         return IS_ERR_ALLOC_MEMORY;
976     }
977     *returnCredInfo = credInfoJsonStr;
978     return IS_SUCCESS;
979 }
980 
981 
PostCredAddMsg(const Credential * entry)982 static void PostCredAddMsg(const Credential *entry)
983 {
984     if (!IsCredListenerSupported()) {
985         return;
986     }
987     char *returnCredInfo = NULL;
988     if (GenerateCredChangedInfo(entry, &returnCredInfo) != IS_SUCCESS) {
989         return;
990     }
991     OnCredAdd(StringGet(&entry->credId), returnCredInfo);
992     FreeJsonString(returnCredInfo);
993 }
994 
PostCredUpdateMsg(const Credential * entry)995 static void PostCredUpdateMsg(const Credential *entry)
996 {
997     if (!IsCredListenerSupported()) {
998         return;
999     }
1000     char *returnCredInfo = NULL;
1001     if (GenerateCredChangedInfo(entry, &returnCredInfo) != IS_SUCCESS) {
1002         return;
1003     }
1004     OnCredUpdate(StringGet(&entry->credId), returnCredInfo);
1005     FreeJsonString(returnCredInfo);
1006 }
1007 
PostCredDeleteMsg(const Credential * entry)1008 static void PostCredDeleteMsg(const Credential *entry)
1009 {
1010     if (!IsCredListenerSupported()) {
1011         return;
1012     }
1013     char *returnCredInfo = NULL;
1014     if (GenerateCredChangedInfo(entry, &returnCredInfo) != IS_SUCCESS) {
1015         return;
1016     }
1017     OnCredDelete(StringGet(&entry->credId), returnCredInfo);
1018     FreeJsonString(returnCredInfo);
1019 }
1020 
AddCredToDb(int32_t osAccountId,const Credential * entry)1021 int32_t AddCredToDb(int32_t osAccountId, const Credential *entry)
1022 {
1023     LOGI("[CRED#DB]: Start to add a cred to database! [OsAccountId]: %" LOG_PUB "d", osAccountId);
1024     if (entry == NULL) {
1025         LOGE("[CRED#DB]: The input entry is NULL!");
1026         return IS_ERR_NULL_PTR;
1027     }
1028     (void)LockHcMutex(g_credMutex);
1029     OsAccountCredInfo *info = GetCredInfoByOsAccountId(osAccountId);
1030     if (info == NULL) {
1031         UnlockHcMutex(g_credMutex);
1032         return IS_ERR_INVALID_PARAMS;
1033     }
1034     Credential *newEntry = DeepCopyCredential(entry);
1035     if (newEntry == NULL) {
1036         UnlockHcMutex(g_credMutex);
1037         return IS_ERR_MEMORY_COPY;
1038     }
1039     QueryCredentialParams params = InitQueryCredentialParams();
1040     params.credId = StringGet(&entry->credId);
1041     Credential **oldEntryPtr = QueryCredentialPtrIfMatch(&info->credentials, &params);
1042     if (oldEntryPtr != NULL) {
1043         DestroyCredential(*oldEntryPtr);
1044         *oldEntryPtr = newEntry;
1045         PostCredUpdateMsg(newEntry);
1046         UnlockHcMutex(g_credMutex);
1047         LOGI("[CRED#DB]: Update an old credential successfully! [credType]: %" LOG_PUB "u", entry->credType);
1048         return IS_SUCCESS;
1049     }
1050     if (info->credentials.pushBackT(&info->credentials, newEntry) == NULL) {
1051         DestroyCredential(newEntry);
1052         UnlockHcMutex(g_credMutex);
1053         LOGE("[CRED#DB]: Failed to push credential to vec!");
1054         return IS_ERR_MEMORY_COPY;
1055     }
1056     PostCredAddMsg(newEntry);
1057     UnlockHcMutex(g_credMutex);
1058     LOGI("[CRED#DB]: Add a credential to database successfully! [credType]: %" LOG_PUB "u", entry->credType);
1059     return IS_SUCCESS;
1060 }
1061 
DelCredential(int32_t osAccountId,const QueryCredentialParams * params)1062 int32_t DelCredential(int32_t osAccountId, const QueryCredentialParams *params)
1063 {
1064     LOGI("[CRED#DB]: Start to delete credential from database! [OsAccountId]: %" LOG_PUB "d", osAccountId);
1065     if (params == NULL) {
1066         LOGE("[CRED#DB]: The input params is NULL!");
1067         return IS_ERR_NULL_PTR;
1068     }
1069     (void)LockHcMutex(g_credMutex);
1070     OsAccountCredInfo *info = GetCredInfoByOsAccountId(osAccountId);
1071     if (info == NULL) {
1072         UnlockHcMutex(g_credMutex);
1073         return IS_ERR_INVALID_PARAMS;
1074     }
1075     int32_t count = 0;
1076     uint32_t index = 0;
1077     Credential **entry = NULL;
1078     while (index < HC_VECTOR_SIZE(&info->credentials)) {
1079         entry = info->credentials.getp(&info->credentials, index);
1080         if ((entry == NULL) || (*entry == NULL) || (!CompareQueryCredentialParams(params, *entry))) {
1081             index++;
1082             continue;
1083         }
1084         Credential *popEntry;
1085         HC_VECTOR_POPELEMENT(&info->credentials, &popEntry, index);
1086         PostCredDeleteMsg(popEntry);
1087         LOGI("[CRED#DB]: Delete a credential from database successfully! [credType]: %" LOG_PUB "u",
1088             popEntry->credType);
1089         DestroyCredential(popEntry);
1090         count++;
1091     }
1092     UnlockHcMutex(g_credMutex);
1093     LOGI("[CRED#DB]: Number of credentials deleted: %" LOG_PUB "d", count);
1094     return IS_SUCCESS;
1095 }
1096 
QueryCredentials(int32_t osAccountId,const QueryCredentialParams * params,CredentialVec * vec)1097 int32_t QueryCredentials(int32_t osAccountId, const QueryCredentialParams *params, CredentialVec *vec)
1098 {
1099     if ((params == NULL) || (vec == NULL)) {
1100         LOGE("[CRED#DB]: The input params or vec is NULL!");
1101         return IS_ERR_NULL_PTR;
1102     }
1103     (void)LockHcMutex(g_credMutex);
1104     OsAccountCredInfo *info = GetCredInfoByOsAccountId(osAccountId);
1105     if (info == NULL) {
1106         UnlockHcMutex(g_credMutex);
1107         return IS_ERR_INVALID_PARAMS;
1108     }
1109     uint32_t index;
1110     Credential **entry;
1111     FOR_EACH_HC_VECTOR(info->credentials, index, entry) {
1112         if (entry != NULL && *entry != NULL && !CompareQueryCredentialParams(params, *entry)) {
1113             continue;
1114         }
1115         Credential *newEntry = DeepCopyCredential(*entry);
1116         if (newEntry == NULL) {
1117             continue;
1118         }
1119         if (vec->pushBackT(vec, newEntry) == NULL) {
1120             LOGE("[CRED#DB]: Failed to push entry to vec!");
1121             DestroyCredential(newEntry);
1122         }
1123     }
1124     UnlockHcMutex(g_credMutex);
1125     return IS_SUCCESS;
1126 }
1127 
SaveOsAccountCredDb(int32_t osAccountId)1128 int32_t SaveOsAccountCredDb(int32_t osAccountId)
1129 {
1130     (void)LockHcMutex(g_credMutex);
1131     OsAccountCredInfo *info = GetCredInfoByOsAccountId(osAccountId);
1132     if (info == NULL) {
1133         UnlockHcMutex(g_credMutex);
1134         return IS_ERR_INVALID_PARAMS;
1135     }
1136     HcParcel parcel = CreateParcel(0, 0);
1137     if (!SaveCredInfoToParcel(info, &parcel)) {
1138         DeleteParcel(&parcel);
1139         UnlockHcMutex(g_credMutex);
1140         return IS_ERR_MEMORY_COPY;
1141     }
1142     char filePath[MAX_DB_PATH_LEN] = { 0 };
1143     if (!GetOsAccountCredInfoPath(osAccountId, filePath, MAX_DB_PATH_LEN)) {
1144         DeleteParcel(&parcel);
1145         UnlockHcMutex(g_credMutex);
1146         return IS_ERR_CONVERT_FAILED;
1147     }
1148     if (!SaveParcelToFile(filePath, &parcel)) {
1149         DeleteParcel(&parcel);
1150         UnlockHcMutex(g_credMutex);
1151         return IS_ERR_MEMORY_COPY;
1152     }
1153     DeleteParcel(&parcel);
1154     UnlockHcMutex(g_credMutex);
1155     LOGI("[CRED#DB]: Save an os account cred database successfully! [Id]: %" LOG_PUB "d", osAccountId);
1156     return IS_SUCCESS;
1157 }
1158 
1159 #ifdef DEV_AUTH_HIVIEW_ENABLE
DumpCredential(int fd,const Credential * credential)1160 static void DumpCredential(int fd, const Credential *credential)
1161 {
1162     dprintf(fd, "||--------------------------Credential--------------------------|                  |\n");
1163     dprintf(fd, "||%-16s = %-43.8s|                  |\n", "credId", StringGet(&credential->credId));
1164     dprintf(fd, "||%-16s = %-43.8s|                  |\n", "deviceId", StringGet(&credential->deviceId));
1165     dprintf(fd, "||%-16s = %-43.8s|                  |\n", "peerUserSpaceId", StringGet(&credential->peerUserSpaceId));
1166     dprintf(fd, "||%-16s = %-43d|                  |\n", "subject", credential->subject);
1167     dprintf(fd, "||%-16s = %-43.8s|                  |\n", "userId", StringGet(&credential->userId));
1168     dprintf(fd, "||%-16s = %-43d|                  |\n", "issuer", credential->issuer);
1169     dprintf(fd, "||%-16s = %-43d|                  |\n", "credType", credential->credType);
1170     dprintf(fd, "||%-16s = %-43d|                  |\n", "keyFormat", credential->keyFormat);
1171     dprintf(fd, "||%-16s = %-43d|                  |\n", "algorithmType", credential->algorithmType);
1172     dprintf(fd, "||%-16s = %-43d|                  |\n", "proofType", credential->proofType);
1173     uint32_t index = 0;
1174     HcString *authorizedApp = NULL;
1175     FOR_EACH_HC_VECTOR(credential->authorizedAppList, index, authorizedApp) {
1176         if (authorizedApp == NULL) {
1177             continue;
1178         }
1179         dprintf(fd, "||%-16s %d = %-43.8s|                  |\n", "app", index, StringGet(authorizedApp));
1180     }
1181     dprintf(fd, "||%-16s = %-43d|                  |\n", "authorizedScope", credential->authorizedScope);
1182     dprintf(fd, "||%-16s = %-43.8s|                  |\n", "credOwner", StringGet(&credential->credOwner));
1183     dprintf(fd, "||%-16s = %-43.8s|                  |\n", "extendInfo", StringGet(&credential->extendInfo));
1184     dprintf(fd, "||--------------------------Credential--------------------------|                  |\n");
1185 }
1186 
DumpDb(int fd,const OsAccountCredInfo * db)1187 static void DumpDb(int fd, const OsAccountCredInfo *db)
1188 {
1189     const CredentialVec *credentials = &db->credentials;
1190     dprintf(fd, "|----------------------------------CRED-DataBase-----------------------------------|\n");
1191     dprintf(fd, "|%-13s = %-66d|\n", "osAccountId", db->osAccountId);
1192     dprintf(fd, "|%-13s = %-66d|\n", "credentialNum", credentials->size(credentials));
1193     uint32_t index;
1194     Credential **credential;
1195     FOR_EACH_HC_VECTOR(*credentials, index, credential) {
1196         if (credential == NULL || *credential == NULL) {
1197             continue;
1198         }
1199         DumpCredential(fd, *credential);
1200     }
1201     dprintf(fd, "|----------------------------------CRED-DataBase-----------------------------------|\n");
1202 }
1203 
LoadAllAccountsData(void)1204 static void LoadAllAccountsData(void)
1205 {
1206     int32_t *accountIds = NULL;
1207     uint32_t size = 0;
1208     int32_t ret = GetAllOsAccountIds(&accountIds, &size);
1209     if (ret != IS_SUCCESS) {
1210         LOGE("[CRED#DB]: Failed to get all os account ids, [res]: %" LOG_PUB "d", ret);
1211         return;
1212     }
1213     for (uint32_t index = 0; index < size; index++) {
1214         LoadDataIfNotLoaded(accountIds[index]);
1215     }
1216     HcFree(accountIds);
1217 }
1218 
DevAuthDataBaseDump(int fd)1219 static void DevAuthDataBaseDump(int fd)
1220 {
1221     if (g_credMutex == NULL) {
1222         LOGE("[CRED#DB]: Init mutex failed");
1223         return;
1224     }
1225     (void)LockHcMutex(g_credMutex);
1226     if (IsOsAccountSupported()) {
1227         LoadAllAccountsData();
1228     }
1229     uint32_t index;
1230     OsAccountCredInfo *info;
1231     FOR_EACH_HC_VECTOR(g_devauthCredDb, index, info) {
1232         if (info == NULL) {
1233             continue;
1234         }
1235         DumpDb(fd, info);
1236     }
1237     UnlockHcMutex(g_credMutex);
1238 }
1239 #endif
1240 
InitCredDatabase(void)1241 int32_t InitCredDatabase(void)
1242 {
1243     if (g_credMutex == NULL) {
1244         g_credMutex = (HcMutex *)HcMalloc(sizeof(HcMutex), 0);
1245         if (g_credMutex == NULL) {
1246             LOGE("[CRED#DB]: Alloc cred databaseMutex failed");
1247             return IS_ERR_ALLOC_MEMORY;
1248         }
1249         if (InitHcMutex(g_credMutex, false) != IS_SUCCESS) {
1250             LOGE("[CRED#DB]: Init mutex failed");
1251             HcFree(g_credMutex);
1252             g_credMutex = NULL;
1253             return IS_ERR_INIT_FAILED;
1254         }
1255     }
1256     g_devauthCredDb = CREATE_HC_VECTOR(DevAuthCredDb);
1257     AddOsAccountEventCallback(CRED_DATA_CALLBACK, OnOsAccountUnlocked, OnOsAccountRemoved);
1258     LoadDevAuthCredDb();
1259     DEV_AUTH_REG_CRED_DUMP_FUNC(DevAuthDataBaseDump);
1260     return IS_SUCCESS;
1261 }
1262 
DestroyCredDatabase(void)1263 void DestroyCredDatabase(void)
1264 {
1265     RemoveOsAccountEventCallback(CRED_DATA_CALLBACK);
1266     (void)LockHcMutex(g_credMutex);
1267     uint32_t index;
1268     OsAccountCredInfo *info;
1269     FOR_EACH_HC_VECTOR(g_devauthCredDb, index, info) {
1270         if (info == NULL) {
1271             continue;
1272         }
1273         ClearCredentialVec(&info->credentials);
1274     }
1275     DESTROY_HC_VECTOR(DevAuthCredDb, &g_devauthCredDb);
1276     UnlockHcMutex(g_credMutex);
1277     DestroyHcMutex(g_credMutex);
1278     HcFree(g_credMutex);
1279     g_credMutex = NULL;
1280 }