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