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