• 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 "device_auth.h"
17 
18 #include "alg_loader.h"
19 #include "callback_manager.h"
20 #include "channel_manager.h"
21 #include "common_defs.h"
22 #include "ext_plugin_manager.h"
23 #include "group_data_manager.h"
24 #include "dev_auth_module_manager.h"
25 #include "dev_session_mgr.h"
26 #include "group_manager.h"
27 #include "group_operation_common.h"
28 #include "hc_dev_info.h"
29 #include "hc_init_protection.h"
30 #include "hc_log.h"
31 #include "hc_time.h"
32 #include "hisysevent_adapter.h"
33 #include "hitrace_adapter.h"
34 #include "json_utils.h"
35 #include "key_manager.h"
36 #include "os_account_adapter.h"
37 #include "plugin_adapter.h"
38 #include "pseudonym_manager.h"
39 #include "task_manager.h"
40 #include "performance_dumper.h"
41 #include "identity_manager.h"
42 #include "group_auth_manager.h"
43 #include "account_task_manager.h"
44 
45 #include "identity_service.h"
46 #include "cred_session_util.h"
47 #include "credential_data_manager.h"
48 #include "identity_service_defines.h"
49 
50 static GroupAuthManager *g_groupAuthManager =  NULL;
51 static DeviceGroupManager *g_groupManagerInstance = NULL;
52 static AccountVerifier *g_accountVerifierInstance = NULL;
53 
54 static CredManager *g_credManager = NULL;
55 static CredAuthManager *g_credAuthManager = NULL;
56 
57 #define CLEAN_CRED 1
58 #define CLEAN_MODULE 2
59 #define CLEAN_CALLBACK 3
60 #define CLEAN_GROUP_MANAGER 4
61 #define CLEAN_IDENTITY_SERVICE 5
62 #define CLEAN_ALL 6
63 
64 typedef struct {
65     HcTaskBase base;
66     int64_t sessionId;
67 } StartSessionTask;
68 
69 typedef struct {
70     HcTaskBase base;
71     int64_t sessionId;
72     CJson *receivedMsg;
73 } ProcSessionTask;
74 
75 typedef struct {
76     HcTaskBase base;
77     int64_t requestId;
78 } SoftBusTask;
79 
IsDeviceIdHashMatch(const char * udid,const char * subUdidHash)80 static int32_t IsDeviceIdHashMatch(const char *udid, const char *subUdidHash)
81 {
82     Uint8Buff udidBuf = { (uint8_t *)udid, (uint32_t)HcStrlen(udid) };
83     uint8_t udidHashByte[SHA256_LEN] = { 0 };
84     Uint8Buff udidHashBuf = { udidHashByte, sizeof(udidHashByte) };
85     int32_t ret = GetLoaderInstance()->sha256(&udidBuf, &udidHashBuf);
86     if (ret != HC_SUCCESS) {
87         LOGE("sha256 failed, ret:%" LOG_PUB "d", ret);
88         return ret;
89     }
90     uint32_t udidHashLen = SHA256_LEN * BYTE_TO_HEX_OPER_LENGTH + 1;
91     char *udidHash = (char *)HcMalloc(udidHashLen, 0);
92     if (udidHash == NULL) {
93         LOGE("malloc udidHash string failed");
94         return HC_ERR_ALLOC_MEMORY;
95     }
96     ret = ByteToHexString(udidHashByte, SHA256_LEN, udidHash, udidHashLen);
97     if (ret != HC_SUCCESS) {
98         LOGE("Byte to hexString failed, ret:%" LOG_PUB "d", ret);
99         HcFree(udidHash);
100         return ret;
101     }
102     char *subUdidHashUpper = NULL;
103     ret = ToUpperCase(subUdidHash, &subUdidHashUpper);
104     if (ret != HC_SUCCESS) {
105         LOGE("Failed to convert the input sub udid hash to upper case!");
106         HcFree(udidHash);
107         return ret;
108     }
109     if (strstr((const char *)udidHash, subUdidHashUpper) != NULL) {
110         LOGI("udid hash is match!");
111         HcFree(udidHash);
112         HcFree(subUdidHashUpper);
113         return HC_SUCCESS;
114     }
115     HcFree(udidHash);
116     HcFree(subUdidHashUpper);
117     return HC_ERROR;
118 }
119 
GetUdidByGroup(int32_t osAccountId,const char * groupId,const char * deviceIdHash)120 static const char *GetUdidByGroup(int32_t osAccountId, const char *groupId, const char *deviceIdHash)
121 {
122     uint32_t index;
123     TrustedDeviceEntry **deviceEntry = NULL;
124     DeviceEntryVec deviceEntryVec = CREATE_HC_VECTOR(DeviceEntryVec);
125     QueryDeviceParams params = InitQueryDeviceParams();
126     params.groupId = groupId;
127     if (QueryDevices(osAccountId, &params, &deviceEntryVec) != HC_SUCCESS) {
128         LOGE("query trusted devices failed!");
129         ClearDeviceEntryVec(&deviceEntryVec);
130         return NULL;
131     }
132     FOR_EACH_HC_VECTOR(deviceEntryVec, index, deviceEntry) {
133         const char *udid = StringGet(&(*deviceEntry)->udid);
134         if (IsDeviceIdHashMatch(udid, deviceIdHash) == HC_SUCCESS) {
135             ClearDeviceEntryVec(&deviceEntryVec);
136             return udid;
137         }
138         continue;
139     }
140     ClearDeviceEntryVec(&deviceEntryVec);
141     return NULL;
142 }
143 
GetDeviceIdByUdidHash(int32_t osAccountId,const char * deviceIdHash)144 static const char *GetDeviceIdByUdidHash(int32_t osAccountId, const char *deviceIdHash)
145 {
146     if (deviceIdHash == NULL) {
147         LOGE("deviceIdHash is null");
148         return NULL;
149     }
150     QueryGroupParams queryParams = InitQueryGroupParams();
151     GroupEntryVec groupEntryVec = CreateGroupEntryVec();
152     int32_t ret = QueryGroups(osAccountId, &queryParams, &groupEntryVec);
153     if (ret != HC_SUCCESS) {
154         LOGE("Failed to query groups!");
155         ClearGroupEntryVec(&groupEntryVec);
156         return NULL;
157     }
158     uint32_t index;
159     TrustedGroupEntry **ptr = NULL;
160     FOR_EACH_HC_VECTOR(groupEntryVec, index, ptr) {
161         const TrustedGroupEntry *groupEntry = (const TrustedGroupEntry *)(*ptr);
162         const char *groupId = StringGet(&(groupEntry->id));
163         if (groupId == NULL) {
164             continue;
165         }
166         const char *udid = GetUdidByGroup(osAccountId, groupId, deviceIdHash);
167         if (udid != NULL) {
168             ClearGroupEntryVec(&groupEntryVec);
169             return udid;
170         }
171     }
172     ClearGroupEntryVec(&groupEntryVec);
173     return NULL;
174 }
175 
GetPeerUdidFromJson(int32_t osAccountId,const CJson * in)176 static const char *GetPeerUdidFromJson(int32_t osAccountId, const CJson *in)
177 {
178     const char *peerConnDeviceId = GetStringFromJson(in, FIELD_PEER_CONN_DEVICE_ID);
179     if (peerConnDeviceId == NULL) {
180         LOGI("get peerConnDeviceId from json fail.");
181         return NULL;
182     }
183     bool isUdidHash = false;
184     (void)GetBoolFromJson(in, FIELD_IS_UDID_HASH, &isUdidHash);
185     if (isUdidHash) {
186         const char *deviceId = GetDeviceIdByUdidHash(osAccountId, peerConnDeviceId);
187         return (deviceId == NULL ? peerConnDeviceId : deviceId);
188     }
189     return peerConnDeviceId;
190 }
191 
GetOpCodeFromContext(const CJson * context)192 static int32_t GetOpCodeFromContext(const CJson *context)
193 {
194     bool isAdmin = true;
195     (void)GetBoolFromJson(context, FIELD_IS_ADMIN, &isAdmin);
196     return isAdmin ? MEMBER_INVITE : MEMBER_JOIN;
197 }
198 
AddClientReqInfoToContext(int32_t osAccountId,int64_t requestId,const char * appId,CJson * context)199 static int32_t AddClientReqInfoToContext(int32_t osAccountId, int64_t requestId, const char *appId, CJson *context)
200 {
201     const char *groupId = GetStringFromJson(context, FIELD_GROUP_ID);
202     if (groupId == NULL) {
203         LOGE("get groupId from json fail.");
204         return HC_ERR_JSON_GET;
205     }
206     if (AddBoolToJson(context, FIELD_IS_BIND, true) != HC_SUCCESS) {
207         LOGE("add isBind to context fail.");
208         return HC_ERR_JSON_ADD;
209     }
210     if (AddBoolToJson(context, FIELD_IS_CLIENT, true) != HC_SUCCESS) {
211         LOGE("add isClient to context fail.");
212         return HC_ERR_JSON_ADD;
213     }
214     if (AddIntToJson(context, FIELD_OS_ACCOUNT_ID, osAccountId) != HC_SUCCESS) {
215         LOGE("add osAccountId to context fail.");
216         return HC_ERR_JSON_ADD;
217     }
218     if (AddInt64StringToJson(context, FIELD_REQUEST_ID, requestId) != HC_SUCCESS) {
219         LOGE("add requestId to context fail.");
220         return HC_ERR_JSON_ADD;
221     }
222     if (AddStringToJson(context, FIELD_APP_ID, appId) != HC_SUCCESS) {
223         LOGE("add appId to context fail.");
224         return HC_ERR_JSON_ADD;
225     }
226     int32_t opCode = GetOpCodeFromContext(context);
227     if (AddIntToJson(context, FIELD_OPERATION_CODE, opCode) != HC_SUCCESS) {
228         LOGE("add operationCode to context fail.");
229         return HC_ERR_JSON_ADD;
230     }
231     if (opCode == MEMBER_JOIN) {
232         return AddDevInfoToContextByInput(context);
233     }
234     int32_t res = AddDevInfoToContextByDb(groupId, context);
235     if (res != HC_SUCCESS) {
236         return res;
237     }
238     return AddGroupInfoToContextByDb(groupId, context);
239 }
240 
AddChannelInfoToContext(int32_t channelType,int64_t channelId,CJson * context)241 static int32_t AddChannelInfoToContext(int32_t channelType, int64_t channelId, CJson *context)
242 {
243     if (AddIntToJson(context, FIELD_CHANNEL_TYPE, channelType) != HC_SUCCESS) {
244         LOGE("add channelType to context fail.");
245         return HC_ERR_JSON_ADD;
246     }
247     if (AddByteToJson(context, FIELD_CHANNEL_ID, (uint8_t *)&channelId, sizeof(int64_t)) != HC_SUCCESS) {
248         LOGE("add channelId to context fail.");
249         return HC_ERR_JSON_ADD;
250     }
251     return HC_SUCCESS;
252 }
253 
BuildClientBindContext(int32_t osAccountId,int64_t requestId,const char * appId,const DeviceAuthCallback * callback,CJson * context)254 static int32_t BuildClientBindContext(int32_t osAccountId, int64_t requestId, const char *appId,
255     const DeviceAuthCallback *callback, CJson *context)
256 {
257     int32_t res = AddClientReqInfoToContext(osAccountId, requestId, appId, context);
258     if (res != HC_SUCCESS) {
259         return res;
260     }
261     ChannelType channelType = GetChannelType(callback, context);
262     int64_t channelId;
263     res = OpenChannel(channelType, context, requestId, &channelId);
264     if (res != HC_SUCCESS) {
265         LOGE("open channel fail.");
266         return res;
267     }
268     return AddChannelInfoToContext(channelType, channelId, context);
269 }
270 
DoStartSession(HcTaskBase * task)271 static void DoStartSession(HcTaskBase *task)
272 {
273     LOGI("start session task begin.");
274     if (task == NULL) {
275         LOGE("The input task is NULL, can't start session!");
276         return;
277     }
278     StartSessionTask *realTask = (StartSessionTask *)task;
279     SET_LOG_MODE(TRACE_MODE);
280     SET_TRACE_ID(realTask->sessionId);
281     int32_t res = StartDevSession(realTask->sessionId);
282     if (res != HC_SUCCESS) {
283         LOGE("start session fail.[Res]: %" LOG_PUB "d", res);
284         CloseDevSession(realTask->sessionId);
285     }
286 }
287 
DoProcSession(HcTaskBase * task)288 static void DoProcSession(HcTaskBase *task)
289 {
290     LOGI("proc session task begin.");
291     if (task == NULL) {
292         LOGE("The input task is NULL, can't start session!");
293         return;
294     }
295     ProcSessionTask *realTask = (ProcSessionTask *)task;
296     SET_LOG_MODE(TRACE_MODE);
297     SET_TRACE_ID(realTask->sessionId);
298     bool isFinish = false;
299     int32_t res = ProcessDevSession(realTask->sessionId, realTask->receivedMsg, &isFinish);
300     if (res != HC_SUCCESS) {
301         LOGE("ProcessDevSession fail. [Res]: %" LOG_PUB "d", res);
302         CloseDevSession(realTask->sessionId);
303         return;
304     }
305     LOGI("ProcessDevSession success. [State]: %" LOG_PUB "s", isFinish ? "FINISH" : "CONTINUE");
306     if (isFinish) {
307         CloseDevSession(realTask->sessionId);
308     }
309 }
310 
InitStartSessionTask(StartSessionTask * task,int64_t sessionId)311 static void InitStartSessionTask(StartSessionTask *task, int64_t sessionId)
312 {
313     task->base.doAction = DoStartSession;
314     task->base.destroy = NULL;
315     task->sessionId = sessionId;
316 }
317 
DestroyProcSessionTask(HcTaskBase * task)318 static void DestroyProcSessionTask(HcTaskBase *task)
319 {
320     ProcSessionTask *realTask = (ProcSessionTask *)task;
321     FreeJson(realTask->receivedMsg);
322 }
323 
InitProcSessionTask(ProcSessionTask * task,int64_t sessionId,CJson * receivedMsg)324 static void InitProcSessionTask(ProcSessionTask *task, int64_t sessionId, CJson *receivedMsg)
325 {
326     task->base.doAction = DoProcSession;
327     task->base.destroy = DestroyProcSessionTask;
328     task->sessionId = sessionId;
329     task->receivedMsg = receivedMsg;
330 }
331 
PushStartSessionTask(int64_t sessionId)332 static int32_t PushStartSessionTask(int64_t sessionId)
333 {
334     StartSessionTask *task = (StartSessionTask *)HcMalloc(sizeof(StartSessionTask), 0);
335     if (task == NULL) {
336         LOGE("Failed to allocate memory for task!");
337         return HC_ERR_ALLOC_MEMORY;
338     }
339     InitStartSessionTask(task, sessionId);
340     if (PushTask((HcTaskBase*)task) != HC_SUCCESS) {
341         LOGE("push start session task fail.");
342         HcFree(task);
343         return HC_ERR_INIT_TASK_FAIL;
344     }
345     LOGI("push start session task success.");
346     return HC_SUCCESS;
347 }
348 
AddOriginDataForPlugin(CJson * receivedMsg,const uint8_t * data)349 static int32_t AddOriginDataForPlugin(CJson *receivedMsg, const uint8_t *data)
350 {
351     if ((receivedMsg == NULL) || (data == NULL)) {
352         LOGE("Invalid params");
353         return HC_ERR_INVALID_PARAMS;
354     }
355     return AddStringToJson(receivedMsg, FIELD_PLUGIN_EXT_DATA, (const char *)data);
356 }
357 
PushProcSessionTask(int64_t sessionId,CJson * receivedMsg)358 static int32_t PushProcSessionTask(int64_t sessionId, CJson *receivedMsg)
359 {
360     ProcSessionTask *task = (ProcSessionTask *)HcMalloc(sizeof(ProcSessionTask), 0);
361     if (task == NULL) {
362         LOGE("Failed to allocate memory for task!");
363         return HC_ERR_ALLOC_MEMORY;
364     }
365     InitProcSessionTask(task, sessionId, receivedMsg);
366     if (PushTask((HcTaskBase*)task) != HC_SUCCESS) {
367         LOGE("push start session task fail.");
368         HcFree(task);
369         return HC_ERR_INIT_TASK_FAIL;
370     }
371     LOGI("push start session task success.");
372     return HC_SUCCESS;
373 }
374 
375 #ifdef ENABLE_P2P_BIND_LITE_PROTOCOL_CHECK
376 // If bind with iso short pin, groupVisibility must be private
CheckGroupVisibility(const CJson * context)377 static int32_t CheckGroupVisibility(const CJson *context)
378 {
379     int32_t osAccountId = INVALID_OS_ACCOUNT;
380     if (GetIntFromJson(context, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) {
381         LOGE("Failed to get osAccountId!");
382         return HC_ERR_JSON_GET;
383     }
384     const char *groupId = GetStringFromJson(context, FIELD_GROUP_ID);
385     if (groupId == NULL) {
386         LOGE("Failed to get groupId!");
387         return HC_ERR_JSON_GET;
388     }
389     const char *appId = GetStringFromJson(context, FIELD_APP_ID);
390     if (appId == NULL) {
391         LOGE("Failed to get appId!");
392         return HC_ERR_JSON_GET;
393     }
394     TrustedGroupEntry *entry = GetGroupEntryById(osAccountId, groupId);
395     if (entry == NULL) {
396         LOGE("Failed to get group entry!");
397         return HC_ERR_GROUP_NOT_EXIST;
398     }
399     int32_t res = CheckUpgradeIdentity(entry->upgradeFlag, appId, NULL);
400     if (res == HC_SUCCESS) {
401         LOGI("Group is from upgrade, no need to check visibility.");
402         DestroyGroupEntry(entry);
403         return HC_SUCCESS;
404     }
405     if (entry->visibility != GROUP_VISIBILITY_PRIVATE) {
406         LOGE("Group is not private, can not bind old version wearable device!");
407         DestroyGroupEntry(entry);
408         return HC_ERR_INVALID_PARAMS;
409     }
410     DestroyGroupEntry(entry);
411     return HC_SUCCESS;
412 }
413 #endif
414 
415 #ifdef ENABLE_P2P_BIND_LITE_PROTOCOL_CHECK
CheckBindParams(const CJson * context,bool isClient)416 static int32_t CheckBindParams(const CJson *context, bool isClient)
417 {
418     int32_t opCode;
419     if (GetIntFromJson(context, FIELD_OPERATION_CODE, &opCode) != HC_SUCCESS) {
420         LOGE("Failed to get operation code!");
421         return HC_ERR_JSON_GET;
422     }
423     if ((isClient && opCode == MEMBER_INVITE) || (!isClient && opCode == MEMBER_JOIN)) {
424         int32_t protocolExpandVal = INVALID_PROTOCOL_EXPAND_VALUE;
425         (void)GetIntFromJson(context, FIELD_PROTOCOL_EXPAND, &protocolExpandVal);
426         if (protocolExpandVal == LITE_PROTOCOL_COMPATIBILITY_MODE) {
427             return CheckGroupVisibility(context);
428         }
429     }
430     return HC_SUCCESS;
431 }
432 #endif
433 
StartClientBindSession(int32_t osAccountId,int64_t requestId,const char * appId,const char * contextParams,const DeviceAuthCallback * callback)434 static int32_t StartClientBindSession(int32_t osAccountId, int64_t requestId, const char *appId,
435     const char *contextParams, const DeviceAuthCallback *callback)
436 {
437     CJson *context = CreateJsonFromString(contextParams);
438     if (context == NULL) {
439         LOGE("Failed to create json from string!");
440         return HC_ERR_JSON_FAIL;
441     }
442     int32_t res = BuildClientBindContext(osAccountId, requestId, appId, callback, context);
443     if (res != HC_SUCCESS) {
444         FreeJson(context);
445         return res;
446     }
447 #ifdef ENABLE_P2P_BIND_LITE_PROTOCOL_CHECK
448     res = CheckBindParams(context, true);
449     if (res != HC_SUCCESS) {
450         FreeJson(context);
451         return res;
452     }
453 #endif
454     ChannelType channelType = GetChannelType(callback, context);
455     SessionInitParams params = { context, *callback };
456     res = OpenDevSession(requestId, appId, &params);
457     FreeJson(context);
458     if (res != HC_SUCCESS) {
459         LOGE("OpenDevSession fail. [Res]: %" LOG_PUB "d", res);
460         return res;
461     }
462     if (channelType == SERVICE_CHANNEL) {
463         res = PushStartSessionTask(requestId);
464         if (res != HC_SUCCESS) {
465             return res;
466         }
467     }
468     return HC_SUCCESS;
469 }
470 
471 #ifdef DEV_AUTH_HIVIEW_ENABLE
GetAddMemberCallEventFuncName(const char * addParams)472 static const char *GetAddMemberCallEventFuncName(const char *addParams)
473 {
474     if (addParams == NULL) {
475         LOGE("add params is null!");
476         return ADD_MEMBER_EVENT;
477     }
478     CJson *in = CreateJsonFromString(addParams);
479     if (in == NULL) {
480         LOGE("Failed to create json param!");
481         return ADD_MEMBER_EVENT;
482     }
483     int32_t protocolExpandVal = INVALID_PROTOCOL_EXPAND_VALUE;
484     (void)GetIntFromJson(in, FIELD_PROTOCOL_EXPAND, &protocolExpandVal);
485     FreeJson(in);
486     if (protocolExpandVal == LITE_PROTOCOL_STANDARD_MODE) {
487         return ADD_MEMBER_WITH_LITE_STANDARD;
488     } else if (protocolExpandVal == LITE_PROTOCOL_COMPATIBILITY_MODE) {
489         return ADD_MEMBER_WITH_LITE_COMPATIBILITY;
490     } else {
491         return ADD_MEMBER_EVENT;
492     }
493 }
494 #endif
495 
AddMemberToGroupInner(int32_t osAccountId,int64_t requestId,const char * appId,const char * addParams)496 static int32_t AddMemberToGroupInner(int32_t osAccountId, int64_t requestId, const char *appId, const char *addParams)
497 {
498     SET_LOG_MODE(TRACE_MODE);
499     SET_TRACE_ID(requestId);
500     ADD_PERFORM_DATA(requestId, true, true, HcGetCurTimeInMillis());
501     osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
502     if ((appId == NULL) || (addParams == NULL) || (osAccountId == INVALID_OS_ACCOUNT)) {
503         LOGE("Invalid input parameters!");
504         return HC_ERR_INVALID_PARAMS;
505     }
506     if (!CheckIsForegroundOsAccountId(osAccountId)) {
507         LOGE("This access is not from the foreground user, rejected it.");
508         return HC_ERR_CROSS_USER_ACCESS;
509     }
510     if (!IsOsAccountUnlocked(osAccountId)) {
511         LOGE("Os account is not unlocked!");
512         return HC_ERR_OS_ACCOUNT_NOT_UNLOCKED;
513     }
514     LOGI("Start to add member to group. [ReqId]: %" LOG_PUB PRId64 ", [OsAccountId]: %" LOG_PUB "d, [AppId]: %"
515         LOG_PUB "s", requestId, osAccountId, appId);
516     const DeviceAuthCallback *callback = GetGMCallbackByAppId(appId);
517     if (callback == NULL) {
518         LOGE("Failed to find callback by appId! [AppId]: %" LOG_PUB "s", appId);
519         return HC_ERR_CALLBACK_NOT_FOUND;
520     }
521     return StartClientBindSession(osAccountId, requestId, appId, addParams, callback);
522 }
523 
524 #ifdef DEV_AUTH_HIVIEW_ENABLE
GetBizScene(bool isBind,bool isClient)525 static DevAuthBizScene GetBizScene(bool isBind, bool isClient)
526 {
527     if (isBind) {
528         if (isClient) {
529             return BIZ_SCENE_ADD_MEMBER_CLIENT;
530         } else {
531             return BIZ_SCENE_ADD_MEMBER_SERVER;
532         }
533     } else {
534         if (isClient) {
535             return BIZ_SCENE_AUTH_DEVICE_CLIENT;
536         } else {
537             return BIZ_SCENE_AUTH_DEVICE_SERVER;
538         }
539     }
540 }
541 #endif
542 
ReportBehaviorBeginEvent(bool isBind,bool isClient,int64_t reqId)543 static void ReportBehaviorBeginEvent(bool isBind, bool isClient, int64_t reqId)
544 {
545 #ifdef DEV_AUTH_HIVIEW_ENABLE
546     char *funcName = isBind ? ADD_MEMBER_EVENT : AUTH_DEV_EVENT;
547     DevAuthBizScene scene = GetBizScene(isBind, isClient);
548     DevAuthBehaviorEvent eventData = { 0 };
549     BuildBehaviorEventData(&eventData, funcName, scene, BIZ_STATE_BEGIN, BIZ_STAGE_BEGIN);
550     char anonymousLocalUdid[ANONYMOUS_UDID_LEN + 1] = { 0 };
551     if (isBind) {
552         eventData.hostPkg = ADD_MEMBER_HOST_PKG_NAME;
553         eventData.toCallPkg = ADD_MEMBER_TO_CALL_PKG_NAME;
554     } else {
555         eventData.hostPkg = AUTH_DEVICE_HOST_PKG_NAME;
556         char selfUdid[INPUT_UDID_LEN] = { 0 };
557         (void)HcGetUdid((uint8_t *)selfUdid, INPUT_UDID_LEN);
558         if (GetAnonymousString(selfUdid, anonymousLocalUdid, ANONYMOUS_UDID_LEN) == HC_SUCCESS) {
559             eventData.localUdid = anonymousLocalUdid;
560         }
561     }
562     char concurrentId[MAX_REQUEST_ID_LEN] = { 0 };
563     (void)sprintf_s(concurrentId, sizeof(concurrentId), "%" PRId64, reqId);
564     eventData.concurrentId = concurrentId;
565     DevAuthReportBehaviorEvent(&eventData);
566 #else
567     (void)isBind;
568     (void)isClient;
569     (void)reqId;
570 #endif
571 }
572 
ReportBehaviorBeginResultEvent(bool isBind,bool isClient,int64_t reqId,const char * peerUdid,int32_t res)573 static void ReportBehaviorBeginResultEvent(bool isBind, bool isClient, int64_t reqId, const char *peerUdid, int32_t res)
574 {
575 #ifdef DEV_AUTH_HIVIEW_ENABLE
576     char *funcName = isBind ? ADD_MEMBER_EVENT : AUTH_DEV_EVENT;
577     DevAuthBizScene scene = GetBizScene(isBind, isClient);
578     DevAuthBehaviorEvent eventData = { 0 };
579     BuildBehaviorEventData(&eventData, funcName, scene, BIZ_STATE_PROCESS, BIZ_STAGE_BEGIN);
580     char anonymousLocalUdid[ANONYMOUS_UDID_LEN + 1] = { 0 };
581     char anonymousPeerUdid[ANONYMOUS_UDID_LEN + 1] = { 0 };
582     if (isBind) {
583         eventData.hostPkg = ADD_MEMBER_HOST_PKG_NAME;
584         eventData.toCallPkg = ADD_MEMBER_TO_CALL_PKG_NAME;
585     } else {
586         eventData.hostPkg = AUTH_DEVICE_HOST_PKG_NAME;
587         char selfUdid[INPUT_UDID_LEN] = { 0 };
588         (void)HcGetUdid((uint8_t *)selfUdid, INPUT_UDID_LEN);
589         if (GetAnonymousString(selfUdid, anonymousLocalUdid, ANONYMOUS_UDID_LEN) == HC_SUCCESS) {
590             eventData.localUdid = anonymousLocalUdid;
591         }
592         if (GetAnonymousString(peerUdid, anonymousPeerUdid, ANONYMOUS_UDID_LEN) == HC_SUCCESS) {
593             eventData.peerUdid = anonymousPeerUdid;
594         }
595     }
596     char concurrentId[MAX_REQUEST_ID_LEN] = { 0 };
597     (void)sprintf_s(concurrentId, sizeof(concurrentId), "%" PRId64, reqId);
598     eventData.concurrentId = concurrentId;
599     if (res == HC_SUCCESS) {
600         eventData.stageRes = STAGE_RES_SUCCESS;
601     } else {
602         eventData.stageRes = STAGE_RES_FAILED;
603         eventData.errorCode = res;
604     }
605     DevAuthReportBehaviorEvent(&eventData);
606 #else
607     (void)isBind;
608     (void)isClient;
609     (void)reqId;
610     (void)peerUdid;
611     (void)res;
612 #endif
613 }
614 
AddMemberToGroup(int32_t osAccountId,int64_t requestId,const char * appId,const char * addParams)615 static int32_t AddMemberToGroup(int32_t osAccountId, int64_t requestId, const char *appId, const char *addParams)
616 {
617     ReportBehaviorBeginEvent(true, true, requestId);
618     int32_t res = AddMemberToGroupInner(osAccountId, requestId, appId, addParams);
619     ReportBehaviorBeginResultEvent(true, true, requestId, NULL, res);
620 #ifdef DEV_AUTH_HIVIEW_ENABLE
621     const char *callEventFuncName = GetAddMemberCallEventFuncName(addParams);
622     DEV_AUTH_REPORT_UE_CALL_EVENT_BY_PARAMS(osAccountId, addParams, appId, callEventFuncName);
623 #endif
624     return res;
625 }
626 
AddServerReqInfoToContext(int64_t requestId,const char * appId,int32_t opCode,const CJson * receivedMsg,CJson * context)627 static int32_t AddServerReqInfoToContext(int64_t requestId, const char *appId, int32_t opCode,
628     const CJson *receivedMsg, CJson *context)
629 {
630     const char *groupId = GetStringFromJson(receivedMsg, FIELD_GROUP_ID);
631     if (groupId == NULL) {
632         LOGE("get groupId from json fail.");
633         return HC_ERR_JSON_GET;
634     }
635     if (AddBoolToJson(context, FIELD_IS_SINGLE_CRED, true) != HC_SUCCESS) {
636         LOGE("add isSingleCred to context fail.");
637         return HC_ERR_JSON_ADD;
638     }
639     if (AddBoolToJson(context, FIELD_IS_BIND, true) != HC_SUCCESS) {
640         LOGE("add isBind to context fail.");
641         return HC_ERR_JSON_ADD;
642     }
643     if (AddBoolToJson(context, FIELD_IS_CLIENT, false) != HC_SUCCESS) {
644         LOGE("add isClient to context fail.");
645         return HC_ERR_JSON_ADD;
646     }
647     if (AddInt64StringToJson(context, FIELD_REQUEST_ID, requestId) != HC_SUCCESS) {
648         LOGE("add requestId to context fail.");
649         return HC_ERR_JSON_ADD;
650     }
651     if (AddStringToJson(context, FIELD_APP_ID, appId) != HC_SUCCESS) {
652         LOGE("add appId to context fail.");
653         return HC_ERR_JSON_ADD;
654     }
655     if (AddIntToJson(context, FIELD_OPERATION_CODE, opCode) != HC_SUCCESS) {
656         LOGE("add opCode to context fail.");
657         return HC_ERR_JSON_ADD;
658     }
659     int32_t res;
660     if (opCode == MEMBER_INVITE) {
661         res = AddGroupInfoToContextByInput(receivedMsg, context);
662         if (res != HC_SUCCESS) {
663             return res;
664         }
665         return AddDevInfoToContextByInput(context);
666     }
667     res = AddGroupInfoToContextByDb(groupId, context);
668     if (res != HC_SUCCESS) {
669         return res;
670     }
671     return AddDevInfoToContextByDb(groupId, context);
672 }
673 
CheckConfirmationExist(const CJson * context)674 static int32_t CheckConfirmationExist(const CJson *context)
675 {
676     uint32_t confirmation = REQUEST_REJECTED;
677     if (GetUnsignedIntFromJson(context, FIELD_CONFIRMATION, &confirmation) != HC_SUCCESS) {
678         LOGE("Failed to get confimation from json!");
679         return HC_ERR_JSON_GET;
680     }
681     if (confirmation == REQUEST_ACCEPTED) {
682         LOGI("The service accepts this request!");
683     } else {
684         LOGW("The service rejects this request!");
685     }
686     return HC_SUCCESS;
687 }
688 
AddOsAccountIdToContextIfValid(CJson * context)689 static int32_t AddOsAccountIdToContextIfValid(CJson *context)
690 {
691     int32_t osAccountId = ANY_OS_ACCOUNT;
692     (void)GetIntFromJson(context, FIELD_OS_ACCOUNT_ID, &osAccountId);
693     osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
694     LOGI("[OsAccountId]: %" LOG_PUB "d", osAccountId);
695     if (osAccountId == INVALID_OS_ACCOUNT) {
696         return HC_ERR_INVALID_PARAMS;
697     }
698     if (!CheckIsForegroundOsAccountId(osAccountId)) {
699         LOGE("This access is not from the foreground user, rejected it.");
700         return HC_ERR_CROSS_USER_ACCESS;
701     }
702     if (!IsOsAccountUnlocked(osAccountId)) {
703         LOGE("Os account is not unlocked!");
704         return HC_ERR_OS_ACCOUNT_NOT_UNLOCKED;
705     }
706     if (AddIntToJson(context, FIELD_OS_ACCOUNT_ID, osAccountId) != HC_SUCCESS) {
707         LOGE("add operationCode to context fail.");
708         return HC_ERR_JSON_ADD;
709     }
710     return HC_SUCCESS;
711 }
712 
BuildServerBindContext(int64_t requestId,const char * appId,int32_t opCode,const CJson * receivedMsg,CJson * context)713 static int32_t BuildServerBindContext(int64_t requestId, const char *appId, int32_t opCode,
714     const CJson *receivedMsg, CJson *context)
715 {
716     int32_t res = CheckConfirmationExist(context);
717     if (res != HC_SUCCESS) {
718         return res;
719     }
720     res = AddOsAccountIdToContextIfValid(context);
721     if (res != HC_SUCCESS) {
722         return res;
723     }
724     res = AddServerReqInfoToContext(requestId, appId, opCode, receivedMsg, context);
725     if (res != HC_SUCCESS) {
726         return res;
727     }
728     int32_t channelType;
729     int64_t channelId = DEFAULT_CHANNEL_ID;
730     if (GetByteFromJson(receivedMsg, FIELD_CHANNEL_ID, (uint8_t *)&channelId, sizeof(int64_t)) == HC_SUCCESS) {
731         channelType = SOFT_BUS;
732     } else {
733         channelType = SERVICE_CHANNEL;
734     }
735     return AddChannelInfoToContext(channelType, channelId, context);
736 }
737 
GetAppIdFromReceivedMsg(const CJson * receivedMsg)738 static const char *GetAppIdFromReceivedMsg(const CJson *receivedMsg)
739 {
740     const char *appId = GetStringFromJson(receivedMsg, FIELD_APP_ID);
741     if (appId == NULL) {
742         LOGW("use default device manager appId.");
743         appId = DM_APP_ID;
744     }
745     return appId;
746 }
747 
CreateAppIdJsonString(const char * appId,char ** reqParames)748 static int32_t CreateAppIdJsonString(const char *appId, char **reqParames)
749 {
750     CJson *reqJson = CreateJson();
751     if ((reqJson == NULL) || (reqParames == NULL)) {
752         LOGE("Failed to create json!");
753         return HC_ERR_JSON_CREATE;
754     }
755     if (AddStringToJson(reqJson, FIELD_APP_ID, appId) != HC_SUCCESS) {
756         LOGE("Failed to add appId!");
757         FreeJson(reqJson);
758         return HC_ERR_JSON_ADD;
759     }
760     *reqParames = PackJsonToString(reqJson);
761     FreeJson(reqJson);
762     if ((*reqParames) == NULL) {
763         LOGE("Failed to create reqParames string!");
764         return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL;
765     }
766     return HC_SUCCESS;
767 }
768 
OpenServerBindSession(int64_t requestId,const CJson * receivedMsg)769 static int32_t OpenServerBindSession(int64_t requestId, const CJson *receivedMsg)
770 {
771     const char *appId = GetAppIdFromReceivedMsg(receivedMsg);
772     const DeviceAuthCallback *callback = GetGMCallbackByAppId(appId);
773     if (callback == NULL) {
774         LOGE("Failed to find callback by appId! [AppId]: %" LOG_PUB "s", appId);
775         return HC_ERR_CALLBACK_NOT_FOUND;
776     }
777     int32_t opCode;
778     if (GetIntFromJson(receivedMsg, FIELD_GROUP_OP, &opCode) != HC_SUCCESS) {
779         if (GetIntFromJson(receivedMsg, FIELD_OP_CODE, &opCode) != HC_SUCCESS) {
780             opCode = MEMBER_JOIN;
781             LOGW("use default opCode.");
782         }
783     }
784     char *reqParames = NULL;
785     int32_t res = CreateAppIdJsonString(appId, &reqParames);
786     if (res != HC_SUCCESS) {
787         LOGE("Create reqParames from appid failed!");
788         return res;
789     }
790     char *returnDataStr = ProcessRequestCallback(requestId, opCode, reqParames, callback);
791     FreeJsonString(reqParames);
792     if (returnDataStr == NULL) {
793         LOGE("The OnRequest callback is fail!");
794         return HC_ERR_REQ_REJECTED;
795     }
796     CJson *context = CreateJsonFromString(returnDataStr);
797     FreeJsonString(returnDataStr);
798     if (context == NULL) {
799         LOGE("Failed to create context from string!");
800         return HC_ERR_JSON_FAIL;
801     }
802     res = BuildServerBindContext(requestId, appId, opCode, receivedMsg, context);
803     if (res != HC_SUCCESS) {
804         FreeJson(context);
805         return res;
806     }
807 #ifdef ENABLE_P2P_BIND_LITE_PROTOCOL_CHECK
808     res = CheckBindParams(context, false);
809     if (res != HC_SUCCESS) {
810         FreeJson(context);
811         return res;
812     }
813 #endif
814     SessionInitParams params = { context, *callback };
815     res = OpenDevSession(requestId, appId, &params);
816     FreeJson(context);
817     return res;
818 }
819 
ProcessBindDataInner(int64_t requestId,const uint8_t * data,uint32_t dataLen)820 static int32_t ProcessBindDataInner(int64_t requestId, const uint8_t *data, uint32_t dataLen)
821 {
822     SET_LOG_MODE(TRACE_MODE);
823     SET_TRACE_ID(requestId);
824     if (!IsSessionExist(requestId)) {
825         ADD_PERFORM_DATA(requestId, true, false, HcGetCurTimeInMillis());
826     } else {
827         UPDATE_PERFORM_DATA_BY_SELF_INDEX(requestId, HcGetCurTimeInMillis());
828     }
829     if ((data == NULL) || (dataLen == 0) || (dataLen > MAX_DATA_BUFFER_SIZE)) {
830         LOGE("The input data is invalid!");
831         return HC_ERR_INVALID_PARAMS;
832     }
833     LOGI("[Start]: RequestProcessBindData! [ReqId]: %" LOG_PUB PRId64, requestId);
834     CJson *receivedMsg = CreateJsonFromString((const char *)data);
835     if (receivedMsg == NULL) {
836         LOGE("Failed to create json from string!");
837         return HC_ERR_JSON_FAIL;
838     }
839     int32_t res;
840     if (!IsSessionExist(requestId)) {
841         res = OpenServerBindSession(requestId, receivedMsg);
842         if (res != HC_SUCCESS) {
843             FreeJson(receivedMsg);
844             return res;
845         }
846     }
847     res = PushProcSessionTask(requestId, receivedMsg);
848     if (res != HC_SUCCESS) {
849         FreeJson(receivedMsg);
850         return res;
851     }
852     return HC_SUCCESS;
853 }
854 
ProcessBindData(int64_t requestId,const uint8_t * data,uint32_t dataLen)855 static int32_t ProcessBindData(int64_t requestId, const uint8_t *data, uint32_t dataLen)
856 {
857     bool isSessionExist = IsSessionExist(requestId);
858     if (!isSessionExist) {
859         ReportBehaviorBeginEvent(true, false, requestId);
860     }
861     int32_t res = ProcessBindDataInner(requestId, data, dataLen);
862     if (!isSessionExist) {
863         ReportBehaviorBeginResultEvent(true, false, requestId, NULL, res);
864     }
865     return res;
866 }
867 
BuildClientAuthContext(int32_t osAccountId,int64_t requestId,const char * appId,CJson * context,char ** returnPeerUdid)868 static int32_t BuildClientAuthContext(int32_t osAccountId, int64_t requestId, const char *appId, CJson *context,
869     char **returnPeerUdid)
870 {
871     const char *peerUdid = GetPeerUdidFromJson(osAccountId, context);
872     if (peerUdid != NULL) {
873         (void)DeepCopyString(peerUdid, returnPeerUdid);
874         char *deviceId = NULL;
875         if (DeepCopyString(peerUdid, &deviceId) != HC_SUCCESS) {
876             LOGE("Failed to copy peerUdid!");
877             return HC_ERR_ALLOC_MEMORY;
878         }
879         if (AddStringToJson(context, FIELD_PEER_UDID, deviceId) != HC_SUCCESS) {
880             LOGE("add peerUdid to context fail.");
881             HcFree(deviceId);
882             return HC_ERR_JSON_ADD;
883         }
884         if (AddStringToJson(context, FIELD_PEER_CONN_DEVICE_ID, deviceId) != HC_SUCCESS) {
885             LOGE("add peerConnDeviceId to context fail.");
886             HcFree(deviceId);
887             return HC_ERR_JSON_ADD;
888         }
889         PRINT_SENSITIVE_DATA("PeerUdid", deviceId);
890         HcFree(deviceId);
891     }
892     if (AddBoolToJson(context, FIELD_IS_BIND, false) != HC_SUCCESS) {
893         LOGE("add isBind to context fail.");
894         return HC_ERR_JSON_ADD;
895     }
896     if (AddBoolToJson(context, FIELD_IS_CLIENT, true) != HC_SUCCESS) {
897         LOGE("add isClient to context fail.");
898         return HC_ERR_JSON_ADD;
899     }
900     if (AddIntToJson(context, FIELD_OS_ACCOUNT_ID, osAccountId) != HC_SUCCESS) {
901         LOGE("add osAccountId to context fail.");
902         return HC_ERR_JSON_ADD;
903     }
904     if (AddInt64StringToJson(context, FIELD_REQUEST_ID, requestId) != HC_SUCCESS) {
905         LOGE("add requestId to context fail.");
906         return HC_ERR_JSON_ADD;
907     }
908     if (AddStringToJson(context, FIELD_APP_ID, appId) != HC_SUCCESS) {
909         LOGE("add appId to context fail.");
910         return HC_ERR_JSON_ADD;
911     }
912     if (AddIntToJson(context, FIELD_OPERATION_CODE, AUTH_FORM_ACCOUNT_UNRELATED) != HC_SUCCESS) {
913         LOGE("add opCode to context fail.");
914         return HC_ERR_JSON_ADD;
915     }
916     return AddChannelInfoToContext(SERVICE_CHANNEL, DEFAULT_CHANNEL_ID, context);
917 }
918 
BuildP2PBindContext(CJson * context)919 static int32_t BuildP2PBindContext(CJson *context)
920 {
921     int32_t acquireType = -1;
922     if (GetIntFromJson(context, FIELD_ACQURIED_TYPE, &acquireType) != HC_SUCCESS) {
923         LOGE("Failed to get acquireType from reqJsonStr!");
924         return HC_ERR_JSON_FAIL;
925     }
926     if ((acquireType == P2P_BIND) && AddBoolToJson(context, FIELD_IS_DIRECT_AUTH, true) != HC_SUCCESS) {
927         LOGE("add isDirectAuth to context fail.");
928         return HC_ERR_JSON_ADD;
929     }
930     if (AddIntToJson(context, FIELD_OPERATION_CODE, acquireType) != HC_SUCCESS) {
931         LOGE("add opCode to context fail.");
932         return HC_ERR_JSON_ADD;
933     }
934     const char *serviceType = GetStringFromJson(context, FIELD_SERVICE_TYPE);
935     if (serviceType == NULL) {
936         if ((acquireType == P2P_BIND) &&
937             AddStringToJson(context, FIELD_SERVICE_TYPE, DEFAULT_SERVICE_TYPE) != HC_SUCCESS) {
938             LOGE("add serviceType to context fail.");
939             return HC_ERR_JSON_ADD;
940         }
941     }
942     return HC_SUCCESS;
943 }
944 
AuthDeviceInner(int32_t osAccountId,int64_t authReqId,const char * authParams,const DeviceAuthCallback * gaCallback,char ** returnPeerUdid)945 static int32_t AuthDeviceInner(int32_t osAccountId, int64_t authReqId, const char *authParams,
946     const DeviceAuthCallback *gaCallback, char **returnPeerUdid)
947 {
948     SET_LOG_MODE(TRACE_MODE);
949     SET_TRACE_ID(authReqId);
950     ADD_PERFORM_DATA(authReqId, false, true, HcGetCurTimeInMillis());
951     osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
952     LOGI("Begin AuthDevice. [ReqId]: %" LOG_PUB PRId64 ", [OsAccountId]: %" LOG_PUB "d", authReqId, osAccountId);
953     if ((authParams == NULL) || (osAccountId == INVALID_OS_ACCOUNT) || (gaCallback == NULL)) {
954         LOGE("The input auth params is invalid!");
955         return HC_ERR_INVALID_PARAMS;
956     }
957     if (!CheckIsForegroundOsAccountId(osAccountId)) {
958         LOGE("This access is not from the foreground user, rejected it.");
959         return HC_ERR_CROSS_USER_ACCESS;
960     }
961     if (!IsOsAccountUnlocked(osAccountId)) {
962         LOGE("Os account is not unlocked!");
963         return HC_ERR_OS_ACCOUNT_NOT_UNLOCKED;
964     }
965     CJson *context = CreateJsonFromString(authParams);
966     if (context == NULL) {
967         LOGE("Failed to create json from string!");
968         return HC_ERR_JSON_FAIL;
969     }
970     const char *appId = GetStringFromJson(context, FIELD_SERVICE_PKG_NAME);
971     if (appId == NULL) {
972         LOGE("get servicePkgName from json fail.");
973         FreeJson(context);
974         return HC_ERR_JSON_GET;
975     }
976     int32_t res = BuildClientAuthContext(osAccountId, authReqId, appId, context, returnPeerUdid);
977     if (res != HC_SUCCESS) {
978         FreeJson(context);
979         return res;
980     }
981     DEV_AUTH_REPORT_UE_CALL_EVENT_BY_PARAMS(osAccountId, authParams, appId, AUTH_DEV_EVENT);
982     SessionInitParams params = { context, *gaCallback };
983     res = OpenDevSession(authReqId, appId, &params);
984     FreeJson(context);
985     if (res != HC_SUCCESS) {
986         LOGE("OpenDevSession fail. [Res]: %" LOG_PUB "d", res);
987         return res;
988     }
989     return PushStartSessionTask(authReqId);
990 }
991 
AuthDevice(int32_t osAccountId,int64_t authReqId,const char * authParams,const DeviceAuthCallback * gaCallback)992 static int32_t AuthDevice(int32_t osAccountId, int64_t authReqId, const char *authParams,
993     const DeviceAuthCallback *gaCallback)
994 {
995     ReportBehaviorBeginEvent(false, true, authReqId);
996     char *peerUdid = NULL;
997     int32_t res = AuthDeviceInner(osAccountId, authReqId, authParams, gaCallback, &peerUdid);
998     ReportBehaviorBeginResultEvent(false, true, authReqId, peerUdid, res);
999     if (peerUdid != NULL) {
1000         HcFree(peerUdid);
1001     }
1002     return res;
1003 }
1004 
AddDeviceIdToJson(CJson * context,const char * peerUdid)1005 static int32_t AddDeviceIdToJson(CJson *context, const char *peerUdid)
1006 {
1007     char *deviceId = NULL;
1008     if (DeepCopyString(peerUdid, &deviceId) != HC_SUCCESS) {
1009         LOGE("Failed to copy peerUdid!");
1010         return HC_ERR_ALLOC_MEMORY;
1011     }
1012     if (AddStringToJson(context, FIELD_PEER_UDID, deviceId) != HC_SUCCESS) {
1013         LOGE("add peerUdid to context fail.");
1014         HcFree(deviceId);
1015         return HC_ERR_JSON_ADD;
1016     }
1017     if (AddStringToJson(context, FIELD_PEER_CONN_DEVICE_ID, deviceId) != HC_SUCCESS) {
1018         LOGE("add peerConnDeviceId to context fail.");
1019         HcFree(deviceId);
1020         return HC_ERR_JSON_ADD;
1021     }
1022     HcFree(deviceId);
1023     return HC_SUCCESS;
1024 }
1025 
BuildServerAuthContext(int64_t requestId,int32_t opCode,const char * appId,CJson * context,char ** returnPeerUdid)1026 static int32_t BuildServerAuthContext(int64_t requestId, int32_t opCode, const char *appId, CJson *context,
1027     char **returnPeerUdid)
1028 {
1029     int32_t res = CheckConfirmationExist(context);
1030     if (res != HC_SUCCESS) {
1031         return res;
1032     }
1033     res = AddOsAccountIdToContextIfValid(context);
1034     if (res != HC_SUCCESS) {
1035         return res;
1036     }
1037     int32_t osAccountId = ANY_OS_ACCOUNT;
1038     (void)GetIntFromJson(context, FIELD_OS_ACCOUNT_ID, &osAccountId);
1039     const char *peerUdid = GetPeerUdidFromJson(osAccountId, context);
1040     if (peerUdid == NULL) {
1041         return HC_ERR_JSON_GET;
1042     }
1043     (void)DeepCopyString(peerUdid, returnPeerUdid);
1044     PRINT_SENSITIVE_DATA("PeerUdid", peerUdid);
1045     if (AddDeviceIdToJson(context, peerUdid) != HC_SUCCESS) {
1046         LOGE("add deviceId to context fail.");
1047         return HC_ERR_JSON_ADD;
1048     }
1049     if (AddBoolToJson(context, FIELD_IS_BIND, false) != HC_SUCCESS) {
1050         LOGE("add isBind to context fail.");
1051         return HC_ERR_JSON_ADD;
1052     }
1053     if (AddBoolToJson(context, FIELD_IS_CLIENT, false) != HC_SUCCESS) {
1054         LOGE("add isClient to context fail.");
1055         return HC_ERR_JSON_ADD;
1056     }
1057     if (AddInt64StringToJson(context, FIELD_REQUEST_ID, requestId) != HC_SUCCESS) {
1058         LOGE("add requestId to context fail.");
1059         return HC_ERR_JSON_ADD;
1060     }
1061     if (AddStringToJson(context, FIELD_APP_ID, appId) != HC_SUCCESS) {
1062         LOGE("add appId to context fail.");
1063         return HC_ERR_JSON_ADD;
1064     }
1065     if (AddIntToJson(context, FIELD_OPERATION_CODE, opCode) != HC_SUCCESS) {
1066         LOGE("add opCode to context fail.");
1067         return HC_ERR_JSON_ADD;
1068     }
1069     return AddChannelInfoToContext(SERVICE_CHANNEL, DEFAULT_CHANNEL_ID, context);
1070 }
1071 
BuildServerP2PAuthContext(int64_t requestId,int32_t opCode,const char * appId,CJson * context)1072 static int32_t BuildServerP2PAuthContext(int64_t requestId, int32_t opCode, const char *appId, CJson *context)
1073 {
1074     int32_t res = CheckConfirmationExist(context);
1075     if (res != HC_SUCCESS) {
1076         return res;
1077     }
1078     res = AddOsAccountIdToContextIfValid(context);
1079     if (res != HC_SUCCESS) {
1080         return res;
1081     }
1082     const char *peerUdid = GetStringFromJson(context, FIELD_PEER_CONN_DEVICE_ID);
1083     const char *pinCode = GetStringFromJson(context, FIELD_PIN_CODE);
1084     if (peerUdid == NULL && pinCode == NULL) {
1085         LOGE("need peerConnDeviceId or pinCode!");
1086         return HC_ERR_JSON_GET;
1087     }
1088     if (peerUdid != NULL) {
1089         PRINT_SENSITIVE_DATA("PeerUdid", peerUdid);
1090         if (AddDeviceIdToJson(context, peerUdid) != HC_SUCCESS) {
1091             LOGE("add deviceId to context fail.");
1092             return HC_ERR_JSON_ADD;
1093         }
1094     }
1095     if (AddBoolToJson(context, FIELD_IS_SINGLE_CRED, true) != HC_SUCCESS) {
1096         LOGE("add isSingleCred to context fail.");
1097         return HC_ERR_JSON_ADD;
1098     }
1099     if (AddBoolToJson(context, FIELD_IS_BIND, false) != HC_SUCCESS) {
1100         LOGE("add isBind to context fail.");
1101         return HC_ERR_JSON_ADD;
1102     }
1103     if (AddBoolToJson(context, FIELD_IS_CLIENT, false) != HC_SUCCESS) {
1104         LOGE("add isClient to context fail.");
1105         return HC_ERR_JSON_ADD;
1106     }
1107     if (AddInt64StringToJson(context, FIELD_REQUEST_ID, requestId) != HC_SUCCESS) {
1108         LOGE("add requestId to context fail.");
1109         return HC_ERR_JSON_ADD;
1110     }
1111     if (AddStringToJson(context, FIELD_APP_ID, appId) != HC_SUCCESS) {
1112         LOGE("add appId to context fail.");
1113         return HC_ERR_JSON_ADD;
1114     }
1115     if (AddIntToJson(context, FIELD_OPERATION_CODE, opCode) != HC_SUCCESS) {
1116         LOGE("add opCode to context fail.");
1117         return HC_ERR_JSON_ADD;
1118     }
1119     return AddChannelInfoToContext(SERVICE_CHANNEL, DEFAULT_CHANNEL_ID, context);
1120 }
1121 
OpenServerAuthSession(int64_t requestId,const CJson * receivedMsg,const DeviceAuthCallback * callback,char ** returnPeerUdid)1122 static int32_t OpenServerAuthSession(int64_t requestId, const CJson *receivedMsg, const DeviceAuthCallback *callback,
1123     char **returnPeerUdid)
1124 {
1125     int32_t opCode = AUTH_FORM_ACCOUNT_UNRELATED;
1126     if (GetIntFromJson(receivedMsg, FIELD_AUTH_FORM, &opCode) != HC_SUCCESS) {
1127         if (GetIntFromJson(receivedMsg, FIELD_OP_CODE, &opCode) != HC_SUCCESS) {
1128             opCode = AUTH_FORM_INVALID_TYPE;
1129             LOGW("use default opCode.");
1130         }
1131     }
1132     char *returnDataStr = ProcessRequestCallback(requestId, opCode, NULL, callback);
1133     if (returnDataStr == NULL) {
1134         LOGE("The OnRequest callback is fail!");
1135         return HC_ERR_REQ_REJECTED;
1136     }
1137     CJson *context = CreateJsonFromString(returnDataStr);
1138     FreeJsonString(returnDataStr);
1139     if (context == NULL) {
1140         LOGE("Failed to create context from string!");
1141         return HC_ERR_JSON_FAIL;
1142     }
1143     const char *appId = GetStringFromJson(context, FIELD_SERVICE_PKG_NAME);
1144     if (appId == NULL) {
1145         LOGE("get appId from json fail.");
1146         FreeJson(context);
1147         return HC_ERR_JSON_GET;
1148     }
1149     int32_t res = BuildServerAuthContext(requestId, opCode, appId, context, returnPeerUdid);
1150     if (res != HC_SUCCESS) {
1151         FreeJson(context);
1152         return res;
1153     }
1154     SessionInitParams params = { context, *callback };
1155     res = OpenDevSession(requestId, appId, &params);
1156     FreeJson(context);
1157     return res;
1158 }
1159 
OpenServerAuthSessionForP2P(int64_t requestId,const CJson * receivedMsg,const DeviceAuthCallback * callback)1160 static int32_t OpenServerAuthSessionForP2P(
1161     int64_t requestId, const CJson *receivedMsg, const DeviceAuthCallback *callback)
1162 {
1163     int32_t opCode = P2P_BIND;
1164     if (GetIntFromJson(receivedMsg, FIELD_OP_CODE, &opCode) != HC_SUCCESS) {
1165         opCode = P2P_BIND;
1166         LOGW("use default opCode.");
1167     }
1168     char *returnDataStr = ProcessRequestCallback(requestId, opCode, NULL, callback);
1169     if (returnDataStr == NULL) {
1170         LOGE("The OnRequest callback is fail!");
1171         return HC_ERR_REQ_REJECTED;
1172     }
1173     CJson *context = CreateJsonFromString(returnDataStr);
1174     FreeJsonString(returnDataStr);
1175     if (context == NULL) {
1176         LOGE("Failed to create context from string!");
1177         return HC_ERR_JSON_FAIL;
1178     }
1179     if (AddBoolToJson(context, FIELD_IS_DIRECT_AUTH, true) != HC_SUCCESS) {
1180         LOGE("Failed to add isDirectAuth to context!");
1181         FreeJson(context);
1182         return HC_ERR_JSON_ADD;
1183     }
1184     const char *pkgName = GetStringFromJson(context, FIELD_SERVICE_PKG_NAME);
1185     if (pkgName == NULL && AddStringToJson(context, FIELD_SERVICE_PKG_NAME, DEFAULT_PACKAGE_NAME) != HC_SUCCESS) {
1186         LOGE("Failed to add default package name to context!");
1187         FreeJson(context);
1188         return HC_ERR_JSON_ADD;
1189     }
1190     const char *serviceType = GetStringFromJson(context, FIELD_SERVICE_TYPE);
1191     if (serviceType == NULL && AddStringToJson(context, FIELD_SERVICE_TYPE, DEFAULT_SERVICE_TYPE) != HC_SUCCESS) {
1192         LOGE("Failed to add default package name to context!");
1193         FreeJson(context);
1194         return HC_ERR_JSON_ADD;
1195     }
1196     const char *appId = pkgName != NULL ? pkgName : DEFAULT_PACKAGE_NAME;
1197     int32_t res = BuildServerP2PAuthContext(requestId, opCode, appId, context);
1198     if (res != HC_SUCCESS) {
1199         FreeJson(context);
1200         return res;
1201     }
1202     SessionInitParams params = { context, *callback };
1203     res = OpenDevSession(requestId, appId, &params);
1204     FreeJson(context);
1205     return res;
1206 }
1207 
ProcessDataInner(int64_t authReqId,const uint8_t * data,uint32_t dataLen,const DeviceAuthCallback * gaCallback,char ** returnPeerUdid)1208 static int32_t ProcessDataInner(int64_t authReqId, const uint8_t *data, uint32_t dataLen,
1209     const DeviceAuthCallback *gaCallback, char **returnPeerUdid)
1210 {
1211     SET_LOG_MODE(TRACE_MODE);
1212     SET_TRACE_ID(authReqId);
1213     if (!IsSessionExist(authReqId)) {
1214         ADD_PERFORM_DATA(authReqId, false, false, HcGetCurTimeInMillis());
1215     } else {
1216         UPDATE_PERFORM_DATA_BY_SELF_INDEX(authReqId, HcGetCurTimeInMillis());
1217     }
1218     LOGI("[GA] Begin ProcessData. [DataLen]: %" LOG_PUB "u, [ReqId]: %" LOG_PUB PRId64, dataLen, authReqId);
1219     if ((data == NULL) || (dataLen > MAX_DATA_BUFFER_SIZE)) {
1220         LOGE("Invalid input for ProcessData!");
1221         return HC_ERR_INVALID_PARAMS;
1222     }
1223     CJson *receivedMsg = CreateJsonFromString((const char *)data);
1224     if (receivedMsg == NULL) {
1225         LOGE("Failed to create json from string!");
1226         return HC_ERR_JSON_FAIL;
1227     }
1228     int32_t res;
1229     if (!IsSessionExist(authReqId)) {
1230         res = OpenServerAuthSession(authReqId, receivedMsg, gaCallback, returnPeerUdid);
1231         if (res != HC_SUCCESS) {
1232             FreeJson(receivedMsg);
1233             return res;
1234         }
1235     }
1236     if (HasAccountPlugin()) {
1237         res = AddOriginDataForPlugin(receivedMsg, data);
1238         if (res != HC_SUCCESS) {
1239             FreeJson(receivedMsg);
1240             return res;
1241         }
1242     }
1243     res = PushProcSessionTask(authReqId, receivedMsg);
1244     if (res != HC_SUCCESS) {
1245         FreeJson(receivedMsg);
1246         return res;
1247     }
1248     return HC_SUCCESS;
1249 }
1250 
ProcessData(int64_t authReqId,const uint8_t * data,uint32_t dataLen,const DeviceAuthCallback * gaCallback)1251 static int32_t ProcessData(int64_t authReqId, const uint8_t *data, uint32_t dataLen,
1252     const DeviceAuthCallback *gaCallback)
1253 {
1254     bool isSessionExist = IsSessionExist(authReqId);
1255     if (!isSessionExist) {
1256         ReportBehaviorBeginEvent(false, false, authReqId);
1257     }
1258     char *peerUdid = NULL;
1259     int32_t res = ProcessDataInner(authReqId, data, dataLen, gaCallback, &peerUdid);
1260     if (!isSessionExist) {
1261         ReportBehaviorBeginResultEvent(false, false, authReqId, peerUdid, res);
1262     }
1263     if (peerUdid != NULL) {
1264         HcFree(peerUdid);
1265     }
1266     return res;
1267 }
1268 
OpenServerCredSession(int64_t requestId,const CJson * receivedMsg,const DeviceAuthCallback * callback,char ** returnPeerUdid)1269 static int32_t OpenServerCredSession(int64_t requestId, const CJson *receivedMsg, const DeviceAuthCallback *callback,
1270     char **returnPeerUdid)
1271 {
1272     int32_t opCode = AUTH_FORM_ACCOUNT_UNRELATED;
1273     if (GetIntFromJson(receivedMsg, FIELD_AUTH_FORM, &opCode) != HC_SUCCESS) {
1274         if (GetIntFromJson(receivedMsg, FIELD_OP_CODE, &opCode) != HC_SUCCESS) {
1275             opCode = AUTH_FORM_INVALID_TYPE;
1276             LOGW("use default opCode.");
1277         }
1278     }
1279     char *returnDataStr = ProcessRequestCallback(requestId, opCode, NULL, callback);
1280     if (returnDataStr == NULL) {
1281         LOGE("The OnRequest callback is fail!");
1282         return HC_ERR_REQ_REJECTED;
1283     }
1284     CJson *context = CreateJsonFromString(returnDataStr);
1285     FreeJsonString(returnDataStr);
1286     if (context == NULL) {
1287         LOGE("Failed to create context from string!");
1288         return HC_ERR_JSON_FAIL;
1289     }
1290     if (AddIntToJson(context, FIELD_OPERATION_CODE, opCode) != HC_SUCCESS) {
1291         LOGE("add opCode to context fail.");
1292         FreeJson(context);
1293         return HC_ERR_JSON_ADD;
1294     }
1295     const char *appId = NULL;
1296     int32_t res = BuildServerCredContext(requestId, context, returnPeerUdid, &appId);
1297     if (res != HC_SUCCESS) {
1298         FreeJson(context);
1299         return res;
1300     }
1301     SessionInitParams params = { context, *callback };
1302     res = OpenDevSession(requestId, appId, &params);
1303     FreeJson(context);
1304     return res;
1305 }
1306 
AuthCredentialInner(int32_t osAccountId,int64_t authReqId,const char * authParams,const DeviceAuthCallback * caCallback,char ** returnPeerUdid)1307 static int32_t AuthCredentialInner(int32_t osAccountId, int64_t authReqId, const char *authParams,
1308     const DeviceAuthCallback *caCallback, char **returnPeerUdid)
1309 {
1310     SET_LOG_MODE(TRACE_MODE);
1311     SET_TRACE_ID(authReqId);
1312     ADD_PERFORM_DATA(authReqId, false, true, HcGetCurTimeInMillis());
1313     LOGI("Begin AuthCredential. [ReqId]: %" LOG_PUB PRId64 ", [OsAccountId]: %" LOG_PUB "d", authReqId, osAccountId);
1314     if (authParams == NULL || osAccountId == INVALID_OS_ACCOUNT || caCallback == NULL ||
1315         returnPeerUdid == NULL) {
1316         LOGE("The input auth cred params is invalid!");
1317         return HC_ERR_INVALID_PARAMS;
1318     }
1319     if (!CheckIsForegroundOsAccountId(osAccountId)) {
1320         LOGE("This access is not from the foreground user, rejected it.");
1321         return HC_ERR_CROSS_USER_ACCESS;
1322     }
1323     if (!IsOsAccountUnlocked(osAccountId)) {
1324         LOGE("Os account is not unlocked!");
1325         return HC_ERR_OS_ACCOUNT_NOT_UNLOCKED;
1326     }
1327     CJson *context = CreateJsonFromString(authParams);
1328     if (context == NULL) {
1329         LOGE("Failed to create json from string!");
1330         return HC_ERR_JSON_FAIL;
1331     }
1332     const char *appId = NULL;
1333     int32_t res = BuildClientCredContext(osAccountId, authReqId, context, &appId);
1334     if (res != HC_SUCCESS) {
1335         FreeJson(context);
1336         return res;
1337     }
1338     SessionInitParams params = { context, *caCallback };
1339     res = OpenDevSession(authReqId, appId, &params);
1340     FreeJson(context);
1341     if (res != HC_SUCCESS) {
1342         LOGE("OpenDevSession fail. [Res]: %" LOG_PUB "d", res);
1343         return res;
1344     }
1345     return PushStartSessionTask(authReqId);
1346 }
1347 
AuthCredential(int32_t osAccountId,int64_t authReqId,const char * authParams,const DeviceAuthCallback * caCallback)1348 int32_t AuthCredential(int32_t osAccountId, int64_t authReqId, const char *authParams,
1349     const DeviceAuthCallback *caCallback)
1350 {
1351     char *peerUdid = NULL;
1352     int32_t res = AuthCredentialInner(osAccountId, authReqId, authParams, caCallback, &peerUdid);
1353     if (peerUdid != NULL) {
1354         HcFree(peerUdid);
1355     }
1356     return res;
1357 }
1358 
ProcessCredDataInner(int64_t authReqId,const uint8_t * data,uint32_t dataLen,const DeviceAuthCallback * caCallback,char ** returnPeerUdid)1359 static int32_t ProcessCredDataInner(int64_t authReqId, const uint8_t *data, uint32_t dataLen,
1360     const DeviceAuthCallback *caCallback, char **returnPeerUdid)
1361 {
1362     SET_LOG_MODE(TRACE_MODE);
1363     SET_TRACE_ID(authReqId);
1364     if (!IsSessionExist(authReqId)) {
1365         ADD_PERFORM_DATA(authReqId, false, false, HcGetCurTimeInMillis());
1366     } else {
1367         UPDATE_PERFORM_DATA_BY_SELF_INDEX(authReqId, HcGetCurTimeInMillis());
1368     }
1369     LOGI("[GA] Begin ProcessCredData. [DataLen]: %" LOG_PUB "u, [ReqId]: %" LOG_PUB PRId64, dataLen, authReqId);
1370     if ((data == NULL) || (dataLen > MAX_DATA_BUFFER_SIZE)) {
1371         LOGE("Invalid input for ProcessCredData!");
1372         return HC_ERR_INVALID_PARAMS;
1373     }
1374     CJson *receivedMsg = CreateJsonFromString((const char *)data);
1375     if (receivedMsg == NULL) {
1376         LOGE("Failed to create json from string!");
1377         return HC_ERR_JSON_CREATE;
1378     }
1379     int32_t res;
1380     if (!IsSessionExist(authReqId)) {
1381         res = OpenServerCredSession(authReqId, receivedMsg, caCallback, returnPeerUdid);
1382         if (res != HC_SUCCESS) {
1383             FreeJson(receivedMsg);
1384             return res;
1385         }
1386     }
1387     if (HasAccountPlugin()) {
1388         res = AddOriginDataForPlugin(receivedMsg, data);
1389         if (res != HC_SUCCESS) {
1390             FreeJson(receivedMsg);
1391             return res;
1392         }
1393     }
1394     res = PushProcSessionTask(authReqId, receivedMsg);
1395     if (res != HC_SUCCESS) {
1396         FreeJson(receivedMsg);
1397         return res;
1398     }
1399     return HC_SUCCESS;
1400 }
1401 
ProcessCredData(int64_t authReqId,const uint8_t * data,uint32_t dataLen,const DeviceAuthCallback * caCallback)1402 static int32_t ProcessCredData(int64_t authReqId, const uint8_t *data, uint32_t dataLen,
1403     const DeviceAuthCallback *caCallback)
1404 {
1405     char *peerUdid = NULL;
1406     int32_t res = ProcessCredDataInner(authReqId, data, dataLen, caCallback, &peerUdid);
1407     if (peerUdid != NULL) {
1408         HcFree(peerUdid);
1409     }
1410     return res;
1411 }
1412 
CancelRequest(int64_t requestId,const char * appId)1413 static void CancelRequest(int64_t requestId, const char *appId)
1414 {
1415     SET_LOG_MODE(TRACE_MODE);
1416     SET_TRACE_ID(requestId);
1417     DEV_AUTH_REPORT_UE_CALL_EVENT_BY_PARAMS(DEFAULT_OS_ACCOUNT, NULL, appId, CANCEL_REQUEST_EVENT);
1418     if (appId == NULL) {
1419         LOGE("Invalid app id!");
1420         return;
1421     }
1422     LOGI("cancel request. [AppId]: %" LOG_PUB "s, [ReqId]: %" LOG_PUB PRId64, appId, requestId);
1423     CancelDevSession(requestId, appId);
1424 }
1425 
GetRealInfo(int32_t osAccountId,const char * pseudonymId,char ** realInfo)1426 static int32_t GetRealInfo(int32_t osAccountId, const char *pseudonymId, char **realInfo)
1427 {
1428     if (pseudonymId == NULL || realInfo == NULL) {
1429         LOGE("Invalid params!");
1430         return HC_ERR_INVALID_PARAMS;
1431     }
1432     PseudonymManager *pseudonymInstance = GetPseudonymInstance();
1433     if (pseudonymInstance == NULL) {
1434         LOGE("not support privacy enhancement!");
1435         return HC_ERR_NOT_SUPPORT;
1436     }
1437     return pseudonymInstance->getRealInfo(osAccountId, pseudonymId, realInfo);
1438 }
1439 
GetPseudonymId(int32_t osAccountId,const char * indexKey,char ** pseudonymId)1440 static int32_t GetPseudonymId(int32_t osAccountId, const char *indexKey, char **pseudonymId)
1441 {
1442     if (indexKey == NULL || pseudonymId == NULL) {
1443         LOGE("Invalid params!");
1444         return HC_ERR_INVALID_PARAMS;
1445     }
1446     PseudonymManager *pseudonymInstance = GetPseudonymInstance();
1447     if (pseudonymInstance == NULL) {
1448         LOGE("not support privacy enhancement!");
1449         return HC_ERR_NOT_SUPPORT;
1450     }
1451     return pseudonymInstance->getPseudonymId(osAccountId, indexKey, pseudonymId);
1452 }
1453 
ProcessCredential(int32_t operationCode,const char * reqJsonStr,char ** returnData)1454 DEVICE_AUTH_API_PUBLIC int32_t ProcessCredential(int32_t operationCode, const char *reqJsonStr, char **returnData)
1455 {
1456     if (reqJsonStr == NULL || returnData == NULL) {
1457         LOGE("Invalid params!");
1458         return HC_ERR_INVALID_PARAMS;
1459     }
1460 
1461     const CredentialOperator *credOperator = GetCredentialOperator();
1462     if (credOperator == NULL) {
1463         LOGE("credOperator is null!");
1464         return HC_ERR_NOT_SUPPORT;
1465     }
1466 
1467     int32_t res = HC_ERR_UNSUPPORTED_OPCODE;
1468     switch (operationCode) {
1469         case CRED_OP_QUERY:
1470             res = credOperator->queryCredential(reqJsonStr, returnData);
1471             break;
1472         case CRED_OP_CREATE:
1473             res = credOperator->genarateCredential(reqJsonStr, returnData);
1474             break;
1475         case CRED_OP_IMPORT:
1476             res = credOperator->importCredential(reqJsonStr, returnData);
1477             break;
1478         case CRED_OP_DELETE:
1479             res = credOperator->deleteCredential(reqJsonStr, returnData);
1480             break;
1481         default:
1482             LOGE("invalid opCode: %" LOG_PUB "d", operationCode);
1483             break;
1484     }
1485 
1486     return res;
1487 }
1488 
ProcessAuthDevice(int64_t authReqId,const char * authParams,const DeviceAuthCallback * callback)1489 DEVICE_AUTH_API_PUBLIC int32_t ProcessAuthDevice(
1490     int64_t authReqId, const char *authParams, const DeviceAuthCallback *callback)
1491 {
1492     SET_LOG_MODE(TRACE_MODE);
1493     SET_TRACE_ID(authReqId);
1494     LOGI("[DA] Begin ProcessAuthDevice [ReqId]: %" LOG_PUB PRId64, authReqId);
1495     if (authParams == NULL || HcStrlen(authParams) > MAX_DATA_BUFFER_SIZE) {
1496         LOGE("Invalid input for ProcessData!");
1497         return HC_ERR_INVALID_PARAMS;
1498     }
1499     CJson *json = CreateJsonFromString(authParams);
1500     if (json == NULL) {
1501         LOGE("Failed to create json from string!");
1502         return HC_ERR_JSON_FAIL;
1503     }
1504     const char *data = GetStringFromJson(json, "data");
1505     if (data == NULL) {
1506         LOGE("Failed to get received data from parameter!");
1507         FreeJson(json);
1508         return HC_ERR_INVALID_PARAMS;
1509     }
1510     CJson *receivedMsg = CreateJsonFromString(data);
1511     FreeJson(json);
1512     if (receivedMsg == NULL) {
1513         LOGE("Failed to create json from string!");
1514         return HC_ERR_JSON_FAIL;
1515     }
1516     int32_t res;
1517     if (!IsSessionExist(authReqId)) {
1518         res = OpenServerAuthSessionForP2P(authReqId, receivedMsg, callback);
1519         if (res != HC_SUCCESS) {
1520             FreeJson(receivedMsg);
1521             return res;
1522         }
1523     }
1524     res = PushProcSessionTask(authReqId, receivedMsg);
1525     if (res != HC_SUCCESS) {
1526         FreeJson(receivedMsg);
1527         return res;
1528     }
1529     return HC_SUCCESS;
1530 }
1531 
StartAuthDevice(int64_t authReqId,const char * authParams,const DeviceAuthCallback * callback)1532 DEVICE_AUTH_API_PUBLIC int32_t StartAuthDevice(
1533     int64_t authReqId, const char *authParams, const DeviceAuthCallback *callback)
1534 {
1535     SET_LOG_MODE(TRACE_MODE);
1536     SET_TRACE_ID(authReqId);
1537     LOGI("StartAuthDevice. [ReqId]:%" LOG_PUB PRId64, authReqId);
1538 
1539     if ((authParams == NULL) || (callback == NULL) || HcStrlen(authParams) > MAX_DATA_BUFFER_SIZE) {
1540         LOGE("The input auth params is invalid!");
1541         return HC_ERR_INVALID_PARAMS;
1542     }
1543     CJson *context = CreateJsonFromString(authParams);
1544     if (context == NULL) {
1545         LOGE("Failed to create json from string!");
1546         return HC_ERR_JSON_FAIL;
1547     }
1548     int32_t osAccountId = INVALID_OS_ACCOUNT;
1549     if (GetIntFromJson(context, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) {
1550         LOGE("Failed to get osAccountId from json!");
1551         FreeJson(context);
1552         return HC_ERR_JSON_FAIL;
1553     }
1554     osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
1555     if (osAccountId == INVALID_OS_ACCOUNT) {
1556         FreeJson(context);
1557         return HC_ERR_INVALID_PARAMS;
1558     }
1559     if (!CheckIsForegroundOsAccountId(osAccountId)) {
1560         LOGE("This access is not from the foreground user, rejected it.");
1561         return HC_ERR_CROSS_USER_ACCESS;
1562     }
1563     int32_t res = BuildClientAuthContext(osAccountId, authReqId, DEFAULT_PACKAGE_NAME, context, NULL);
1564     if (res != HC_SUCCESS) {
1565         FreeJson(context);
1566         return res;
1567     }
1568     res = BuildP2PBindContext(context);
1569     if (res != HC_SUCCESS) {
1570         FreeJson(context);
1571         return res;
1572     }
1573     SessionInitParams params = { context, *callback };
1574     res = OpenDevSession(authReqId, DEFAULT_PACKAGE_NAME, &params);
1575     FreeJson(context);
1576     if (res != HC_SUCCESS) {
1577         LOGE("OpenDevSession fail. [Res]: %" LOG_PUB "d", res);
1578         return res;
1579     }
1580     return PushStartSessionTask(authReqId);
1581 }
1582 
CancelAuthRequest(int64_t requestId,const char * authParams)1583 DEVICE_AUTH_API_PUBLIC int32_t CancelAuthRequest(int64_t requestId, const char *authParams)
1584 {
1585     SET_LOG_MODE(TRACE_MODE);
1586     SET_TRACE_ID(requestId);
1587     if (authParams == NULL || HcStrlen(authParams) > MAX_DATA_BUFFER_SIZE) {
1588         LOGE("Invalid authParams!");
1589         return HC_ERR_INVALID_PARAMS;
1590     }
1591     LOGI("cancel request. [ReqId]: %" LOG_PUB PRId64, requestId);
1592     CancelDevSession(requestId, DEFAULT_PACKAGE_NAME);
1593     return HC_SUCCESS;
1594 }
1595 
AllocGmAndGa(void)1596 static int32_t AllocGmAndGa(void)
1597 {
1598     if (g_groupManagerInstance == NULL) {
1599         g_groupManagerInstance = (DeviceGroupManager *)HcMalloc(sizeof(DeviceGroupManager), 0);
1600         if (g_groupManagerInstance == NULL) {
1601             LOGE("Failed to allocate groupManager Instance memory!");
1602             return HC_ERR_ALLOC_MEMORY;
1603         }
1604     }
1605     if (g_groupAuthManager == NULL) {
1606         g_groupAuthManager = (GroupAuthManager *)HcMalloc(sizeof(GroupAuthManager), 0);
1607         if (g_groupAuthManager == NULL) {
1608             LOGE("Failed to allocate groupAuth Instance memory!");
1609             HcFree(g_groupManagerInstance);
1610             g_groupManagerInstance = NULL;
1611             return HC_ERR_ALLOC_MEMORY;
1612         }
1613     }
1614     if (g_accountVerifierInstance == NULL) {
1615         g_accountVerifierInstance = (AccountVerifier *)HcMalloc(sizeof(AccountVerifier), 0);
1616         if (g_accountVerifierInstance == NULL) {
1617             LOGE("Failed to allocate accountVerifier Instance memory!");
1618             HcFree(g_groupManagerInstance);
1619             g_groupManagerInstance = NULL;
1620             HcFree(g_groupAuthManager);
1621             g_groupAuthManager = NULL;
1622             return HC_ERR_ALLOC_MEMORY;
1623         }
1624     }
1625     return HC_SUCCESS;
1626 }
1627 
DestroyGmAndGa(void)1628 static void DestroyGmAndGa(void)
1629 {
1630     if (g_groupAuthManager != NULL) {
1631         HcFree(g_groupAuthManager);
1632         g_groupAuthManager = NULL;
1633     }
1634     if (g_groupManagerInstance != NULL) {
1635         HcFree(g_groupManagerInstance);
1636         g_groupManagerInstance = NULL;
1637     }
1638     if (g_accountVerifierInstance != NULL) {
1639         HcFree(g_accountVerifierInstance);
1640         g_accountVerifierInstance = NULL;
1641     }
1642 }
1643 
AllocCredentialMgr(void)1644 static int32_t AllocCredentialMgr(void)
1645 {
1646     if (g_credManager == NULL) {
1647         g_credManager = (CredManager *)HcMalloc(sizeof(CredManager), 0);
1648         if (g_credManager == NULL) {
1649             LOGE("Failed to allocate g_credManager Instance memory!");
1650             return HC_ERR_ALLOC_MEMORY;
1651         }
1652     }
1653     return HC_SUCCESS;
1654 }
1655 
DestroyCredentialMgr(void)1656 static void DestroyCredentialMgr(void)
1657 {
1658     if (g_credManager != NULL) {
1659         HcFree(g_credManager);
1660         g_credManager = NULL;
1661     }
1662 }
1663 
AllocCa(void)1664 static int32_t AllocCa(void)
1665 {
1666     if (g_credAuthManager == NULL) {
1667         g_credAuthManager = (CredAuthManager *)HcMalloc(sizeof(CredAuthManager), 0);
1668         if (g_credAuthManager == NULL) {
1669             LOGE("Failed to allocate groupManager Instance memory!");
1670             return HC_ERR_ALLOC_MEMORY;
1671         }
1672     }
1673     return HC_SUCCESS;
1674 }
1675 
DestroyCa(void)1676 static void DestroyCa(void)
1677 {
1678     if (g_credAuthManager != NULL) {
1679         HcFree(g_credAuthManager);
1680         g_credAuthManager = NULL;
1681     }
1682 }
1683 
CleanAllModules(int32_t type)1684 static void CleanAllModules(int32_t type)
1685 {
1686     switch (type) {
1687         case CLEAN_ALL:
1688             DestroyDevSessionManager();
1689         // fallthrough
1690         case CLEAN_IDENTITY_SERVICE:
1691             DestroyIdentityService();
1692         // fallthrough
1693         case CLEAN_GROUP_MANAGER:
1694             DestroyGroupManager();
1695         // fallthrough
1696         case CLEAN_CALLBACK:
1697             DestroyCallbackManager();
1698         // fallthrough
1699         case CLEAN_MODULE:
1700             DestroyModules();
1701         // fallthrough
1702         case CLEAN_CRED:
1703             DestroyCredMgr();
1704         // fallthrough
1705         default:
1706             break;
1707     }
1708 }
1709 
InitAllModules(void)1710 static int32_t InitAllModules(void)
1711 {
1712     int32_t res = GetLoaderInstance()->initAlg();
1713     if (res != HC_SUCCESS) {
1714         LOGE("[End]: [Service]: Failed to init algorithm module!");
1715         return res;
1716     }
1717     do {
1718         if ((res = InitCredMgr()) != HC_SUCCESS) {
1719             LOGE("[End]: [Service]: Failed to init cred mgr!");
1720             break;
1721         }
1722         if ((res = InitModules()) != HC_SUCCESS) {
1723             LOGE("[End]: [Service]: Failed to init all authenticator modules!");
1724             CleanAllModules(CLEAN_CRED);
1725             break;
1726         }
1727         if ((res = InitCallbackManager()) != HC_SUCCESS) {
1728             LOGE("[End]: [Service]: Failed to init callback manage module!");
1729             CleanAllModules(CLEAN_MODULE);
1730             break;
1731         }
1732         if ((res = InitGroupManager()) != HC_SUCCESS) {
1733             LOGE("[End]: [Service]: Failed to init group manage module!");
1734             CleanAllModules(CLEAN_CALLBACK);
1735             break;
1736         }
1737         if ((res = InitIdentityService()) != HC_SUCCESS) {
1738             LOGE("[End]: [Service]: Failed to init IS module!");
1739             CleanAllModules(CLEAN_GROUP_MANAGER);
1740             break;
1741         }
1742         if ((res = InitDevSessionManager()) != HC_SUCCESS) {
1743             LOGE("[End]: [Service]: Failed to init dev session manager module!");
1744             CleanAllModules(CLEAN_IDENTITY_SERVICE);
1745             break;
1746         }
1747         (void)InitGroupAuthManager();
1748         if ((res = InitTaskManager()) != HC_SUCCESS) {
1749             LOGE("[End]: [Service]: Failed to init worker thread!");
1750             CleanAllModules(CLEAN_ALL);
1751             break;
1752         }
1753     } while (0);
1754     return res;
1755 }
1756 
InitPseudonymModule(void)1757 static void InitPseudonymModule(void)
1758 {
1759     PseudonymManager *manager = GetPseudonymInstance();
1760     if (manager == NULL) {
1761         LOGE("Pseudonym manager is null!");
1762         return;
1763     }
1764     manager->loadPseudonymData();
1765 }
1766 
DoOnChannelOpened(HcTaskBase * baseTask)1767 static void DoOnChannelOpened(HcTaskBase *baseTask)
1768 {
1769     if (baseTask == NULL) {
1770         LOGE("The input task is NULL!");
1771         return;
1772     }
1773     SoftBusTask *task = (SoftBusTask *)baseTask;
1774     SET_LOG_MODE(TRACE_MODE);
1775     SET_TRACE_ID(task->requestId);
1776     LOGI("[Start]: DoOnChannelOpened!");
1777     int32_t res = StartDevSession(task->requestId);
1778     if (res != HC_SUCCESS) {
1779         LOGE("start session fail.[Res]: %" LOG_PUB "d", res);
1780         CloseDevSession(task->requestId);
1781     }
1782 }
1783 
InitSoftBusTask(SoftBusTask * task,int64_t requestId)1784 static void InitSoftBusTask(SoftBusTask *task, int64_t requestId)
1785 {
1786     task->base.doAction = DoOnChannelOpened;
1787     task->base.destroy = NULL;
1788     task->requestId = requestId;
1789 }
1790 
OnChannelOpenedCb(int64_t requestId,int result)1791 static int OnChannelOpenedCb(int64_t requestId, int result)
1792 {
1793     if (result != HC_SUCCESS) {
1794         LOGE("[SoftBus][Out]: Failed to open channel! res: %" LOG_PUB "d", result);
1795         CloseDevSession(requestId);
1796         return HC_ERR_SOFT_BUS;
1797     }
1798     LOGI("[Start]: OnChannelOpened! [ReqId]: %" LOG_PUB PRId64, requestId);
1799     SoftBusTask *task = (SoftBusTask *)HcMalloc(sizeof(SoftBusTask), 0);
1800     if (task == NULL) {
1801         LOGE("Failed to allocate task memory!");
1802         CloseDevSession(requestId);
1803         return HC_ERR_ALLOC_MEMORY;
1804     }
1805     InitSoftBusTask(task, requestId);
1806     if (PushTask((HcTaskBase *)task) != HC_SUCCESS) {
1807         HcFree(task);
1808         CloseDevSession(requestId);
1809         return HC_ERR_INIT_TASK_FAIL;
1810     }
1811     LOGI("[End]: OnChannelOpened!");
1812     return HC_SUCCESS;
1813 }
1814 
OnChannelClosedCb(void)1815 static void OnChannelClosedCb(void)
1816 {
1817     return;
1818 }
1819 
OnBytesReceivedCb(int64_t requestId,uint8_t * data,uint32_t dataLen)1820 static void OnBytesReceivedCb(int64_t requestId, uint8_t *data, uint32_t dataLen)
1821 {
1822     if ((data == NULL) || (dataLen == 0) || (dataLen > MAX_DATA_BUFFER_SIZE)) {
1823         LOGE("Invalid input params!");
1824         return;
1825     }
1826     (void)ProcessBindData(requestId, data, dataLen);
1827 }
1828 
RegCallback(const char * appId,const DeviceAuthCallback * callback)1829 static int32_t RegCallback(const char *appId, const DeviceAuthCallback *callback)
1830 {
1831     SET_LOG_MODE(NORMAL_MODE);
1832     if ((appId == NULL) || (callback == NULL)) {
1833         LOGE("The input parameters contains NULL value!");
1834         return HC_ERR_INVALID_PARAMS;
1835     }
1836     ChannelProxy proxy = {
1837         .onChannelOpened = OnChannelOpenedCb,
1838         .onChannelClosed = OnChannelClosedCb,
1839         .onBytesReceived = OnBytesReceivedCb
1840     };
1841     int32_t res = InitChannelManager(&proxy);
1842     if (res != HC_SUCCESS) {
1843         LOGE("[End]: [Service]: Failed to init channel manage module!");
1844         return res;
1845     }
1846     return RegGroupManagerCallback(appId, callback);
1847 }
1848 
InitDeviceAuthService(void)1849 DEVICE_AUTH_API_PUBLIC int InitDeviceAuthService(void)
1850 {
1851     LOGI("[Service]: Start to init device auth service!");
1852     if (CheckInit() == FINISH_INIT) {
1853         LOGI("[End]: [Service]: Device auth service is running!");
1854         return HC_SUCCESS;
1855     }
1856     int32_t res = AllocGmAndGa();
1857     if (res != HC_SUCCESS) {
1858         return res;
1859     }
1860     res = AllocCa();
1861     if (res != HC_SUCCESS) {
1862         DestroyGmAndGa();
1863         return res;
1864     }
1865     res = AllocCredentialMgr();
1866     if (res != HC_SUCCESS) {
1867         DestroyGmAndGa();
1868         DestroyCa();
1869         return res;
1870     }
1871     InitOsAccountAdapter();
1872     res = InitAllModules();
1873     if (res != HC_SUCCESS) {
1874         DestroyGmAndGa();
1875         DestroyCa();
1876         DestroyCredentialMgr();
1877         return res;
1878     }
1879     INIT_PERFORMANCE_DUMPER();
1880     InitPseudonymModule();
1881     InitAccountTaskManager();
1882     SetInitStatus();
1883     LOGI("[End]: [Service]: Init device auth service successfully!");
1884     return HC_SUCCESS;
1885 }
1886 
DestroyDeviceAuthService(void)1887 DEVICE_AUTH_API_PUBLIC void DestroyDeviceAuthService(void)
1888 {
1889     LOGI("[Service]: Start to destroy device auth service!");
1890     if (CheckDestroy() == FINISH_DESTROY) {
1891         LOGI("[End]: [Service]: The service has not been initialized!");
1892         return;
1893     }
1894     DestroyTaskManager();
1895     DestroyDevSessionManager();
1896     DestroyIdentityService();
1897     DestroyGroupManager();
1898     DestroyGmAndGa();
1899     DestroyAccountTaskManager();
1900     DestroyCa();
1901     DestroyCredentialMgr();
1902     DestroyModules();
1903     DestroyCredMgr();
1904     DestroyChannelManager();
1905     DestroyCallbackManager();
1906     DESTROY_PERFORMANCE_DUMPER();
1907     DestroyPseudonymManager();
1908     DestroyOsAccountAdapter();
1909     SetDeInitStatus();
1910     LOGI("[End]: [Service]: Destroy device auth service successfully!");
1911 }
1912 
GetGmInstance(void)1913 DEVICE_AUTH_API_PUBLIC const DeviceGroupManager *GetGmInstance(void)
1914 {
1915     if (g_groupManagerInstance == NULL) {
1916         LOGE("Service not init.");
1917         return NULL;
1918     }
1919 
1920     g_groupManagerInstance->regCallback = RegCallback;
1921     g_groupManagerInstance->unRegCallback = UnRegGroupManagerCallback;
1922     g_groupManagerInstance->regDataChangeListener = RegListenerImpl;
1923     g_groupManagerInstance->unRegDataChangeListener = UnRegListenerImpl;
1924     g_groupManagerInstance->createGroup = CreateGroupImpl;
1925     g_groupManagerInstance->deleteGroup = DeleteGroupImpl;
1926     g_groupManagerInstance->addMemberToGroup = AddMemberToGroup;
1927     g_groupManagerInstance->deleteMemberFromGroup = DeleteMemberFromGroupImpl;
1928     g_groupManagerInstance->addMultiMembersToGroup = AddMultiMembersToGroupImpl;
1929     g_groupManagerInstance->delMultiMembersFromGroup = DelMultiMembersFromGroupImpl;
1930     g_groupManagerInstance->processData = ProcessBindData;
1931     g_groupManagerInstance->getRegisterInfo = GetRegisterInfoImpl;
1932     g_groupManagerInstance->checkAccessToGroup = CheckAccessToGroupImpl;
1933     g_groupManagerInstance->getPkInfoList = GetPkInfoListImpl;
1934     g_groupManagerInstance->getGroupInfoById = GetGroupInfoByIdImpl;
1935     g_groupManagerInstance->getGroupInfo = GetGroupInfoImpl;
1936     g_groupManagerInstance->getJoinedGroups = GetJoinedGroupsImpl;
1937     g_groupManagerInstance->getRelatedGroups = GetRelatedGroupsImpl;
1938     g_groupManagerInstance->getDeviceInfoById = GetDeviceInfoByIdImpl;
1939     g_groupManagerInstance->getTrustedDevices = GetTrustedDevicesImpl;
1940     g_groupManagerInstance->isDeviceInGroup = IsDeviceInGroupImpl;
1941     g_groupManagerInstance->cancelRequest = CancelRequest;
1942     g_groupManagerInstance->destroyInfo = DestroyInfoImpl;
1943     return g_groupManagerInstance;
1944 }
1945 
GetGaInstance(void)1946 DEVICE_AUTH_API_PUBLIC const GroupAuthManager *GetGaInstance(void)
1947 {
1948     if (g_groupAuthManager == NULL) {
1949         LOGE("Service not init.");
1950         return NULL;
1951     }
1952 
1953     g_groupAuthManager->processData = ProcessData;
1954     g_groupAuthManager->authDevice = AuthDevice;
1955     g_groupAuthManager->cancelRequest = CancelRequest;
1956     g_groupAuthManager->getRealInfo = GetRealInfo;
1957     g_groupAuthManager->getPseudonymId = GetPseudonymId;
1958     return g_groupAuthManager;
1959 }
1960 
GetSharedKeyFromOutJson(const CJson * out,DataBuff * returnSharedKey)1961 static int32_t GetSharedKeyFromOutJson(const CJson *out, DataBuff *returnSharedKey)
1962 {
1963     int sharedKeyLen = 0;
1964     if (GetIntFromJson(out, FIELD_ACCOUNT_SHARED_KEY_LEN, &sharedKeyLen) != HC_SUCCESS) {
1965         LOGE("Failed to get shared key len!");
1966         return HC_ERR_JSON_GET;
1967     }
1968     uint8_t *sharedKeyVal = (uint8_t *)HcMalloc(sharedKeyLen, 0);
1969     if (sharedKeyVal == NULL) {
1970         LOGE("Failed to alloc shared key!");
1971         return HC_ERR_ALLOC_MEMORY;
1972     }
1973     if (GetByteFromJson(out, FIELD_ACCOUNT_SHARED_KEY_VAL, sharedKeyVal, sharedKeyLen) != HC_SUCCESS) {
1974         LOGE("Failed to get shared key val!");
1975         HcFree(sharedKeyVal);
1976         return HC_ERR_JSON_GET;
1977     }
1978     returnSharedKey->data = sharedKeyVal;
1979     returnSharedKey->length = sharedKeyLen;
1980     return HC_SUCCESS;
1981 }
1982 
GetRandomFromOutJson(const CJson * out,DataBuff * returnRandom)1983 static int32_t GetRandomFromOutJson(const CJson *out, DataBuff *returnRandom)
1984 {
1985     int randomLen = 0;
1986     if (GetIntFromJson(out, FIELD_ACCOUNT_RANDOM_LEN, &randomLen) != HC_SUCCESS) {
1987         LOGE("Failed to get random len!");
1988         return HC_ERR_JSON_GET;
1989     }
1990     uint8_t *randomVal = (uint8_t *)HcMalloc(randomLen, 0);
1991     if (randomVal == NULL) {
1992         LOGE("Failed to alloc random!");
1993         return HC_ERR_ALLOC_MEMORY;
1994     }
1995     if (GetByteFromJson(out, FIELD_ACCOUNT_RANDOM_VAL, randomVal, randomLen) != HC_SUCCESS) {
1996         LOGE("Failed to get random val!");
1997         HcFree(randomVal);
1998         return HC_ERR_JSON_GET;
1999     }
2000     returnRandom->data = randomVal;
2001     returnRandom->length = randomLen;
2002     return HC_SUCCESS;
2003 }
2004 
DestroyDataBuff(DataBuff * data)2005 static void DestroyDataBuff(DataBuff *data)
2006 {
2007     if (data == NULL || data->data == NULL) {
2008         return;
2009     }
2010     HcFree(data->data);
2011     data->data = NULL;
2012     data->length = 0;
2013 }
2014 
ConstructClientInJson(CJson * in,const char * peerPk,const char * serviceId)2015 static int32_t ConstructClientInJson(CJson *in, const char *peerPk, const char *serviceId)
2016 {
2017     if (AddStringToJson(in, FIELD_ACCOUNT_PEER_PK, peerPk) != HC_SUCCESS) {
2018         LOGE("Failed to add peer pk to json!");
2019         return HC_ERR_JSON_ADD;
2020     }
2021     if (AddStringToJson(in, FIELD_ACCOUNT_SERVICE_ID, serviceId) != HC_SUCCESS) {
2022         LOGE("Failed to add serviceId to json!");
2023         return HC_ERR_JSON_ADD;
2024     }
2025     return HC_SUCCESS;
2026 }
2027 
GetClientSharedKey(const char * peerPk,const char * serviceId,DataBuff * returnSharedKey,DataBuff * returnRandom)2028 static int32_t GetClientSharedKey(const char *peerPk, const char *serviceId, DataBuff *returnSharedKey,
2029     DataBuff *returnRandom)
2030 {
2031     if (peerPk == NULL || serviceId == NULL || returnSharedKey == NULL || returnRandom == NULL) {
2032         LOGE("Invalid params!");
2033         return HC_ERR_INVALID_PARAMS;
2034     }
2035     CJson *in = CreateJson();
2036     if (in == NULL) {
2037         LOGE("Failed to create in json!");
2038         return HC_ERR_JSON_CREATE;
2039     }
2040     int32_t res = ConstructClientInJson(in, peerPk, serviceId);
2041     if (res != HC_SUCCESS) {
2042         FreeJson(in);
2043         return res;
2044     }
2045     CJson *out = CreateJson();
2046     if (out == NULL) {
2047         LOGE("Failed to create out json!");
2048         FreeJson(in);
2049         return HC_ERR_JSON_CREATE;
2050     }
2051     res = ExecuteAccountAuthCmd(DEFAULT_OS_ACCOUNT, ACCOUNT_GET_CLIENT_SHARED_KEY, in, out);
2052     FreeJson(in);
2053     if (res != HC_SUCCESS) {
2054         LOGE("Failed to get client shared key!");
2055         FreeJson(out);
2056         return res;
2057     }
2058     res = GetSharedKeyFromOutJson(out, returnSharedKey);
2059     if (res != HC_SUCCESS) {
2060         LOGE("Failed to get shared key from out json!");
2061         FreeJson(out);
2062         return res;
2063     }
2064 
2065     res = GetRandomFromOutJson(out, returnRandom);
2066     FreeJson(out);
2067     if (res != HC_SUCCESS) {
2068         LOGE("Failed to get random from out json!");
2069         DestroyDataBuff(returnSharedKey);
2070     }
2071     return res;
2072 }
2073 
ConstructServerInJson(CJson * in,const char * peerPk,const char * serviceId,const DataBuff * random)2074 static int32_t ConstructServerInJson(CJson *in, const char *peerPk, const char *serviceId, const DataBuff *random)
2075 {
2076     if (AddStringToJson(in, FIELD_ACCOUNT_PEER_PK, peerPk) != HC_SUCCESS) {
2077         LOGE("Failed to add peer pk to json!");
2078         return HC_ERR_JSON_ADD;
2079     }
2080     if (AddStringToJson(in, FIELD_ACCOUNT_SERVICE_ID, serviceId) != HC_SUCCESS) {
2081         LOGE("Failed to add serviceId to json!");
2082         return HC_ERR_JSON_ADD;
2083     }
2084     if (AddByteToJson(in, FIELD_ACCOUNT_RANDOM_VAL, random->data, random->length) != HC_SUCCESS) {
2085         LOGE("Failed to add random val to json!");
2086         return HC_ERR_JSON_ADD;
2087     }
2088     if (AddIntToJson(in, FIELD_ACCOUNT_RANDOM_LEN, random->length) != HC_SUCCESS) {
2089         LOGE("Failed to add random len to json!");
2090         return HC_ERR_JSON_ADD;
2091     }
2092     return HC_SUCCESS;
2093 }
2094 
GetServerSharedKey(const char * peerPk,const char * serviceId,const DataBuff * random,DataBuff * returnSharedKey)2095 static int32_t GetServerSharedKey(const char *peerPk, const char *serviceId, const DataBuff *random,
2096     DataBuff *returnSharedKey)
2097 {
2098     if (peerPk == NULL || serviceId == NULL || random == NULL || random->data == NULL || returnSharedKey == NULL) {
2099         LOGE("Invalid params!");
2100         return HC_ERR_INVALID_PARAMS;
2101     }
2102     CJson *in = CreateJson();
2103     if (in == NULL) {
2104         LOGE("Failed to create in json!");
2105         return HC_ERR_JSON_CREATE;
2106     }
2107     int32_t res = ConstructServerInJson(in, peerPk, serviceId, random);
2108     if (res != HC_SUCCESS) {
2109         FreeJson(in);
2110         return res;
2111     }
2112     CJson *out = CreateJson();
2113     if (out == NULL) {
2114         LOGE("Failed to create out json!");
2115         FreeJson(in);
2116         return HC_ERR_JSON_CREATE;
2117     }
2118     res = ExecuteAccountAuthCmd(DEFAULT_OS_ACCOUNT, ACCOUNT_GET_SERVER_SHARED_KEY, in, out);
2119     FreeJson(in);
2120     if (res != HC_SUCCESS) {
2121         LOGE("Failed to get server shared key!");
2122         FreeJson(out);
2123         return res;
2124     }
2125 
2126     res = GetSharedKeyFromOutJson(out, returnSharedKey);
2127     FreeJson(out);
2128     if (res != HC_SUCCESS) {
2129         LOGE("Failed to get shared key from out json!");
2130     }
2131     return res;
2132 }
2133 
GetAccountVerifierInstance(void)2134 DEVICE_AUTH_API_PUBLIC const AccountVerifier *GetAccountVerifierInstance(void)
2135 {
2136     if (g_accountVerifierInstance == NULL) {
2137         LOGE("Account verifier instance not init!");
2138         return NULL;
2139     }
2140     g_accountVerifierInstance->getClientSharedKey = GetClientSharedKey;
2141     g_accountVerifierInstance->getServerSharedKey = GetServerSharedKey;
2142     g_accountVerifierInstance->destroyDataBuff = DestroyDataBuff;
2143     return g_accountVerifierInstance;
2144 }
2145 
GetCredMgrInstance(void)2146 DEVICE_AUTH_API_PUBLIC const CredManager *GetCredMgrInstance(void)
2147 {
2148     if (g_credManager == NULL) {
2149         LOGE("Service not init");
2150         return NULL;
2151     }
2152 
2153     g_credManager->addCredential = AddCredential;
2154     g_credManager->exportCredential = ExportCredential;
2155     g_credManager->queryCredentialByParams = QueryCredentialByParams;
2156     g_credManager->queryCredInfoByCredId = QueryCredInfoByCredId;
2157     g_credManager->deleteCredential = DeleteCredential;
2158     g_credManager->updateCredInfo = UpdateCredInfo;
2159     g_credManager->agreeCredential = AgreeCredential;
2160     g_credManager->registerChangeListener = RegisterChangeListener;
2161     g_credManager->unregisterChangeListener = UnregisterChangeListener;
2162     g_credManager->deleteCredByParams = DeleteCredByParams;
2163     g_credManager->batchUpdateCredentials = BatchUpdateCredentials;
2164     g_credManager->destroyInfo = DestroyInfo;
2165 
2166     return g_credManager;
2167 }
2168 
GetCredAuthInstance(void)2169 DEVICE_AUTH_API_PUBLIC const CredAuthManager *GetCredAuthInstance(void)
2170 {
2171     if (g_credAuthManager == NULL) {
2172         LOGE("Service not init.");
2173         return NULL;
2174     }
2175 
2176     g_credAuthManager->processCredData = ProcessCredData;
2177     g_credAuthManager->authCredential = AuthCredential;
2178     return g_credAuthManager;
2179 }