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