• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021-2025 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *    http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "group_operation.h"
17 
18 #include "alg_defs.h"
19 #include "broadcast_manager.h"
20 #include "callback_manager.h"
21 #include "common_defs.h"
22 #include "ext_plugin_manager.h"
23 #include "dev_auth_module_manager.h"
24 #include "group_operation_common.h"
25 #include "hc_dev_info.h"
26 #include "hc_log.h"
27 #include "hitrace_adapter.h"
28 #include "os_account_adapter.h"
29 #include "task_manager.h"
30 
31 #include "across_account_group.h"
32 #include "identical_account_group.h"
33 #include "peer_to_peer_group.h"
34 #include "hc_time.h"
35 #include "account_task_manager.h"
36 #include "dev_session_mgr.h"
37 #include "hisysevent_common.h"
38 #include "device_auth_common.h"
39 #include "performance_dumper.h"
40 #include "channel_manager.h"
41 #include "critical_handler.h"
42 #include "string_util.h"
43 
44 #define EXT_PART_APP_ID "ext_part"
45 
46 typedef struct {
47     HcTaskBase base;
48     int64_t requestId;
49 } SoftBusTask;
50 
IsGroupTypeSupported(int groupType)51 static bool IsGroupTypeSupported(int groupType)
52 {
53     if (((groupType == PEER_TO_PEER_GROUP) && (IsPeerToPeerGroupSupported())) ||
54         ((groupType == IDENTICAL_ACCOUNT_GROUP) && (IsIdenticalAccountGroupSupported())) ||
55         ((groupType == ACROSS_ACCOUNT_AUTHORIZE_GROUP) && (IsAcrossAccountGroupSupported()))) {
56         return true;
57     }
58     LOGE("The group type is not supported! [GroupType]: %" LOG_PUB "d", groupType);
59     return false;
60 }
61 
RemoveNoPermissionGroup(int32_t osAccountId,GroupEntryVec * groupEntryVec,const char * appId)62 static void RemoveNoPermissionGroup(int32_t osAccountId, GroupEntryVec *groupEntryVec, const char *appId)
63 {
64     uint32_t index = 0;
65     TrustedGroupEntry **groupEntryPtr = NULL;
66     while (index < groupEntryVec->size(groupEntryVec)) {
67         groupEntryPtr = groupEntryVec->getp(groupEntryVec, index);
68         if (groupEntryPtr == NULL) {
69             LOGW("groupEntryPtr is NULL!");
70             index++;
71             continue;
72         }
73         if (CheckGroupAccessible(osAccountId, StringGet(&(*groupEntryPtr)->id), appId) == HC_SUCCESS) {
74             index++;
75             continue;
76         }
77         LOGI("Remove a group without permission!");
78         TrustedGroupEntry *tempEntry = NULL;
79         HC_VECTOR_POPELEMENT(groupEntryVec, &tempEntry, index);
80         DestroyGroupEntry(tempEntry);
81     }
82 }
83 
GenerateReturnEmptyArrayStr(char ** returnVec)84 static int32_t GenerateReturnEmptyArrayStr(char **returnVec)
85 {
86     CJson *json = CreateJsonArray();
87     if (json == NULL) {
88         LOGE("Failed to allocate json memory!");
89         return HC_ERR_JSON_FAIL;
90     }
91     *returnVec = PackJsonToString(json);
92     FreeJson(json);
93     if (*returnVec == NULL) {
94         LOGE("Failed to convert json to string!");
95         return HC_ERR_JSON_FAIL;
96     }
97     return HC_SUCCESS;
98 }
99 
GenerateReturnGroupVec(GroupEntryVec * groupInfoVec,char ** returnGroupVec,uint32_t * groupNum)100 static int32_t GenerateReturnGroupVec(GroupEntryVec *groupInfoVec, char **returnGroupVec, uint32_t *groupNum)
101 {
102     if (HC_VECTOR_SIZE(groupInfoVec) == 0) {
103         *groupNum = 0;
104         return GenerateReturnEmptyArrayStr(returnGroupVec);
105     }
106 
107     CJson *json = CreateJsonArray();
108     if (json == NULL) {
109         LOGE("Failed to allocate json memory!");
110         return HC_ERR_JSON_FAIL;
111     }
112     uint32_t groupCount = 0;
113     uint32_t index;
114     TrustedGroupEntry **groupInfoPtr = NULL;
115     FOR_EACH_HC_VECTOR(*groupInfoVec, index, groupInfoPtr) {
116         TrustedGroupEntry *groupInfo = *groupInfoPtr;
117         CJson *groupInfoJson = CreateJson();
118         if (groupInfoJson == NULL) {
119             LOGE("Failed to allocate groupInfoJson memory!");
120             FreeJson(json);
121             return HC_ERR_ALLOC_MEMORY;
122         }
123         int32_t result = GenerateReturnGroupInfo(groupInfo, groupInfoJson);
124         if (result != HC_SUCCESS) {
125             FreeJson(groupInfoJson);
126             FreeJson(json);
127             return result;
128         }
129         if (AddObjToArray(json, groupInfoJson) != HC_SUCCESS) {
130             LOGE("Failed to add groupInfoStr to returnGroupVec!");
131             FreeJson(groupInfoJson);
132             FreeJson(json);
133             return HC_ERR_JSON_FAIL;
134         }
135         ++groupCount;
136     }
137     *returnGroupVec = PackJsonToString(json);
138     FreeJson(json);
139     if ((*returnGroupVec) == NULL) {
140         LOGE("Failed to convert json to string!");
141         return HC_ERR_JSON_FAIL;
142     }
143     *groupNum = groupCount;
144     return HC_SUCCESS;
145 }
146 
GenerateReturnDeviceVec(DeviceEntryVec * devInfoVec,char ** returnDevInfoVec,uint32_t * deviceNum)147 static int32_t GenerateReturnDeviceVec(DeviceEntryVec *devInfoVec, char **returnDevInfoVec, uint32_t *deviceNum)
148 {
149     CJson *json = CreateJsonArray();
150     if (json == NULL) {
151         LOGE("Failed to allocate json memory!");
152         return HC_ERR_JSON_FAIL;
153     }
154     uint32_t devCount = 0;
155     uint32_t index;
156     TrustedDeviceEntry **devInfoPtr = NULL;
157     FOR_EACH_HC_VECTOR(*devInfoVec, index, devInfoPtr) {
158         TrustedDeviceEntry *devInfo = (TrustedDeviceEntry*)(*devInfoPtr);
159         CJson *devInfoJson = CreateJson();
160         if (devInfoJson == NULL) {
161             LOGE("Failed to allocate devInfoJson memory!");
162             FreeJson(json);
163             return HC_ERR_ALLOC_MEMORY;
164         }
165         int32_t result = GenerateReturnDevInfo(devInfo, devInfoJson);
166         if (result != HC_SUCCESS) {
167             FreeJson(devInfoJson);
168             FreeJson(json);
169             return result;
170         }
171         if (AddObjToArray(json, devInfoJson) != HC_SUCCESS) {
172             LOGE("Failed to add devInfoStr to returnGroupVec!");
173             FreeJson(devInfoJson);
174             FreeJson(json);
175             return HC_ERR_JSON_FAIL;
176         }
177         ++devCount;
178     }
179     *returnDevInfoVec = PackJsonToString(json);
180     FreeJson(json);
181     if ((*returnDevInfoVec) == NULL) {
182         LOGE("Failed to convert json to string!");
183         return HC_ERR_JSON_FAIL;
184     }
185     *deviceNum = devCount;
186     return HC_SUCCESS;
187 }
188 
IsQueryParamsValid(int groupType,const char * groupId,const char * groupName,const char * groupOwner)189 static bool IsQueryParamsValid(int groupType, const char *groupId, const char *groupName, const char *groupOwner)
190 {
191     if ((groupType == ALL_GROUP) && (groupId == NULL) && (groupName == NULL) && (groupOwner == NULL)) {
192         return false;
193     } else {
194         return true;
195     }
196 }
197 
QueryRelatedGroupsForGetPk(int32_t osAccountId,const char * udid,GroupEntryVec * returnGroupEntryVec)198 static int32_t QueryRelatedGroupsForGetPk(int32_t osAccountId, const char *udid, GroupEntryVec *returnGroupEntryVec)
199 {
200     DeviceEntryVec deviceEntryVec = CreateDeviceEntryVec();
201     QueryDeviceParams params = InitQueryDeviceParams();
202     params.udid = udid;
203     int32_t result = QueryDevices(osAccountId, &params, &deviceEntryVec);
204     if (result != HC_SUCCESS) {
205         LOGE("Failed to query trusted devices!");
206         ClearDeviceEntryVec(&deviceEntryVec);
207         return result;
208     }
209     uint32_t index;
210     TrustedDeviceEntry **entry = NULL;
211     FOR_EACH_HC_VECTOR(deviceEntryVec, index, entry) {
212         /* In order to improve availability, even if there is an error, it does not terminate. */
213         TrustedGroupEntry *groupEntry = GetGroupEntryById(osAccountId, StringGet(&(*entry)->groupId));
214         if (groupEntry == NULL) {
215             LOGW("An exception occurred! Device found, but group not found. There may be dirty data.");
216             continue;
217         }
218         if (groupEntry->visibility != GROUP_VISIBILITY_PUBLIC) {
219             DestroyGroupEntry(groupEntry);
220             continue;
221         }
222         if (returnGroupEntryVec->pushBackT(returnGroupEntryVec, groupEntry) == NULL) {
223             LOGW("An exception occurred! Failed to push groupEntry to returnGroupEntryVec!");
224             DestroyGroupEntry(groupEntry);
225         }
226     }
227     ClearDeviceEntryVec(&deviceEntryVec);
228     return HC_SUCCESS;
229 }
230 
GetPkByParams(int32_t osAccountId,const char * groupId,const TrustedDeviceEntry * deviceEntry,char * returnPkHexStr,int32_t returnPkHexStrLen)231 static int32_t GetPkByParams(int32_t osAccountId, const char *groupId, const TrustedDeviceEntry *deviceEntry,
232     char *returnPkHexStr, int32_t returnPkHexStrLen)
233 {
234     /* Use the DeviceGroupManager package name. */
235     const char *appId = GROUP_MANAGER_PACKAGE_NAME;
236     int userType = deviceEntry->devType;
237     const char *authId = StringGet(&deviceEntry->authId);
238     Uint8Buff authIdBuff = { 0, 0 };
239     authIdBuff.length = HcStrlen(authId);
240     authIdBuff.val = (uint8_t *)HcMalloc(authIdBuff.length, 0);
241     if (authIdBuff.val == NULL) {
242         LOGE("Failed to allocate authIdBuff memory!");
243         return HC_ERR_ALLOC_MEMORY;
244     }
245     if (memcpy_s(authIdBuff.val, authIdBuff.length, authId, authIdBuff.length) != HC_SUCCESS) {
246         LOGE("Failed to copy authId!");
247         HcFree(authIdBuff.val);
248         return HC_ERR_MEMORY_COPY;
249     }
250     uint8_t returnPkBytes[PUBLIC_KEY_MAX_LENGTH] = { 0 };
251     Uint8Buff returnPkBuff = { 0, 0 };
252     returnPkBuff.length = PUBLIC_KEY_MAX_LENGTH;
253     returnPkBuff.val = returnPkBytes;
254     AuthModuleParams authParams = {
255         .osAccountId = osAccountId,
256         .pkgName = appId,
257         .serviceType = groupId,
258         .authId = &authIdBuff,
259         .userType = userType
260     };
261     int32_t res = GetPublicKey(DAS_MODULE, &authParams, &returnPkBuff);
262     HcFree(authIdBuff.val);
263     if (res != HC_SUCCESS) {
264         return res;
265     }
266     res = GetHashResult(returnPkBuff.val, returnPkBuff.length, returnPkHexStr, returnPkHexStrLen);
267     if (res != HC_SUCCESS) {
268         LOGE("Failed to get hash for pk!");
269         return HC_ERR_HASH_FAIL;
270     }
271     return HC_SUCCESS;
272 }
273 
GeneratePkInfo(int32_t osAccountId,const char * queryUdid,const char * groupId,CJson * pkInfo)274 static int32_t GeneratePkInfo(int32_t osAccountId, const char *queryUdid, const char *groupId, CJson *pkInfo)
275 {
276     TrustedDeviceEntry *deviceEntry = GetTrustedDeviceEntryById(osAccountId, queryUdid, true, groupId);
277     if (deviceEntry == NULL) {
278         LOGE("The trusted device is not found!");
279         return HC_ERR_DEVICE_NOT_EXIST;
280     }
281     char returnPkHexStr[SHA256_LEN * BYTE_TO_HEX_OPER_LENGTH + 1] = { 0 };
282     int32_t result = GetPkByParams(osAccountId, groupId, deviceEntry, returnPkHexStr, sizeof(returnPkHexStr));
283     DestroyDeviceEntry(deviceEntry);
284     if (result != HC_SUCCESS) {
285         return result;
286     }
287     if (AddStringToJson(pkInfo, FIELD_GROUP_ID, groupId) != HC_SUCCESS) {
288         LOGE("Failed to add groupId to pkInfo!");
289         return HC_ERR_JSON_ADD;
290     }
291     if (AddStringToJson(pkInfo, FIELD_PUBLIC_KEY, returnPkHexStr) != HC_SUCCESS) {
292         LOGE("Failed to add publicKey to pkInfo!");
293         return HC_ERR_JSON_ADD;
294     }
295     return HC_SUCCESS;
296 }
297 
AddAllPkInfoToList(int32_t osAccountId,const char * queryUdid,const GroupEntryVec * groupEntryVec,CJson * pkInfoList)298 static void AddAllPkInfoToList(int32_t osAccountId, const char *queryUdid, const GroupEntryVec *groupEntryVec,
299     CJson *pkInfoList)
300 {
301     uint32_t index;
302     TrustedGroupEntry **entry = NULL;
303     FOR_EACH_HC_VECTOR(*groupEntryVec, index, entry) {
304         /* Account related group cannot export public key. */
305         if (IsAccountRelatedGroup((*entry)->type)) {
306             continue;
307         }
308         const char *groupId = StringGet(&((*entry)->id));
309         CJson *pkInfo = CreateJson();
310         if (pkInfo == NULL) {
311             LOGE("Failed to create json!");
312             continue;
313         }
314         int32_t res = GeneratePkInfo(osAccountId, queryUdid, groupId, pkInfo);
315         if (res != HC_SUCCESS) {
316             FreeJson(pkInfo);
317             continue;
318         }
319         if (AddObjToArray(pkInfoList, pkInfo) != HC_SUCCESS) {
320             LOGE("Failed to add pkInfo to pkInfoList!");
321             FreeJson(pkInfo);
322         }
323     }
324 }
325 
IsOnlyAccountRelatedGroups(const GroupEntryVec * groupEntryVec)326 static bool IsOnlyAccountRelatedGroups(const GroupEntryVec *groupEntryVec)
327 {
328     if (groupEntryVec->size(groupEntryVec) == 0) {
329         LOGW("No groups available.");
330         return false;
331     }
332     uint32_t index;
333     TrustedGroupEntry **entry = NULL;
334     FOR_EACH_HC_VECTOR(*groupEntryVec, index, entry) {
335         if (!IsAccountRelatedGroup((*entry)->type)) {
336             return false;
337         }
338     }
339     return true;
340 }
341 
GeneratePkInfoList(int32_t osAccountId,const CJson * params,CJson * pkInfoList)342 static int32_t GeneratePkInfoList(int32_t osAccountId, const CJson *params, CJson *pkInfoList)
343 {
344     const char *udid = GetStringFromJson(params, FIELD_UDID);
345     if (udid == NULL) {
346         LOGE("Failed to get udid from params!");
347         return HC_ERR_JSON_GET;
348     }
349     bool isSelfPk = false;
350     if (GetBoolFromJson(params, FIELD_IS_SELF_PK, &isSelfPk) != HC_SUCCESS) {
351         LOGE("Failed to get isSelfPk from json!");
352         return HC_ERR_JSON_GET;
353     }
354     GroupEntryVec groupEntryVec = CreateGroupEntryVec();
355     int32_t res = QueryRelatedGroupsForGetPk(osAccountId, udid, &groupEntryVec);
356     if (res != HC_SUCCESS) {
357         ClearGroupEntryVec(&groupEntryVec);
358         return res;
359     }
360     /**
361      * Specification requirements:
362      * when there are only account related groups in the group list of public key information to be queried,
363      * a special error code needs to be returned.
364      */
365     if (IsOnlyAccountRelatedGroups(&groupEntryVec)) {
366         LOGE("There are only account related groups in the group list.");
367         ClearGroupEntryVec(&groupEntryVec);
368         return HC_ERR_ONLY_ACCOUNT_RELATED;
369     }
370     const char *queryUdid = NULL;
371     char selfUdid[INPUT_UDID_LEN] = { 0 };
372     if (isSelfPk) {
373         res = HcGetUdid((uint8_t *)selfUdid, INPUT_UDID_LEN);
374         if (res != HC_SUCCESS) {
375             LOGE("Failed to get local udid! res: %" LOG_PUB "d", res);
376             ClearGroupEntryVec(&groupEntryVec);
377             return HC_ERR_DB;
378         }
379         queryUdid = selfUdid;
380     } else {
381         queryUdid = udid;
382     }
383     AddAllPkInfoToList(osAccountId, queryUdid, &groupEntryVec, pkInfoList);
384     ClearGroupEntryVec(&groupEntryVec);
385     return HC_SUCCESS;
386 }
387 
GetGroupInstance(int32_t groupType)388 static BaseGroup *GetGroupInstance(int32_t groupType)
389 {
390     if (!IsGroupTypeSupported(groupType)) {
391         return NULL;
392     }
393     BaseGroup *instance = NULL;
394     if (groupType == PEER_TO_PEER_GROUP) {
395         instance = GetPeerToPeerGroupInstance();
396     } else if (groupType == IDENTICAL_ACCOUNT_GROUP) {
397         instance = GetIdenticalAccountGroupInstance();
398     } else if (groupType == ACROSS_ACCOUNT_AUTHORIZE_GROUP) {
399         instance = GetAcrossAccountGroupInstance();
400     }
401     return instance;
402 }
403 
CreateGroup(int32_t osAccountId,CJson * jsonParams,char ** returnJsonStr)404 static int32_t CreateGroup(int32_t osAccountId, CJson *jsonParams, char **returnJsonStr)
405 {
406     int32_t groupType = PEER_TO_PEER_GROUP;
407     if (GetIntFromJson(jsonParams, FIELD_GROUP_TYPE, &groupType) != HC_SUCCESS) {
408         LOGE("Failed to get groupType from jsonParams!");
409         return HC_ERR_JSON_GET;
410     }
411     BaseGroup *instance = GetGroupInstance(groupType);
412     if (instance == NULL) {
413         LOGE("The group instance is NULL or its function ptr is NULL!");
414         return HC_ERR_NULL_PTR;
415     }
416     return instance->createGroup(osAccountId, jsonParams, returnJsonStr);
417 }
418 
DeleteGroup(int32_t osAccountId,CJson * jsonParams,char ** returnJsonStr)419 static int32_t DeleteGroup(int32_t osAccountId, CJson *jsonParams, char **returnJsonStr)
420 {
421     int32_t result;
422     const char *groupId = NULL;
423     const char *appId = NULL;
424     uint32_t groupType = PEER_TO_PEER_GROUP;
425     if (((result = GetGroupIdFromJson(jsonParams, &groupId)) != HC_SUCCESS) ||
426         ((result = GetAppIdFromJson(jsonParams, &appId)) != HC_SUCCESS) ||
427         ((result = CheckGroupExist(osAccountId, groupId)) != HC_SUCCESS) ||
428         ((result = GetGroupTypeFromDb(osAccountId, groupId, &groupType)) != HC_SUCCESS) ||
429         ((result = CheckPermForGroup(osAccountId, GROUP_DISBAND, appId, groupId)) != HC_SUCCESS)) {
430         return result;
431     }
432     BaseGroup *instance = GetGroupInstance(groupType);
433     if (instance == NULL) {
434         LOGE("The group instance is NULL or its function ptr is NULL!");
435         return HC_ERR_NULL_PTR;
436     }
437     return instance->deleteGroup(osAccountId, jsonParams, returnJsonStr);
438 }
439 
DeleteMemberFromPeerToPeerGroup(int32_t osAccountId,int64_t requestId,CJson * jsonParams,const DeviceAuthCallback * callback)440 static int32_t DeleteMemberFromPeerToPeerGroup(int32_t osAccountId, int64_t requestId, CJson *jsonParams,
441     const DeviceAuthCallback *callback)
442 {
443     if (!IsPeerToPeerGroupSupported()) {
444         LOGE("Peer to peer group is not supported!");
445         return HC_ERR_NOT_SUPPORT;
446     }
447     PeerToPeerGroup *instance = (PeerToPeerGroup *)GetPeerToPeerGroupInstance();
448     return instance->deleteMember(osAccountId, requestId, jsonParams, callback);
449 }
450 
DoCreateGroup(HcTaskBase * baseTask)451 static void DoCreateGroup(HcTaskBase *baseTask)
452 {
453     GroupManagerTask *task = (GroupManagerTask *)baseTask;
454     SET_LOG_MODE(TRACE_MODE);
455     SET_TRACE_ID(task->reqId);
456     LOGI("[Start]: DoCreateGroup! [ReqId]: %" LOG_PUB PRId64, task->reqId);
457     char *returnJsonStr = NULL;
458     int32_t result = CreateGroup(task->osAccountId, task->params, &returnJsonStr);
459     if (result != HC_SUCCESS) {
460         ProcessErrorCallback(task->reqId, GROUP_CREATE, result, NULL, task->cb);
461     } else {
462         ProcessFinishCallback(task->reqId, GROUP_CREATE, returnJsonStr, task->cb);
463         FreeJsonString(returnJsonStr);
464     }
465     DecreaseCriticalCnt();
466 }
467 
DoDeleteGroup(HcTaskBase * baseTask)468 static void DoDeleteGroup(HcTaskBase *baseTask)
469 {
470     GroupManagerTask *task = (GroupManagerTask *)baseTask;
471     SET_LOG_MODE(TRACE_MODE);
472     SET_TRACE_ID(task->reqId);
473     LOGI("[Start]: DoDeleteGroup! [ReqId]: %" LOG_PUB PRId64, task->reqId);
474     char *returnJsonStr = NULL;
475     int32_t result = DeleteGroup(task->osAccountId, task->params, &returnJsonStr);
476     if (result != HC_SUCCESS) {
477         ProcessErrorCallback(task->reqId, GROUP_DISBAND, result, NULL, task->cb);
478     } else {
479         ProcessFinishCallback(task->reqId, GROUP_DISBAND, returnJsonStr, task->cb);
480         FreeJsonString(returnJsonStr);
481     }
482     DecreaseCriticalCnt();
483 }
484 
DoDeleteMember(HcTaskBase * baseTask)485 static void DoDeleteMember(HcTaskBase *baseTask)
486 {
487     GroupManagerTask *task = (GroupManagerTask *)baseTask;
488     SET_LOG_MODE(TRACE_MODE);
489     SET_TRACE_ID(task->reqId);
490     LOGI("[Start]: DoDeleteMember! [ReqId]: %" LOG_PUB PRId64, task->reqId);
491     (void)DeleteMemberFromPeerToPeerGroup(task->osAccountId, task->reqId, task->params, task->cb);
492     DecreaseCriticalCnt();
493 }
494 
CreateGroupInner(int32_t osAccountId,int64_t requestId,const char * appId,const char * createParams)495 static int32_t CreateGroupInner(int32_t osAccountId, int64_t requestId, const char *appId, const char *createParams)
496 {
497     osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
498     if ((appId == NULL) || (createParams == NULL) || (osAccountId == INVALID_OS_ACCOUNT)) {
499         LOGE("Invalid input parameters!");
500         return HC_ERR_INVALID_PARAMS;
501     }
502     if (!IsOsAccountUnlocked(osAccountId)) {
503         LOGE("Os account is not unlocked!");
504         return HC_ERR_OS_ACCOUNT_NOT_UNLOCKED;
505     }
506     LOGI("[Start]: [AppId]: %" LOG_PUB "s, [ReqId]: %" LOG_PUB PRId64, appId, requestId);
507     CJson *params = CreateJsonFromString(createParams);
508     if (params == NULL) {
509         LOGE("Failed to create json from string!");
510         return HC_ERR_JSON_FAIL;
511     }
512     int32_t result = AddBindParamsToJson(GROUP_CREATE, requestId, appId, params);
513     if (result != HC_SUCCESS) {
514         FreeJson(params);
515         return result;
516     }
517     if (InitAndPushGMTask(osAccountId, GROUP_CREATE, requestId, params, DoCreateGroup) != HC_SUCCESS) {
518         FreeJson(params);
519         return HC_ERR_INIT_TASK_FAIL;
520     }
521     LOGI("[End]: create group successfully!");
522     return HC_SUCCESS;
523 }
524 
525 #ifdef DEV_AUTH_HIVIEW_ENABLE
BuildCallEventData(const char * appId,const char * funcName,const int32_t osAccountId,const int32_t callResult,const int32_t processCode)526 static DevAuthCallEvent BuildCallEventData(const char *appId, const char *funcName, const int32_t osAccountId,
527     const int32_t callResult, const int32_t processCode)
528 {
529     DevAuthCallEvent eventData;
530     eventData.appId = appId;
531     eventData.funcName = funcName;
532     eventData.osAccountId = osAccountId;
533     eventData.callResult = callResult;
534     eventData.processCode = processCode;
535     eventData.credType = DEFAULT_CRED_TYPE;
536     eventData.groupType = DEFAULT_GROUP_TYPE;
537     eventData.executionTime = DEFAULT_EXECUTION_TIME;
538     eventData.extInfo = DEFAULT_EXT_INFO;
539     return eventData;
540 }
541 #endif
542 
543 #ifdef DEV_AUTH_HIVIEW_ENABLE
GetGroupTypeFromParams(const char * createParams)544 static int32_t GetGroupTypeFromParams(const char *createParams)
545 {
546     CJson *params = CreateJsonFromString(createParams);
547     if (params == NULL) {
548         LOGE("Failed to create json from string!");
549         return DEFAULT_GROUP_TYPE;
550     }
551     int32_t groupType = DEFAULT_GROUP_TYPE;
552     (void)GetIntFromJson(params, FIELD_GROUP_TYPE, &groupType);
553     FreeJson(params);
554     return groupType;
555 }
556 #endif
557 
RequestCreateGroup(int32_t osAccountId,int64_t requestId,const char * appId,const char * createParams)558 static int32_t RequestCreateGroup(int32_t osAccountId, int64_t requestId, const char *appId, const char *createParams)
559 {
560     int64_t startTime = HcGetCurTimeInMillis();
561     int32_t res = CreateGroupInner(osAccountId, requestId, appId, createParams);
562     int64_t endTime = HcGetCurTimeInMillis();
563     int64_t elapsedTime = endTime - startTime;
564     LOGI("CreateGroup elapsed time:  %" LOG_PUB PRId64 " milliseconds, [OsAccountId]: %" LOG_PUB "d",
565         elapsedTime, osAccountId);
566     DEV_AUTH_REPORT_UE_CALL_EVENT_BY_PARAMS(osAccountId, createParams, appId, CREATE_GROUP_EVENT);
567 #ifdef DEV_AUTH_HIVIEW_ENABLE
568     DevAuthCallEvent eventData = BuildCallEventData(appId, CREATE_GROUP_EVENT, osAccountId,
569         res, PROCESS_CREATE_GROUP);
570     eventData.groupType = GetGroupTypeFromParams(createParams);
571     eventData.executionTime = elapsedTime;
572     DEV_AUTH_REPORT_CALL_EVENT(eventData);
573 #endif
574     return res;
575 }
576 
DeleteGroupInner(int32_t osAccountId,int64_t requestId,const char * appId,const char * disbandParams)577 static int32_t DeleteGroupInner(int32_t osAccountId, int64_t requestId, const char *appId, const char *disbandParams)
578 {
579     osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
580     if ((appId == NULL) || (disbandParams == NULL) || (osAccountId == INVALID_OS_ACCOUNT)) {
581         LOGE("Invalid input parameters!");
582         return HC_ERR_INVALID_PARAMS;
583     }
584     if (!IsOsAccountUnlocked(osAccountId)) {
585         LOGE("Os account is not unlocked!");
586         return HC_ERR_OS_ACCOUNT_NOT_UNLOCKED;
587     }
588     LOGI("[Start]: [AppId]: %" LOG_PUB "s, [ReqId]: %" LOG_PUB PRId64, appId, requestId);
589     CJson *params = CreateJsonFromString(disbandParams);
590     if (params == NULL) {
591         LOGE("Failed to create json from string!");
592         return HC_ERR_JSON_FAIL;
593     }
594     int32_t result = AddBindParamsToJson(GROUP_DISBAND, requestId, appId, params);
595     if (result != HC_SUCCESS) {
596         FreeJson(params);
597         return result;
598     }
599     if (InitAndPushGMTask(osAccountId, GROUP_DISBAND, requestId, params, DoDeleteGroup) != HC_SUCCESS) {
600         FreeJson(params);
601         return HC_ERR_INIT_TASK_FAIL;
602     }
603     LOGI("[End]: delete group successfully!");
604     return HC_SUCCESS;
605 }
606 
RequestDeleteGroup(int32_t osAccountId,int64_t requestId,const char * appId,const char * disbandParams)607 static int32_t RequestDeleteGroup(int32_t osAccountId, int64_t requestId, const char *appId, const char *disbandParams)
608 {
609     int64_t startTime = HcGetCurTimeInMillis();
610     int32_t res = DeleteGroupInner(osAccountId, requestId, appId, disbandParams);
611     int64_t endTime = HcGetCurTimeInMillis();
612     int64_t elapsedTime = endTime - startTime;
613     LOGI("DeleteGroup elapsed time:  %" LOG_PUB PRId64 " milliseconds", elapsedTime);
614     DEV_AUTH_REPORT_UE_CALL_EVENT_BY_PARAMS(osAccountId, disbandParams, appId, DELETE_GROUP_EVENT);
615 #ifdef DEV_AUTH_HIVIEW_ENABLE
616     DevAuthCallEvent eventData = BuildCallEventData(appId, DELETE_GROUP_EVENT, osAccountId,
617         res, PROCESS_DELETE_GROUP);
618     eventData.executionTime = elapsedTime;
619     DEV_AUTH_REPORT_CALL_EVENT(eventData);
620 #endif
621     return res;
622 }
623 
DeleteMemberFromGroupInner(int32_t osAccountId,int64_t requestId,const char * appId,const char * deleteParams)624 static int32_t DeleteMemberFromGroupInner(int32_t osAccountId, int64_t requestId, const char *appId,
625     const char *deleteParams)
626 {
627     osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
628     if ((appId == NULL) || (deleteParams == NULL) || (osAccountId == INVALID_OS_ACCOUNT)) {
629         LOGE("Input parameters appId, deleteParams or osAccountId invliad!");
630         return HC_ERR_INVALID_PARAMS;
631     }
632     if (!IsOsAccountUnlocked(osAccountId)) {
633         LOGE("Os account is not unlocked!");
634         return HC_ERR_OS_ACCOUNT_NOT_UNLOCKED;
635     }
636     LOGI("[Start]: [AppId]: %" LOG_PUB "s, [ReqId]: %" LOG_PUB PRId64, appId, requestId);
637     CJson *params = CreateJsonFromString(deleteParams);
638     if (params == NULL) {
639         LOGE("Failed to create json from string!");
640         return HC_ERR_JSON_FAIL;
641     }
642     int32_t result = AddBindParamsToJson(MEMBER_DELETE, requestId, appId, params);
643     if (result != HC_SUCCESS) {
644         FreeJson(params);
645         return result;
646     }
647     if (InitAndPushGMTask(osAccountId, MEMBER_DELETE, requestId, params, DoDeleteMember) != HC_SUCCESS) {
648         FreeJson(params);
649         return HC_ERR_INIT_TASK_FAIL;
650     }
651     LOGI("[End]: delete member from group successully!");
652     return HC_SUCCESS;
653 }
654 
GetOpCodeFromContext(const CJson * context)655 static int32_t GetOpCodeFromContext(const CJson *context)
656 {
657     bool isAdmin = true;
658     (void)GetBoolFromJson(context, FIELD_IS_ADMIN, &isAdmin);
659     return isAdmin ? MEMBER_INVITE : MEMBER_JOIN;
660 }
661 
AddClientReqInfoToContext(int32_t osAccountId,int64_t requestId,const char * appId,CJson * context)662 static int32_t AddClientReqInfoToContext(int32_t osAccountId, int64_t requestId, const char *appId, CJson *context)
663 {
664     const char *groupId = GetStringFromJson(context, FIELD_GROUP_ID);
665     if (groupId == NULL) {
666         LOGE("Failed to get groupId from context json.");
667         return HC_ERR_JSON_GET;
668     }
669     if (AddBoolToJson(context, FIELD_IS_BIND, true) != HC_SUCCESS) {
670         LOGE("Failed to add isBind to context json.");
671         return HC_ERR_JSON_ADD;
672     }
673     if (AddBoolToJson(context, FIELD_IS_CLIENT, true) != HC_SUCCESS) {
674         LOGE("Failed to add isClient to context json.");
675         return HC_ERR_JSON_ADD;
676     }
677     if (AddIntToJson(context, FIELD_OS_ACCOUNT_ID, osAccountId) != HC_SUCCESS) {
678         LOGE("Failed to add osAccountId to context json.");
679         return HC_ERR_JSON_ADD;
680     }
681     if (AddInt64StringToJson(context, FIELD_REQUEST_ID, requestId) != HC_SUCCESS) {
682         LOGE("Failed to add requestId to context json.");
683         return HC_ERR_JSON_ADD;
684     }
685     if (AddStringToJson(context, FIELD_APP_ID, appId) != HC_SUCCESS) {
686         LOGE("Failed to add appId to context json.");
687         return HC_ERR_JSON_ADD;
688     }
689     int32_t opCode = GetOpCodeFromContext(context);
690     if (AddIntToJson(context, FIELD_OPERATION_CODE, opCode) != HC_SUCCESS) {
691         LOGE("Failed to add operationCode to context json.");
692         return HC_ERR_JSON_ADD;
693     }
694     if (opCode == MEMBER_JOIN) {
695         return AddDevInfoToContextByInput(context);
696     }
697     int32_t res = AddDevInfoToContextByDb(groupId, context);
698     if (res != HC_SUCCESS) {
699         return res;
700     }
701     return AddGroupInfoToContextByDb(groupId, context);
702 }
703 
704 #ifdef ENABLE_P2P_BIND_LITE_PROTOCOL_CHECK
705 // If bind with iso short pin, groupVisibility must be private
CheckGroupVisibility(const CJson * context)706 static int32_t CheckGroupVisibility(const CJson *context)
707 {
708     int32_t osAccountId = INVALID_OS_ACCOUNT;
709     if (GetIntFromJson(context, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) {
710         LOGE("Failed to get osAccountId!");
711         return HC_ERR_JSON_GET;
712     }
713     const char *groupId = GetStringFromJson(context, FIELD_GROUP_ID);
714     if (groupId == NULL) {
715         LOGE("Failed to get groupId!");
716         return HC_ERR_JSON_GET;
717     }
718     const char *appId = GetStringFromJson(context, FIELD_APP_ID);
719     if (appId == NULL) {
720         LOGE("Failed to get appId!");
721         return HC_ERR_JSON_GET;
722     }
723     TrustedGroupEntry *entry = GetGroupEntryById(osAccountId, groupId);
724     if (entry == NULL) {
725         LOGE("Failed to get group entry!");
726         return HC_ERR_GROUP_NOT_EXIST;
727     }
728     int32_t res = CheckUpgradeIdentity(entry->upgradeFlag, appId, NULL);
729     if (res == HC_SUCCESS) {
730         LOGI("Group is from upgrade, no need to check visibility.");
731         DestroyGroupEntry(entry);
732         return HC_SUCCESS;
733     }
734     if (entry->visibility != GROUP_VISIBILITY_PRIVATE) {
735         LOGE("Group is not private, can not bind old version wearable device!");
736         DestroyGroupEntry(entry);
737         return HC_ERR_INVALID_PARAMS;
738     }
739     DestroyGroupEntry(entry);
740     return HC_SUCCESS;
741 }
742 #endif
743 
744 #ifdef ENABLE_P2P_BIND_LITE_PROTOCOL_CHECK
CheckBindParams(const CJson * context,bool isClient)745 static int32_t CheckBindParams(const CJson *context, bool isClient)
746 {
747     int32_t opCode;
748     if (GetIntFromJson(context, FIELD_OPERATION_CODE, &opCode) != HC_SUCCESS) {
749         LOGE("Failed to get operation code!");
750         return HC_ERR_JSON_GET;
751     }
752     if ((isClient && opCode == MEMBER_INVITE) || (!isClient && opCode == MEMBER_JOIN)) {
753         int32_t protocolExpandVal = INVALID_PROTOCOL_EXPAND_VALUE;
754         (void)GetIntFromJson(context, FIELD_PROTOCOL_EXPAND, &protocolExpandVal);
755         if (protocolExpandVal == LITE_PROTOCOL_COMPATIBILITY_MODE) {
756             return CheckGroupVisibility(context);
757         }
758     }
759     return HC_SUCCESS;
760 }
761 #endif
762 
BuildClientBindContext(int32_t osAccountId,int64_t requestId,const char * appId,const DeviceAuthCallback * callback,CJson * context)763 static int32_t BuildClientBindContext(int32_t osAccountId, int64_t requestId, const char *appId,
764     const DeviceAuthCallback *callback, CJson *context)
765 {
766     int32_t res = AddClientReqInfoToContext(osAccountId, requestId, appId, context);
767     if (res != HC_SUCCESS) {
768         return res;
769     }
770     ChannelType channelType = GetChannelType(callback, context);
771     int64_t channelId;
772     res = OpenChannel(channelType, context, requestId, &channelId);
773     if (res != HC_SUCCESS) {
774         LOGE("open channel fail.");
775         return res;
776     }
777     return AddChannelInfoToContext(channelType, channelId, context);
778 }
779 
StartClientBindSession(int32_t osAccountId,int64_t requestId,const char * appId,const char * contextParams,const DeviceAuthCallback * callback)780 static int32_t StartClientBindSession(int32_t osAccountId, int64_t requestId, const char *appId,
781     const char *contextParams, const DeviceAuthCallback *callback)
782 {
783     CJson *context = CreateJsonFromString(contextParams);
784     if (context == NULL) {
785         LOGE("Failed to create json from string!");
786         return HC_ERR_JSON_FAIL;
787     }
788     int32_t res = BuildClientBindContext(osAccountId, requestId, appId, callback, context);
789     if (res != HC_SUCCESS) {
790         FreeJson(context);
791         return res;
792     }
793 #ifdef ENABLE_P2P_BIND_LITE_PROTOCOL_CHECK
794     res = CheckBindParams(context, true);
795     if (res != HC_SUCCESS) {
796         FreeJson(context);
797         return res;
798     }
799 #endif
800     ChannelType channelType = GetChannelType(callback, context);
801     SessionInitParams params = { context, *callback };
802     res = OpenDevSession(requestId, appId, &params);
803     FreeJson(context);
804     if (res != HC_SUCCESS) {
805         LOGE("OpenDevSession fail. [Res]: %" LOG_PUB "d", res);
806         return res;
807     }
808     if (channelType == SERVICE_CHANNEL) {
809         res = PushStartSessionTask(requestId);
810         if (res != HC_SUCCESS) {
811             return res;
812         }
813     }
814     return HC_SUCCESS;
815 }
816 
RequestAddMemberToGroupInner(int32_t osAccountId,int64_t requestId,const char * appId,const char * addParams)817 static int32_t RequestAddMemberToGroupInner(int32_t osAccountId, int64_t requestId, const char *appId,
818     const char *addParams)
819 {
820     ADD_PERFORM_DATA(requestId, true, true, HcGetCurTimeInMillis());
821     osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
822     if ((appId == NULL) || (addParams == NULL) || (osAccountId == INVALID_OS_ACCOUNT)) {
823         LOGE("Invalid input parameters!");
824         return HC_ERR_INVALID_PARAMS;
825     }
826     if (!CheckIsForegroundOsAccountId(osAccountId)) {
827         LOGE("This access is not from the foreground user, rejected it.");
828         return HC_ERR_CROSS_USER_ACCESS;
829     }
830     if (!IsOsAccountUnlocked(osAccountId)) {
831         LOGE("Os account is not unlocked! Please unlock it firstly!");
832         return HC_ERR_OS_ACCOUNT_NOT_UNLOCKED;
833     }
834     LOGI("Start to add member to group. [ReqId]: %" LOG_PUB PRId64 ", [OsAccountId]: %" LOG_PUB "d, [AppId]: %"
835         LOG_PUB "s", requestId, osAccountId, appId);
836     const DeviceAuthCallback *callback = GetGMCallbackByAppId(appId);
837     if (callback == NULL) {
838         LOGE("Failed to find callback by appId! [AppId]: %" LOG_PUB "s", appId);
839         return HC_ERR_CALLBACK_NOT_FOUND;
840     }
841     return StartClientBindSession(osAccountId, requestId, appId, addParams, callback);
842 }
843 
RequestAddMemberToGroup(int32_t osAccountId,int64_t requestId,const char * appId,const char * addParams)844 static int32_t RequestAddMemberToGroup(int32_t osAccountId, int64_t requestId, const char *appId, const char *addParams)
845 {
846     ReportBehaviorBeginEvent(true, true, requestId);
847     int32_t res = RequestAddMemberToGroupInner(osAccountId, requestId, appId, addParams);
848     ReportBehaviorBeginResultEvent(true, true, requestId, NULL, res);
849 #ifdef DEV_AUTH_HIVIEW_ENABLE
850     const char *callEventFuncName = GetAddMemberCallEventFuncName(addParams);
851     DEV_AUTH_REPORT_UE_CALL_EVENT_BY_PARAMS(osAccountId, addParams, appId, callEventFuncName);
852 #endif
853     return res;
854 }
855 
CreateAppIdJsonString(const char * appId,char ** reqParames)856 static int32_t CreateAppIdJsonString(const char *appId, char **reqParames)
857 {
858     CJson *reqJson = CreateJson();
859     if ((reqJson == NULL) || (reqParames == NULL)) {
860         LOGE("Failed to create json!");
861         return HC_ERR_JSON_CREATE;
862     }
863     if (AddStringToJson(reqJson, FIELD_APP_ID, appId) != HC_SUCCESS) {
864         LOGE("Failed to add appId!");
865         FreeJson(reqJson);
866         return HC_ERR_JSON_ADD;
867     }
868     *reqParames = PackJsonToString(reqJson);
869     FreeJson(reqJson);
870     if ((*reqParames) == NULL) {
871         LOGE("Failed to create reqParames string!");
872         return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL;
873     }
874     return HC_SUCCESS;
875 }
876 
GetAppIdFromReceivedMsg(const CJson * receivedMsg)877 static const char *GetAppIdFromReceivedMsg(const CJson *receivedMsg)
878 {
879     const char *appId = GetStringFromJson(receivedMsg, FIELD_APP_ID);
880     if (appId == NULL) {
881         LOGW("use default device manager appId.");
882         appId = DM_APP_ID;
883     }
884     return appId;
885 }
886 
AddServerReqInfoToContext(int64_t requestId,const char * appId,int32_t opCode,const CJson * receivedMsg,CJson * context)887 static int32_t AddServerReqInfoToContext(int64_t requestId, const char *appId, int32_t opCode,
888     const CJson *receivedMsg, CJson *context)
889 {
890     const char *groupId = GetStringFromJson(receivedMsg, FIELD_GROUP_ID);
891     if (groupId == NULL) {
892         LOGE("get groupId from json fail.");
893         return HC_ERR_JSON_GET;
894     }
895     if (AddBoolToJson(context, FIELD_IS_SINGLE_CRED, true) != HC_SUCCESS) {
896         LOGE("add isSingleCred to context fail.");
897         return HC_ERR_JSON_ADD;
898     }
899     if (AddBoolToJson(context, FIELD_IS_BIND, true) != HC_SUCCESS) {
900         LOGE("add isBind to context fail.");
901         return HC_ERR_JSON_ADD;
902     }
903     if (AddInt64StringToJson(context, FIELD_REQUEST_ID, requestId) != HC_SUCCESS) {
904         LOGE("add requestId to context fail.");
905         return HC_ERR_JSON_ADD;
906     }
907     if (AddStringToJson(context, FIELD_APP_ID, appId) != HC_SUCCESS) {
908         LOGE("add appId to context fail.");
909         return HC_ERR_JSON_ADD;
910     }
911     if (AddBoolToJson(context, FIELD_IS_CLIENT, false) != HC_SUCCESS) {
912         LOGE("add isClient to context fail.");
913         return HC_ERR_JSON_ADD;
914     }
915     if (AddIntToJson(context, FIELD_OPERATION_CODE, opCode) != HC_SUCCESS) {
916         LOGE("add opCode to context fail.");
917         return HC_ERR_JSON_ADD;
918     }
919     int32_t res;
920     if (opCode == MEMBER_INVITE) {
921         res = AddGroupInfoToContextByInput(receivedMsg, context);
922         if (res != HC_SUCCESS) {
923             return res;
924         }
925         return AddDevInfoToContextByInput(context);
926     }
927     res = AddGroupInfoToContextByDb(groupId, context);
928     if (res != HC_SUCCESS) {
929         return res;
930     }
931     return AddDevInfoToContextByDb(groupId, context);
932 }
933 
BuildServerBindContext(int64_t requestId,const char * appId,int32_t opCode,const CJson * receivedMsg,CJson * context)934 static int32_t BuildServerBindContext(int64_t requestId, const char *appId, int32_t opCode,
935     const CJson *receivedMsg, CJson *context)
936 {
937     int32_t res = CheckConfirmationExist(context);
938     if (res != HC_SUCCESS) {
939         return res;
940     }
941     res = AddOsAccountIdToContextIfValid(context);
942     if (res != HC_SUCCESS) {
943         return res;
944     }
945     res = AddServerReqInfoToContext(requestId, appId, opCode, receivedMsg, context);
946     if (res != HC_SUCCESS) {
947         return res;
948     }
949     int32_t channelType;
950     int64_t channelId = DEFAULT_CHANNEL_ID;
951     if (GetByteFromJson(receivedMsg, FIELD_CHANNEL_ID, (uint8_t *)&channelId, sizeof(int64_t)) == HC_SUCCESS) {
952         channelType = SOFT_BUS;
953     } else {
954         channelType = SERVICE_CHANNEL;
955     }
956     return AddChannelInfoToContext(channelType, channelId, context);
957 }
958 
OpenServerBindSession(int64_t requestId,const CJson * receivedMsg)959 static int32_t OpenServerBindSession(int64_t requestId, const CJson *receivedMsg)
960 {
961     const char *appId = GetAppIdFromReceivedMsg(receivedMsg);
962     const DeviceAuthCallback *callback = GetGMCallbackByAppId(appId);
963     if (callback == NULL) {
964         LOGE("Failed to find callback by appId! [AppId]: %" LOG_PUB "s", appId);
965         return HC_ERR_CALLBACK_NOT_FOUND;
966     }
967     int32_t opCode;
968     if (GetIntFromJson(receivedMsg, FIELD_GROUP_OP, &opCode) != HC_SUCCESS) {
969         if (GetIntFromJson(receivedMsg, FIELD_OP_CODE, &opCode) != HC_SUCCESS) {
970             opCode = MEMBER_JOIN;
971             LOGW("use default opCode.");
972         }
973     }
974     char *reqParames = NULL;
975     int32_t res = CreateAppIdJsonString(appId, &reqParames);
976     if (res != HC_SUCCESS) {
977         LOGE("Create reqParames from appid failed!");
978         return res;
979     }
980     char *returnDataStr = ProcessRequestCallback(requestId, opCode, reqParames, callback);
981     FreeJsonString(reqParames);
982     if (returnDataStr == NULL) {
983         LOGE("The OnRequest callback failed!");
984         return HC_ERR_REQ_REJECTED;
985     }
986     CJson *context = CreateJsonFromString(returnDataStr);
987     FreeJsonString(returnDataStr);
988     if (context == NULL) {
989         LOGE("Failed to create context json from string!");
990         return HC_ERR_JSON_FAIL;
991     }
992     res = BuildServerBindContext(requestId, appId, opCode, receivedMsg, context);
993     if (res != HC_SUCCESS) {
994         FreeJson(context);
995         return res;
996     }
997 #ifdef ENABLE_P2P_BIND_LITE_PROTOCOL_CHECK
998     res = CheckBindParams(context, false);
999     if (res != HC_SUCCESS) {
1000         FreeJson(context);
1001         return res;
1002     }
1003 #endif
1004     SessionInitParams params = { context, *callback };
1005     res = OpenDevSession(requestId, appId, &params);
1006     FreeJson(context);
1007     return res;
1008 }
1009 
RequestProcessBindDataInner(int64_t requestId,const uint8_t * data,uint32_t dataLen)1010 static int32_t RequestProcessBindDataInner(int64_t requestId, const uint8_t *data, uint32_t dataLen)
1011 {
1012     if (!IsSessionExist(requestId)) {
1013         ADD_PERFORM_DATA(requestId, true, false, HcGetCurTimeInMillis());
1014     } else {
1015         UPDATE_PERFORM_DATA_BY_SELF_INDEX(requestId, HcGetCurTimeInMillis());
1016     }
1017     if ((data == NULL) || (dataLen == 0) || (dataLen > MAX_DATA_BUFFER_SIZE)) {
1018         LOGE("The input data is invalid!");
1019         return HC_ERR_INVALID_PARAMS;
1020     }
1021     LOGI("[Start]: RequestProcessBindData! [ReqId]: %" LOG_PUB PRId64, requestId);
1022     CJson *receivedMsg = CreateJsonFromString((const char *)data);
1023     if (receivedMsg == NULL) {
1024         LOGE("Failed to create json from string!");
1025         return HC_ERR_JSON_FAIL;
1026     }
1027     int32_t res;
1028     if (!IsSessionExist(requestId)) {
1029         res = OpenServerBindSession(requestId, receivedMsg);
1030         if (res != HC_SUCCESS) {
1031             FreeJson(receivedMsg);
1032             return res;
1033         }
1034     }
1035     res = PushProcSessionTask(requestId, receivedMsg);
1036     if (res != HC_SUCCESS) {
1037         FreeJson(receivedMsg);
1038         return res;
1039     }
1040     return HC_SUCCESS;
1041 }
1042 
RequestProcessBindData(int64_t requestId,const uint8_t * data,uint32_t dataLen)1043 static int32_t RequestProcessBindData(int64_t requestId, const uint8_t *data, uint32_t dataLen)
1044 {
1045     bool isSessionExist = IsSessionExist(requestId);
1046     if (!isSessionExist) {
1047         ReportBehaviorBeginEvent(true, false, requestId);
1048     }
1049     int32_t res = RequestProcessBindDataInner(requestId, data, dataLen);
1050     if (!isSessionExist) {
1051         ReportBehaviorBeginResultEvent(true, false, requestId, NULL, res);
1052     }
1053     return res;
1054 }
1055 
RequestDeleteMemberFromGroup(int32_t osAccountId,int64_t requestId,const char * appId,const char * deleteParams)1056 static int32_t RequestDeleteMemberFromGroup(int32_t osAccountId, int64_t requestId, const char *appId,
1057     const char *deleteParams)
1058 {
1059     int64_t startTime = HcGetCurTimeInMillis();
1060     int32_t res = DeleteMemberFromGroupInner(osAccountId, requestId, appId, deleteParams);
1061     int64_t endTime = HcGetCurTimeInMillis();
1062     int64_t elapsedTime = endTime - startTime;
1063     LOGI("DeleteMemberFromGroup elapsed time:  %" LOG_PUB PRId64 " milliseconds", elapsedTime);
1064     DEV_AUTH_REPORT_UE_CALL_EVENT_BY_PARAMS(osAccountId, deleteParams, appId, DEL_MEMBER_EVENT);
1065 #ifdef DEV_AUTH_HIVIEW_ENABLE
1066     DevAuthCallEvent eventData = BuildCallEventData(appId, DEL_MEMBER_EVENT, osAccountId,
1067         res, PROCESS_DELETE_MEMBER_FROM_GROUP);
1068     eventData.executionTime = elapsedTime;
1069     DEV_AUTH_REPORT_CALL_EVENT(eventData);
1070 #endif
1071     return res;
1072 }
1073 
AddMultiMembersToGroupInner(int32_t osAccountId,const char * appId,const char * addParams)1074 static int32_t AddMultiMembersToGroupInner(int32_t osAccountId, const char *appId, const char *addParams)
1075 {
1076     osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
1077     if ((appId == NULL) || (addParams == NULL) || (osAccountId == INVALID_OS_ACCOUNT)) {
1078         LOGE("Invalid input parameters!");
1079         return HC_ERR_INVALID_PARAMS;
1080     }
1081     if (!IsOsAccountUnlocked(osAccountId)) {
1082         LOGE("Os account is not unlocked!");
1083         return HC_ERR_OS_ACCOUNT_NOT_UNLOCKED;
1084     }
1085     LOGI("[Start]: [AppId]: %" LOG_PUB "s", appId);
1086     CJson *params = CreateJsonFromString(addParams);
1087     if (params == NULL) {
1088         LOGE("Failed to create json from add params str!");
1089         return HC_ERR_JSON_CREATE;
1090     }
1091     int32_t groupType = GROUP_TYPE_INVALID;
1092     if (GetIntFromJson(params, FIELD_GROUP_TYPE, &groupType) != HC_SUCCESS) {
1093         LOGE("Failed to get groupType from params!");
1094         FreeJson(params);
1095         return HC_ERR_JSON_GET;
1096     }
1097     if (!IsGroupTypeSupported(groupType)) {
1098         FreeJson(params);
1099         return HC_ERR_NOT_SUPPORT;
1100     }
1101     int32_t res;
1102     if (groupType == IDENTICAL_ACCOUNT_GROUP) {
1103         IdenticalAccountGroup *instance = (IdenticalAccountGroup *)GetIdenticalAccountGroupInstance();
1104         res = instance->addMultiMembersToGroup(osAccountId, appId, params);
1105     } else if (groupType == ACROSS_ACCOUNT_AUTHORIZE_GROUP) {
1106         AcrossAccountGroup *instance = (AcrossAccountGroup *)GetAcrossAccountGroupInstance();
1107         res = instance->addMultiMembersToGroup(osAccountId, appId, params);
1108     } else {
1109         LOGE("The input groupType is invalid! [GroupType]: %" LOG_PUB "d", groupType);
1110         res = HC_ERR_INVALID_PARAMS;
1111     }
1112     FreeJson(params);
1113     LOGI("[End]: [Res]: %" LOG_PUB "d!", res);
1114     return res;
1115 }
1116 
DevAuthReportCallEventWithResult(const char * appId,const char * funcName,const int32_t osAccountId,const int32_t callResult,const int32_t processCode)1117 static void DevAuthReportCallEventWithResult(const char *appId, const char *funcName, const int32_t osAccountId,
1118     const int32_t callResult, const int32_t processCode)
1119 {
1120 #ifdef DEV_AUTH_HIVIEW_ENABLE
1121     DevAuthCallEvent eventData;
1122     eventData.appId = appId;
1123     eventData.funcName = funcName;
1124     eventData.osAccountId = osAccountId;
1125     eventData.callResult = callResult;
1126     eventData.processCode = processCode;
1127     eventData.credType = DEFAULT_CRED_TYPE;
1128     eventData.groupType = DEFAULT_MULTI_MEMBER_GROUP_TYPE;
1129     eventData.executionTime = DEFAULT_EXECUTION_TIME;
1130     eventData.extInfo = DEFAULT_EXT_INFO;
1131     DevAuthReportCallEvent(eventData);
1132     return;
1133 #endif
1134     (void)appId;
1135     (void)funcName;
1136     (void)osAccountId;
1137     (void)callResult;
1138     (void)processCode;
1139     return;
1140 }
1141 
RequestAddMultiMembersToGroup(int32_t osAccountId,const char * appId,const char * addParams)1142 static int32_t RequestAddMultiMembersToGroup(int32_t osAccountId, const char *appId, const char *addParams)
1143 {
1144     int32_t res = AddMultiMembersToGroupInner(osAccountId, appId, addParams);
1145     DEV_AUTH_REPORT_UE_CALL_EVENT_BY_PARAMS(osAccountId, addParams, appId, ADD_MULTI_MEMBER_EVENT);
1146     DevAuthReportCallEventWithResult(appId, ADD_MULTI_MEMBER_EVENT, osAccountId,
1147         res, PROCESS_ADD_MULTI_MEMBERS_TO_GROUP);
1148     return res;
1149 }
1150 
DelMultiMembersFromGroupInner(int32_t osAccountId,const char * appId,const char * deleteParams)1151 static int32_t DelMultiMembersFromGroupInner(int32_t osAccountId, const char *appId, const char *deleteParams)
1152 {
1153     osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
1154     if ((appId == NULL) || (deleteParams == NULL) || (osAccountId == INVALID_OS_ACCOUNT)) {
1155         LOGE("Invalid input!");
1156         return HC_ERR_INVALID_PARAMS;
1157     }
1158     if (!IsOsAccountUnlocked(osAccountId)) {
1159         LOGE("Os account is not unlocked!");
1160         return HC_ERR_OS_ACCOUNT_NOT_UNLOCKED;
1161     }
1162     LOGI("[Start]: [AppId]: %" LOG_PUB "s", appId);
1163     CJson *params = CreateJsonFromString(deleteParams);
1164     if (params == NULL) {
1165         LOGE("Failed to create json from string!");
1166         return HC_ERR_JSON_CREATE;
1167     }
1168     int32_t groupType = GROUP_TYPE_INVALID;
1169     if (GetIntFromJson(params, FIELD_GROUP_TYPE, &groupType) != HC_SUCCESS) {
1170         LOGE("Failed to get groupType from json!");
1171         FreeJson(params);
1172         return HC_ERR_JSON_GET;
1173     }
1174     if (!IsGroupTypeSupported(groupType)) {
1175         FreeJson(params);
1176         return HC_ERR_NOT_SUPPORT;
1177     }
1178     int32_t res;
1179     if (groupType == IDENTICAL_ACCOUNT_GROUP) {
1180         IdenticalAccountGroup *instance = (IdenticalAccountGroup *)GetIdenticalAccountGroupInstance();
1181         res = instance->delMultiMembersFromGroup(osAccountId, appId, params);
1182     } else if (groupType == ACROSS_ACCOUNT_AUTHORIZE_GROUP) {
1183         AcrossAccountGroup *instance = (AcrossAccountGroup *)GetAcrossAccountGroupInstance();
1184         res = instance->delMultiMembersFromGroup(osAccountId, appId, params);
1185     } else {
1186         LOGE("The input groupType is invalid! [GroupType]: %" LOG_PUB "d", groupType);
1187         res = HC_ERR_INVALID_PARAMS;
1188     }
1189     FreeJson(params);
1190     LOGI("[End]: [Res]: %" LOG_PUB "d!", res);
1191     return res;
1192 }
1193 
RequestDelMultiMembersFromGroup(int32_t osAccountId,const char * appId,const char * deleteParams)1194 static int32_t RequestDelMultiMembersFromGroup(int32_t osAccountId, const char *appId, const char *deleteParams)
1195 {
1196     int32_t res = DelMultiMembersFromGroupInner(osAccountId, appId, deleteParams);
1197     DEV_AUTH_REPORT_UE_CALL_EVENT_BY_PARAMS(osAccountId, deleteParams, appId, DEL_MULTI_MEMBER_EVENT);
1198     DevAuthReportCallEventWithResult(appId, DEL_MULTI_MEMBER_EVENT, osAccountId,
1199         res, PROCESS_DEL_MULTI_MEMBERS_FROM_GROUP);
1200     return res;
1201 }
1202 
RegListener(const char * appId,const DataChangeListener * listener)1203 static int32_t RegListener(const char *appId, const DataChangeListener *listener)
1204 {
1205     if ((appId == NULL) || (listener == NULL)) {
1206         LOGE("The input parameter contains NULL value!");
1207         return HC_ERR_INVALID_PARAMS;
1208     }
1209     if (!IsBroadcastSupported()) {
1210         LOGE("Broadcast is not supported!");
1211         return HC_ERR_NOT_SUPPORT;
1212     }
1213     return AddListener(appId, listener);
1214 }
1215 
DoOnChannelOpened(HcTaskBase * baseTask)1216 static void DoOnChannelOpened(HcTaskBase *baseTask)
1217 {
1218     if (baseTask == NULL) {
1219         LOGE("The input task is NULL!");
1220         DecreaseCriticalCnt();
1221         return;
1222     }
1223     SoftBusTask *task = (SoftBusTask *)baseTask;
1224     SET_LOG_MODE(TRACE_MODE);
1225     SET_TRACE_ID(task->requestId);
1226     LOGI("[Start]: DoOnChannelOpened!");
1227     int32_t res = StartDevSession(task->requestId);
1228     if (res != HC_SUCCESS) {
1229         LOGE("start session fail.[Res]: %" LOG_PUB "d", res);
1230         CloseDevSession(task->requestId);
1231     }
1232     DecreaseCriticalCnt();
1233 }
1234 
InitSoftBusTask(SoftBusTask * task,int64_t requestId)1235 static void InitSoftBusTask(SoftBusTask *task, int64_t requestId)
1236 {
1237     task->base.doAction = DoOnChannelOpened;
1238     task->base.destroy = NULL;
1239     task->requestId = requestId;
1240 }
1241 
OnChannelOpenedCb(int64_t requestId,int result)1242 static int OnChannelOpenedCb(int64_t requestId, int result)
1243 {
1244     if (result != HC_SUCCESS) {
1245         LOGE("[SoftBus][Out]: Failed to open channel! res: %" LOG_PUB "d", result);
1246         CloseDevSession(requestId);
1247         return HC_ERR_SOFT_BUS;
1248     }
1249     LOGI("[Start]: OnChannelOpened! [ReqId]: %" LOG_PUB PRId64, requestId);
1250     SoftBusTask *task = (SoftBusTask *)HcMalloc(sizeof(SoftBusTask), 0);
1251     if (task == NULL) {
1252         LOGE("Failed to allocate task memory!");
1253         CloseDevSession(requestId);
1254         return HC_ERR_ALLOC_MEMORY;
1255     }
1256     InitSoftBusTask(task, requestId);
1257     if (PushTask((HcTaskBase *)task) != HC_SUCCESS) {
1258         HcFree(task);
1259         CloseDevSession(requestId);
1260         return HC_ERR_INIT_TASK_FAIL;
1261     }
1262     IncreaseCriticalCnt(ADD_ONE);
1263     LOGI("[End]: OnChannelOpened!");
1264     return HC_SUCCESS;
1265 }
1266 
OnChannelClosedCb(void)1267 static void OnChannelClosedCb(void)
1268 {
1269     return;
1270 }
1271 
OnBytesReceivedCb(int64_t requestId,uint8_t * data,uint32_t dataLen)1272 static void OnBytesReceivedCb(int64_t requestId, uint8_t *data, uint32_t dataLen)
1273 {
1274     if ((data == NULL) || (dataLen == 0) || (dataLen > MAX_DATA_BUFFER_SIZE)) {
1275         LOGE("Invalid input params!");
1276         return;
1277     }
1278     (void)RequestProcessBindData(requestId, data, dataLen);
1279 }
1280 
RegCallback(const char * appId,const DeviceAuthCallback * callback)1281 static int32_t RegCallback(const char *appId, const DeviceAuthCallback *callback)
1282 {
1283     if ((appId == NULL) || (callback == NULL)) {
1284         LOGE("The input parameters contains NULL value!");
1285         return HC_ERR_INVALID_PARAMS;
1286     }
1287     ChannelProxy proxy = {
1288         .onChannelOpened = OnChannelOpenedCb,
1289         .onChannelClosed = OnChannelClosedCb,
1290         .onBytesReceived = OnBytesReceivedCb
1291     };
1292     int32_t res = InitChannelManager(&proxy);
1293     if (res != HC_SUCCESS) {
1294         LOGE("[End]: [Service]: Failed to init channel manage module!");
1295         return res;
1296     }
1297     return RegGroupManagerCallback(appId, callback);
1298 }
1299 
UnRegCallback(const char * appId)1300 static int32_t UnRegCallback(const char *appId)
1301 {
1302     if (appId == NULL) {
1303         LOGE("The input parameters contains NULL value!");
1304         return HC_ERR_INVALID_PARAMS;
1305     }
1306     return UnRegGroupManagerCallback(appId);
1307 }
1308 
UnRegListener(const char * appId)1309 static int32_t UnRegListener(const char *appId)
1310 {
1311     if (appId == NULL) {
1312         LOGE("The input appId is NULL!");
1313         return HC_ERR_INVALID_PARAMS;
1314     }
1315     if (!IsBroadcastSupported()) {
1316         LOGE("Broadcast is not supported!");
1317         return HC_ERR_NOT_SUPPORT;
1318     }
1319     return RemoveListener(appId);
1320 }
1321 
GetRegisterInfo(const char * reqJsonStr,char ** returnRegisterInfo)1322 static int32_t GetRegisterInfo(const char *reqJsonStr, char **returnRegisterInfo)
1323 {
1324     DEV_AUTH_REPORT_UE_CALL_EVENT_BY_PARAMS(DEFAULT_OS_ACCOUNT, reqJsonStr, NULL, GET_REGISTER_INFO_EVENT);
1325     if ((reqJsonStr == NULL) || (returnRegisterInfo == NULL)) {
1326         LOGE("The input param is NULL!");
1327         return HC_ERR_INVALID_PARAMS;
1328     }
1329     CJson *requestJson = CreateJsonFromString(reqJsonStr);
1330     if (requestJson == NULL) {
1331         LOGE("Failed to create request json!");
1332         return HC_ERR_JSON_CREATE;
1333     }
1334     if (AddIntToJson(requestJson, FIELD_CREDENTIAL_TYPE, ASYMMETRIC_CRED) != HC_SUCCESS) {
1335         LOGE("Failed to add credentialType to input json!");
1336         FreeJson(requestJson);
1337         return HC_ERR_JSON_GET;
1338     }
1339     CJson *registerInfo = CreateJson();
1340     if (registerInfo == NULL) {
1341         LOGE("Failed to allocate registerInfo memory!");
1342         FreeJson(requestJson);
1343         return HC_ERR_JSON_CREATE;
1344     }
1345     int32_t osAccountId;
1346     if (GetIntFromJson(requestJson, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) {
1347         LOGI("No osAccountId in request params, use current active osAccountId.");
1348         osAccountId = GetCurrentActiveOsAccountId();
1349     }
1350     int32_t result = ProcCred(ACCOUNT_RELATED_PLUGIN, osAccountId, REQUEST_SIGNATURE, requestJson, registerInfo);
1351     FreeJson(requestJson);
1352     if (result != HC_SUCCESS) {
1353         LOGE("Failed to get register info!");
1354         FreeJson(registerInfo);
1355         return result;
1356     }
1357     *returnRegisterInfo = PackJsonToString(registerInfo);
1358     FreeJson(registerInfo);
1359     if (*returnRegisterInfo == NULL) {
1360         LOGE("Failed to convert json to string!");
1361         return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL;
1362     }
1363     return HC_SUCCESS;
1364 }
1365 
CheckAccessToGroup(int32_t osAccountId,const char * appId,const char * groupId)1366 static int32_t CheckAccessToGroup(int32_t osAccountId, const char *appId, const char *groupId)
1367 {
1368     osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
1369     if ((appId == NULL) || (groupId == NULL) || (osAccountId == INVALID_OS_ACCOUNT)) {
1370         LOGE("Invalid input parameters!");
1371         return HC_ERR_INVALID_PARAMS;
1372     }
1373     if (!IsOsAccountUnlocked(osAccountId)) {
1374         LOGE("Os account is not unlocked!");
1375         return HC_ERR_OS_ACCOUNT_NOT_UNLOCKED;
1376     }
1377     if (CheckGroupAccessible(osAccountId, groupId, appId) != HC_SUCCESS) {
1378         LOGE("You do not have the permission to query the group information!");
1379         return HC_ERR_ACCESS_DENIED;
1380     }
1381     return HC_SUCCESS;
1382 }
1383 
GetAccessibleGroupInfoById(int32_t osAccountId,const char * appId,const char * groupId,char ** returnGroupInfo)1384 static int32_t GetAccessibleGroupInfoById(int32_t osAccountId, const char *appId, const char *groupId,
1385     char **returnGroupInfo)
1386 {
1387     osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
1388     if ((appId == NULL) || (groupId == NULL) || (returnGroupInfo == NULL) || (osAccountId == INVALID_OS_ACCOUNT)) {
1389         LOGE("Invalid parameters!");
1390         return HC_ERR_INVALID_PARAMS;
1391     }
1392     if (!IsOsAccountUnlocked(osAccountId)) {
1393         LOGE("Os account is not unlocked! Please unlock it firstly!");
1394         return HC_ERR_OS_ACCOUNT_NOT_UNLOCKED;
1395     }
1396     if (!IsGroupExistByGroupId(osAccountId, groupId)) {
1397         LOGE("No group found based on the query parameters!");
1398         return HC_ERR_GROUP_NOT_EXIST;
1399     }
1400     if (CheckGroupAccessible(osAccountId, groupId, appId) != HC_SUCCESS) {
1401         LOGE("You do not have the permission to query the group information!");
1402         return HC_ERR_ACCESS_DENIED;
1403     }
1404     TrustedGroupEntry *groupEntry = GetGroupEntryById(osAccountId, groupId);
1405     if (groupEntry == NULL) {
1406         LOGE("Failed to get groupEntry from db!");
1407         return HC_ERR_DB;
1408     }
1409     CJson *groupInfoJson = CreateJson();
1410     if (groupInfoJson == NULL) {
1411         LOGE("Failed to allocate groupInfoJson memory!");
1412         DestroyGroupEntry(groupEntry);
1413         return HC_ERR_JSON_FAIL;
1414     }
1415     int32_t result = GenerateReturnGroupInfo(groupEntry, groupInfoJson);
1416     DestroyGroupEntry(groupEntry);
1417     if (result != HC_SUCCESS) {
1418         FreeJson(groupInfoJson);
1419         return result;
1420     }
1421     *returnGroupInfo = PackJsonToString(groupInfoJson);
1422     FreeJson(groupInfoJson);
1423     if (*returnGroupInfo == NULL) {
1424         LOGE("Failed to convert json to string!");
1425         return HC_ERR_JSON_FAIL;
1426     }
1427     return HC_SUCCESS;
1428 }
1429 
GetAccessibleGroupInfo(int32_t osAccountId,const char * appId,const char * queryParams,char ** returnGroupVec,uint32_t * groupNum)1430 static int32_t GetAccessibleGroupInfo(int32_t osAccountId, const char *appId, const char *queryParams,
1431     char **returnGroupVec, uint32_t *groupNum)
1432 {
1433     osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
1434     if ((appId == NULL) || (queryParams == NULL) || (returnGroupVec == NULL) || (groupNum == NULL) ||
1435         (osAccountId == INVALID_OS_ACCOUNT)) {
1436         LOGE("Invalid input parameters!");
1437         return HC_ERR_INVALID_PARAMS;
1438     }
1439     if (!IsOsAccountUnlocked(osAccountId)) {
1440         LOGE("Os account is not unlocked!");
1441         return HC_ERR_OS_ACCOUNT_NOT_UNLOCKED;
1442     }
1443     CJson *queryParamsJson = CreateJsonFromString(queryParams);
1444     if (queryParamsJson == NULL) {
1445         LOGE("Failed to create queryParamsJson from string!");
1446         return HC_ERR_JSON_FAIL;
1447     }
1448     int32_t groupType = ALL_GROUP;
1449     (void)GetIntFromJson(queryParamsJson, FIELD_GROUP_TYPE, &groupType);
1450     if ((groupType != ALL_GROUP) && (!IsGroupTypeSupported(groupType))) {
1451         LOGE("Invalid group type!");
1452         FreeJson(queryParamsJson);
1453         return HC_ERR_INVALID_PARAMS;
1454     }
1455     const char *groupId = GetStringFromJson(queryParamsJson, FIELD_GROUP_ID);
1456     const char *groupName = GetStringFromJson(queryParamsJson, FIELD_GROUP_NAME);
1457     const char *groupOwner = GetStringFromJson(queryParamsJson, FIELD_GROUP_OWNER);
1458     if (!IsQueryParamsValid(groupType, groupId, groupName, groupOwner)) {
1459         LOGE("The query parameters cannot be all null!");
1460         FreeJson(queryParamsJson);
1461         return HC_ERR_INVALID_PARAMS;
1462     }
1463     GroupEntryVec groupEntryVec = CreateGroupEntryVec();
1464     QueryGroupParams params = InitQueryGroupParams();
1465     params.groupId = groupId;
1466     params.groupName = groupName;
1467     params.ownerName = groupOwner;
1468     params.groupType = (uint32_t)groupType;
1469     int32_t result = GetGroupInfo(osAccountId, &params, &groupEntryVec);
1470     FreeJson(queryParamsJson);
1471     if (result != HC_SUCCESS) {
1472         ClearGroupEntryVec(&groupEntryVec);
1473         return result;
1474     }
1475     RemoveNoPermissionGroup(osAccountId, &groupEntryVec, appId);
1476     result = GenerateReturnGroupVec(&groupEntryVec, returnGroupVec, groupNum);
1477     ClearGroupEntryVec(&groupEntryVec);
1478     return result;
1479 }
1480 
GetAccessibleJoinedGroups(int32_t osAccountId,const char * appId,int groupType,char ** returnGroupVec,uint32_t * groupNum)1481 static int32_t GetAccessibleJoinedGroups(int32_t osAccountId, const char *appId, int groupType,
1482     char **returnGroupVec, uint32_t *groupNum)
1483 {
1484     osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
1485     if ((appId == NULL) || (returnGroupVec == NULL) || (groupNum == NULL) || (osAccountId == INVALID_OS_ACCOUNT)) {
1486         LOGE("Invalid input parameters!");
1487         return HC_ERR_INVALID_PARAMS;
1488     }
1489     if (!IsOsAccountUnlocked(osAccountId)) {
1490         LOGE("Os account is not unlocked!");
1491         return HC_ERR_OS_ACCOUNT_NOT_UNLOCKED;
1492     }
1493     if (!IsGroupTypeSupported(groupType)) {
1494         LOGE("Invalid group type!");
1495         return HC_ERR_INVALID_PARAMS;
1496     }
1497     GroupEntryVec groupEntryVec = CreateGroupEntryVec();
1498     int32_t result = GetJoinedGroups(osAccountId, groupType, &groupEntryVec);
1499     if (result != HC_SUCCESS) {
1500         ClearGroupEntryVec(&groupEntryVec);
1501         return result;
1502     }
1503     RemoveNoPermissionGroup(osAccountId, &groupEntryVec, appId);
1504     result = GenerateReturnGroupVec(&groupEntryVec, returnGroupVec, groupNum);
1505     ClearGroupEntryVec(&groupEntryVec);
1506     return result;
1507 }
1508 
GetAccessibleRelatedGroups(int32_t osAccountId,const char * appId,const char * peerDeviceId,char ** returnGroupVec,uint32_t * groupNum)1509 static int32_t GetAccessibleRelatedGroups(int32_t osAccountId, const char *appId, const char *peerDeviceId,
1510     char **returnGroupVec, uint32_t *groupNum)
1511 {
1512     osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
1513     if ((appId == NULL) || (peerDeviceId == NULL) || (returnGroupVec == NULL) || (groupNum == NULL) ||
1514         (osAccountId == INVALID_OS_ACCOUNT)) {
1515         LOGE("Invalid input parameters!");
1516         return HC_ERR_INVALID_PARAMS;
1517     }
1518     if (!IsOsAccountUnlocked(osAccountId)) {
1519         LOGE("Os account is not unlocked!");
1520         return HC_ERR_OS_ACCOUNT_NOT_UNLOCKED;
1521     }
1522     PRINT_SENSITIVE_DATA("PeerUdid", peerDeviceId);
1523     GroupEntryVec groupEntryVec = CreateGroupEntryVec();
1524     int32_t result = GetRelatedGroups(osAccountId, peerDeviceId, true, &groupEntryVec);
1525     if (result != HC_SUCCESS) {
1526         LOGE("Failed to get related groups by udid!");
1527         ClearGroupEntryVec(&groupEntryVec);
1528         return result;
1529     }
1530     if (groupEntryVec.size(&groupEntryVec) == 0) {
1531         LOGI("Group entry not found by udid, try to get by authId!");
1532         result = GetRelatedGroups(osAccountId, peerDeviceId, false, &groupEntryVec);
1533         if (result != HC_SUCCESS) {
1534             LOGE("Failed to get related groups by authId!");
1535             ClearGroupEntryVec(&groupEntryVec);
1536             return result;
1537         }
1538     }
1539     RemoveNoPermissionGroup(osAccountId, &groupEntryVec, appId);
1540     result = GenerateReturnGroupVec(&groupEntryVec, returnGroupVec, groupNum);
1541     ClearGroupEntryVec(&groupEntryVec);
1542     return result;
1543 }
1544 
CheckParams(int32_t osAccountId,const char * appId,const DeviceQueryParams * devQueryParams,const char * groupId,char ** returnDeviceInfo)1545 static int32_t CheckParams(int32_t osAccountId, const char *appId,
1546     const DeviceQueryParams *devQueryParams, const char *groupId, char **returnDeviceInfo)
1547 {
1548     if ((appId == NULL) || (devQueryParams == NULL) || (devQueryParams->deviceId == NULL) ||
1549         (groupId == NULL) || (returnDeviceInfo == NULL) || (osAccountId == INVALID_OS_ACCOUNT)) {
1550         LOGE("Invalid input parameters!");
1551         return HC_ERR_INVALID_PARAMS;
1552     }
1553     return HC_SUCCESS;
1554 }
1555 
GetAccessibleDeviceInfoById(int32_t osAccountId,const char * appId,const DeviceQueryParams * devQueryParams,const char * groupId,char ** returnDeviceInfo)1556 static int32_t GetAccessibleDeviceInfoById(int32_t osAccountId, const char *appId,
1557     const DeviceQueryParams *devQueryParams, const char *groupId, char **returnDeviceInfo)
1558 {
1559     osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
1560     if (CheckParams(osAccountId, appId, devQueryParams, groupId, returnDeviceInfo) != HC_SUCCESS) {
1561         return HC_ERR_INVALID_PARAMS;
1562     }
1563     if (!IsOsAccountUnlocked(osAccountId)) {
1564         LOGE("Os account is not unlocked!");
1565         return HC_ERR_OS_ACCOUNT_NOT_UNLOCKED;
1566     }
1567     if (!IsGroupExistByGroupId(osAccountId, groupId)) {
1568         LOGE("No group is found with groupId!");
1569         return HC_ERR_GROUP_NOT_EXIST;
1570     }
1571     if (CheckGroupAccessible(osAccountId, groupId, appId) != HC_SUCCESS) {
1572         LOGE("You do not have the permission to query the group information!");
1573         return HC_ERR_ACCESS_DENIED;
1574     }
1575     TrustedDeviceEntry *deviceEntry = CreateDeviceEntry();
1576     if (deviceEntry == NULL) {
1577         LOGE("Failed to allocate deviceEntry memory!");
1578         return HC_ERR_ALLOC_MEMORY;
1579     }
1580     if (GetTrustedDevInfoById(osAccountId, devQueryParams->deviceId,
1581         devQueryParams->isUdid, groupId, deviceEntry) != HC_SUCCESS) {
1582         LOGE("No device is found based on the query parameters!");
1583         DestroyDeviceEntry(deviceEntry);
1584         return HC_ERR_DEVICE_NOT_EXIST;
1585     }
1586     CJson *devInfoJson = CreateJson();
1587     if (devInfoJson == NULL) {
1588         LOGE("Failed to allocate devInfoJson memory!");
1589         DestroyDeviceEntry(deviceEntry);
1590         return HC_ERR_JSON_FAIL;
1591     }
1592     int32_t result = GenerateReturnDevInfo(deviceEntry, devInfoJson);
1593     DestroyDeviceEntry(deviceEntry);
1594     if (result != HC_SUCCESS) {
1595         FreeJson(devInfoJson);
1596         return result;
1597     }
1598     *returnDeviceInfo = PackJsonToString(devInfoJson);
1599     FreeJson(devInfoJson);
1600     if (*returnDeviceInfo == NULL) {
1601         LOGE("Failed to convert json to string!");
1602         return HC_ERR_JSON_FAIL;
1603     }
1604     return HC_SUCCESS;
1605 }
1606 
GetAccessibleTrustedDevices(int32_t osAccountId,const char * appId,const char * groupId,char ** returnDevInfoVec,uint32_t * deviceNum)1607 static int32_t GetAccessibleTrustedDevices(int32_t osAccountId, const char *appId, const char *groupId,
1608     char **returnDevInfoVec, uint32_t *deviceNum)
1609 {
1610     osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
1611     if ((appId == NULL) || (groupId == NULL) || (returnDevInfoVec == NULL) || (deviceNum == NULL) ||
1612         (osAccountId == INVALID_OS_ACCOUNT)) {
1613         LOGE("Invalid input parameters!");
1614         return HC_ERR_INVALID_PARAMS;
1615     }
1616     if (!IsOsAccountUnlocked(osAccountId)) {
1617         LOGE("Os account is not unlocked!");
1618         return HC_ERR_OS_ACCOUNT_NOT_UNLOCKED;
1619     }
1620     if (!IsGroupExistByGroupId(osAccountId, groupId)) {
1621         LOGE("No group is found based on the query parameters!");
1622         return HC_ERR_GROUP_NOT_EXIST;
1623     }
1624     if (CheckGroupAccessible(osAccountId, groupId, appId) != HC_SUCCESS) {
1625         LOGE("You do not have the permission to query the group information!");
1626         return HC_ERR_ACCESS_DENIED;
1627     }
1628     DeviceEntryVec deviceEntryVec = CreateDeviceEntryVec();
1629     int32_t result = GetTrustedDevices(osAccountId, groupId, &deviceEntryVec);
1630     if (result != HC_SUCCESS) {
1631         ClearDeviceEntryVec(&deviceEntryVec);
1632         return result;
1633     }
1634     result = GenerateReturnDeviceVec(&deviceEntryVec, returnDevInfoVec, deviceNum);
1635     ClearDeviceEntryVec(&deviceEntryVec);
1636     return result;
1637 }
1638 
IsDeviceInAccessibleGroup(int32_t osAccountId,const char * appId,const char * groupId,const char * deviceId,bool isUdid)1639 static bool IsDeviceInAccessibleGroup(int32_t osAccountId, const char *appId, const char *groupId,
1640     const char *deviceId, bool isUdid)
1641 {
1642     osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
1643     if ((appId == NULL) || (groupId == NULL) || (deviceId == NULL) || (osAccountId == INVALID_OS_ACCOUNT)) {
1644         LOGE("Invalid input parameters!");
1645         return false;
1646     }
1647     if (!IsOsAccountUnlocked(osAccountId)) {
1648         LOGE("Os account is not unlocked!");
1649         return false;
1650     }
1651     if (!IsGroupExistByGroupId(osAccountId, groupId)) {
1652         LOGE("No group is found based on the query parameters!");
1653         return false;
1654     }
1655     if (CheckGroupAccessible(osAccountId, groupId, appId) != HC_SUCCESS) {
1656         LOGE("You do not have the permission to query the group information!");
1657         return false;
1658     }
1659     return IsTrustedDeviceInGroup(osAccountId, groupId, deviceId, isUdid);
1660 }
1661 
GetPkInfoList(int32_t osAccountId,const char * appId,const char * queryParams,char ** returnInfoList,uint32_t * returnInfoNum)1662 static int32_t GetPkInfoList(int32_t osAccountId, const char *appId, const char *queryParams,
1663     char **returnInfoList, uint32_t *returnInfoNum)
1664 {
1665     LOGI("[Start]: start to get pk list!");
1666     osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
1667     DEV_AUTH_REPORT_UE_CALL_EVENT_BY_PARAMS(osAccountId, NULL, appId, GET_PK_INFO_LIST_EVENT);
1668     if ((appId == NULL) || (queryParams == NULL) || (returnInfoList == NULL) ||
1669         (returnInfoNum == NULL) || (osAccountId == INVALID_OS_ACCOUNT)) {
1670         LOGE("Invalid input parameters!");
1671         return HC_ERR_INVALID_PARAMS;
1672     }
1673     if (!IsOsAccountUnlocked(osAccountId)) {
1674         LOGE("Os account is not unlocked!");
1675         return HC_ERR_OS_ACCOUNT_NOT_UNLOCKED;
1676     }
1677     CJson *params = CreateJsonFromString(queryParams);
1678     if (params == NULL) {
1679         LOGE("Failed to create json from string!");
1680         return HC_ERR_JSON_CREATE;
1681     }
1682     CJson *pkInfoList = CreateJsonArray();
1683     if (pkInfoList == NULL) {
1684         LOGE("Failed to create json array!");
1685         FreeJson(params);
1686         return HC_ERR_JSON_CREATE;
1687     }
1688     int32_t res = GeneratePkInfoList(osAccountId, params, pkInfoList);
1689     FreeJson(params);
1690     if (res != HC_SUCCESS) {
1691         FreeJson(pkInfoList);
1692         return res;
1693     }
1694     int32_t pkInfoNum = GetItemNum(pkInfoList);
1695     char *pkInfoListStr = PackJsonToString(pkInfoList);
1696     FreeJson(pkInfoList);
1697     if (pkInfoListStr == NULL) {
1698         LOGE("Failed to convert json to string!");
1699         return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL;
1700     }
1701     *returnInfoList = pkInfoListStr;
1702     *returnInfoNum = pkInfoNum;
1703     LOGI("[End]: Get pk list successfully! [PkInfoNum]: %" LOG_PUB "" PRId32, pkInfoNum);
1704     return HC_SUCCESS;
1705 }
1706 
DestroyInfo(char ** returnInfo)1707 static void DestroyInfo(char **returnInfo)
1708 {
1709     if ((returnInfo == NULL) || (*returnInfo == NULL)) {
1710         return;
1711     }
1712     FreeJsonString(*returnInfo);
1713     *returnInfo = NULL;
1714 }
1715 
1716 static const GroupImpl GROUP_IMPL_INSTANCE = {
1717     .createGroup = RequestCreateGroup,
1718     .deleteGroup = RequestDeleteGroup,
1719     .addMemberToGroup = RequestAddMemberToGroup,
1720     .processBindData = RequestProcessBindData,
1721     .deleteMember = RequestDeleteMemberFromGroup,
1722     .addMultiMembers = RequestAddMultiMembersToGroup,
1723     .delMultiMembers = RequestDelMultiMembersFromGroup,
1724     .regCallback = RegCallback,
1725     .unRegCallback = UnRegCallback,
1726     .regListener = RegListener,
1727     .unRegListener = UnRegListener,
1728     .getRegisterInfo = GetRegisterInfo,
1729     .checkAccessToGroup = CheckAccessToGroup,
1730     .getAccessibleGroupInfoById = GetAccessibleGroupInfoById,
1731     .getAccessibleGroupInfo = GetAccessibleGroupInfo,
1732     .getAccessibleJoinedGroups = GetAccessibleJoinedGroups,
1733     .getAccessibleRelatedGroups = GetAccessibleRelatedGroups,
1734     .getAccessibleDeviceInfoById = GetAccessibleDeviceInfoById,
1735     .getAccessibleTrustedDevices = GetAccessibleTrustedDevices,
1736     .isDeviceInAccessibleGroup = IsDeviceInAccessibleGroup,
1737     .getPkInfoList = GetPkInfoList,
1738     .destroyInfo = DestroyInfo
1739 };
1740 
InitGroupManagerTask(GroupManagerTask * task,GMTaskParams * taskParams,TaskFunc func)1741 static int32_t InitGroupManagerTask(GroupManagerTask *task, GMTaskParams *taskParams, TaskFunc func)
1742 {
1743     task->base.doAction = func;
1744     task->base.destroy = DestroyGroupManagerTask;
1745     task->osAccountId = taskParams->osAccountId;
1746     task->opCode = taskParams->opCode;
1747     task->reqId = taskParams->reqId;
1748     task->params = taskParams->params;
1749     return BindCallbackToTask(task, taskParams->params);
1750 }
1751 
IsCallerExtPart(int32_t opCode,CJson * params)1752 static bool IsCallerExtPart(int32_t opCode, CJson *params)
1753 {
1754     if (opCode != GROUP_CREATE && opCode != GROUP_DISBAND) {
1755         return false;
1756     }
1757     const char *appId = GetStringFromJson(params, FIELD_APP_ID);
1758     if (appId == NULL) {
1759         LOGE("Failed to get appId!");
1760         return false;
1761     }
1762     if (!IsStrEqual(appId, EXT_PART_APP_ID)) {
1763         return false;
1764     }
1765     return true;
1766 }
1767 
DestroyGroupManagerTask(HcTaskBase * task)1768 void DestroyGroupManagerTask(HcTaskBase *task)
1769 {
1770     if (task == NULL) {
1771         LOGE("The input task is NULL!");
1772         DecreaseCriticalCnt();
1773         return;
1774     }
1775     if (IsCallerExtPart(((GroupManagerTask *)task)->opCode, ((GroupManagerTask *)task)->params)) {
1776         DecreaseLoadCount();
1777     }
1778     FreeJson(((GroupManagerTask *)task)->params);
1779     DecreaseCriticalCnt();
1780 }
1781 
AddReqInfoToJson(int64_t requestId,const char * appId,CJson * jsonParams)1782 int32_t AddReqInfoToJson(int64_t requestId, const char *appId, CJson *jsonParams)
1783 {
1784     if (AddInt64StringToJson(jsonParams, FIELD_REQUEST_ID, requestId) != HC_SUCCESS) {
1785         LOGE("Failed to add requestId to json!");
1786         return HC_ERR_JSON_FAIL;
1787     }
1788     if (AddStringToJson(jsonParams, FIELD_APP_ID, appId) != HC_SUCCESS) {
1789         LOGE("Failed to add appId to json!");
1790         return HC_ERR_JSON_FAIL;
1791     }
1792     return HC_SUCCESS;
1793 }
1794 
BindCallbackToTask(GroupManagerTask * task,const CJson * jsonParams)1795 int32_t BindCallbackToTask(GroupManagerTask *task, const CJson *jsonParams)
1796 {
1797     const char *appId = GetStringFromJson(jsonParams, FIELD_APP_ID);
1798     if (appId == NULL) {
1799         LOGE("Failed to get appId from jsonParams!");
1800         return HC_ERR_JSON_GET;
1801     }
1802     task->cb = GetGMCallbackByAppId(appId);
1803     if (task->cb == NULL) {
1804         LOGE("Failed to find callback by appId! [AppId]: %" LOG_PUB "s", appId);
1805         return HC_ERR_CALLBACK_NOT_FOUND;
1806     }
1807     return HC_SUCCESS;
1808 }
1809 
AddBindParamsToJson(int operationCode,int64_t requestId,const char * appId,CJson * jsonParams)1810 int32_t AddBindParamsToJson(int operationCode, int64_t requestId, const char *appId, CJson *jsonParams)
1811 {
1812     if (AddIntToJson(jsonParams, FIELD_OPERATION_CODE, operationCode) != HC_SUCCESS) {
1813         LOGE("Failed to add operationCode to json!");
1814         return HC_ERR_JSON_FAIL;
1815     }
1816     return AddReqInfoToJson(requestId, appId, jsonParams);
1817 }
1818 
InitAndPushGMTask(int32_t osAccountId,int32_t opCode,int64_t reqId,CJson * params,TaskFunc func)1819 int32_t InitAndPushGMTask(int32_t osAccountId, int32_t opCode, int64_t reqId, CJson *params, TaskFunc func)
1820 {
1821     GroupManagerTask *task = (GroupManagerTask *)HcMalloc(sizeof(GroupManagerTask), 0);
1822     if (task == NULL) {
1823         LOGE("Failed to allocate task memory!");
1824         return HC_ERR_ALLOC_MEMORY;
1825     }
1826     GMTaskParams taskParams;
1827     taskParams.osAccountId = osAccountId;
1828     taskParams.opCode = opCode;
1829     taskParams.reqId = reqId;
1830     taskParams.params = params;
1831     if (InitGroupManagerTask(task, &taskParams, func) != HC_SUCCESS) {
1832         HcFree(task);
1833         return HC_ERR_INIT_TASK_FAIL;
1834     }
1835     if (IsCallerExtPart(opCode, params)) {
1836         IncreaseLoadCount();
1837     }
1838     if (PushTask((HcTaskBase *)task) != HC_SUCCESS) {
1839         if (IsCallerExtPart(opCode, params)) {
1840             DecreaseLoadCount();
1841         }
1842         HcFree(task);
1843         return HC_ERR_INIT_TASK_FAIL;
1844     }
1845     IncreaseCriticalCnt(ADD_TWO);
1846     return HC_SUCCESS;
1847 }
1848 
InitGroupRelatedModule(void)1849 int32_t InitGroupRelatedModule(void)
1850 {
1851     if (IsBroadcastSupported()) {
1852         if (InitBroadcastManager() != HC_SUCCESS) {
1853             LOGE("[End]: [Service]: Failed to init broadcast manage module!");
1854             return HC_ERR_SERVICE_NEED_RESTART;
1855         }
1856     }
1857     return HC_SUCCESS;
1858 }
1859 
DestroyGroupRelatedModule(void)1860 void DestroyGroupRelatedModule(void)
1861 {
1862     DestroyBroadcastManager();
1863 }
1864 
GetGroupImplInstance(void)1865 const GroupImpl *GetGroupImplInstance(void)
1866 {
1867     return &GROUP_IMPL_INSTANCE;
1868 }
1869 
IsGroupSupport(void)1870 bool IsGroupSupport(void)
1871 {
1872     return true;
1873 }