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