1 /*
2  * Copyright (c) 2022-2024 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 "auth_manager.h"
17 
18 #include <securec.h>
19 
20 #include "anonymizer.h"
21 #include "auth_common.h"
22 #include "auth_connection.h"
23 #include "auth_device_common_key.h"
24 #include "auth_hichain.h"
25 #include "auth_interface.h"
26 #include "auth_log.h"
27 #include "auth_normalize_request.h"
28 #include "auth_request.h"
29 #include "auth_session_fsm.h"
30 #include "auth_session_message.h"
31 #include "auth_tcp_connection.h"
32 #include "bus_center_manager.h"
33 #include "device_profile_listener.h"
34 #include "lnn_app_bind_interface.h"
35 #include "lnn_async_callback_utils.h"
36 #include "lnn_ctrl_lane.h"
37 #include "lnn_decision_db.h"
38 #include "lnn_device_info.h"
39 #include "lnn_distributed_net_ledger.h"
40 #include "lnn_event.h"
41 #include "lnn_feature_capability.h"
42 #include "lnn_net_builder.h"
43 #include "softbus_adapter_hitrace.h"
44 #include "softbus_adapter_mem.h"
45 #include "softbus_adapter_socket.h"
46 #include "softbus_def.h"
47 
48 #define MAX_AUTH_VALID_PERIOD              (30 * 60 * 1000L)            /* 30 mins */
49 #define SCHEDULE_UPDATE_SESSION_KEY_PERIOD ((5 * 60 + 30) * 60 * 1000L) /* 5 hour 30 mins */
50 #define FLAG_REPLY                         1
51 #define FLAG_ACTIVE                        0
52 #define AUTH_COUNT                         2
53 #define DELAY_REG_DP_TIME                  10000
54 #define RECV_DATA_WAIT_TIME                100
55 
56 static ListNode g_authClientList = { &g_authClientList, &g_authClientList };
57 static ListNode g_authServerList = { &g_authServerList, &g_authServerList };
58 static AuthTransCallback g_transCallback = { 0 };
59 
60 /* Auth Manager */
NewAuthManager(int64_t authSeq,const AuthSessionInfo * info)61 AuthManager *NewAuthManager(int64_t authSeq, const AuthSessionInfo *info)
62 {
63     AUTH_CHECK_AND_RETURN_RET_LOGE(info != NULL, NULL, AUTH_FSM, "info is null");
64     AUTH_CHECK_AND_RETURN_RET_LOGE(CheckAuthConnInfoType(&info->connInfo), NULL, AUTH_FSM, "connInfo type error");
65     AuthManager *auth = (AuthManager *)SoftBusCalloc(sizeof(AuthManager));
66     if (auth == NULL) {
67         AUTH_LOGW(AUTH_FSM, "malloc AuthManager fail");
68         return NULL;
69     }
70     auth->authId = authSeq;
71     auth->isServer = info->isServer;
72     auth->connId[info->connInfo.type] = info->connId;
73     auth->connInfo[info->connInfo.type] = info->connInfo;
74     if (strcpy_s(auth->udid, sizeof(auth->udid), info->udid) != EOK ||
75         strcpy_s(auth->uuid, sizeof(auth->uuid), info->uuid) != EOK) {
76         AUTH_LOGW(AUTH_FSM, "copy uuid/udid fail");
77         SoftBusFree(auth);
78         return NULL;
79     }
80     auth->version = info->version;
81     auth->hasAuthPassed[info->connInfo.type] = false;
82     InitSessionKeyList(&auth->sessionKeyList);
83     if (auth->isServer) {
84         ListTailInsert(&g_authServerList, &auth->node);
85     } else {
86         ListTailInsert(&g_authClientList, &auth->node);
87     }
88     char *anonyUuid = NULL;
89     Anonymize(auth->uuid, &anonyUuid);
90     AUTH_LOGI(AUTH_FSM, "create auth manager, uuid=%{public}s, side=%{public}s, authId=%{public}" PRId64,
91         anonyUuid, GetAuthSideStr(auth->isServer), auth->authId);
92     AnonymizeFree(anonyUuid);
93     return auth;
94 }
95 
DupAuthManager(const AuthManager * auth)96 static AuthManager *DupAuthManager(const AuthManager *auth)
97 {
98     AuthManager *newAuth = (AuthManager *)DupMemBuffer((const uint8_t *)auth, sizeof(AuthManager));
99     if (newAuth == NULL) {
100         AUTH_LOGE(AUTH_FSM, "auth manager dup fail. authId=%{public}" PRId64 "", auth->authId);
101         return NULL;
102     }
103     ListInit(&newAuth->node);
104     ListInit(&newAuth->sessionKeyList);
105     if (DupSessionKeyList(&auth->sessionKeyList, &newAuth->sessionKeyList)) {
106         AUTH_LOGE(AUTH_FSM, "auth manager dup session key fail. authId=%{public}" PRId64 "", auth->authId);
107         SoftBusFree(newAuth);
108         return NULL;
109     }
110     return newAuth;
111 }
112 
DelDupAuthManager(AuthManager * auth)113 void DelDupAuthManager(AuthManager *auth)
114 {
115     AUTH_CHECK_AND_RETURN_LOGE(auth != NULL, AUTH_FSM, "auth is null");
116     DestroySessionKeyList(&auth->sessionKeyList);
117     SoftBusFree(auth);
118 }
119 
DelAuthManager(AuthManager * auth,int32_t type)120 void DelAuthManager(AuthManager *auth, int32_t type)
121 {
122     AUTH_CHECK_AND_RETURN_LOGE(auth != NULL, AUTH_FSM, "auth is null");
123     if (type < AUTH_LINK_TYPE_WIFI || type > AUTH_LINK_TYPE_MAX) {
124         AUTH_LOGE(AUTH_FSM, "type error.");
125         return;
126     }
127     char *anonyUdid = NULL;
128     Anonymize(auth->udid, &anonyUdid);
129     if (type != AUTH_LINK_TYPE_MAX) {
130         if (auth->connId[type] == 0) {
131             AUTH_LOGE(AUTH_FSM, "authManager has been deleted, authId=%{public}" PRId64, auth->authId);
132             AnonymizeFree(anonyUdid);
133             return;
134         }
135         auth->hasAuthPassed[type] = false;
136         auth->connId[type] = 0;
137         (void)memset_s(&auth->connInfo[type], sizeof(AuthConnInfo), 0, sizeof(AuthConnInfo));
138         for (int32_t i = AUTH_LINK_TYPE_WIFI; i < AUTH_LINK_TYPE_MAX; i++) {
139             if (auth->connId[i] == 0) {
140                 continue;
141             }
142             ClearSessionkeyByAuthLinkType(auth->authId, &auth->sessionKeyList, (AuthLinkType)type);
143             AUTH_LOGI(AUTH_FSM, "only clear connInfo, udid=%{public}s, side=%{public}s, type=%{public}d,"
144                 " authId=%{public}" PRId64, anonyUdid, GetAuthSideStr(auth->isServer), type, auth->authId);
145             AnonymizeFree(anonyUdid);
146             return;
147         }
148     }
149     AUTH_LOGI(AUTH_FSM, "delete auth manager, udid=%{public}s, side=%{public}s, authId=%{public}" PRId64,
150         AnonymizeWrapper(anonyUdid), GetAuthSideStr(auth->isServer), auth->authId);
151     AnonymizeFree(anonyUdid);
152     ListDelete(&auth->node);
153     CancelUpdateSessionKey(auth->authId);
154     DestroySessionKeyList(&auth->sessionKeyList);
155     SoftBusFree(auth);
156 }
157 
FindAuthManagerByConnInfo(const AuthConnInfo * connInfo,bool isServer)158 static AuthManager *FindAuthManagerByConnInfo(const AuthConnInfo *connInfo, bool isServer)
159 {
160     AuthManager *item = NULL;
161     ListNode *list = isServer ? &g_authServerList : &g_authClientList;
162     LIST_FOR_EACH_ENTRY(item, list, AuthManager, node) {
163         if (CompareConnInfo(&item->connInfo[connInfo->type], connInfo, true)) {
164             return item;
165         }
166     }
167     return NULL;
168 }
169 
FindAuthManagerByUuid(const char * uuid,AuthLinkType type,bool isServer)170 static AuthManager *FindAuthManagerByUuid(const char *uuid, AuthLinkType type, bool isServer)
171 {
172     AuthManager *item = NULL;
173     ListNode *list = isServer ? &g_authServerList : &g_authClientList;
174     LIST_FOR_EACH_ENTRY(item, list, AuthManager, node) {
175         if (item->connInfo[type].type == type && (strcmp(item->uuid, uuid) == 0) && item->hasAuthPassed[type]) {
176             return item;
177         }
178     }
179     return NULL;
180 }
181 
FindAuthManagerByUdid(const char * udid,AuthLinkType type,bool isServer)182 static AuthManager *FindAuthManagerByUdid(const char *udid, AuthLinkType type, bool isServer)
183 {
184     AuthManager *item = NULL;
185     ListNode *list = isServer ? &g_authServerList : &g_authClientList;
186     LIST_FOR_EACH_ENTRY(item, list, AuthManager, node) {
187         if (item->connInfo[type].type == type && (strcmp(item->udid, udid) == 0) && item->hasAuthPassed[type]) {
188             return item;
189         }
190     }
191     return NULL;
192 }
193 
FindNormalizedKeyAuthManagerByUdid(const char * udid,bool isServer)194 static AuthManager *FindNormalizedKeyAuthManagerByUdid(const char *udid, bool isServer)
195 {
196     AuthManager *item = NULL;
197     ListNode *list = isServer ? &g_authServerList : &g_authClientList;
198     LIST_FOR_EACH_ENTRY(item, list, AuthManager, node) {
199         if ((strcmp(item->udid, udid) == 0)) {
200             return item;
201         }
202     }
203     return NULL;
204 }
205 
FindAuthManagerByAuthId(int64_t authId)206 static AuthManager *FindAuthManagerByAuthId(int64_t authId)
207 {
208     AuthManager *item = NULL;
209     LIST_FOR_EACH_ENTRY(item, &g_authClientList, AuthManager, node) {
210         if (item->authId == authId) {
211             return item;
212         }
213     }
214     LIST_FOR_EACH_ENTRY(item, &g_authServerList, AuthManager, node) {
215         if (item->authId == authId) {
216             return item;
217         }
218     }
219     return NULL;
220 }
221 
FindAuthManagerByConnId(uint64_t connId,bool isServer)222 static AuthManager *FindAuthManagerByConnId(uint64_t connId, bool isServer)
223 {
224     AuthManager *item = NULL;
225     int32_t type = GetConnType(connId);
226     ListNode *list = isServer ? &g_authServerList : &g_authClientList;
227     LIST_FOR_EACH_ENTRY(item, list, AuthManager, node) {
228         if (item->connId[type] == connId) {
229             return item;
230         }
231     }
232     return NULL;
233 }
234 
DestroyAuthManagerList(void)235 static void DestroyAuthManagerList(void)
236 {
237     if (!RequireAuthLock()) {
238         return;
239     }
240     AuthManager *item = NULL;
241     AuthManager *next = NULL;
242     LIST_FOR_EACH_ENTRY_SAFE(item, next, &g_authClientList, AuthManager, node) {
243         DelAuthManager(item, AUTH_LINK_TYPE_MAX);
244     }
245     LIST_FOR_EACH_ENTRY_SAFE(item, next, &g_authServerList, AuthManager, node) {
246         DelAuthManager(item, AUTH_LINK_TYPE_MAX);
247     }
248     ReleaseAuthLock();
249 }
250 
SetAuthConnId(AuthManager * auth,const AuthManager * inAuth,AuthLinkType type)251 static int32_t SetAuthConnId(AuthManager *auth, const AuthManager *inAuth, AuthLinkType type)
252 {
253     auth->connId[type] = inAuth->connId[type];
254     return SOFTBUS_OK;
255 }
256 
SetAuthP2pMac(AuthManager * auth,const AuthManager * inAuth,AuthLinkType type)257 static int32_t SetAuthP2pMac(AuthManager *auth, const AuthManager *inAuth, AuthLinkType type)
258 {
259     (void)type;
260     if (strcpy_s(auth->p2pMac, sizeof(auth->p2pMac), inAuth->p2pMac) != EOK) {
261         AUTH_LOGE(AUTH_CONN, "copy auth p2p mac fail, authId=%{public}" PRId64, auth->authId);
262         return SOFTBUS_MEM_ERR;
263     }
264     return SOFTBUS_OK;
265 }
266 
UpdateAuthManagerByAuthId(int64_t authId,int32_t (* updateFunc)(AuthManager *,const AuthManager *,AuthLinkType),const AuthManager * inAuth,AuthLinkType type)267 static int32_t UpdateAuthManagerByAuthId(
268     int64_t authId, int32_t (*updateFunc)(AuthManager *, const AuthManager *, AuthLinkType),
269     const AuthManager *inAuth, AuthLinkType type)
270 {
271     if (!RequireAuthLock()) {
272         return SOFTBUS_LOCK_ERR;
273     }
274     AuthManager *auth = FindAuthManagerByAuthId(authId);
275     if (auth == NULL) {
276         AUTH_LOGE(AUTH_FSM, "auth manager not found, authId=%{public}" PRId64, authId);
277         ReleaseAuthLock();
278         return SOFTBUS_AUTH_NOT_FOUND;
279     }
280     if (updateFunc(auth, inAuth, type) != SOFTBUS_OK) {
281         AUTH_LOGE(AUTH_FSM, "update auth manager fail, authId=%{public}" PRId64, authId);
282         ReleaseAuthLock();
283         return SOFTBUS_ERR;
284     }
285     ReleaseAuthLock();
286     return SOFTBUS_OK;
287 }
288 
RemoveAuthSessionKeyByIndex(int64_t authId,int32_t index,AuthLinkType type)289 void RemoveAuthSessionKeyByIndex(int64_t authId, int32_t index, AuthLinkType type)
290 {
291     if (!RequireAuthLock()) {
292         return;
293     }
294     AuthManager *auth = FindAuthManagerByAuthId(authId);
295     if (auth == NULL) {
296         AUTH_LOGE(AUTH_CONN, "auth manager already removed, authId=%{public}" PRId64, authId);
297         ReleaseAuthLock();
298         return;
299     }
300     RemoveSessionkeyByIndex(&auth->sessionKeyList, index, type);
301     char udid[UDID_BUF_LEN] = { 0 };
302     (void)memcpy_s(udid, UDID_BUF_LEN, auth->udid, UDID_BUF_LEN);
303     ReleaseAuthLock();
304     AuthRemoveDeviceKeyByUdid(udid);
305     if (IsListEmpty(&auth->sessionKeyList)) {
306         AUTH_LOGI(AUTH_CONN, "auth key clear empty, Lnn offline. authId=%{public}" PRId64, authId);
307         LnnNotifyEmptySessionKey(authId);
308     } else if (!CheckSessionKeyListExistType(&auth->sessionKeyList, type)) {
309         AUTH_LOGI(AUTH_CONN, "auth key type=%{public}d clear, Lnn offline. authId=%{public}" PRId64, type, authId);
310         AuthHandle authHandle = { .authId = authId, .type = type };
311         LnnNotifyLeaveLnnByAuthHandle(&authHandle);
312     }
313 }
314 
RemoveAuthManagerByAuthId(AuthHandle authHandle)315 void RemoveAuthManagerByAuthId(AuthHandle authHandle)
316 {
317     if (!RequireAuthLock()) {
318         return;
319     }
320     AuthManager *auth = FindAuthManagerByAuthId(authHandle.authId);
321     if (auth == NULL) {
322         AUTH_LOGI(AUTH_CONN, "auth manager already removed, authId=%{public}" PRId64, authHandle.authId);
323         ReleaseAuthLock();
324         return;
325     }
326     DelAuthManager(auth, authHandle.type);
327     ReleaseAuthLock();
328 }
329 
RemoveAuthManagerByConnInfo(const AuthConnInfo * connInfo,bool isServer)330 static void RemoveAuthManagerByConnInfo(const AuthConnInfo *connInfo, bool isServer)
331 {
332     if (!RequireAuthLock()) {
333         return;
334     }
335     AuthManager *auth = FindAuthManagerByConnInfo(connInfo, isServer);
336     if (auth == NULL) {
337         PrintAuthConnInfo(connInfo);
338         ReleaseAuthLock();
339         AUTH_LOGI(AUTH_CONN, "auth manager already removed, connType=%{public}d, side=%{public}s", connInfo->type,
340             GetAuthSideStr(isServer));
341         return;
342     }
343     DelAuthManager(auth, connInfo->type);
344     ReleaseAuthLock();
345 }
346 
HasAuthPassed(AuthManager * auth)347 static bool HasAuthPassed(AuthManager *auth)
348 {
349     for (uint32_t i = AUTH_LINK_TYPE_WIFI; i < AUTH_LINK_TYPE_MAX; i++) {
350         if (auth->hasAuthPassed[i]) {
351             return true;
352         }
353     }
354     return false;
355 }
356 
RemoveNotPassedAuthManagerByUdid(const char * udid)357 void RemoveNotPassedAuthManagerByUdid(const char *udid)
358 {
359     if (udid == NULL) {
360         AUTH_LOGE(AUTH_CONN, "udid is empty");
361         return;
362     }
363     if (!RequireAuthLock()) {
364         return;
365     }
366     AuthManager *item = NULL;
367     AuthManager *next = NULL;
368     LIST_FOR_EACH_ENTRY_SAFE(item, next, &g_authClientList, AuthManager, node) {
369         if (HasAuthPassed(item) || strcmp(item->udid, udid) != 0) {
370             continue;
371         }
372         DelAuthManager(item, AUTH_LINK_TYPE_MAX);
373     }
374     LIST_FOR_EACH_ENTRY_SAFE(item, next, &g_authServerList, AuthManager, node) {
375         if (HasAuthPassed(item) || strcmp(item->udid, udid) != 0) {
376             continue;
377         }
378         DelAuthManager(item, AUTH_LINK_TYPE_MAX);
379     }
380     ReleaseAuthLock();
381 }
382 
GetAuthConnInfoByUuid(const char * uuid,AuthLinkType type,AuthConnInfo * connInfo)383 int32_t GetAuthConnInfoByUuid(const char *uuid, AuthLinkType type, AuthConnInfo *connInfo)
384 {
385     AUTH_CHECK_AND_RETURN_RET_LOGE(uuid != NULL, SOFTBUS_INVALID_PARAM, AUTH_CONN, "uuid is NULL");
386     AUTH_CHECK_AND_RETURN_RET_LOGE(connInfo != NULL, SOFTBUS_INVALID_PARAM, AUTH_CONN, "connInfo is NULL");
387     if (type < AUTH_LINK_TYPE_WIFI || type >= AUTH_LINK_TYPE_MAX) {
388         AUTH_LOGE(AUTH_CONN, "connInfo type error");
389         return SOFTBUS_INVALID_PARAM;
390     }
391     if (!RequireAuthLock()) {
392         return SOFTBUS_LOCK_ERR;
393     }
394     AuthManager *auth = FindAuthManagerByUuid(uuid, type, false);
395     if (auth == NULL) {
396         auth = FindAuthManagerByUuid(uuid, type, true);
397     }
398     char *anonyUuid = NULL;
399     Anonymize(uuid, &anonyUuid);
400     if (auth == NULL) {
401         AUTH_LOGI(AUTH_CONN, "auth not found by uuid, connType=%{public}d, uuid=%{public}s",
402             type, AnonymizeWrapper(anonyUuid));
403         AnonymizeFree(anonyUuid);
404         ReleaseAuthLock();
405         return SOFTBUS_AUTH_NOT_FOUND;
406     }
407     AnonymizeFree(anonyUuid);
408     *connInfo = auth->connInfo[type];
409     ReleaseAuthLock();
410     return SOFTBUS_OK;
411 }
412 
GetAvailableAuthConnInfoByUuid(const char * uuid,AuthLinkType type,AuthConnInfo * connInfo)413 static int32_t GetAvailableAuthConnInfoByUuid(const char *uuid, AuthLinkType type, AuthConnInfo *connInfo)
414 {
415     if (!RequireAuthLock()) {
416         return SOFTBUS_LOCK_ERR;
417     }
418     AuthManager *auth = FindAuthManagerByUuid(uuid, type, false);
419     if (auth == NULL) {
420         auth = FindAuthManagerByUuid(uuid, type, true);
421     }
422     char *anonyUuid = NULL;
423     Anonymize(uuid, &anonyUuid);
424     if (auth == NULL) {
425         AUTH_LOGI(AUTH_CONN, "auth not found by uuid, connType=%{public}d, uuid=%{public}s",
426             type, AnonymizeWrapper(anonyUuid));
427         AnonymizeFree(anonyUuid);
428         ReleaseAuthLock();
429         return SOFTBUS_AUTH_NOT_FOUND;
430     }
431     if (GetLatestAvailableSessionKeyTime(&auth->sessionKeyList, type) == 0) {
432         AUTH_LOGI(AUTH_FSM, "not available session key, connType=%{public}d, uuid=%{public}s",
433             type, AnonymizeWrapper(anonyUuid));
434         AnonymizeFree(anonyUuid);
435         ReleaseAuthLock();
436         return SOFTBUS_AUTH_SESSION_KEY_INVALID;
437     }
438     AnonymizeFree(anonyUuid);
439     *connInfo = auth->connInfo[type];
440     ReleaseAuthLock();
441     return SOFTBUS_OK;
442 }
443 
444 /* Note: must call DelDupAuthManager(auth) to free. */
GetAuthManagerByAuthId(int64_t authId)445 AuthManager *GetAuthManagerByAuthId(int64_t authId)
446 {
447     if (!RequireAuthLock()) {
448         return NULL;
449     }
450     AuthManager *item = FindAuthManagerByAuthId(authId);
451     if (item == NULL) {
452         AUTH_LOGI(AUTH_FSM, "auth manager not found. authId=%{public}" PRId64 "", authId);
453         ReleaseAuthLock();
454         return NULL;
455     }
456     AuthManager *newAuth = DupAuthManager(item);
457     ReleaseAuthLock();
458     return newAuth;
459 }
460 
GetAuthManagerByConnInfo(const AuthConnInfo * connInfo,bool isServer)461 AuthManager *GetAuthManagerByConnInfo(const AuthConnInfo *connInfo, bool isServer)
462 {
463     AUTH_CHECK_AND_RETURN_RET_LOGE(connInfo != NULL, NULL, AUTH_FSM, "info is null");
464     AUTH_CHECK_AND_RETURN_RET_LOGE(CheckAuthConnInfoType(connInfo), NULL, AUTH_FSM, "connInfo type error");
465     if (!RequireAuthLock()) {
466         return NULL;
467     }
468     AuthManager *item = FindAuthManagerByConnInfo(connInfo, isServer);
469     if (item == NULL) {
470         PrintAuthConnInfo(connInfo);
471         ReleaseAuthLock();
472         AUTH_LOGI(AUTH_FSM, "auth manager not found, connType=%{public}d, side=%{public}s", connInfo->type,
473             GetAuthSideStr(isServer));
474         return NULL;
475     }
476     AuthManager *newAuth = DupAuthManager(item);
477     ReleaseAuthLock();
478     return newAuth;
479 }
480 
GetAuthIdByConnId(uint64_t connId,bool isServer)481 static int64_t GetAuthIdByConnId(uint64_t connId, bool isServer)
482 {
483     int64_t authId;
484     if (!RequireAuthLock()) {
485         return AUTH_INVALID_ID;
486     }
487     AuthManager *auth = FindAuthManagerByConnId(connId, isServer);
488     if (auth == NULL) {
489         ReleaseAuthLock();
490         AUTH_LOGI(AUTH_CONN, "auth manager not found, isServer=%{public}s, " CONN_INFO,
491             GetAuthSideStr(isServer), CONN_DATA(connId));
492         return AUTH_INVALID_ID;
493     }
494     authId = auth->authId;
495     ReleaseAuthLock();
496     return authId;
497 }
498 
GetLatestIdByConnInfo(const AuthConnInfo * connInfo)499 int64_t GetLatestIdByConnInfo(const AuthConnInfo *connInfo)
500 {
501     if (connInfo == NULL) {
502         AUTH_LOGE(AUTH_CONN, "connInfo is empty");
503         return AUTH_INVALID_ID;
504     }
505     if (!RequireAuthLock()) {
506         return AUTH_INVALID_ID;
507     }
508     uint32_t num = 0;
509     const AuthManager *auth[2] = { NULL, NULL }; /* 2: client + server */
510     auth[num++] = FindAuthManagerByConnInfo(connInfo, false);
511     auth[num++] = FindAuthManagerByConnInfo(connInfo, true);
512     int64_t latestAuthId = AUTH_INVALID_ID;
513     uint64_t latestVerifyTime = 0;
514     for (uint32_t i = 0; i < num; i++) {
515         if (auth[i] != NULL && auth[i]->lastVerifyTime > latestVerifyTime && auth[i]->hasAuthPassed[connInfo->type]) {
516             latestAuthId = auth[i]->authId;
517             latestVerifyTime = auth[i]->lastVerifyTime;
518         }
519     }
520     ReleaseAuthLock();
521     AUTH_LOGD(AUTH_CONN,
522         "latest auth manager found. num=%{public}d, latestAuthId=%{public}" PRId64 ", lastVerifyTime=%{public}" PRIu64,
523         num, latestAuthId, latestVerifyTime);
524     return latestAuthId;
525 }
526 
GetAuthIdByConnInfo(const AuthConnInfo * connInfo,bool isServer)527 static int64_t GetAuthIdByConnInfo(const AuthConnInfo *connInfo, bool isServer)
528 {
529     int64_t authId;
530     if (!RequireAuthLock()) {
531         return AUTH_INVALID_ID;
532     }
533     AuthManager *auth = FindAuthManagerByConnInfo(connInfo, isServer);
534     if (auth == NULL) {
535         AUTH_LOGE(AUTH_CONN, "auth manager not found, connType=%{public}d, side=%{public}s", connInfo->type,
536             GetAuthSideStr(isServer));
537         ReleaseAuthLock();
538         return AUTH_INVALID_ID;
539     }
540     authId = auth->authId;
541     ReleaseAuthLock();
542     return authId;
543 }
544 
GetActiveAuthIdByConnInfo(const AuthConnInfo * connInfo,bool judgeTimeOut)545 int64_t GetActiveAuthIdByConnInfo(const AuthConnInfo *connInfo, bool judgeTimeOut)
546 {
547     AUTH_CHECK_AND_RETURN_RET_LOGE(connInfo != NULL, AUTH_INVALID_ID, AUTH_CONN, "info is null");
548     if (!RequireAuthLock()) {
549         return AUTH_INVALID_ID;
550     }
551     uint32_t num = 0;
552     AuthManager *auth[2] = { NULL, NULL }; /* 2: client + server */
553     auth[num++] = FindAuthManagerByConnInfo(connInfo, false);
554     auth[num++] = FindAuthManagerByConnInfo(connInfo, true);
555     /* Check auth valid period */
556     uint64_t currentTime = GetCurrentTimeMs();
557     for (uint32_t i = 0; i < num; i++) {
558         if (auth[i] == NULL) {
559             continue;
560         }
561         if (!auth[i]->hasAuthPassed[connInfo->type]) {
562             AUTH_LOGI(AUTH_CONN, "auth manager has not auth pass. authId=%{public}" PRId64, auth[i]->authId);
563             auth[i] = NULL;
564             continue;
565         }
566         if (CheckSessionKeyListExistType(&auth[i]->sessionKeyList, connInfo->type) &&
567             GetLatestAvailableSessionKeyTime(&auth[i]->sessionKeyList, connInfo->type) == 0) {
568             AUTH_LOGI(AUTH_CONN, "auth manager has not available key. authId=%{public}" PRId64, auth[i]->authId);
569             auth[i] = NULL;
570             continue;
571         }
572         if ((currentTime - auth[i]->lastActiveTime >= MAX_AUTH_VALID_PERIOD) && judgeTimeOut) {
573             AUTH_LOGI(AUTH_CONN, "auth manager timeout. authId=%{public}" PRId64, auth[i]->authId);
574             auth[i] = NULL;
575         }
576     }
577     /* Get lastest authId */
578     int64_t authId = AUTH_INVALID_ID;
579     uint64_t maxVerifyTime = 0;
580     for (uint32_t i = 0; i < sizeof(auth) / sizeof(auth[0]); i++) {
581         if (auth[i] == NULL) {
582             continue;
583         }
584         if (auth[i]->lastVerifyTime > maxVerifyTime) {
585             authId = auth[i]->authId;
586         }
587     }
588     AUTH_LOGI(AUTH_CONN, "get active auth manager. authId=%{public}" PRId64 "", authId);
589     ReleaseAuthLock();
590     return authId;
591 }
592 
ProcessSessionKey(SessionKeyList * list,int64_t * index,const SessionKey * key,AuthSessionInfo * info,bool isOldKey)593 static int32_t ProcessSessionKey(SessionKeyList *list, int64_t *index, const SessionKey *key, AuthSessionInfo *info,
594     bool isOldKey)
595 {
596     if (info->normalizedType == NORMALIZED_SUPPORT) {
597         if (SetSessionKeyAuthLinkType(list, info->normalizedIndex, info->connInfo.type) == SOFTBUS_OK) {
598             AUTH_LOGI(AUTH_FSM, "index is alread exist");
599             return SOFTBUS_OK;
600         }
601         *index = info->normalizedIndex;
602     }
603     if (AddSessionKey(list, TO_INT32(*index), key, info->connInfo.type, isOldKey) != SOFTBUS_OK) {
604         AUTH_LOGE(AUTH_FSM, "failed to add a sessionKey");
605         return SOFTBUS_ERR;
606     }
607     AUTH_LOGI(AUTH_FSM, "add session key index=%{public}d, new type=%{public}d", TO_INT32(*index), info->connInfo.type);
608     return SOFTBUS_OK;
609 }
610 
GetExistAuthManager(int64_t authSeq,const AuthSessionInfo * info)611 static AuthManager *GetExistAuthManager(int64_t authSeq, const AuthSessionInfo *info)
612 {
613     if (info->normalizedType == NORMALIZED_NOT_SUPPORT) {
614         AUTH_LOGI(AUTH_FSM, "peer not support normalized");
615         return NewAuthManager(authSeq, info);
616     }
617     AuthManager *auth = FindNormalizedKeyAuthManagerByUdid(info->udid, info->isServer);
618     if (auth == NULL) {
619         return NewAuthManager(authSeq, info);
620     }
621     auth->connId[info->connInfo.type] = info->connId;
622     if (strcpy_s(auth->uuid, UUID_BUF_LEN, info->uuid) != EOK) {
623         char *anonyUuid = NULL;
624         Anonymize(info->uuid, &anonyUuid);
625         AUTH_LOGE(AUTH_FSM, "str copy uuid fail, uuid=%{public}s", anonyUuid);
626         AnonymizeFree(anonyUuid);
627     }
628     if (memcpy_s(&auth->connInfo[info->connInfo.type], sizeof(AuthConnInfo),
629         &info->connInfo, sizeof(AuthConnInfo)) != EOK) {
630         AUTH_LOGE(AUTH_FSM, "connInfo cpy fail");
631         return NULL;
632     }
633     return auth;
634 }
635 
GetDeviceAuthManager(int64_t authSeq,const AuthSessionInfo * info,bool * isNewCreated,int64_t lastAuthSeq)636 AuthManager *GetDeviceAuthManager(int64_t authSeq, const AuthSessionInfo *info, bool *isNewCreated,
637     int64_t lastAuthSeq)
638 {
639     AUTH_CHECK_AND_RETURN_RET_LOGE(info != NULL, NULL, AUTH_FSM, "info is NULL");
640     AUTH_CHECK_AND_RETURN_RET_LOGE(isNewCreated != NULL, NULL, AUTH_FSM, "isNewCreated is NULL");
641     AUTH_CHECK_AND_RETURN_RET_LOGE(CheckAuthConnInfoType(&info->connInfo), NULL, AUTH_FSM, "connInfo type error");
642     *isNewCreated = false;
643     AuthManager *auth = FindAuthManagerByConnInfo(&info->connInfo, info->isServer);
644     if (auth != NULL && auth->connInfo[info->connInfo.type].type != 0) {
645         if (strcpy_s(auth->uuid, UUID_BUF_LEN, info->uuid) != EOK) {
646             AUTH_LOGE(AUTH_FSM, "str copy uuid fail");
647         }
648         if (auth->connId[info->connInfo.type] != info->connId &&
649             auth->connInfo[info->connInfo.type].type == AUTH_LINK_TYPE_WIFI) {
650             AuthFsm *fsm = GetAuthFsmByConnId(auth->connId[info->connInfo.type], info->isServer, false);
651             DisconnectAuthDevice(&auth->connId[info->connInfo.type]);
652             if (fsm != NULL) {
653                 UpdateFd(&fsm->info.connId, AUTH_INVALID_FD);
654             }
655             auth->hasAuthPassed[info->connInfo.type] = false;
656             AUTH_LOGI(AUTH_FSM, "auth manager may single device on line");
657         }
658         char *anonyUuid = NULL;
659         Anonymize(auth->uuid, &anonyUuid);
660         AUTH_LOGI(AUTH_FSM, "uuid=%{public}s, authId=%{public}" PRId64, anonyUuid, auth->authId);
661         AnonymizeFree(anonyUuid);
662     } else {
663         auth = GetExistAuthManager(authSeq, info);
664         if (auth != NULL) {
665             *isNewCreated = true;
666         } else {
667             AUTH_LOGE(AUTH_FSM, "auth manager is null.");
668             return NULL;
669         }
670     }
671     auth->connId[info->connInfo.type] = info->connId;
672     auth->lastAuthSeq[info->connInfo.type] = lastAuthSeq;
673     auth->lastVerifyTime = GetCurrentTimeMs();
674     auth->lastActiveTime = GetCurrentTimeMs();
675 
676     AUTH_LOGI(AUTH_FSM, "auth manager exist.");
677     return auth;
678 }
679 
ProcessEmptySessionKey(const AuthSessionInfo * info,int32_t index,bool isServer,const SessionKey * sessionKey)680 static int32_t ProcessEmptySessionKey(const AuthSessionInfo *info, int32_t index, bool isServer,
681     const SessionKey *sessionKey)
682 {
683     AuthManager *auth = FindAuthManagerByUdid(info->udid, AUTH_LINK_TYPE_BLE, isServer);
684     if (auth == NULL || auth->connInfo[AUTH_LINK_TYPE_BLE].type != AUTH_LINK_TYPE_BLE) {
685         AUTH_LOGI(AUTH_FSM, "should not process empty session key.");
686         return SOFTBUS_OK;
687     }
688     (void)ClearOldKey(&auth->sessionKeyList, AUTH_LINK_TYPE_BLE);
689     if (SetSessionKeyAuthLinkType(&auth->sessionKeyList, index, AUTH_LINK_TYPE_BLE) == SOFTBUS_OK) {
690         AUTH_LOGI(AUTH_FSM, "add keyType, index=%{public}d, type=%{public}d, authId=%{public}" PRId64,
691             index, AUTH_LINK_TYPE_BLE, auth->authId);
692         return SOFTBUS_OK;
693     }
694     if (AddSessionKey(&auth->sessionKeyList, index, sessionKey, AUTH_LINK_TYPE_BLE, false) != SOFTBUS_OK ||
695         SetSessionKeyAvailable(&auth->sessionKeyList, index) != SOFTBUS_OK) {
696         AUTH_LOGE(AUTH_FSM, "add sessionkey fail, index=%{public}d, newType=%{public}d",
697             index, AUTH_LINK_TYPE_BLE);
698         return SOFTBUS_AUTH_SESSION_KEY_INVALID;
699     }
700     AUTH_LOGI(AUTH_FSM, "add sessionkey, index=%{public}d, type=%{public}d, authId=%{public}" PRId64,
701         index, AUTH_LINK_TYPE_BLE, auth->authId);
702     return SOFTBUS_OK;
703 }
704 
AuthProcessEmptySessionKey(const AuthSessionInfo * info,int32_t index)705 static int32_t AuthProcessEmptySessionKey(const AuthSessionInfo *info, int32_t index)
706 {
707     if (info->module != AUTH_MODULE_TRANS) {
708         AUTH_LOGI(AUTH_FSM, "no need AuthProcessEmptySessionKey");
709         return SOFTBUS_OK;
710     }
711     AuthManager *auth = FindAuthManagerByUdid(info->udid, info->connInfo.type, info->isServer);
712     if (auth == NULL) {
713         return SOFTBUS_ERR;
714     }
715     SessionKey sessionKey;
716     (void)memset_s(&sessionKey, sizeof(SessionKey), 0, sizeof(SessionKey));
717     if (GetSessionKeyByIndex(&auth->sessionKeyList, index, info->connInfo.type, &sessionKey) != SOFTBUS_OK) {
718         AUTH_LOGE(AUTH_FSM, "GetSessionKeyByIndex fail index=%{public}d", index);
719         return SOFTBUS_AUTH_GET_SESSION_KEY_FAIL;
720     }
721     if (ProcessEmptySessionKey(info, index, !info->isServer, &sessionKey) != SOFTBUS_OK ||
722         ProcessEmptySessionKey(info, index, info->isServer, &sessionKey) != SOFTBUS_OK) {
723         (void)memset_s(&sessionKey, sizeof(SessionKey), 0, sizeof(SessionKey));
724         return SOFTBUS_ERR;
725     }
726     (void)memset_s(&sessionKey, sizeof(SessionKey), 0, sizeof(SessionKey));
727     return SOFTBUS_OK;
728 }
729 
AuthManagerSetSessionKey(int64_t authSeq,AuthSessionInfo * info,const SessionKey * sessionKey,bool isConnect,bool isOldKey)730 int32_t AuthManagerSetSessionKey(int64_t authSeq, AuthSessionInfo *info, const SessionKey *sessionKey,
731     bool isConnect, bool isOldKey)
732 {
733     AUTH_CHECK_AND_RETURN_RET_LOGE(info != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "info is NULL");
734     AUTH_CHECK_AND_RETURN_RET_LOGE(sessionKey != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "sessionKey is NULL");
735     AUTH_CHECK_AND_RETURN_RET_LOGE(CheckAuthConnInfoType(&info->connInfo), SOFTBUS_INVALID_PARAM,
736         AUTH_FSM, "connInfo type error");
737     int64_t sessionKeyIndex = authSeq;
738     if ((info->isSupportFastAuth) && (info->version <= SOFTBUS_OLD_V2)) {
739         sessionKeyIndex = info->oldIndex;
740     }
741     authSeq = isConnect ? authSeq : GenSeq(info->isServer);
742     AUTH_LOGI(AUTH_FSM, "SetSessionKey: authSeq=%{public}" PRId64 ", side=%{public}s, requestId=%{public}u", authSeq,
743         GetAuthSideStr(info->isServer), info->requestId);
744     if (!RequireAuthLock()) {
745         return SOFTBUS_LOCK_ERR;
746     }
747     if (!isConnect && info->connInfo.type != AUTH_LINK_TYPE_BLE) {
748         AUTH_LOGE(AUTH_FSM, "only support ble direct on line");
749         ReleaseAuthLock();
750         return SOFTBUS_OK;
751     }
752     bool isNewCreated = false;
753     AuthManager *auth = GetDeviceAuthManager(authSeq, info, &isNewCreated, sessionKeyIndex);
754     if (auth == NULL) {
755         AUTH_LOGE(AUTH_FSM, "auth manager does not exist.");
756         ReleaseAuthLock();
757         return SOFTBUS_ERR;
758     }
759     if (ProcessSessionKey(&auth->sessionKeyList, &sessionKeyIndex, sessionKey, info, isOldKey) != SOFTBUS_OK) {
760         if (isNewCreated) {
761             DelAuthManager(auth, info->connInfo.type);
762         }
763         ReleaseAuthLock();
764         return SOFTBUS_ERR;
765     }
766     AuthHandle authHandle = { .authId = auth->authId, .type = info->connInfo.type };
767     if (auth->connInfo[info->connInfo.type].type == AUTH_LINK_TYPE_WIFI && !auth->isServer) {
768         ScheduleUpdateSessionKey(authHandle, SCHEDULE_UPDATE_SESSION_KEY_PERIOD);
769     }
770     int32_t ret = SOFTBUS_OK;
771     if (!isConnect) {
772         ret = SetSessionKeyAvailable(&auth->sessionKeyList, TO_INT32(sessionKeyIndex));
773         auth->hasAuthPassed[info->connInfo.type] = true;
774     }
775     info->isSavedSessionKey = true;
776     AUTH_LOGI(AUTH_FSM,
777         "authId=%{public}" PRId64 ", authSeq=%{public}" PRId64 ", index=%{public}d, lastVerifyTime=%{public}" PRId64,
778         auth->authId, authSeq, TO_INT32(sessionKeyIndex), auth->lastVerifyTime);
779     ReleaseAuthLock();
780     return ret;
781 }
782 
AuthManagerGetSessionKey(int64_t authSeq,const AuthSessionInfo * info,SessionKey * sessionKey)783 int32_t AuthManagerGetSessionKey(int64_t authSeq, const AuthSessionInfo *info, SessionKey *sessionKey)
784 {
785     AUTH_CHECK_AND_RETURN_RET_LOGE(info != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "info is NULL");
786     AUTH_CHECK_AND_RETURN_RET_LOGE(sessionKey != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "sessionKey is NULL");
787     AUTH_CHECK_AND_RETURN_RET_LOGE(CheckAuthConnInfoType(&info->connInfo), SOFTBUS_INVALID_PARAM,
788         AUTH_FSM, "connInfo type error");
789     AUTH_LOGI(AUTH_FSM, "GetSessionKey: authSeq=%{public}" PRId64 ", side=%{public}s, requestId=%{public}u",
790         authSeq, GetAuthSideStr(info->isServer), info->requestId);
791     if (!RequireAuthLock()) {
792         return SOFTBUS_LOCK_ERR;
793     }
794     AuthManager *auth = FindAuthManagerByConnInfo(&info->connInfo, info->isServer);
795     if (auth == NULL) {
796         PrintAuthConnInfo(&info->connInfo);
797         AUTH_LOGI(AUTH_FSM, "auth manager not found, connType=%{public}d", info->connInfo.type);
798         ReleaseAuthLock();
799         return SOFTBUS_AUTH_NOT_FOUND;
800     }
801     if (GetSessionKeyByIndex(&auth->sessionKeyList, TO_INT32(authSeq), info->connInfo.type,
802         sessionKey) != SOFTBUS_OK) {
803         AUTH_LOGE(AUTH_FSM, "GetSessionKeyByIndex fail");
804         ReleaseAuthLock();
805         return SOFTBUS_AUTH_GET_SESSION_KEY_FAIL;
806     }
807     ReleaseAuthLock();
808     return SOFTBUS_OK;
809 }
810 
ReportAuthRequestPassed(uint32_t requestId,AuthHandle authHandle,const NodeInfo * nodeInfo)811 static void ReportAuthRequestPassed(uint32_t requestId, AuthHandle authHandle, const NodeInfo *nodeInfo)
812 {
813     AuthRequest request;
814     if (GetAuthRequest(requestId, &request) != SOFTBUS_OK) {
815         AUTH_LOGI(AUTH_FSM, "auth request not found, only notify LNN to update nodeInfo");
816         AuthNotifyDeviceVerifyPassed(authHandle, nodeInfo);
817         return;
818     }
819     do {
820         if (CheckAuthConnCallback(&request.connCb)) {
821             AuthNotifyDeviceVerifyPassed(authHandle, nodeInfo);
822             if (request.connInfo.type == AUTH_LINK_TYPE_WIFI || request.connInfo.type == AUTH_LINK_TYPE_P2P ||
823                 request.connInfo.type == AUTH_LINK_TYPE_ENHANCED_P2P) {
824                 PerformAuthConnCallback(request.requestId, SOFTBUS_OK, authHandle.authId);
825                 DelAuthRequest(request.requestId);
826                 continue;
827             }
828             if (request.module != AUTH_MODULE_LNN) {
829                 PerformAuthConnCallback(request.requestId, SOFTBUS_OK, authHandle.authId);
830                 DelAuthRequest(request.requestId);
831                 continue;
832             }
833             DelAuthRequest(request.requestId);
834             /* For open auth br/ble connection, reconnect to keep long-connection. */
835             if (AuthStartReconnectDevice(authHandle, &request.connInfo, request.requestId,
836                 &request.connCb) != SOFTBUS_OK) {
837                 AUTH_LOGE(AUTH_CONN, "open auth reconnect fail");
838                 request.connCb.onConnOpenFailed(request.requestId, SOFTBUS_AUTH_CONN_FAIL);
839             }
840             continue;
841         }
842         PerformVerifyCallback(request.requestId, SOFTBUS_OK, authHandle, nodeInfo);
843         DelAuthRequest(request.requestId);
844     } while (FindAuthRequestByConnInfo(&request.connInfo, &request) == SOFTBUS_OK);
845 }
846 
ReportAuthRequestFailed(uint32_t requestId,int32_t reason)847 static void ReportAuthRequestFailed(uint32_t requestId, int32_t reason)
848 {
849     AuthRequest request;
850     if (GetAuthRequest(requestId, &request) != SOFTBUS_OK) {
851         AUTH_LOGE(AUTH_FSM, "auth request not found");
852         return;
853     }
854     if (CheckAuthConnCallback(&request.connCb)) {
855         PerformAuthConnCallback(request.requestId, reason, AUTH_INVALID_ID);
856     } else {
857         AuthHandle authHandle = { .authId = AUTH_INVALID_ID, .type = request.connInfo.type };
858         PerformVerifyCallback(request.requestId, reason, authHandle, NULL);
859     }
860     DelAuthRequest(request.requestId);
861     if (FindAuthRequestByConnInfo(&request.connInfo, &request) != SOFTBUS_OK) {
862         /* verify request wait list is empty, return. */
863         return;
864     }
865     AUTH_LOGI(AUTH_CONN, "find another verify request in wait list, do verify again");
866     if (ConnectAuthDevice(request.requestId, &request.connInfo, CONN_SIDE_ANY) != SOFTBUS_OK) {
867         ReportAuthRequestFailed(request.requestId, SOFTBUS_AUTH_CONN_FAIL);
868     }
869 }
870 
PostCancelAuthMessage(int64_t authSeq,const AuthSessionInfo * info)871 static void PostCancelAuthMessage(int64_t authSeq, const AuthSessionInfo *info)
872 {
873     AUTH_LOGI(AUTH_FSM, "post cancel auth msg, authSeq=%{public}" PRId64, authSeq);
874     const char *msg = "";
875     AuthDataHead head = {
876         .dataType = DATA_TYPE_CANCEL_AUTH,
877         .module = MODULE_AUTH_CANCEL,
878         .seq = authSeq,
879         .flag = 0,
880         .len = strlen(msg) + 1,
881     };
882     if (PostAuthData(info->connId, !info->isConnectServer, &head, (uint8_t *)msg) != SOFTBUS_OK) {
883         AUTH_LOGE(AUTH_FSM, "post cancel auth fail");
884     }
885 }
886 
AuthNotifyAuthPassed(int64_t authSeq,const AuthSessionInfo * info)887 void AuthNotifyAuthPassed(int64_t authSeq, const AuthSessionInfo *info)
888 {
889     AUTH_CHECK_AND_RETURN_LOGE(info != NULL, AUTH_FSM, "info is null");
890     AUTH_CHECK_AND_RETURN_LOGE(CheckAuthConnInfoType(&info->connInfo), AUTH_FSM, "connInfo type error");
891     AUTH_LOGI(AUTH_FSM, "AuthNotifyAuthPassed, authSeq=%{public}" PRId64, authSeq);
892     DelAuthNormalizeRequest(authSeq);
893     if (!RequireAuthLock()) {
894         return;
895     }
896     AuthManager *auth = FindAuthManagerByConnInfo(&info->connInfo, info->isServer);
897     if (auth == NULL) {
898         PrintAuthConnInfo(&info->connInfo);
899         AUTH_LOGE(AUTH_FSM, "auth manager not found, continue find, connType=%{public}d, side=%{public}s",
900             info->connInfo.type, GetAuthSideStr(info->isServer));
901         auth = FindAuthManagerByConnInfo(&info->connInfo, !info->isServer);
902     }
903     if (auth == NULL) {
904         PrintAuthConnInfo(&info->connInfo);
905         AUTH_LOGE(AUTH_FSM, "auth manager not found, connType=%{public}d, side=%{public}s",
906             info->connInfo.type, GetAuthSideStr(!info->isServer));
907         ReleaseAuthLock();
908         return;
909     }
910     AuthHandle authHandle = { .authId = auth->authId, .type = info->connInfo.type };
911     ReleaseAuthLock();
912     if (info->connInfo.type != AUTH_LINK_TYPE_WIFI) {
913         PostCancelAuthMessage(authSeq, info);
914     }
915     if (!info->isConnectServer) {
916         ReportAuthRequestPassed(info->requestId, authHandle, NULL);
917         AUTH_LOGI(AUTH_FSM, "notify auth passed, disconnect connId=%{public}" PRIu64, info->connId);
918         DisconnectAuthDevice((uint64_t *)&info->connId);
919     }
920 }
921 
NotifyAuthResult(AuthHandle authHandle,const AuthSessionInfo * info)922 static void NotifyAuthResult(AuthHandle authHandle, const AuthSessionInfo *info)
923 {
924     if (info->isConnectServer) {
925         AuthNotifyDeviceVerifyPassed(authHandle, &info->nodeInfo);
926     } else {
927         ReportAuthRequestPassed(info->requestId, authHandle, &info->nodeInfo);
928         UpdateAuthDevicePriority(info->connId);
929     }
930 }
931 
AuthManagerSetAuthPassed(int64_t authSeq,const AuthSessionInfo * info)932 void AuthManagerSetAuthPassed(int64_t authSeq, const AuthSessionInfo *info)
933 {
934     AUTH_CHECK_AND_RETURN_LOGE(info != NULL, AUTH_FSM, "info is null");
935     AUTH_CHECK_AND_RETURN_LOGE(CheckAuthConnInfoType(&info->connInfo), AUTH_FSM, "connInfo type error");
936     AUTH_LOGI(AUTH_FSM, "SetAuthPassed: authSeq=%{public}" PRId64 ", side=%{public}s, requestId=%{public}u", authSeq,
937         GetAuthSideStr(info->isServer), info->requestId);
938 
939     if (!RequireAuthLock()) {
940         return;
941     }
942     AuthManager *auth = FindAuthManagerByConnInfo(&info->connInfo, info->isServer);
943     if (auth == NULL) {
944         PrintAuthConnInfo(&info->connInfo);
945         AUTH_LOGE(AUTH_FSM, "auth manager not found, connType=%{public}d, side=%{public}s",
946             info->connInfo.type, GetAuthSideStr(info->isServer));
947         ReleaseAuthLock();
948         return;
949     }
950     int64_t index = authSeq;
951     if (info->normalizedType == NORMALIZED_SUPPORT) {
952         index = info->normalizedIndex;
953     }
954     if (SetSessionKeyAvailable(&auth->sessionKeyList, TO_INT32(index)) != SOFTBUS_OK) {
955         AUTH_LOGE(AUTH_FSM, "set sessionKey available fail, index=%{public}d", TO_INT32(index));
956         ReleaseAuthLock();
957         return;
958     }
959     auth->hasAuthPassed[info->connInfo.type] = true;
960     if (AuthProcessEmptySessionKey(info, TO_INT32(index)) != SOFTBUS_OK) {
961         AUTH_LOGE(AUTH_FSM, "process empty session key error, index=%{public}d", TO_INT32(index));
962         ReleaseAuthLock();
963         return;
964     }
965     if (info->nodeInfo.p2pInfo.p2pMac[0] != '\0') {
966         if (strcpy_s(auth->p2pMac, sizeof(auth->p2pMac), info->nodeInfo.p2pInfo.p2pMac)) {
967             AUTH_LOGE(AUTH_FSM, "copy p2pMac fail, authSeq=%{public}" PRId64, authSeq);
968         }
969     }
970     AuthHandle authHandle = { .authId = auth->authId, .type = info->connInfo.type };
971     ReleaseAuthLock();
972     if (!LnnSetDlPtk(info->nodeInfo.networkId, info->nodeInfo.remotePtk)) {
973         AUTH_LOGE(AUTH_FSM, "set remote ptk error, index=%{public}d", TO_INT32(index));
974     }
975     bool isExchangeUdid = true;
976     if (GetIsExchangeUdidByNetworkId(info->nodeInfo.networkId, &isExchangeUdid) == SOFTBUS_OK && isExchangeUdid) {
977         AUTH_LOGI(AUTH_FSM, "clear isExchangeUdid");
978         LnnClearAuthExchangeUdid(info->nodeInfo.networkId);
979     }
980     NotifyAuthResult(authHandle, info);
981 }
982 
AuthManagerSetAuthFailed(int64_t authSeq,const AuthSessionInfo * info,int32_t reason)983 void AuthManagerSetAuthFailed(int64_t authSeq, const AuthSessionInfo *info, int32_t reason)
984 {
985     AUTH_CHECK_AND_RETURN_LOGE(info != NULL, AUTH_FSM, "auth session info is null");
986     AUTH_CHECK_AND_RETURN_LOGE(CheckAuthConnInfoType(&info->connInfo), AUTH_FSM, "connInfo type error");
987     AUTH_LOGE(AUTH_FSM, "SetAuthFailed: authSeq=%{public}" PRId64 ", requestId=%{public}u, reason=%{public}d", authSeq,
988         info->requestId, reason);
989     AuthManager *auth = NULL;
990     if (info->isSavedSessionKey) {
991         int64_t authId = GetAuthIdByConnId(info->connId, info->isServer);
992         auth = GetAuthManagerByAuthId(authId);
993         AUTH_LOGE(AUTH_FSM, "already save sessionkey, get auth mgr. authSeq=%{public}" PRId64, authSeq);
994     }
995     bool needDisconnect = true;
996     if (auth != NULL && reason == SOFTBUS_AUTH_TIMEOUT && info->connInfo.type == AUTH_LINK_TYPE_WIFI
997         && info->connInfo.info.ipInfo.port != auth->connInfo[AUTH_LINK_TYPE_WIFI].info.ipInfo.port) {
998         AUTH_LOGE(AUTH_FSM, "auth manager port change, connType=%{public}d, side=%{public}s",
999             info->connInfo.type, GetAuthSideStr(info->isServer));
1000         needDisconnect = false;
1001     }
1002     if (auth != NULL && auth->hasAuthPassed[info->connInfo.type] && needDisconnect) {
1003         AUTH_LOGE(AUTH_FSM, "update session key fail, authId=%{public}" PRId64, auth->authId);
1004         AuthHandle authHandle = { .authId = auth->authId, .type = info->connInfo.type };
1005         AuthNotifyDeviceDisconnect(authHandle);
1006     }
1007     DelDupAuthManager(auth);
1008 
1009     if (needDisconnect && auth != NULL) {
1010         RemoveAuthManagerByConnInfo(&info->connInfo, info->isServer);
1011     }
1012     ReportAuthRequestFailed(info->requestId, reason);
1013     if (GetConnType(info->connId) == AUTH_LINK_TYPE_WIFI) {
1014         DisconnectAuthDevice((uint64_t *)&info->connId);
1015     } else if (!info->isConnectServer) {
1016         /* Bluetooth networking only the client to close the connection. */
1017         UpdateAuthDevicePriority(info->connId);
1018         DisconnectAuthDevice((uint64_t *)&info->connId);
1019     }
1020     AuthAddNodeToLimitMap(info->udid, reason);
1021 }
1022 
HandleBleDisconnectDelay(const void * para)1023 static void HandleBleDisconnectDelay(const void *para)
1024 {
1025     AUTH_CHECK_AND_RETURN_LOGE(para != NULL, AUTH_FSM, "para is null");
1026     uint64_t connId = *((uint64_t *)para);
1027     DisconnectAuthDevice(&connId);
1028 }
1029 
BleDisconnectDelay(uint64_t connId,uint64_t delayMs)1030 static void BleDisconnectDelay(uint64_t connId, uint64_t delayMs)
1031 {
1032     (void)PostAuthEvent(EVENT_BLE_DISCONNECT_DELAY, HandleBleDisconnectDelay, &connId, sizeof(connId), delayMs);
1033 }
1034 
GenerateUdidHash(const char * udid,uint8_t * hash)1035 static int32_t GenerateUdidHash(const char *udid, uint8_t *hash)
1036 {
1037     if (SoftBusGenerateStrHash((uint8_t *)udid, strlen(udid), hash) != SOFTBUS_OK) {
1038         AUTH_LOGE(AUTH_FSM, "generate udidHash fail");
1039         return SOFTBUS_ERR;
1040     }
1041     return SOFTBUS_OK;
1042 }
1043 
AuthManagerSetAuthFinished(int64_t authSeq,const AuthSessionInfo * info)1044 void AuthManagerSetAuthFinished(int64_t authSeq, const AuthSessionInfo *info)
1045 {
1046     AUTH_CHECK_AND_RETURN_LOGE(info != NULL, AUTH_FSM, "auth session info is null");
1047     AUTH_LOGI(AUTH_FSM, "SetAuthFinished: authSeq=%{public}" PRId64 ", requestId=%{public}u", authSeq, info->requestId);
1048     if (info->isConnectServer) {
1049         AUTH_LOGI(AUTH_FSM, "SERVER: wait client close connection");
1050         return;
1051     }
1052     /* br and ble NOT long-connection, close connection after auth pass. */
1053     if (info->connInfo.type == AUTH_LINK_TYPE_BLE) {
1054         uint64_t localFeature;
1055         int32_t ret = LnnGetLocalNumU64Info(NUM_KEY_FEATURE_CAPA, &localFeature);
1056         if (ret != SOFTBUS_OK) {
1057             AUTH_LOGE(AUTH_FSM, "ret=%{public}d, local=%{public}" PRIu64, ret, localFeature);
1058             return;
1059         }
1060         if (info->connInfo.info.bleInfo.protocol == BLE_GATT &&
1061             IsFeatureSupport(localFeature, BIT_BLE_ONLINE_REUSE_CAPABILITY) &&
1062             IsFeatureSupport(info->nodeInfo.feature, BIT_BLE_ONLINE_REUSE_CAPABILITY)) {
1063             AUTH_LOGI(
1064                 AUTH_FSM, "support ble reuse, bleConnCloseDelayTime=%{public}ds", info->nodeInfo.bleConnCloseDelayTime);
1065             BleDisconnectDelay(info->connId, info->nodeInfo.bleConnCloseDelayTime);
1066         } else {
1067             AUTH_LOGI(AUTH_FSM, "ble disconn now");
1068             DisconnectAuthDevice((uint64_t *)&info->connId);
1069         }
1070         AUTH_CHECK_AND_RETURN_LOGE(info->udid != NULL, AUTH_FSM, "udid is null");
1071         uint8_t hash[SHA_256_HASH_LEN] = { 0 };
1072         char udidHash[SHORT_UDID_HASH_HEX_LEN + 1] = { 0 };
1073         if (GenerateUdidHash(info->udid, hash) != SOFTBUS_OK) {
1074             AUTH_LOGE(AUTH_FSM, "GenerateUdidShortHash fail.");
1075             return;
1076         }
1077         if (ConvertBytesToUpperCaseHexString(udidHash, SHORT_UDID_HASH_HEX_LEN + 1, hash, UDID_SHORT_HASH_LEN_TEMP) !=
1078             SOFTBUS_OK) {
1079             AUTH_LOGE(AUTH_FSM, "convert bytes to string fail");
1080             return;
1081         }
1082         AuthDeleteLimitMap(udidHash);
1083     }
1084     if (info->connInfo.type == AUTH_LINK_TYPE_BR) {
1085         AUTH_LOGI(AUTH_FSM, "br disconn now");
1086         DisconnectAuthDevice((uint64_t *)&info->connId);
1087     }
1088 }
1089 
HandleReconnectResult(const AuthRequest * request,uint64_t connId,int32_t result,int32_t type)1090 static void HandleReconnectResult(const AuthRequest *request, uint64_t connId, int32_t result, int32_t type)
1091 {
1092     if (result != SOFTBUS_OK) {
1093         PerformAuthConnCallback(request->requestId, result, AUTH_INVALID_ID);
1094         DelAuthRequest(request->requestId);
1095         return;
1096     }
1097     AuthManager inAuth = {0};
1098     inAuth.connId[type] = connId;
1099     if (UpdateAuthManagerByAuthId(request->authId, SetAuthConnId, &inAuth, (AuthLinkType)type) != SOFTBUS_OK) {
1100         AUTH_LOGE(AUTH_CONN, "set auth connId fail, requestId=%{public}u", request->requestId);
1101         PerformAuthConnCallback(request->requestId, SOFTBUS_AUTH_NOT_FOUND, AUTH_INVALID_ID);
1102         DelAuthRequest(request->requestId);
1103         return;
1104     }
1105     PerformAuthConnCallback(request->requestId, SOFTBUS_OK, request->authId);
1106     DelAuthRequest(request->requestId);
1107 }
1108 
DfxRecordLnnConnectEnd(uint32_t requestId,uint64_t connId,const AuthConnInfo * connInfo,int32_t reason)1109 static void DfxRecordLnnConnectEnd(uint32_t requestId, uint64_t connId, const AuthConnInfo *connInfo, int32_t reason)
1110 {
1111     LnnEventExtra extra = { 0 };
1112     LnnEventExtraInit(&extra);
1113     extra.authRequestId = (int32_t)requestId;
1114     extra.connectionId = (int32_t)connId;
1115     extra.errcode = reason;
1116     extra.result = (reason == SOFTBUS_OK) ? EVENT_STAGE_RESULT_OK : EVENT_STAGE_RESULT_FAILED;
1117 
1118     if (connInfo != NULL) {
1119         extra.authLinkType = connInfo->type;
1120     }
1121     LNN_EVENT(EVENT_SCENE_JOIN_LNN, EVENT_STAGE_AUTH_CONNECTION, extra);
1122 }
1123 
OnConnectResult(uint32_t requestId,uint64_t connId,int32_t result,const AuthConnInfo * connInfo)1124 static void OnConnectResult(uint32_t requestId, uint64_t connId, int32_t result, const AuthConnInfo *connInfo)
1125 {
1126     DfxRecordLnnConnectEnd(requestId, connId, connInfo, result);
1127     AUTH_LOGI(AUTH_CONN, "OnConnectResult: requestId=%{public}u, result=%{public}d", requestId, result);
1128     AuthRequest request;
1129     if (GetAuthRequest(requestId, &request) != SOFTBUS_OK) {
1130         AUTH_LOGE(AUTH_CONN, "request not found, requestId=%{public}u", requestId);
1131         return;
1132     }
1133     SoftbusHitraceStart(SOFTBUS_HITRACE_ID_VALID, (uint64_t)request.traceId);
1134     if (request.type == REQUEST_TYPE_RECONNECT && connInfo != NULL) {
1135         HandleReconnectResult(&request, connId, result, connInfo->type);
1136         SoftbusHitraceStop();
1137         return;
1138     }
1139     if (result != SOFTBUS_OK) {
1140         ReportAuthRequestFailed(requestId, result);
1141         SoftbusHitraceStop();
1142         return;
1143     }
1144     AuthParam authInfo = {
1145         .authSeq = request.traceId,
1146         .requestId = requestId,
1147         .connId = connId,
1148         .isServer = false,
1149         .isFastAuth = request.isFastAuth,
1150     };
1151     int32_t ret = AuthSessionStartAuth(&authInfo, connInfo);
1152     if (ret != SOFTBUS_OK) {
1153         AUTH_LOGE(AUTH_CONN, "start auth session fail=%{public}d, requestId=%{public}u", ret, requestId);
1154         DisconnectAuthDevice(&connId);
1155         ReportAuthRequestFailed(requestId, ret);
1156         SoftbusHitraceStop();
1157         return;
1158     }
1159     SoftbusHitraceStop();
1160 }
1161 
HandleDeviceIdData(uint64_t connId,const AuthConnInfo * connInfo,bool fromServer,const AuthDataHead * head,const uint8_t * data)1162 static void HandleDeviceIdData(
1163     uint64_t connId, const AuthConnInfo *connInfo, bool fromServer, const AuthDataHead *head, const uint8_t *data)
1164 {
1165     int32_t ret;
1166     if (head->flag == CLIENT_SIDE_FLAG) {
1167         if (!GetConfigSupportAsServer()) {
1168             AUTH_LOGE(AUTH_FSM, "local device NOT support as server, ignore auth seq=%{public}" PRId64, head->seq);
1169             return;
1170         }
1171         if (!RequireAuthLock()) {
1172             AUTH_LOGE(AUTH_FSM, "lock fail");
1173             return;
1174         }
1175         AuthFsm *fsm = GetAuthFsmByConnId(connId, true, true);
1176         if (fsm != NULL && (fsm->info.idType == EXCHANGE_NETWORKID || fsm->info.idType == EXCHANGE_FAIL ||
1177             fsm->info.localState != AUTH_STATE_COMPATIBLE)) {
1178             ReleaseAuthLock();
1179             ret = AuthSessionProcessDevIdData(head->seq, data, head->len);
1180             if (ret != SOFTBUS_OK) {
1181                 AUTH_LOGE(AUTH_FSM,
1182                     "perform auth session recv devId fail. seq=%{public}" PRId64 ", ret=%{public}d", head->seq, ret);
1183             }
1184             return;
1185         }
1186         if (fsm != NULL && fsm->info.idType == EXCHANGE_UDID && fsm->info.localState == AUTH_STATE_COMPATIBLE) {
1187             AUTH_LOGE(AUTH_FSM, "the same connId fsm not support, ignore auth seq=%{public}" PRId64, head->seq);
1188             ReleaseAuthLock();
1189             HandleRepeatDeviceIdDataDelay(connId, connInfo, fromServer, head, data);
1190             return;
1191         }
1192         ReleaseAuthLock();
1193         AuthParam authInfo = {
1194             .authSeq = head->seq,
1195             .requestId = AuthGenRequestId(),
1196             .connId = connId,
1197             .isServer = true,
1198             .isFastAuth = true,
1199         };
1200         ret = AuthSessionStartAuth(&authInfo, connInfo);
1201         if (ret != SOFTBUS_OK) {
1202             AUTH_LOGE(AUTH_FSM,
1203                 "perform auth session start auth fail. seq=%{public}" PRId64 ", ret=%{public}d", head->seq, ret);
1204             return;
1205         }
1206     }
1207     ret = AuthSessionProcessDevIdData(head->seq, data, head->len);
1208     if (ret != SOFTBUS_OK) {
1209         AUTH_LOGE(AUTH_FSM,
1210             "perform auth session recv devId fail. seq=%{public}" PRId64 ", ret=%{public}d", head->seq, ret);
1211         return;
1212     }
1213 }
1214 
HandleAuthData(const AuthConnInfo * connInfo,const AuthDataHead * head,const uint8_t * data)1215 static void HandleAuthData(const AuthConnInfo *connInfo, const AuthDataHead *head, const uint8_t *data)
1216 {
1217     int32_t ret = AuthSessionProcessAuthData(head->seq, data, head->len);
1218     if (ret != SOFTBUS_OK) {
1219         AUTH_LOGE(AUTH_FSM,
1220             "perform auth session recv authData fail. seq=%{public}" PRId64 ", ret=%{public}d", head->seq, ret);
1221         return;
1222     }
1223 }
1224 
FlushDeviceProcess(const AuthConnInfo * connInfo,bool isServer,DeviceMessageParse * messageParse)1225 static void FlushDeviceProcess(const AuthConnInfo *connInfo, bool isServer, DeviceMessageParse *messageParse)
1226 {
1227     if (!RequireAuthLock()) {
1228         return;
1229     }
1230     AuthManager *auth = FindAuthManagerByConnInfo(connInfo, isServer);
1231     if (auth == NULL) {
1232         PrintAuthConnInfo(connInfo);
1233         AUTH_LOGE(AUTH_FSM, "auth manager not found");
1234         ReleaseAuthLock();
1235         return;
1236     }
1237     if (PostDeviceMessage(auth, FLAG_REPLY, connInfo->type, messageParse) == SOFTBUS_OK) {
1238         AUTH_LOGI(AUTH_FSM, "post flush device ok");
1239     }
1240     ReleaseAuthLock();
1241     return;
1242 }
1243 
AuthSetTcpKeepaliveByConnInfo(const AuthConnInfo * connInfo,ModeCycle cycle)1244 static int32_t AuthSetTcpKeepaliveByConnInfo(const AuthConnInfo *connInfo, ModeCycle cycle)
1245 {
1246     if (connInfo == NULL) {
1247         AUTH_LOGE(AUTH_CONN, "invalid param");
1248         return SOFTBUS_INVALID_PARAM;
1249     }
1250 
1251     int32_t ret = SOFTBUS_ERR;
1252     AuthManager *auth[AUTH_COUNT] = { NULL, NULL }; /* 2: WiFi * (Client + Server) */
1253     auth[0] = GetAuthManagerByConnInfo(connInfo, false);
1254     auth[1] = GetAuthManagerByConnInfo(connInfo, true);
1255     for (uint32_t i = 0; i < AUTH_COUNT; i++) {
1256         if (auth[i] == NULL) {
1257             continue;
1258         }
1259         ret = AuthSetTcpKeepaliveOption(GetFd(auth[i]->connId[AUTH_LINK_TYPE_WIFI]), cycle);
1260         if (ret != SOFTBUS_OK) {
1261             AUTH_LOGE(AUTH_CONN, "auth set tcp keepalive option fail");
1262             break;
1263         }
1264     }
1265     DelDupAuthManager(auth[0]);
1266     DelDupAuthManager(auth[1]);
1267     return ret;
1268 }
1269 
HandleDeviceInfoData(uint64_t connId,const AuthConnInfo * connInfo,bool fromServer,const AuthDataHead * head,const uint8_t * data)1270 static void HandleDeviceInfoData(
1271     uint64_t connId, const AuthConnInfo *connInfo, bool fromServer, const AuthDataHead *head, const uint8_t *data)
1272 {
1273     int32_t ret = SOFTBUS_OK;
1274     DeviceMessageParse messageParse = { 0 };
1275     if (IsDeviceMessagePacket(connInfo, head, data, !fromServer, &messageParse)) {
1276         if (head->flag == 0 && messageParse.messageType == CODE_VERIFY_DEVICE) {
1277             AUTH_LOGE(AUTH_FSM, "flush device need relay");
1278             FlushDeviceProcess(connInfo, !fromServer, &messageParse);
1279         } else if (head->flag == 0 && messageParse.messageType == CODE_TCP_KEEPALIVE) {
1280             if (AuthSetTcpKeepaliveByConnInfo(connInfo, messageParse.cycle) != SOFTBUS_OK) {
1281                 AUTH_LOGE(AUTH_FSM, "set tcp keepalive by connInfo fail");
1282             }
1283         } else {
1284             AUTH_LOGE(AUTH_FSM, "device message not need relay");
1285         }
1286         return;
1287     }
1288 
1289     if (AuthSessionProcessDevInfoData(head->seq, data, head->len) != SOFTBUS_OK) {
1290         /* To be compatible with ohos-3.1 and early. */
1291         AUTH_LOGI(AUTH_FSM,
1292             "auth processDeviceInfo. type=0x%{public}x, module=%{public}d, seq=%{public}" PRId64 ", "
1293             "flag=%{public}d, len=%{public}u, " CONN_INFO ", fromServer=%{public}s",
1294             head->dataType, head->module, head->seq, head->flag, head->len, CONN_DATA(connId),
1295             GetAuthSideStr(fromServer));
1296         ret = AuthSessionProcessDevInfoDataByConnId(connId, !fromServer, data, head->len);
1297     }
1298     if (ret != SOFTBUS_OK) {
1299         AUTH_LOGE(AUTH_FSM, "perform auth session recv devInfo fail. seq=%{public}" PRId64 ", ret=%{public}d",
1300             head->seq, ret);
1301         return;
1302     }
1303 }
1304 
HandleCloseAckData(uint64_t connId,const AuthConnInfo * connInfo,bool fromServer,const AuthDataHead * head,const uint8_t * data)1305 static void HandleCloseAckData(
1306     uint64_t connId, const AuthConnInfo *connInfo, bool fromServer, const AuthDataHead *head, const uint8_t *data)
1307 {
1308     int32_t ret;
1309     if (head->seq != 0) {
1310         ret = AuthSessionProcessCloseAck(head->seq, data, head->len);
1311     } else {
1312         /* To be compatible with nearby. */
1313         ret = AuthSessionProcessCloseAckByConnId(connId, !fromServer, data, head->len);
1314     }
1315     if (ret != SOFTBUS_OK) {
1316         AUTH_LOGE(AUTH_CONN, "perform auth session recv closeAck fail. seq=%{public}" PRId64 ", ret=%{public}d",
1317             head->seq, ret);
1318         return;
1319     }
1320 }
1321 
PostDecryptFailAuthData(uint64_t connId,bool fromServer,const AuthDataHead * inputHead,const uint8_t * data)1322 static int32_t PostDecryptFailAuthData(
1323     uint64_t connId, bool fromServer, const AuthDataHead *inputHead, const uint8_t *data)
1324 {
1325     AuthDataHead head = {
1326         .dataType = DATA_TYPE_DECRYPT_FAIL,
1327         .module = 0,
1328         .seq = inputHead->seq,
1329         .flag = 0,
1330         .len = inputHead->len,
1331     };
1332     AUTH_LOGI(AUTH_CONN, "post decrypt fail data");
1333     if (PostAuthData(connId, fromServer, &head, data) != SOFTBUS_OK) {
1334         AUTH_LOGE(AUTH_CONN, "post data fail");
1335         return SOFTBUS_ERR;
1336     }
1337     return SOFTBUS_OK;
1338 }
1339 
HandleConnectionData(uint64_t connId,const AuthConnInfo * connInfo,bool fromServer,const AuthDataHead * head,const uint8_t * data)1340 static void HandleConnectionData(
1341     uint64_t connId, const AuthConnInfo *connInfo, bool fromServer, const AuthDataHead *head, const uint8_t *data)
1342 {
1343     if (!RequireAuthLock()) {
1344         return;
1345     }
1346     char udid[UDID_BUF_LEN] = { 0 };
1347     AuthManager *auth = FindAuthManagerByConnInfo(connInfo, !fromServer);
1348     if (auth == NULL) {
1349         PrintAuthConnInfo(connInfo);
1350         AUTH_LOGE(AUTH_CONN, "AuthManager not found, connType=%{public}d", connInfo->type);
1351         ReleaseAuthLock();
1352         if (connInfo->type == AUTH_LINK_TYPE_P2P || connInfo->type == AUTH_LINK_TYPE_WIFI) {
1353             return;
1354         }
1355         (void)PostDecryptFailAuthData(connId, fromServer, head, data);
1356         return;
1357     }
1358     int64_t authId = auth->authId;
1359     AuthLinkType type = connInfo->type;
1360     uint8_t *decData = NULL;
1361     uint32_t decDataLen = 0;
1362     InDataInfo inDataInfo = { .inData = data, .inLen = head->len };
1363     if (DecryptInner(&auth->sessionKeyList, type, &inDataInfo, &decData, &decDataLen) != SOFTBUS_OK) {
1364         AUTH_LOGE(AUTH_CONN, "decrypt trans data fail");
1365         ReleaseAuthLock();
1366         return;
1367     }
1368     int32_t index = (int32_t)SoftBusLtoHl(*(uint32_t *)data);
1369     (void)SetSessionKeyAvailable(&auth->sessionKeyList, index);
1370     auth->hasAuthPassed[connInfo->type] = true;
1371     auth->lastActiveTime = GetCurrentTimeMs();
1372     auth->connId[type] = connId;
1373     AuthHandle authHandle = { .authId = authId, .type = GetConnType(connId) };
1374     int32_t ret = SOFTBUS_OK;
1375     if (strcpy_s(udid, UDID_BUF_LEN, auth->udid) != EOK) {
1376         AUTH_LOGE(AUTH_CONN, "copy udid fail");
1377         ret = SOFTBUS_MEM_ERR;
1378     }
1379     ReleaseAuthLock();
1380     if (ret == SOFTBUS_OK && !LnnGetOnlineStateById(udid, CATEGORY_UDID)) {
1381         AUTH_LOGE(AUTH_CONN, "device is offline, need wait");
1382         (void)SoftBusSleepMs(RECV_DATA_WAIT_TIME);
1383     }
1384     if (g_transCallback.onDataReceived != NULL) {
1385         g_transCallback.onDataReceived(authHandle, head, decData, decDataLen);
1386     }
1387     SoftBusFree(decData);
1388 }
1389 
HandleDecryptFailData(uint64_t connId,const AuthConnInfo * connInfo,bool fromServer,const AuthDataHead * head,const uint8_t * data)1390 static void HandleDecryptFailData(
1391     uint64_t connId, const AuthConnInfo *connInfo, bool fromServer, const AuthDataHead *head, const uint8_t *data)
1392 {
1393     if (!RequireAuthLock()) {
1394         return;
1395     }
1396     int32_t num = 0;
1397     const AuthManager *auth[2] = { NULL, NULL }; /* 2: client + server */
1398     auth[num++] = FindAuthManagerByConnInfo(connInfo, false);
1399     auth[num++] = FindAuthManagerByConnInfo(connInfo, true);
1400     if (auth[0] == NULL && auth[1] == NULL) {
1401         PrintAuthConnInfo(connInfo);
1402         AUTH_LOGE(AUTH_CONN, "AuthManager not found, conntype=%{public}d", connInfo->type);
1403         ReleaseAuthLock();
1404         return;
1405     }
1406     uint8_t *decData = NULL;
1407     uint32_t decDataLen = 0;
1408     int32_t index = (int32_t)SoftBusLtoHl(*(uint32_t *)data);
1409     InDataInfo inDataInfo = { .inData = data, .inLen = head->len };
1410     AuthHandle authHandle = { .authId = AUTH_INVALID_ID, .type = connInfo->type };
1411     if (auth[0] != NULL && DecryptInner(&auth[0]->sessionKeyList, connInfo->type, &inDataInfo,
1412         &decData, &decDataLen) == SOFTBUS_OK) {
1413         ReleaseAuthLock();
1414         SoftBusFree(decData);
1415         RemoveAuthSessionKeyByIndex(auth[0]->authId, index, connInfo->type);
1416         authHandle.authId = auth[0]->authId;
1417     } else if (auth[1] != NULL && DecryptInner(&auth[1]->sessionKeyList, connInfo->type, &inDataInfo,
1418         &decData, &decDataLen) == SOFTBUS_OK) {
1419         ReleaseAuthLock();
1420         SoftBusFree(decData);
1421         RemoveAuthSessionKeyByIndex(auth[1]->authId, index, connInfo->type);
1422         authHandle.authId = auth[1]->authId;
1423     } else {
1424         ReleaseAuthLock();
1425         AUTH_LOGE(AUTH_CONN, "decrypt trans data fail.");
1426     }
1427     if (g_transCallback.onException != NULL && authHandle.authId != AUTH_INVALID_ID) {
1428         AUTH_LOGE(AUTH_CONN, "notify exception");
1429         g_transCallback.onException(authHandle, SOFTBUS_AUTH_DECRYPT_ERR);
1430     }
1431 }
1432 
HandleCancelAuthData(uint64_t connId,const AuthConnInfo * connInfo,bool fromServer,const AuthDataHead * head,const uint8_t * data)1433 static void HandleCancelAuthData(
1434     uint64_t connId, const AuthConnInfo *connInfo, bool fromServer, const AuthDataHead *head, const uint8_t *data)
1435 {
1436     int32_t ret = AuthSessionProcessCancelAuthByConnId(connId, !fromServer, data, head->len);
1437     if (ret != SOFTBUS_OK) {
1438         AUTH_LOGE(AUTH_CONN, "perform auth session cancel auth fail. seq=%{public}" PRId64 ", ret=%{public}d",
1439             head->seq, ret);
1440     }
1441 }
1442 
CorrectFromServer(uint64_t connId,const AuthConnInfo * connInfo,bool * fromServer)1443 static void CorrectFromServer(uint64_t connId, const AuthConnInfo *connInfo, bool *fromServer)
1444 {
1445     if (connInfo->type != AUTH_LINK_TYPE_WIFI) {
1446         return;
1447     }
1448     uint32_t num = 0;
1449     int64_t authIds[2];
1450     bool tmp = *fromServer;
1451     authIds[num++] = GetAuthIdByConnId(connId, false);
1452     authIds[num++] = GetAuthIdByConnId(connId, true);
1453     if (authIds[0] != AUTH_INVALID_ID) {
1454         *fromServer = true;
1455     }
1456     if (authIds[1] != AUTH_INVALID_ID) {
1457         *fromServer = false;
1458     }
1459     if (tmp != *fromServer) {
1460         AUTH_LOGE(AUTH_CONN, "CorrectFromServer succ.");
1461     }
1462 }
1463 
OnDataReceived(uint64_t connId,const AuthConnInfo * connInfo,bool fromServer,const AuthDataHead * head,const uint8_t * data)1464 static void OnDataReceived(
1465     uint64_t connId, const AuthConnInfo *connInfo, bool fromServer, const AuthDataHead *head, const uint8_t *data)
1466 {
1467     if (connInfo == NULL || head == NULL || data == NULL) {
1468         AUTH_LOGE(AUTH_CONN, "invalid param");
1469         return;
1470     }
1471     SoftbusHitraceStart(SOFTBUS_HITRACE_ID_VALID, (uint64_t)head->seq);
1472     CorrectFromServer(connId, connInfo, &fromServer);
1473     AUTH_LOGI(AUTH_CONN,
1474         "auth recv data. type=0x%{public}x, module=%{public}d, seq=%{public}" PRId64 ", "
1475         "flag=%{public}d, len=%{public}u, " CONN_INFO ", fromServer=%{public}s",
1476         head->dataType, head->module, head->seq, head->flag, head->len, CONN_DATA(connId), GetAuthSideStr(fromServer));
1477     switch (head->dataType) {
1478         case DATA_TYPE_DEVICE_ID:
1479             HandleDeviceIdData(connId, connInfo, fromServer, head, data);
1480             break;
1481         case DATA_TYPE_AUTH:
1482             HandleAuthData(connInfo, head, data);
1483             break;
1484         case DATA_TYPE_DEVICE_INFO:
1485             HandleDeviceInfoData(connId, connInfo, fromServer, head, data);
1486             break;
1487         case DATA_TYPE_CLOSE_ACK:
1488             HandleCloseAckData(connId, connInfo, fromServer, head, data);
1489             break;
1490         case DATA_TYPE_CONNECTION:
1491             HandleConnectionData(connId, connInfo, fromServer, head, data);
1492             break;
1493         case DATA_TYPE_DECRYPT_FAIL:
1494             HandleDecryptFailData(connId, connInfo, fromServer, head, data);
1495             break;
1496         case DATA_TYPE_CANCEL_AUTH:
1497             HandleCancelAuthData(connId, connInfo, fromServer, head, data);
1498             break;
1499         default:
1500             break;
1501     }
1502     SoftbusHitraceStop();
1503 }
1504 
HandleDisconnectedEvent(const void * para)1505 static void HandleDisconnectedEvent(const void *para)
1506 {
1507     AUTH_CHECK_AND_RETURN_LOGE(para != NULL, AUTH_FSM, "para is null");
1508     uint64_t connId = *((uint64_t *)para);
1509     uint32_t num = 0;
1510     uint64_t dupConnId = connId;
1511     int64_t authIds[2]; /* 2: client and server may use same connection. */
1512     authIds[num++] = GetAuthIdByConnId(connId, false);
1513     authIds[num++] = GetAuthIdByConnId(connId, true);
1514     for (uint32_t i = 0; i < num; i++) {
1515         if (authIds[i] == AUTH_INVALID_ID) {
1516             continue;
1517         }
1518         AuthHandle authHandle = { .authId = authIds[i], .type = GetConnType(connId) };
1519         if (g_transCallback.onDisconnected != NULL) {
1520             g_transCallback.onDisconnected(authHandle);
1521         }
1522         if (GetConnType(connId) == AUTH_LINK_TYPE_WIFI || GetConnType(connId) == AUTH_LINK_TYPE_P2P ||
1523             GetConnType(connId) == AUTH_LINK_TYPE_ENHANCED_P2P) {
1524             AuthNotifyDeviceDisconnect(authHandle);
1525             DisconnectAuthDevice(&dupConnId);
1526             AuthManager inAuth = {0};
1527             inAuth.connId[GetConnType(connId)] = dupConnId;
1528             (void)UpdateAuthManagerByAuthId(authIds[i], SetAuthConnId, &inAuth, (AuthLinkType)GetConnType(connId));
1529             RemoveAuthManagerByAuthId(authHandle);
1530         }
1531     }
1532     /* Try to terminate authing session. */
1533     (void)AuthSessionHandleDeviceDisconnected(connId);
1534 }
1535 
OnDisconnected(uint64_t connId,const AuthConnInfo * connInfo)1536 static void OnDisconnected(uint64_t connId, const AuthConnInfo *connInfo)
1537 {
1538     (void)connInfo;
1539     (void)PostAuthEvent(EVENT_AUTH_DISCONNECT, HandleDisconnectedEvent, &connId, sizeof(connId), 0);
1540 }
1541 
AuthGenRequestId(void)1542 uint32_t AuthGenRequestId(void)
1543 {
1544     return ConnGetNewRequestId(MODULE_DEVICE_AUTH);
1545 }
1546 
AuthHandleLeaveLNN(AuthHandle authHandle)1547 void AuthHandleLeaveLNN(AuthHandle authHandle)
1548 {
1549     if (authHandle.type < AUTH_LINK_TYPE_WIFI || authHandle.type >= AUTH_LINK_TYPE_MAX) {
1550         AUTH_LOGE(AUTH_FSM, "authHandle type error");
1551         return;
1552     }
1553     if (!RequireAuthLock()) {
1554         return;
1555     }
1556     AuthManager *auth = FindAuthManagerByAuthId(authHandle.authId);
1557     if (auth == NULL) {
1558         AUTH_LOGE(AUTH_FSM, "auth manager not found, authId=%{public}" PRId64, authHandle.authId);
1559         ReleaseAuthLock();
1560         return;
1561     }
1562     if (!auth->hasAuthPassed[authHandle.type]) {
1563         AUTH_LOGI(AUTH_FSM, "auth pass = false, don't need to leave");
1564         ReleaseAuthLock();
1565         return;
1566     }
1567     AuthFsm *authFsm = GetAuthFsmByConnId(auth->connId[authHandle.type], auth->isServer, false);
1568     if (authFsm == NULL) {
1569         authFsm = GetAuthFsmByConnId(auth->connId[authHandle.type], !auth->isServer, false);
1570     }
1571     if (authFsm != NULL && authFsm->curState >= STATE_SYNC_DEVICE_INFO) {
1572         AUTH_LOGI(AUTH_FSM, "another fsm use this auth manager");
1573         ReleaseAuthLock();
1574         return;
1575     }
1576     if (auth->connInfo[authHandle.type].type == AUTH_LINK_TYPE_WIFI) {
1577         AUTH_LOGI(AUTH_FSM, "AuthHandleLeaveLNN disconnect");
1578         DisconnectAuthDevice(&auth->connId[authHandle.type]);
1579     }
1580     DelAuthManager(auth, authHandle.type);
1581     ReleaseAuthLock();
1582 }
1583 
PostDeviceMessageByUuid(const char * uuid,int32_t messageType,ModeCycle cycle)1584 static int32_t PostDeviceMessageByUuid(const char *uuid, int32_t messageType, ModeCycle cycle)
1585 {
1586     if (!RequireAuthLock()) {
1587         return SOFTBUS_LOCK_ERR;
1588     }
1589     uint32_t num = 0;
1590     int32_t ret = SOFTBUS_ERR;
1591     DeviceMessageParse messageParse = { messageType, cycle };
1592     AuthManager *auth[2] = { NULL, NULL }; /* 2: WiFi * (Client + Server) */
1593     auth[num++] = FindAuthManagerByUuid(uuid, AUTH_LINK_TYPE_WIFI, false);
1594     auth[num++] = FindAuthManagerByUuid(uuid, AUTH_LINK_TYPE_WIFI, true);
1595     for (uint32_t i = 0; i < num; i++) {
1596         if (auth[i] == NULL) {
1597             continue;
1598         }
1599         ret = PostDeviceMessage(auth[i], FLAG_ACTIVE, AUTH_LINK_TYPE_WIFI, &messageParse);
1600         if (ret != SOFTBUS_OK) {
1601             AUTH_LOGE(AUTH_CONN, "%{public}d:messageType=%{public}d, post device message fail", i, messageType);
1602             ReleaseAuthLock();
1603             return ret;
1604         }
1605     }
1606     ReleaseAuthLock();
1607     return ret;
1608 }
1609 
SetLocalTcpKeepalive(const char * uuid,ModeCycle cycle)1610 static int32_t SetLocalTcpKeepalive(const char *uuid, ModeCycle cycle)
1611 {
1612     int32_t ret = SOFTBUS_ERR;
1613     AuthConnInfo connInfo;
1614     (void)memset_s(&connInfo, sizeof(connInfo), 0, sizeof(connInfo));
1615     ret = GetAuthConnInfoByUuid(uuid, AUTH_LINK_TYPE_WIFI, &connInfo);
1616     if (ret != SOFTBUS_OK) {
1617         AUTH_LOGE(AUTH_CONN, "get AuthConnInfo by uuid fail, ret=%{public}d", ret);
1618         return ret;
1619     }
1620     ret = AuthSetTcpKeepaliveByConnInfo(&connInfo, cycle);
1621     if (ret != SOFTBUS_OK) {
1622         AUTH_LOGE(AUTH_CONN, "set tcp keepalive fail, ret=%{public}d", ret);
1623     }
1624     return ret;
1625 }
1626 
AuthFlushDevice(const char * uuid)1627 int32_t AuthFlushDevice(const char *uuid)
1628 {
1629     if (uuid == NULL || uuid[0] == '\0') {
1630         AUTH_LOGE(AUTH_CONN, "uuid is empty");
1631         return SOFTBUS_INVALID_PARAM;
1632     }
1633     if (PostDeviceMessageByUuid(uuid, CODE_VERIFY_DEVICE, DEFAULT_FREQ_CYCLE) != SOFTBUS_OK) {
1634         AUTH_LOGE(AUTH_CONN, "post flush device message by uuid fail");
1635         return SOFTBUS_ERR;
1636     }
1637     return SOFTBUS_OK;
1638 }
1639 
AuthSendKeepaliveOption(const char * uuid,ModeCycle cycle)1640 int32_t AuthSendKeepaliveOption(const char *uuid, ModeCycle cycle)
1641 {
1642     if (uuid == NULL || uuid[0] == '\0' || cycle < HIGH_FREQ_CYCLE || cycle > DEFAULT_FREQ_CYCLE) {
1643         AUTH_LOGE(AUTH_CONN, "uuid is empty or invalid cycle");
1644         return SOFTBUS_INVALID_PARAM;
1645     }
1646     if (SetLocalTcpKeepalive(uuid, cycle) != SOFTBUS_OK) {
1647         AUTH_LOGE(AUTH_CONN, "set local tcp keepalive fail");
1648         return SOFTBUS_ERR;
1649     }
1650     if (PostDeviceMessageByUuid(uuid, CODE_TCP_KEEPALIVE, cycle) != SOFTBUS_OK) {
1651         AUTH_LOGE(AUTH_CONN, "post device keepalive message by uuid fail");
1652         return SOFTBUS_ERR;
1653     }
1654     return SOFTBUS_OK;
1655 }
1656 
TryGetBrConnInfo(const char * uuid,AuthConnInfo * connInfo)1657 int32_t TryGetBrConnInfo(const char *uuid, AuthConnInfo *connInfo)
1658 {
1659     AUTH_CHECK_AND_RETURN_RET_LOGE(uuid != NULL, AUTH_INVALID_ID, AUTH_CONN, "uuid is null");
1660     AUTH_CHECK_AND_RETURN_RET_LOGE(connInfo != NULL, AUTH_INVALID_ID, AUTH_CONN, "connInfo is null");
1661     char networkId[NETWORK_ID_BUF_LEN] = { 0 };
1662     if (LnnGetNetworkIdByUuid(uuid, networkId, sizeof(networkId)) != SOFTBUS_OK) {
1663         AUTH_LOGE(AUTH_CONN, "get networkId by uuid fail");
1664         return SOFTBUS_AUTH_GET_BR_CONN_INFO_FAIL;
1665     }
1666 
1667     uint32_t local, remote;
1668     if (LnnGetLocalNumU32Info(NUM_KEY_NET_CAP, &local) != SOFTBUS_OK ||
1669         LnnGetRemoteNumU32Info(networkId, NUM_KEY_NET_CAP, &remote) != SOFTBUS_OK) {
1670         AUTH_LOGE(AUTH_CONN, "get NET_CAP fail");
1671         return SOFTBUS_AUTH_GET_BR_CONN_INFO_FAIL;
1672     }
1673     if (((local & (1 << BIT_BR)) == 0) || ((remote & (1 << BIT_BR)) == 0)) {
1674         AUTH_LOGI(AUTH_CONN, "can't support BR");
1675         return SOFTBUS_AUTH_GET_BR_CONN_INFO_FAIL;
1676     }
1677     if (LnnGetRemoteStrInfo(networkId, STRING_KEY_BT_MAC, connInfo->info.brInfo.brMac, BT_MAC_LEN) != SOFTBUS_OK ||
1678         connInfo->info.brInfo.brMac[0] == '\0') {
1679         AUTH_LOGE(AUTH_CONN, "get bt mac fail");
1680         return SOFTBUS_AUTH_GET_BR_CONN_INFO_FAIL;
1681     }
1682     connInfo->type = AUTH_LINK_TYPE_BR;
1683     return SOFTBUS_OK;
1684 }
1685 
AuthDeviceGetPreferConnInfo(const char * uuid,AuthConnInfo * connInfo)1686 int32_t AuthDeviceGetPreferConnInfo(const char *uuid, AuthConnInfo *connInfo)
1687 {
1688     if (uuid == NULL || uuid[0] == '\0' || connInfo == NULL) {
1689         AUTH_LOGE(AUTH_CONN, "invalid uuid or connInfo");
1690         return SOFTBUS_INVALID_PARAM;
1691     }
1692     AuthLinkType linkList[] = { AUTH_LINK_TYPE_WIFI, AUTH_LINK_TYPE_BR, AUTH_LINK_TYPE_BLE };
1693     for (uint32_t i = 0; i < sizeof(linkList) / sizeof(linkList[0]); i++) {
1694         if (GetAuthConnInfoByUuid(uuid, linkList[i], connInfo) != SOFTBUS_OK) {
1695             continue;
1696         }
1697         if (linkList[i] == AUTH_LINK_TYPE_BLE) {
1698             if (!CheckActiveAuthConnection(connInfo)) {
1699                 AUTH_LOGI(AUTH_CONN, "auth ble connection not active");
1700                 continue;
1701             }
1702         }
1703         AUTH_LOGI(AUTH_CONN, "select auth type. i=%{public}d, linkList[i]=%{public}d", i, linkList[i]);
1704         return SOFTBUS_OK;
1705     }
1706     AUTH_LOGI(AUTH_CONN, "no active auth, try br connection");
1707     return TryGetBrConnInfo(uuid, connInfo);
1708 }
1709 
AuthDeviceGetConnInfoByType(const char * uuid,AuthLinkType type,AuthConnInfo * connInfo)1710 int32_t AuthDeviceGetConnInfoByType(const char *uuid, AuthLinkType type, AuthConnInfo *connInfo)
1711 {
1712     if (uuid == NULL || uuid[0] == '\0' || connInfo == NULL) {
1713         AUTH_LOGE(AUTH_CONN, "invalid uuid or connInfo");
1714         return SOFTBUS_INVALID_PARAM;
1715     }
1716     if (GetAuthConnInfoByUuid(uuid, type, connInfo) != SOFTBUS_OK) {
1717         if (type == AUTH_LINK_TYPE_BR) {
1718             return TryGetBrConnInfo(uuid, connInfo);
1719         }
1720         return SOFTBUS_AUTH_NOT_FOUND;
1721     }
1722     if (type == AUTH_LINK_TYPE_BLE) {
1723         if (!CheckActiveAuthConnection(connInfo)) {
1724             AUTH_LOGI(AUTH_CONN, "auth ble connection not active");
1725             return SOFTBUS_ERR;
1726         }
1727     }
1728     return SOFTBUS_OK;
1729 }
1730 
AuthDeviceGetP2pConnInfo(const char * uuid,AuthConnInfo * connInfo)1731 int32_t AuthDeviceGetP2pConnInfo(const char *uuid, AuthConnInfo *connInfo)
1732 {
1733     if (uuid == NULL || uuid[0] == '\0' || connInfo == NULL) {
1734         AUTH_LOGE(AUTH_CONN, "invalid uuid or connInfo");
1735         return SOFTBUS_INVALID_PARAM;
1736     }
1737     int32_t ret = GetAvailableAuthConnInfoByUuid(uuid, AUTH_LINK_TYPE_P2P, connInfo);
1738     if (ret == SOFTBUS_OK) {
1739         AUTH_LOGI(AUTH_CONN, "select auth type=%{public}d", AUTH_LINK_TYPE_P2P);
1740     }
1741     return ret;
1742 }
1743 
AuthDeviceGetHmlConnInfo(const char * uuid,AuthConnInfo * connInfo)1744 int32_t AuthDeviceGetHmlConnInfo(const char *uuid, AuthConnInfo *connInfo)
1745 {
1746     if (uuid == NULL || uuid[0] == '\0' || connInfo == NULL) {
1747         AUTH_LOGE(AUTH_CONN, "invalid uuid or connInfo");
1748         return SOFTBUS_INVALID_PARAM;
1749     }
1750     int32_t ret = GetAuthConnInfoByUuid(uuid, AUTH_LINK_TYPE_ENHANCED_P2P, connInfo);
1751     if (ret == SOFTBUS_OK) {
1752         AUTH_LOGI(AUTH_CONN, "select auth type=%{public}d", AUTH_LINK_TYPE_ENHANCED_P2P);
1753     }
1754     return ret;
1755 }
1756 
AuthDeviceCheckConnInfo(const char * uuid,AuthLinkType type,bool checkConnection)1757 bool AuthDeviceCheckConnInfo(const char *uuid, AuthLinkType type, bool checkConnection)
1758 {
1759     AUTH_CHECK_AND_RETURN_RET_LOGE(uuid, false, AUTH_CONN, "invalid null uuid");
1760     AUTH_CHECK_AND_RETURN_RET_LOGE(uuid[0] != '\0', false, AUTH_CONN, "invalid empty uuid");
1761 
1762     AuthConnInfo connInfo;
1763     (void)memset_s(&connInfo, sizeof(connInfo), 0, sizeof(connInfo));
1764     if (GetAuthConnInfoByUuid(uuid, type, &connInfo) != SOFTBUS_OK) {
1765         return false;
1766     }
1767     return checkConnection ? CheckActiveAuthConnection(&connInfo) : true;
1768 }
1769 
AuthGetLatestAuthSeqListByType(const char * udid,int64_t * seqList,uint64_t * authVerifyTime,DiscoveryType type)1770 int32_t AuthGetLatestAuthSeqListByType(const char *udid, int64_t *seqList, uint64_t *authVerifyTime, DiscoveryType type)
1771 {
1772     if (udid == NULL || udid[0] == '\0' || seqList == NULL || authVerifyTime == NULL) {
1773         AUTH_LOGE(AUTH_CONN, "invalid param");
1774         return SOFTBUS_INVALID_PARAM;
1775     }
1776     if (!RequireAuthLock()) {
1777         AUTH_LOGE(AUTH_CONN, "lock fail");
1778         return SOFTBUS_LOCK_ERR;
1779     }
1780     const AuthManager *authClient = NULL;
1781     const AuthManager *authServer = NULL;
1782     authClient = FindAuthManagerByUdid(udid, ConvertToAuthLinkType(type), false);
1783     authServer = FindAuthManagerByUdid(udid, ConvertToAuthLinkType(type), true);
1784     if (authClient == NULL && authServer == NULL) {
1785         AUTH_LOGE(AUTH_CONN, "authManager not found");
1786         ReleaseAuthLock();
1787         return SOFTBUS_ERR;
1788     }
1789     AuthLinkType seqType = ConvertToAuthLinkType(type);
1790     if (seqType == AUTH_LINK_TYPE_MAX) {
1791         AUTH_LOGE(AUTH_CONN, "seqType is invalid");
1792         ReleaseAuthLock();
1793         return SOFTBUS_ERR;
1794     }
1795     if (authClient != NULL) {
1796         seqList[0] = authClient->lastAuthSeq[seqType];
1797         authVerifyTime[0] = authClient->lastVerifyTime;
1798     }
1799     if (authServer != NULL) {
1800         seqList[1] = authServer->lastAuthSeq[seqType];
1801         authVerifyTime[1] = authServer->lastVerifyTime;
1802     }
1803     ReleaseAuthLock();
1804     return SOFTBUS_OK;
1805 }
1806 
AuthGetLatestAuthSeqList(const char * udid,int64_t * seqList,uint32_t num)1807 int32_t AuthGetLatestAuthSeqList(const char *udid, int64_t *seqList, uint32_t num)
1808 {
1809     if (udid == NULL || udid[0] == '\0' || seqList == NULL || num != DISCOVERY_TYPE_COUNT) {
1810         AUTH_LOGE(AUTH_CONN, "invalid param");
1811         return SOFTBUS_INVALID_PARAM;
1812     }
1813     if (!RequireAuthLock()) {
1814         return SOFTBUS_LOCK_ERR;
1815     }
1816     bool notFound = true;
1817     AuthManager *authClient = NULL;
1818     AuthManager *authServer = NULL;
1819     AuthLinkType linkList[] = { AUTH_LINK_TYPE_WIFI, AUTH_LINK_TYPE_BLE, AUTH_LINK_TYPE_BR };
1820     for (size_t i = 0; i < sizeof(linkList) / sizeof(AuthLinkType); i++) {
1821         authClient = FindAuthManagerByUdid(udid, linkList[i], false);
1822         authServer = FindAuthManagerByUdid(udid, linkList[i], true);
1823         if (authClient == NULL && authServer == NULL) {
1824             seqList[ConvertToDiscoveryType(linkList[i])] = 0;
1825             continue;
1826         }
1827         notFound = false;
1828         if (authClient != NULL && authServer == NULL) {
1829             seqList[ConvertToDiscoveryType(linkList[i])] = authClient->lastAuthSeq[linkList[i]];
1830         } else if (authClient == NULL && authServer != NULL) {
1831             seqList[ConvertToDiscoveryType(linkList[i])] = authServer->lastAuthSeq[linkList[i]];
1832         } else if (authClient->lastVerifyTime >= authServer->lastVerifyTime) {
1833             seqList[ConvertToDiscoveryType(linkList[i])] = authClient->lastAuthSeq[linkList[i]];
1834         } else {
1835             seqList[ConvertToDiscoveryType(linkList[i])] = authServer->lastAuthSeq[linkList[i]];
1836         }
1837     }
1838     if (notFound) {
1839         ReleaseAuthLock();
1840         char *anonyUdid = NULL;
1841         Anonymize(udid, &anonyUdid);
1842         AUTH_LOGE(AUTH_CONN, "not found active authManager, udid=%{public}s", anonyUdid);
1843         AnonymizeFree(anonyUdid);
1844         return SOFTBUS_AUTH_NOT_FOUND;
1845     }
1846     ReleaseAuthLock();
1847     return SOFTBUS_OK;
1848 }
1849 
FillAuthHandleList(ListNode * list,AuthHandle * handle,int32_t * num,int32_t count)1850 static void FillAuthHandleList(ListNode *list, AuthHandle *handle, int32_t *num, int32_t count)
1851 {
1852     AuthManager *item = NULL;
1853     LIST_FOR_EACH_ENTRY(item, list, AuthManager, node) {
1854         if (item->connInfo[AUTH_LINK_TYPE_ENHANCED_P2P].type == AUTH_LINK_TYPE_ENHANCED_P2P &&
1855             item->hasAuthPassed[AUTH_LINK_TYPE_ENHANCED_P2P]) {
1856             handle[*num].authId = item->authId;
1857             handle[*num].type = AUTH_LINK_TYPE_ENHANCED_P2P;
1858             (*num)++;
1859         } else if (item->connInfo[AUTH_LINK_TYPE_P2P].type == AUTH_LINK_TYPE_P2P &&
1860             item->hasAuthPassed[AUTH_LINK_TYPE_P2P]) {
1861             handle[*num].authId = item->authId;
1862             handle[*num].type = AUTH_LINK_TYPE_P2P;
1863             (*num)++;
1864         }
1865         if (*num == count) {
1866             break;
1867         }
1868     }
1869 }
1870 
GetAllHmlOrP2pAuthHandleNum(void)1871 static uint32_t GetAllHmlOrP2pAuthHandleNum(void)
1872 {
1873     uint32_t count = 0;
1874     AuthManager *item = NULL;
1875     LIST_FOR_EACH_ENTRY(item, &g_authServerList, AuthManager, node) {
1876         if ((item->connInfo[AUTH_LINK_TYPE_ENHANCED_P2P].type == AUTH_LINK_TYPE_ENHANCED_P2P &&
1877             item->hasAuthPassed[AUTH_LINK_TYPE_ENHANCED_P2P]) ||
1878             (item->connInfo[AUTH_LINK_TYPE_P2P].type == AUTH_LINK_TYPE_P2P &&
1879             item->hasAuthPassed[AUTH_LINK_TYPE_P2P])) {
1880             count++;
1881         }
1882     }
1883     LIST_FOR_EACH_ENTRY(item, &g_authClientList, AuthManager, node) {
1884         if ((item->connInfo[AUTH_LINK_TYPE_ENHANCED_P2P].type == AUTH_LINK_TYPE_ENHANCED_P2P &&
1885             item->hasAuthPassed[AUTH_LINK_TYPE_ENHANCED_P2P]) ||
1886             (item->connInfo[AUTH_LINK_TYPE_P2P].type == AUTH_LINK_TYPE_P2P &&
1887             item->hasAuthPassed[AUTH_LINK_TYPE_P2P])) {
1888             count++;
1889         }
1890     }
1891     return count;
1892 }
1893 
GetHmlOrP2pAuthHandle(AuthHandle ** authHandle,int32_t * num)1894 int32_t GetHmlOrP2pAuthHandle(AuthHandle **authHandle, int32_t *num)
1895 {
1896     if (authHandle == NULL || num == NULL) {
1897         AUTH_LOGE(AUTH_CONN, "authHandle is empty");
1898         return SOFTBUS_INVALID_PARAM;
1899     }
1900     if (!RequireAuthLock()) {
1901         AUTH_LOGE(AUTH_CONN, "get auth lock fail");
1902         return SOFTBUS_LOCK_ERR;
1903     }
1904     uint32_t count = GetAllHmlOrP2pAuthHandleNum();
1905     if (count == 0) {
1906         AUTH_LOGE(AUTH_CONN, "not found hml or p2p authHandle");
1907         ReleaseAuthLock();
1908         return SOFTBUS_AUTH_NOT_FOUND;
1909     }
1910     AuthHandle *handle = (AuthHandle *)SoftBusCalloc(sizeof(AuthHandle) * count);
1911     if (handle == NULL) {
1912         AUTH_LOGE(AUTH_CONN, "authHandle calloc fail");
1913         ReleaseAuthLock();
1914         return SOFTBUS_MALLOC_ERR;
1915     }
1916     *num = 0;
1917     FillAuthHandleList(&g_authServerList, handle, num, count);
1918     FillAuthHandleList(&g_authClientList, handle, num, count);
1919 
1920     *authHandle = handle;
1921     ReleaseAuthLock();
1922     return SOFTBUS_OK;
1923 }
1924 
AuthDeviceGetLatestIdByUuid(const char * uuid,AuthLinkType type,AuthHandle * authHandle)1925 void AuthDeviceGetLatestIdByUuid(const char *uuid, AuthLinkType type, AuthHandle *authHandle)
1926 {
1927     if (uuid == NULL || uuid[0] == '\0' || authHandle == NULL) {
1928         AUTH_LOGE(AUTH_CONN, "uuid is empty");
1929         return;
1930     }
1931     if (!RequireAuthLock()) {
1932         return;
1933     }
1934     authHandle->type = type;
1935     uint32_t num = 0;
1936     AuthManager *auth[2] = { NULL, NULL }; /* 2: max size for (CLIENT+ SERVER) */
1937     auth[num++] = FindAuthManagerByUuid(uuid, type, false);
1938     auth[num++] = FindAuthManagerByUuid(uuid, type, true);
1939     if (type == AUTH_LINK_TYPE_BR && auth[0] == NULL && auth[1] == NULL) {
1940         num = 0;
1941         auth[num++] = FindAuthManagerByUuid(uuid, AUTH_LINK_TYPE_BLE, false);
1942         auth[num++] = FindAuthManagerByUuid(uuid, AUTH_LINK_TYPE_BLE, true);
1943         authHandle->type = AUTH_LINK_TYPE_BLE;
1944     }
1945     authHandle->authId = AUTH_INVALID_ID;
1946     uint64_t latestVerifyTime = 0;
1947     for (uint32_t i = 0; i < num; i++) {
1948         uint64_t tmpTime = 0;
1949         if (auth[i] != NULL) {
1950             tmpTime = GetLatestAvailableSessionKeyTime(&auth[i]->sessionKeyList, (AuthLinkType)authHandle->type);
1951         }
1952         if (tmpTime > latestVerifyTime) {
1953             authHandle->authId = auth[i]->authId;
1954             latestVerifyTime = tmpTime;
1955         }
1956     }
1957     ReleaseAuthLock();
1958     char *anonyUuid = NULL;
1959     Anonymize(uuid, &anonyUuid);
1960     AUTH_LOGI(AUTH_CONN,
1961         "latest auth manager found, latestAuthId=%{public}" PRId64 ", lastVerifyTime=%{public}" PRIu64
1962         ", uuid=%{public}s, type=%{public}d",
1963         authHandle->authId, latestVerifyTime, anonyUuid, authHandle->type);
1964     AnonymizeFree(anonyUuid);
1965 }
1966 
AuthDeviceGetIdByConnInfo(const AuthConnInfo * connInfo,bool isServer)1967 int64_t AuthDeviceGetIdByConnInfo(const AuthConnInfo *connInfo, bool isServer)
1968 {
1969     if (connInfo == NULL) {
1970         AUTH_LOGE(AUTH_CONN, "connInfo is null");
1971         return AUTH_INVALID_ID;
1972     }
1973     AUTH_CHECK_AND_RETURN_RET_LOGE(CheckAuthConnInfoType(connInfo), AUTH_INVALID_ID,
1974         AUTH_FSM, "connInfo type error");
1975     return GetAuthIdByConnInfo(connInfo, isServer);
1976 }
1977 
AuthDeviceGetIdByUuid(const char * uuid,AuthLinkType type,bool isServer)1978 int64_t AuthDeviceGetIdByUuid(const char *uuid, AuthLinkType type, bool isServer)
1979 {
1980     if (uuid == NULL || uuid[0] == '\0') {
1981         AUTH_LOGE(AUTH_FSM, "uuid is empty");
1982         return AUTH_INVALID_ID;
1983     }
1984     if (!RequireAuthLock()) {
1985         return AUTH_INVALID_ID;
1986     }
1987     AuthManager *auth = FindAuthManagerByUuid(uuid, type, isServer);
1988     if (auth == NULL) {
1989         ReleaseAuthLock();
1990         char *anoyUuid = NULL;
1991         Anonymize(uuid, &anoyUuid);
1992         AUTH_LOGE(AUTH_CONN, "not found auth manager, uuid=%{public}s, connType=%{public}d, side=%{public}s",
1993             anoyUuid, type, GetAuthSideStr(isServer));
1994         AnonymizeFree(anoyUuid);
1995         return AUTH_INVALID_ID;
1996     }
1997     int64_t authId = auth->authId;
1998     ReleaseAuthLock();
1999     return authId;
2000 }
2001 
AuthDeviceGetAuthHandleByIndex(const char * udid,bool isServer,int32_t index,AuthHandle * authHandle)2002 int32_t AuthDeviceGetAuthHandleByIndex(const char *udid, bool isServer, int32_t index, AuthHandle *authHandle)
2003 {
2004     if (udid == NULL || authHandle == NULL) {
2005         AUTH_LOGE(AUTH_FSM, "param error");
2006         return SOFTBUS_INVALID_PARAM;
2007     }
2008     if (!RequireAuthLock()) {
2009         AUTH_LOGE(AUTH_CONN, "RequireAuthLock fail");
2010         return SOFTBUS_LOCK_ERR;
2011     }
2012     AuthManager *auth = FindNormalizedKeyAuthManagerByUdid(udid, isServer);
2013     if (auth == NULL) {
2014         AUTH_LOGE(AUTH_CONN, "not found auth manager, side=%{public}s", GetAuthSideStr(isServer));
2015         ReleaseAuthLock();
2016         return SOFTBUS_AUTH_NOT_FOUND;
2017     }
2018     AuthLinkType type = GetSessionKeyTypeByIndex(&auth->sessionKeyList, index);
2019     ReleaseAuthLock();
2020     if (type == AUTH_LINK_TYPE_MAX || type < AUTH_LINK_TYPE_WIFI) {
2021         AUTH_LOGE(AUTH_CONN, "auth type error");
2022         return SOFTBUS_AUTH_NOT_FOUND;
2023     }
2024     authHandle->authId = auth->authId;
2025     authHandle->type = type;
2026     AUTH_LOGI(AUTH_CONN, "found auth manager, side=%{public}s, type=%{public}d, authId=%{public}" PRId64,
2027         GetAuthSideStr(isServer), type, auth->authId);
2028     return SOFTBUS_OK;
2029 }
2030 
AuthGetEncryptSize(int64_t authId,uint32_t inLen)2031 uint32_t AuthGetEncryptSize(int64_t authId, uint32_t inLen)
2032 {
2033     AuthManager *auth = GetAuthManagerByAuthId(authId);
2034     if (auth != NULL) {
2035         DelDupAuthManager(auth);
2036         return inLen + ENCRYPT_OVER_HEAD_LEN;
2037     }
2038     return inLen + OVERHEAD_LEN;
2039 }
2040 
AuthGetDecryptSize(uint32_t inLen)2041 uint32_t AuthGetDecryptSize(uint32_t inLen)
2042 {
2043     if (inLen <= OVERHEAD_LEN) {
2044         return inLen;
2045     }
2046     return inLen - OVERHEAD_LEN;
2047 }
2048 
AuthDeviceSetP2pMac(int64_t authId,const char * p2pMac)2049 int32_t AuthDeviceSetP2pMac(int64_t authId, const char *p2pMac)
2050 {
2051     if (p2pMac == NULL || p2pMac[0] == '\0') {
2052         AUTH_LOGE(AUTH_CONN, "p2pMac is empty");
2053         return SOFTBUS_INVALID_PARAM;
2054     }
2055     AuthManager inAuth = { 0 };
2056     if (strcpy_s(inAuth.p2pMac, sizeof(inAuth.p2pMac), p2pMac) != EOK) {
2057         AUTH_LOGE(AUTH_CONN, "copy p2pMac fail, authId=%{public}" PRId64, authId);
2058         return SOFTBUS_MEM_ERR;
2059     }
2060     return UpdateAuthManagerByAuthId(authId, SetAuthP2pMac, &inAuth, AUTH_LINK_TYPE_P2P);
2061 }
2062 
AuthDeviceInit(const AuthTransCallback * callback)2063 int32_t AuthDeviceInit(const AuthTransCallback *callback)
2064 {
2065     AUTH_LOGI(AUTH_INIT, "auth init enter");
2066     if (callback == NULL) {
2067         AUTH_LOGE(AUTH_INIT, "Auth notify trans callback is null");
2068         return SOFTBUS_INVALID_PARAM;
2069     }
2070     g_transCallback = *callback;
2071     ListInit(&g_authClientList);
2072     ListInit(&g_authServerList);
2073     if (AuthCommonInit() != SOFTBUS_OK) {
2074         AUTH_LOGE(AUTH_INIT, "AuthCommonInit fail");
2075         return SOFTBUS_ERR;
2076     }
2077     InitAuthReqInfo();
2078 
2079     AuthConnListener connListener = {
2080         .onConnectResult = OnConnectResult,
2081         .onDisconnected = OnDisconnected,
2082         .onDataReceived = OnDataReceived,
2083     };
2084     if (AuthConnInit(&connListener) != SOFTBUS_OK) {
2085         AUTH_LOGE(AUTH_INIT, "AuthConnInit fail");
2086         AuthCommonDeinit();
2087         return SOFTBUS_ERR;
2088     }
2089     if (LnnAsyncCallbackDelayHelper(GetLooper(LOOP_TYPE_DEFAULT), AuthRegisterToDpDelay, NULL, DELAY_REG_DP_TIME) !=
2090         SOFTBUS_OK) {
2091         AUTH_LOGE(AUTH_INIT, "delay registertoDp failed");
2092         return SOFTBUS_AUTH_INIT_FAIL;
2093     }
2094     AUTH_LOGI(AUTH_INIT, "auth init succ");
2095     return SOFTBUS_OK;
2096 }
2097 
AuthDeviceDeinit(void)2098 void AuthDeviceDeinit(void)
2099 {
2100     AUTH_LOGI(AUTH_INIT, "auth deinit enter");
2101     UnregTrustDataChangeListener();
2102     UnRegHichainSaStatusListener();
2103     DestroyAuthManagerList();
2104     ClearAuthRequest();
2105     AuthConnDeinit();
2106     AuthSessionFsmExit();
2107     DeInitAuthReqInfo();
2108     AuthCommonDeinit();
2109     AUTH_LOGI(AUTH_INIT, "auth deinit succ");
2110 }
2111