• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_session_fsm.h"
17 
18 #include <securec.h>
19 
20 #include "anonymizer.h"
21 #include "auth_connection.h"
22 #include "auth_deviceprofile.h"
23 #include "auth_hichain.h"
24 #include "auth_log.h"
25 #include "auth_manager.h"
26 #include "auth_normalize_request.h"
27 #include "auth_request.h"
28 #include "auth_pre_link.h"
29 #include "auth_session_json.h"
30 #include "auth_session_message.h"
31 #include "auth_tcp_connection.h"
32 #include "bus_center_adapter.h"
33 #include "bus_center_manager.h"
34 #include "comm_log.h"
35 #include "g_enhance_lnn_func.h"
36 #include "g_enhance_lnn_func_pack.h"
37 #include "g_enhance_auth_func.h"
38 #include "g_enhance_auth_func_pack.h"
39 #include "legacy/softbus_adapter_hitrace.h"
40 #include "lnn_async_callback_utils.h"
41 #include "lnn_distributed_net_ledger.h"
42 #include "lnn_event.h"
43 #include "lnn_feature_capability.h"
44 #include "lnn_heartbeat_ctrl.h"
45 #include "lnn_ohos_account_adapter.h"
46 #include "lnn_log.h"
47 #include "softbus_adapter_bt_common.h"
48 #include "softbus_adapter_mem.h"
49 #include "softbus_base_listener.h"
50 #include "softbus_def.h"
51 #include "softbus_socket.h"
52 #include "softbus_init_common.h"
53 #include "wifi_direct_manager.h"
54 
55 #define AUTH_TIMEOUT_MS            (10 * 1000)
56 #define TO_AUTH_FSM(ptr)           CONTAINER_OF(ptr, AuthFsm, fsm)
57 #define SHORT_UDID_HASH_LEN        8
58 #define HICHAIN_RETURN_NOT_TRUSTED (-425919748)
59 #define PTK_32_BIT_LEN 16
60 #define DEFAULT_USERID 0
61 
62 typedef enum {
63     FSM_MSG_RECV_DEVICE_ID,
64     FSM_MSG_RECV_AUTH_DATA,
65     FSM_MSG_SAVE_SESSION_KEY,
66     FSM_MSG_AUTH_ERROR,
67     FSM_MSG_RECV_DEVICE_INFO,
68     FSM_MSG_RECV_CLOSE_ACK,
69     FSM_MSG_AUTH_FINISH,
70     FSM_MSG_AUTH_TIMEOUT,
71     FSM_MSG_DEVICE_NOT_TRUSTED,
72     FSM_MSG_DEVICE_DISCONNECTED,
73     FSM_MSG_DEVICE_POST_DEVICEID,
74     FSM_MSG_STOP_AUTH_FSM,
75     FSM_MSG_UNKNOWN,
76 } StateMessageType;
77 typedef struct {
78     StateMessageType type;
79     char *msg;
80 } StateMsgMap;
81 
82 static const StateMsgMap g_StateMsgMap[] = {
83     { FSM_MSG_RECV_DEVICE_ID,       (char *)"RECV_DEVICE_ID"       },
84     { FSM_MSG_RECV_AUTH_DATA,       (char *)"RECV_AUTH_DATA"       },
85     { FSM_MSG_SAVE_SESSION_KEY,     (char *)"SAVE_SESSION_KEY"     },
86     { FSM_MSG_AUTH_ERROR,           (char *)"AUTH_ERROR"           },
87     { FSM_MSG_RECV_DEVICE_INFO,     (char *)"RECV_DEVICE_INFO"     },
88     { FSM_MSG_RECV_CLOSE_ACK,       (char *)"RECV_CLOSE_ACK"       },
89     { FSM_MSG_AUTH_FINISH,          (char *)"AUTH_FINISH"          },
90     { FSM_MSG_AUTH_TIMEOUT,         (char *)"AUTH_TIMEOUT"         },
91     { FSM_MSG_DEVICE_NOT_TRUSTED,   (char *)"DEVICE_NOT_TRUSTED"   },
92     { FSM_MSG_DEVICE_DISCONNECTED,  (char *)"DEVICE_DISCONNECTED"  },
93     { FSM_MSG_DEVICE_POST_DEVICEID, (char *)"DEVICE_POST_DEVICEID" },
94     { FSM_MSG_STOP_AUTH_FSM,        (char *)"STOP_AUTH_FSM"        },
95     { FSM_MSG_UNKNOWN,              (char *)"UNKNOWN MSG!!"        },
96 };
97 
98 typedef struct {
99     uint32_t len;
100     uint8_t data[0];
101 } MessagePara;
102 
103 typedef struct {
104     char uuid[UUID_BUF_LEN];
105     int32_t result;
106 } OnPtkSyncCallBackParam;
107 
108 typedef struct {
109     int64_t param1;
110     bool param2;
111     AuthFsm *(*getFunc)(int64_t param1, bool param2);
112 } AuthFsmGetFunc;
113 
114 typedef struct {
115     char localIp[IP_LEN];
116     char localBrMac[MAC_LEN];
117     char localBleMac[MAC_LEN];
118     char localUdid[UDID_BUF_LEN];
119     char localNetworkId[NETWORK_ID_BUF_LEN];
120     char localDevName[DEVICE_NAME_BUF_LEN];
121 } AuditReportDevInfo;
122 
123 static ListNode g_authFsmList = { &g_authFsmList, &g_authFsmList };
124 
125 static void SyncNegotiationEnter(FsmStateMachine *fsm);
126 static bool SyncNegotiationStateProcess(FsmStateMachine *fsm, int32_t msgType, void *para);
127 static void SyncDevIdStateEnter(FsmStateMachine *fsm);
128 static bool SyncDevIdStateProcess(FsmStateMachine *fsm, int32_t msgType, void *para);
129 static void DeviceAuthStateEnter(FsmStateMachine *fsm);
130 static bool DeviceAuthStateProcess(FsmStateMachine *fsm, int32_t msgType, void *para);
131 static bool SyncDevInfoStateProcess(FsmStateMachine *fsm, int32_t msgType, void *para);
132 static void AuthFsmDeinitCallback(FsmStateMachine *fsm);
133 static void HandleMsgSaveSessionKey(AuthFsm *authFsm, const MessagePara *para);
134 
135 static FsmState g_states[STATE_NUM_MAX] = {
136     [STATE_SYNC_NEGOTIATION] = {
137         .enter = SyncNegotiationEnter,
138         .process = SyncNegotiationStateProcess,
139         .exit = NULL,
140     },
141     [STATE_SYNC_DEVICE_ID] = {
142         .enter = SyncDevIdStateEnter,
143         .process = SyncDevIdStateProcess,
144         .exit = NULL,
145     },
146     [STATE_DEVICE_AUTH] = {
147         .enter = DeviceAuthStateEnter,
148         .process = DeviceAuthStateProcess,
149         .exit = NULL,
150     },
151     [STATE_SYNC_DEVICE_INFO] = {
152         .enter = NULL,
153         .process = SyncDevInfoStateProcess,
154         .exit = NULL,
155     },
156 };
157 
FsmMsgTypeToStr(int32_t type)158 static char *FsmMsgTypeToStr(int32_t type)
159 {
160     if (type < FSM_MSG_RECV_DEVICE_ID || type >= FSM_MSG_UNKNOWN) {
161         return g_StateMsgMap[FSM_MSG_UNKNOWN].msg;
162     }
163     return g_StateMsgMap[type].msg;
164 }
165 
TranslateToAuthFsm(FsmStateMachine * fsm,int32_t msgType,MessagePara * para)166 static AuthFsm *TranslateToAuthFsm(FsmStateMachine *fsm, int32_t msgType, MessagePara *para)
167 {
168     if (fsm == NULL) {
169         AUTH_LOGE(AUTH_FSM, "fsm is null");
170         return NULL;
171     }
172     AuthFsm *authFsm = TO_AUTH_FSM(fsm);
173     if (authFsm == NULL) {
174         AUTH_LOGE(AUTH_FSM, "authFsm is null");
175         return NULL;
176     }
177     if (authFsm->isDead) {
178         AUTH_LOGE(AUTH_FSM, "auth fsm has dead. authSeq=%{public}" PRId64 "", authFsm->authSeq);
179         return NULL;
180     }
181     /* check para */
182     if ((msgType != FSM_MSG_AUTH_TIMEOUT && msgType != FSM_MSG_DEVICE_NOT_TRUSTED &&
183         msgType != FSM_MSG_DEVICE_DISCONNECTED && msgType != FSM_MSG_STOP_AUTH_FSM) && para == NULL) {
184         AUTH_LOGE(AUTH_FSM, "invalid msgType. msgType=%{public}d", msgType);
185         return NULL;
186     }
187     return authFsm;
188 }
189 
GetNextAuthFsmId(void)190 static uint32_t GetNextAuthFsmId(void)
191 {
192     static uint32_t authFsmId = 0;
193     return ++authFsmId;
194 }
195 
IsNeedExchangeNetworkId(uint32_t feature,AuthCapability capaBit)196 static bool IsNeedExchangeNetworkId(uint32_t feature, AuthCapability capaBit)
197 {
198     return ((feature & (1 << (uint32_t)capaBit)) != 0);
199 }
200 
AddUdidInfo(uint32_t requestId,bool isServer,AuthConnInfo * connInfo)201 static void AddUdidInfo(uint32_t requestId, bool isServer, AuthConnInfo *connInfo)
202 {
203     if (isServer) {
204         AUTH_LOGD(AUTH_FSM, "is not client");
205         return;
206     }
207     AuthRequest request;
208     (void)memset_s(&request, sizeof(request), 0, sizeof(request));
209     if (GetAuthRequestNoLock(requestId, &request) != SOFTBUS_OK) {
210         AUTH_LOGE(AUTH_FSM, "get auth request fail");
211         return;
212     }
213     switch (connInfo->type) {
214         case AUTH_LINK_TYPE_BR:
215         case AUTH_LINK_TYPE_SESSION:
216         case AUTH_LINK_TYPE_SLE:
217             break;
218         case AUTH_LINK_TYPE_WIFI:
219         case AUTH_LINK_TYPE_SESSION_KEY:
220         case AUTH_LINK_TYPE_USB:
221             (void)memcpy_s(connInfo->info.ipInfo.deviceIdHash, UDID_HASH_LEN, request.connInfo.info.ipInfo.deviceIdHash,
222                 UDID_HASH_LEN);
223             break;
224         case AUTH_LINK_TYPE_BLE:
225             (void)memcpy_s(connInfo->info.bleInfo.deviceIdHash, UDID_HASH_LEN,
226                 request.connInfo.info.bleInfo.deviceIdHash, UDID_HASH_LEN);
227             break;
228         case AUTH_LINK_TYPE_P2P:
229         case AUTH_LINK_TYPE_ENHANCED_P2P:
230             if (strcpy_s(connInfo->info.ipInfo.udid, UDID_BUF_LEN, request.connInfo.info.ipInfo.udid) != EOK) {
231                 AUTH_LOGE(AUTH_FSM, "strcpy udid fail");
232                 return;
233             }
234             break;
235         default:
236             AUTH_LOGE(AUTH_FSM, "error type");
237     }
238 }
239 
ProcAuthFsm(uint32_t requestId,bool isServer,AuthFsm * authFsm)240 static int32_t ProcAuthFsm(uint32_t requestId, bool isServer, AuthFsm *authFsm)
241 {
242     AuthRequest request;
243     NodeInfo nodeInfo;
244     (void)memset_s(&request, sizeof(request), 0, sizeof(request));
245     (void)memset_s(&nodeInfo, sizeof(nodeInfo), 0, sizeof(nodeInfo));
246     AddUdidInfo(requestId, isServer, &authFsm->info.connInfo);
247     if (authFsm->info.connInfo.type == AUTH_LINK_TYPE_BLE) {
248         if (GetAuthRequestNoLock(requestId, &request) != SOFTBUS_OK) {
249             AUTH_LOGE(AUTH_FSM, "get auth request fail");
250             return SOFTBUS_AUTH_NOT_FOUND;
251         }
252         char udidHash[SHORT_UDID_HASH_HEX_LEN + 1] = { 0 };
253         int32_t ret = ConvertBytesToHexString(udidHash, SHORT_UDID_HASH_HEX_LEN + 1,
254             (const unsigned char *)request.connInfo.info.bleInfo.deviceIdHash, SHORT_UDID_HASH_LEN);
255         if (ret == SOFTBUS_OK && LnnRetrieveDeviceInfoPacked((const char *)udidHash, &nodeInfo) == SOFTBUS_OK &&
256             IsNeedExchangeNetworkId(nodeInfo.authCapacity, BIT_SUPPORT_EXCHANGE_NETWORKID)) {
257             AUTH_LOGI(AUTH_FSM, "LnnRetrieveDeviceInfo success");
258             authFsm->info.idType = EXCHANGE_NETWORKID;
259         }
260     }
261     return SOFTBUS_OK;
262 }
263 
FillSessionInfoModule(uint32_t requestId,AuthSessionInfo * info)264 static int32_t FillSessionInfoModule(uint32_t requestId, AuthSessionInfo *info)
265 {
266     if (!info->isServer) {
267         AuthRequest request;
268         (void)memset_s(&request, sizeof(request), 0, sizeof(request));
269         int32_t ret = GetAuthRequestNoLock(requestId, &request);
270         if (ret != SOFTBUS_OK) {
271             AUTH_LOGE(AUTH_FSM, "get auth request fail");
272             return ret;
273         }
274         info->module = request.module;
275     }
276     return SOFTBUS_OK;
277 }
278 
CreateAuthFsm(AuthFsmParam * authFsmParam,const AuthConnInfo * connInfo)279 static AuthFsm *CreateAuthFsm(AuthFsmParam *authFsmParam, const AuthConnInfo *connInfo)
280 {
281     AuthFsm *authFsm = (AuthFsm *)SoftBusCalloc(sizeof(AuthFsm));
282     if (authFsm == NULL) {
283         AUTH_LOGE(AUTH_FSM, "malloc AuthFsm fail");
284         return NULL;
285     }
286     authFsm->id = GetNextAuthFsmId();
287     authFsm->authSeq = authFsmParam->authSeq;
288     authFsm->info.requestId = authFsmParam->requestId;
289     authFsm->info.isServer = authFsmParam->isServer;
290     authFsm->info.isConnectServer = authFsmParam->isServer;
291     authFsm->info.connId = authFsmParam->connId;
292     authFsm->info.connInfo = *connInfo;
293     authFsm->info.version = SOFTBUS_NEW_V2;
294     authFsm->info.authVersion = AUTH_VERSION_INVALID;
295     authFsm->info.idType = EXCHANGE_UDID;
296     authFsm->info.isSupportDmDeviceKey = false;
297     authFsm->info.deviceKeyId = authFsmParam->deviceKeyId;
298     if (FillSessionInfoModule(authFsmParam->requestId, &authFsm->info) != SOFTBUS_OK) {
299         AUTH_LOGE(AUTH_FSM, "fill module fail");
300         SoftBusFree(authFsm);
301         return NULL;
302     }
303     if (!authFsmParam->isServer) {
304         if (ProcAuthFsm(authFsmParam->requestId, authFsmParam->isServer, authFsm) != SOFTBUS_OK) {
305             SoftBusFree(authFsm);
306             return NULL;
307         }
308     }
309     if (sprintf_s(authFsm->fsmName, sizeof(authFsm->fsmName), "AuthFsm-%u", authFsm->id) == -1) {
310         AUTH_LOGE(AUTH_FSM, "format auth fsm name fail");
311         SoftBusFree(authFsm);
312         return NULL;
313     }
314     if (LnnFsmInit(&authFsm->fsm, NULL, authFsm->fsmName, AuthFsmDeinitCallback) != SOFTBUS_OK) {
315         AUTH_LOGE(AUTH_FSM, "init fsm fail");
316         SoftBusFree(authFsm);
317         return NULL;
318     }
319     for (int32_t i = 0; i < STATE_NUM_MAX; ++i) {
320         LnnFsmAddState(&authFsm->fsm, &g_states[i]);
321     }
322     ListNodeInsert(&g_authFsmList, &authFsm->node);
323     AUTH_LOGI(AUTH_FSM,
324         "create auth fsm. authSeq=%{public}" PRId64 ", name=%{public}s, side=%{public}s, requestId=%{public}u, "
325         "" CONN_INFO, authFsm->authSeq, authFsm->fsmName, GetAuthSideStr(authFsmParam->isServer),
326         authFsmParam->requestId, CONN_DATA(authFsmParam->connId));
327     return authFsm;
328 }
329 
DestroyAuthFsm(AuthFsm * authFsm)330 static void DestroyAuthFsm(AuthFsm *authFsm)
331 {
332     AUTH_LOGI(AUTH_FSM, "destroy auth. authSeq=%{public}" PRId64 ", side=%{public}s, requestId=%{public}u",
333         authFsm->authSeq, GetAuthSideStr(authFsm->info.isServer), authFsm->info.requestId);
334     ListDelete(&authFsm->node);
335     if (authFsm->info.deviceInfoData != NULL) {
336         SoftBusFree(authFsm->info.deviceInfoData);
337         authFsm->info.deviceInfoData = NULL;
338     }
339     if (authFsm->info.normalizedKey != NULL) {
340         SoftBusFree(authFsm->info.normalizedKey);
341         authFsm->info.normalizedKey = NULL;
342     }
343     if (authFsm->info.credId != NULL) {
344         SoftBusFree(authFsm->info.credId);
345         authFsm->info.credId = NULL;
346     }
347     SoftBusFree(authFsm);
348 }
349 
AuthFsmDeinitCallback(FsmStateMachine * fsm)350 static void AuthFsmDeinitCallback(FsmStateMachine *fsm)
351 {
352     static uint32_t callCount = 0;
353     AUTH_LOGI(AUTH_FSM, "auth fsm deinit callback enter, callCount=%{public}u", callCount++);
354     if (fsm == NULL) {
355         AUTH_LOGE(AUTH_FSM, "fsm is null");
356         return;
357     }
358     if (!RequireAuthLock()) {
359         return;
360     }
361     DestroyAuthFsm(TO_AUTH_FSM(fsm));
362     ReleaseAuthLock();
363 }
364 
NewMessagePara(const uint8_t * data,uint32_t len)365 static MessagePara *NewMessagePara(const uint8_t *data, uint32_t len)
366 {
367     MessagePara *para = (MessagePara *)SoftBusCalloc(sizeof(MessagePara) + len);
368     if (para == NULL) {
369         AUTH_LOGE(AUTH_FSM, "malloc ExchangeDataPara fail");
370         return NULL;
371     }
372     para->len = len;
373     if (data != NULL && len > 0 && memcpy_s(para->data, len, data, len) != EOK) {
374         AUTH_LOGE(AUTH_FSM, "copy data fail");
375         SoftBusFree(para);
376         return NULL;
377     }
378     return para;
379 }
380 
FreeMessagePara(MessagePara * para)381 static void FreeMessagePara(MessagePara *para)
382 {
383     if (para != NULL) {
384         SoftBusFree(para);
385     }
386 }
387 
ConvertAuthLinkTypeToHisysEvtLinkType(AuthLinkType type)388 static SoftBusLinkType ConvertAuthLinkTypeToHisysEvtLinkType(AuthLinkType type)
389 {
390     switch (type) {
391         case AUTH_LINK_TYPE_WIFI:
392         case AUTH_LINK_TYPE_SESSION_KEY:
393             return SOFTBUS_HISYSEVT_LINK_TYPE_WLAN;
394         case AUTH_LINK_TYPE_BR:
395             return SOFTBUS_HISYSEVT_LINK_TYPE_BR;
396         case AUTH_LINK_TYPE_BLE:
397             return SOFTBUS_HISYSEVT_LINK_TYPE_BLE;
398         case AUTH_LINK_TYPE_P2P:
399             return SOFTBUS_HISYSEVT_LINK_TYPE_P2P;
400         case AUTH_LINK_TYPE_SLE:
401             return SOFTBUS_HISYSEVT_LINK_TYPE_SLE;
402         default:
403             return SOFTBUS_HISYSEVT_LINK_TYPE_BUTT;
404     }
405 }
406 
DfxRecordLnnAuthEnd(AuthFsm * authFsm,uint64_t costTime,int32_t reason)407 static void DfxRecordLnnAuthEnd(AuthFsm *authFsm, uint64_t costTime, int32_t reason)
408 {
409     LnnEventExtra extra = { 0 };
410     LnnEventExtraInit(&extra);
411     extra.errcode = reason;
412     extra.authCostTime = (int32_t)costTime;
413     extra.result = (reason == SOFTBUS_OK) ? EVENT_STAGE_RESULT_OK : EVENT_STAGE_RESULT_FAILED;
414 
415     if (authFsm != NULL) {
416         extra.authLinkType = authFsm->info.connInfo.type;
417         extra.authId = (int32_t)authFsm->authSeq;
418         extra.authRequestId = (int32_t)authFsm->info.requestId;
419     }
420     LNN_EVENT(EVENT_SCENE_JOIN_LNN, EVENT_STAGE_AUTH, extra);
421 }
422 
ReportAuthResultEvt(AuthFsm * authFsm,int32_t result)423 static void ReportAuthResultEvt(AuthFsm *authFsm, int32_t result)
424 {
425     AUTH_LOGE(AUTH_FSM, "report auth result evt enter");
426     SoftBusLinkType linkType = ConvertAuthLinkTypeToHisysEvtLinkType(authFsm->info.connInfo.type);
427     if (linkType == SOFTBUS_HISYSEVT_LINK_TYPE_BUTT) {
428         return;
429     }
430     authFsm->statisticData.endAuthTime = (uint64_t)LnnUpTimeMs();
431     uint64_t costTime = authFsm->statisticData.endAuthTime - authFsm->statisticData.startAuthTime;
432     DfxRecordLnnAuthEnd(authFsm, costTime, result);
433     AuthFailStage stage = AUTH_STAGE_BUTT;
434 
435     if (result == SOFTBUS_OK) {
436         if (SoftBusRecordAuthResult(linkType, SOFTBUS_OK, costTime, AUTH_STAGE_BUTT) != SOFTBUS_OK) {
437             AUTH_LOGE(AUTH_FSM, "report static auth result fail");
438         }
439         return;
440     } else if (result == SOFTBUS_AUTH_SYNC_DEVID_FAIL || result == SOFTBUS_AUTH_SYNC_DEVINFO_FAIL ||
441         result == SOFTBUS_AUTH_UNPACK_DEVINFO_FAIL || result == SOFTBUS_AUTH_SEND_FAIL ||
442         result == SOFTBUS_AUTH_NOT_SUPPORT_THREE_STATE) {
443         stage = AUTH_EXCHANGE_STAGE;
444     } else if (result == SOFTBUS_AUTH_DEVICE_DISCONNECTED) {
445         stage = AUTH_CONNECT_STAGE;
446     } else if (result == SOFTBUS_AUTH_HICHAIN_PROCESS_FAIL || result == SOFTBUS_AUTH_TIMEOUT ||
447         result == SOFTBUS_AUTH_HICHAIN_NOT_TRUSTED) {
448         stage = AUTH_VERIFY_STAGE;
449     } else if (result >= SOFTBUS_HICHAIN_MIN && result <= SOFTBUS_HICHAIN_MAX) {
450         stage = AUTH_VERIFY_STAGE;
451     } else {
452         AUTH_LOGE(AUTH_FSM, "unsupport result=%{public}d.", result);
453         return;
454     }
455 
456     if (SoftBusRecordAuthResult(linkType, result, costTime, stage) != SOFTBUS_OK) {
457         AUTH_LOGE(AUTH_FSM, "report static auth result fail");
458     }
459     SoftBusFaultEvtInfo info;
460     (void)memset_s(&info, sizeof(SoftBusFaultEvtInfo), 0, sizeof(SoftBusFaultEvtInfo));
461     info.moduleType = MODULE_TYPE_AUTH;
462     info.linkType = linkType;
463     info.errorCode = result;
464     if (SoftBusReportBusCenterFaultEvt(&info) != SOFTBUS_OK) {
465         AUTH_LOGE(AUTH_FSM, "report buscenter fault evt fail");
466     }
467 }
468 
SaveDeviceKey(AuthFsm * authFsm,int32_t keyType,AuthLinkType type)469 static void SaveDeviceKey(AuthFsm *authFsm, int32_t keyType, AuthLinkType type)
470 {
471     AuthDeviceKeyInfo deviceKey;
472     SessionKey sessionKey;
473     (void)memset_s(&deviceKey, sizeof(AuthDeviceKeyInfo), 0, sizeof(AuthDeviceKeyInfo));
474     (void)memset_s(&sessionKey, sizeof(SessionKey), 0, sizeof(SessionKey));
475     if (AuthManagerGetSessionKey(authFsm->authSeq, &authFsm->info, &sessionKey) != SOFTBUS_OK) {
476         AUTH_LOGE(AUTH_FSM, "get session key fail");
477         return;
478     }
479     if (memcpy_s(deviceKey.deviceKey, sizeof(deviceKey.deviceKey), sessionKey.value, sizeof(sessionKey.value)) != EOK) {
480         AUTH_LOGE(AUTH_FSM, "session key cpy fail");
481         (void)memset_s(&sessionKey, sizeof(SessionKey), 0, sizeof(SessionKey));
482         return;
483     }
484     deviceKey.keyLen = sessionKey.len;
485     deviceKey.keyIndex = authFsm->authSeq;
486     deviceKey.keyType = keyType;
487     deviceKey.isServerSide = authFsm->info.isServer;
488     if (AuthInsertDeviceKeyPacked(&authFsm->info.nodeInfo, &deviceKey, type) != SOFTBUS_OK) {
489         AUTH_LOGE(AUTH_FSM, "insert deviceKey fail");
490     }
491     (void)memset_s(&deviceKey, sizeof(AuthDeviceKeyInfo), 0, sizeof(AuthDeviceKeyInfo));
492     (void)memset_s(&sessionKey, sizeof(SessionKey), 0, sizeof(SessionKey));
493 }
494 
GetAuthFsmByConnInfo(const AuthConnInfo * connInfo,bool isServer)495 static AuthFsm *GetAuthFsmByConnInfo(const AuthConnInfo *connInfo, bool isServer)
496 {
497     AuthFsm *item = NULL;
498     LIST_FOR_EACH_ENTRY(item, &g_authFsmList, AuthFsm, node) {
499         if (!CompareConnInfo(&item->info.connInfo, connInfo, true) || item->info.isConnectServer != isServer) {
500             continue;
501         }
502         if (item->isDead) {
503             AUTH_LOGE(AUTH_FSM, "auth fsm has dead. authSeq=%{public}" PRId64 "", item->authSeq);
504             break;
505         }
506         return item;
507     }
508     return NULL;
509 }
510 
ProcessTimeoutErrorCode(AuthFsm * authFsm,int32_t * result)511 static void ProcessTimeoutErrorCode(AuthFsm *authFsm, int32_t *result)
512 {
513     AuthFsmStateIndex curState = authFsm->curState;
514     if (curState == STATE_SYNC_NEGOTIATION || curState == STATE_SYNC_DEVICE_ID) {
515         *result = SOFTBUS_AUTH_SYNC_DEVICEID_TIMEOUT;
516     } else if (curState == STATE_DEVICE_AUTH) {
517         *result = (authFsm->info.normalizedType == NORMALIZED_SUPPORT || authFsm->info.isSupportFastAuth) ?
518             SOFTBUS_AUTH_SAVE_SESSIONKEY_TIMEOUT : SOFTBUS_AUTH_HICHAIN_TIMEOUT;
519     } else if (curState == STATE_SYNC_DEVICE_INFO) {
520         *result = SOFTBUS_AUTH_SYNC_DEVICEINFO_TIMEOUT;
521     } else {
522         AUTH_LOGE(AUTH_FSM, "authFsm state error, curState=%{public}d", curState);
523     }
524 }
525 
UpdateDpAclSKId(AuthFsm * authFsm)526 static void UpdateDpAclSKId(AuthFsm *authFsm)
527 {
528     SessionKey sessionKey;
529     (void)memset_s(&sessionKey, sizeof(SessionKey), 0, sizeof(SessionKey));
530     if (AuthManagerGetSessionKey(authFsm->authSeq, &authFsm->info, &sessionKey) != SOFTBUS_OK) {
531         AUTH_LOGE(AUTH_FSM, "get session key fail");
532         return;
533     }
534     AuthSessionInfo *info = &authFsm->info;
535     UpdateDpAclParams aclParams = {
536         .accountId = 0,
537         .deviceId = info->udid,
538         .peerUserId = info->userId
539     };
540     bool isNeedUpdateDk = (info->nodeInfo.aclState == ACL_CAN_WRITE) &&
541         IsSupportFeatureByCapaBit(info->nodeInfo.authCapacity, BIT_SUPPORT_USERKEY_NEGO);
542     AUTH_LOGI(AUTH_FSM, "judge insert user key aclState=%{public}d, authCapacity=%{public}d", info->nodeInfo.aclState,
543         info->nodeInfo.authCapacity);
544     UpdateDpSameAccount(&aclParams, sessionKey, isNeedUpdateDk, info->nodeInfo.aclState);
545     (void)memset_s(&sessionKey, sizeof(SessionKey), 0, sizeof(SessionKey));
546 }
547 
StopAuthFsm(AuthFsm * authFsm)548 static void StopAuthFsm(AuthFsm *authFsm)
549 {
550     authFsm->isDead = true;
551     DelAuthNormalizeRequest(authFsm->authSeq);
552     LnnFsmStop(&authFsm->fsm);
553     LnnFsmDeinit(&authFsm->fsm);
554 }
555 
CompleteAuthSession(AuthFsm * authFsm,int32_t result)556 static void CompleteAuthSession(AuthFsm *authFsm, int32_t result)
557 {
558     SoftbusHitraceStart(SOFTBUS_HITRACE_ID_VALID, (uint64_t)authFsm->authSeq);
559     AUTH_LOGI(AUTH_FSM, "auth fsm complete. authSeq=%{public}" PRId64 ", side=%{public}s, result=%{public}d",
560         authFsm->authSeq, GetAuthSideStr(authFsm->info.isServer), result);
561     ReportAuthResultEvt(authFsm, result);
562     if (result == SOFTBUS_OK) {
563         AuthManagerSetAuthFinished(authFsm->authSeq, &authFsm->info);
564         UpdateDpAclSKId(authFsm);
565         if (authFsm->info.normalizedType == NORMALIZED_KEY_ERROR) {
566             AUTH_LOGI(AUTH_FSM, "only hichain verify, save the device key");
567             SaveDeviceKey(authFsm, AUTH_LINK_TYPE_NORMALIZED, authFsm->info.connInfo.type);
568         } else if (authFsm->info.normalizedType == NORMALIZED_SUPPORT && authFsm->info.deviceKeyId.hasDeviceKeyId) {
569             AUTH_LOGI(AUTH_FSM, "use dm devicekey, save the device key");
570             SaveDeviceKey(authFsm, AUTH_LINK_TYPE_NORMALIZED, authFsm->info.connInfo.type);
571         } else if ((authFsm->info.normalizedType == NORMALIZED_NOT_SUPPORT) &&
572             (authFsm->info.connInfo.type == AUTH_LINK_TYPE_BLE) && !authFsm->info.isSupportFastAuth) {
573             AUTH_LOGI(AUTH_FSM, "save device key for fast auth");
574             SaveDeviceKey(authFsm, AUTH_LINK_TYPE_BLE, AUTH_LINK_TYPE_BLE);
575         }
576         if (!authFsm->info.isServer) {
577             NotifyNormalizeRequestSuccess(authFsm->authSeq, true);
578         }
579         // Disconnect another request and notify auth success
580         if (authFsm->info.isConnectServer && authFsm->info.peerState != AUTH_STATE_COMPATIBLE) {
581             AuthFsm *stopFsm = GetAuthFsmByConnInfo(&authFsm->info.connInfo, !authFsm->info.isConnectServer);
582             if (stopFsm != NULL) {
583                 AuthNotifyAuthPassed(stopFsm->authSeq, &stopFsm->info);
584                 LnnFsmPostMessage(&stopFsm->fsm, FSM_MSG_STOP_AUTH_FSM, NULL);
585             }
586         }
587     } else {
588         if (result == SOFTBUS_AUTH_TIMEOUT) {
589             ProcessTimeoutErrorCode(authFsm, &result);
590         }
591         LnnFsmRemoveMessage(&authFsm->fsm, FSM_MSG_AUTH_TIMEOUT);
592         if (!authFsm->info.isServer) {
593             NotifyNormalizeRequestFail(authFsm->authSeq, result);
594         }
595         AuthManagerSetAuthFailed(authFsm->authSeq, &authFsm->info, result);
596     }
597 
598     StopAuthFsm(authFsm);
599     SoftbusHitraceStop();
600 }
601 
HandleCommonMsg(AuthFsm * authFsm,int32_t msgType,MessagePara * msgPara)602 static void HandleCommonMsg(AuthFsm *authFsm, int32_t msgType, MessagePara *msgPara)
603 {
604     (void)msgPara;
605     switch (msgType) {
606         case FSM_MSG_AUTH_TIMEOUT:
607             AUTH_LOGE(AUTH_FSM, "auth fsm timeout. authSeq=%{public}" PRId64 "", authFsm->authSeq);
608             CompleteAuthSession(authFsm, SOFTBUS_AUTH_TIMEOUT);
609             HichainCancelRequest(authFsm->authSeq);
610             break;
611         case FSM_MSG_DEVICE_NOT_TRUSTED:
612             CompleteAuthSession(authFsm, SOFTBUS_AUTH_HICHAIN_NOT_TRUSTED);
613             HichainCancelRequest(authFsm->authSeq);
614             break;
615         case FSM_MSG_DEVICE_DISCONNECTED:
616             if (authFsm->info.isNodeInfoReceived && authFsm->info.isCloseAckReceived) {
617                 AUTH_LOGW(AUTH_FSM,
618                     "auth fsm wait for the finish event, ignore this disconnect event. authSeq=%{public}" PRId64 "",
619                     authFsm->authSeq);
620                 /*
621                  * Note: Local hichain NOT onFinish, but remote hichain already onFinish
622                  *      Regard this situation as auth finish
623                  */
624                 CompleteAuthSession(authFsm, SOFTBUS_OK);
625                 break;
626             }
627             CompleteAuthSession(authFsm, SOFTBUS_AUTH_DEVICE_DISCONNECTED);
628             HichainCancelRequest(authFsm->authSeq);
629             break;
630         case FSM_MSG_STOP_AUTH_FSM:
631             StopAuthFsm(authFsm);
632             break;
633         default:
634             AUTH_LOGE(AUTH_FSM, "auth fsm cannot handle msgType. authSeq=%{public}" PRId64 ", msgType=%{public}d",
635                 authFsm->authSeq, msgType);
636             break;
637     }
638 }
639 
AddConcurrentAuthRequest(AuthFsm * authFsm)640 static uint32_t AddConcurrentAuthRequest(AuthFsm *authFsm)
641 {
642     uint32_t num = 0;
643     if (strlen(authFsm->info.udidHash) == 0) {
644         AUTH_LOGE(AUTH_FSM, "udidHash is null, authSeq=%{public}" PRId64, authFsm->authSeq);
645         return num;
646     }
647     NormalizeRequest normalizeRequest = {
648         .authSeq = authFsm->authSeq,
649         .connInfo = authFsm->info.connInfo,
650         .isConnectServer = authFsm->info.isConnectServer,
651         .isNeedNotifyVerify = false
652     };
653     if (strcpy_s(normalizeRequest.udidHash, sizeof(normalizeRequest.udidHash), authFsm->info.udidHash) != EOK) {
654         AUTH_LOGE(AUTH_FSM, "strcpy udid hash fail. authSeq=%{public}" PRId64, authFsm->authSeq);
655         return num;
656     }
657     num = AddNormalizeRequest(&normalizeRequest);
658     char *anonyUdidHash = NULL;
659     Anonymize(normalizeRequest.udidHash, &anonyUdidHash);
660     AUTH_LOGI(AUTH_CONN, "add normalize queue, num=%{public}d, udidHash=%{public}s",
661         num, AnonymizeWrapper(anonyUdidHash));
662     AnonymizeFree(anonyUdidHash);
663     return num;
664 }
665 
SyncNegotiationEnter(FsmStateMachine * fsm)666 static void SyncNegotiationEnter(FsmStateMachine *fsm)
667 {
668     if (fsm == NULL) {
669         AUTH_LOGE(AUTH_FSM, "fsm is null");
670         return;
671     }
672     AuthFsm *authFsm = TO_AUTH_FSM(fsm);
673     if (authFsm == NULL) {
674         AUTH_LOGE(AUTH_FSM, "authFsm is null");
675         return;
676     }
677     authFsm->curState = STATE_SYNC_NEGOTIATION;
678     AUTH_LOGI(AUTH_FSM, "SyncNegotiationState: auth fsm enter. authSeq=%{public}" PRId64, authFsm->authSeq);
679     if (!authFsm->info.isServer) {
680         if (PostDeviceIdMessage(authFsm->authSeq, &authFsm->info) != SOFTBUS_OK) {
681             CompleteAuthSession(authFsm, SOFTBUS_AUTH_SYNC_DEVID_FAIL);
682         }
683     }
684 }
685 
HandleMsgPostDeviceId(AuthFsm * authFsm,const MessagePara * para)686 static void HandleMsgPostDeviceId(AuthFsm *authFsm, const MessagePara *para)
687 {
688     (void)para;
689     AuthSessionInfo *info = &authFsm->info;
690     if (PostDeviceIdMessage(authFsm->authSeq, info) != SOFTBUS_OK) {
691         CompleteAuthSession(authFsm, SOFTBUS_AUTH_SYNC_DEVID_FAIL);
692         return;
693     }
694     if (info->isServer) {
695         LnnFsmTransactState(&authFsm->fsm, g_states + STATE_DEVICE_AUTH);
696     }
697 }
698 
SyncDevIdStateEnter(FsmStateMachine * fsm)699 static void SyncDevIdStateEnter(FsmStateMachine *fsm)
700 {
701     if (fsm == NULL) {
702         AUTH_LOGE(AUTH_FSM, "fsm is null");
703         return;
704     }
705     AuthFsm *authFsm = TO_AUTH_FSM(fsm);
706     if (authFsm == NULL) {
707         AUTH_LOGE(AUTH_FSM, "authFsm is null");
708         return;
709     }
710     authFsm->curState = STATE_SYNC_DEVICE_ID;
711     SoftbusHitraceStart(SOFTBUS_HITRACE_ID_VALID, (uint64_t)authFsm->authSeq);
712     AUTH_LOGI(AUTH_FSM, "SyncDevIdState: auth fsm enter. authSeq=%{public}" PRId64 "", authFsm->authSeq);
713     if (!authFsm->info.isServer) {
714         if (authFsm->info.localState == AUTH_STATE_START) {
715             if (!AuthIsRepeatedAuthRequest(authFsm->authSeq) && AddConcurrentAuthRequest(authFsm) > 1) {
716                 AUTH_LOGI(AUTH_FSM, "wait another auth, authSeq=%{public}" PRId64 "", authFsm->authSeq);
717                 return;
718             }
719         }
720         if (PostDeviceIdMessage(authFsm->authSeq, &authFsm->info) != SOFTBUS_OK) {
721             CompleteAuthSession(authFsm, SOFTBUS_AUTH_SYNC_DEVID_FAIL);
722         }
723     }
724     SoftbusHitraceStop();
725 }
726 
SaveLastAuthSeq(const unsigned char * udidHash,int64_t authSeq)727 static void SaveLastAuthSeq(const unsigned char *udidHash, int64_t authSeq)
728 {
729     AUTH_LOGI(AUTH_FSM, "save auth seq.authSeq=%{public}" PRId64, authSeq);
730     char hashStr[SHORT_UDID_HASH_HEX_LEN + 1] = { 0 };
731     if (ConvertBytesToHexString(
732         hashStr, SHORT_UDID_HASH_HEX_LEN + 1, udidHash, SHORT_UDID_HASH_HEX_LEN / HEXIFY_UNIT_LEN) != SOFTBUS_OK) {
733         AUTH_LOGE(AUTH_FSM, "convert udidhash to hexstr fail.");
734         return;
735     }
736     NodeInfo deviceInfo;
737     (void)memset_s(&deviceInfo, sizeof(NodeInfo), 0, sizeof(NodeInfo));
738     if (LnnRetrieveDeviceInfoPacked(hashStr, &deviceInfo) != SOFTBUS_OK) {
739         AUTH_LOGE(AUTH_FSM, "no this device info.");
740         return;
741     }
742     deviceInfo.lastAuthSeq = authSeq;
743     if (LnnSaveRemoteDeviceInfoPacked(&deviceInfo) != SOFTBUS_OK) {
744         AUTH_LOGE(AUTH_FSM, "save device info fail.");
745     }
746 }
747 
RecoveryNormalizedDeviceKey(AuthFsm * authFsm)748 static int32_t RecoveryNormalizedDeviceKey(AuthFsm *authFsm)
749 {
750     if (authFsm->info.normalizedKey == NULL) {
751         AUTH_LOGE(AUTH_FSM, "normalizedKey is NULL, auth fail");
752         return SOFTBUS_INVALID_PARAM;
753     }
754     uint8_t hash[SHA_256_HASH_LEN] = { 0 };
755     int32_t ret = SoftBusGenerateStrHash((uint8_t *)authFsm->info.udid, strlen(authFsm->info.udid), hash);
756     if (ret != SOFTBUS_OK) {
757         AUTH_LOGE(AUTH_FSM, "generate udidHash fail");
758         return ret;
759     }
760     char udidShortHash[SHORT_UDID_HASH_HEX_LEN + 1] = { 0 };
761     if (ConvertBytesToUpperCaseHexString(udidShortHash, SHORT_UDID_HASH_HEX_LEN + 1, hash, SHORT_UDID_HASH_LEN) !=
762         SOFTBUS_OK) {
763         AUTH_LOGE(AUTH_FSM, "convert bytes to string fail");
764         return SOFTBUS_NETWORK_BYTES_TO_HEX_STR_ERR;
765     }
766     AuthUpdateNormalizeKeyIndexPacked(udidShortHash, authFsm->info.normalizedIndex, authFsm->info.connInfo.type,
767         authFsm->info.normalizedKey, authFsm->info.isServer);
768     if (authFsm->info.connInfo.type == AUTH_LINK_TYPE_BLE) {
769         SaveLastAuthSeq(hash, authFsm->authSeq);
770     }
771     ret = AuthSessionSaveSessionKey(
772         authFsm->authSeq, authFsm->info.normalizedKey->value, authFsm->info.normalizedKey->len);
773     if (ret != SOFTBUS_OK) {
774         AUTH_LOGE(AUTH_FSM, "post save sessionKey event fail");
775         return ret;
776     }
777     return AuthSessionHandleAuthFinish(authFsm->authSeq, authFsm->info.nodeInfo.aclState);
778 }
779 
RecoveryFastAuthKey(AuthFsm * authFsm)780 static int32_t RecoveryFastAuthKey(AuthFsm *authFsm)
781 {
782     AuthDeviceKeyInfo key = { 0 };
783     uint8_t hash[SHA_256_HASH_LEN] = { 0 };
784     int32_t ret = SoftBusGenerateStrHash((uint8_t *)authFsm->info.udid, strlen(authFsm->info.udid), hash);
785     if (ret != SOFTBUS_OK) {
786         AUTH_LOGE(AUTH_FSM, "generate udidHash fail");
787         return ret;
788     }
789     char udidShortHash[SHORT_UDID_HASH_HEX_LEN + 1] = { 0 };
790     if (ConvertBytesToUpperCaseHexString(udidShortHash, SHORT_UDID_HASH_HEX_LEN + 1, hash, SHORT_UDID_HASH_LEN) !=
791         SOFTBUS_OK) {
792         AUTH_LOGE(AUTH_FSM, "convert bytes to string fail");
793         return SOFTBUS_NETWORK_BYTES_TO_HEX_STR_ERR;
794     }
795     AuthLinkType linkType = authFsm->info.connInfo.type;
796     if (authFsm->info.connInfo.type == AUTH_LINK_TYPE_ENHANCED_P2P) {
797         // enhanced p2p reuse ble authKey
798         linkType = AUTH_LINK_TYPE_BLE;
799     }
800     if (AuthFindDeviceKeyPacked(udidShortHash, linkType, &key) != SOFTBUS_OK) {
801         AUTH_LOGE(AUTH_FSM, "find key fail, fastAuth error");
802         return SOFTBUS_AUTH_NOT_FOUND;
803     }
804     AuthUpdateKeyIndexPacked(udidShortHash, authFsm->info.connInfo.type, authFsm->authSeq, authFsm->info.isServer);
805     authFsm->info.oldIndex = key.keyIndex;
806     ret = AuthSessionSaveSessionKey(authFsm->authSeq, key.deviceKey, key.keyLen);
807     if (ret != SOFTBUS_OK) {
808         AUTH_LOGE(AUTH_FSM, "post save sessionKey event");
809         (void)memset_s(&key, sizeof(AuthDeviceKeyInfo), 0, sizeof(AuthDeviceKeyInfo));
810         return ret;
811     }
812     (void)memset_s(&key, sizeof(AuthDeviceKeyInfo), 0, sizeof(AuthDeviceKeyInfo));
813     return AuthSessionHandleAuthFinish(authFsm->authSeq, authFsm->info.nodeInfo.aclState);
814 }
815 
AuditReportSetPeerDevInfo(LnnAuditExtra * lnnAuditExtra,AuthSessionInfo * info)816 static void AuditReportSetPeerDevInfo(LnnAuditExtra *lnnAuditExtra, AuthSessionInfo *info)
817 {
818     if (lnnAuditExtra == NULL || info == NULL) {
819         AUTH_LOGE(AUTH_FSM, "lnnAuditExtra or info is null");
820         return;
821     }
822     char *anonyBrMac = NULL;
823     char *anonyBleMac = NULL;
824     char *anonySleMac = NULL;
825     char *anonyIp = NULL;
826     switch (info->connInfo.type) {
827         case AUTH_LINK_TYPE_BR:
828             Anonymize(info->connInfo.info.brInfo.brMac, &anonyBrMac);
829             if (strcpy_s((char *)lnnAuditExtra->peerBrMac, BT_MAC_LEN, AnonymizeWrapper(anonyBrMac)) != EOK) {
830                 AUTH_LOGE(AUTH_FSM, "BR MAC COPY ERROR");
831             }
832             AnonymizeFree(anonyBrMac);
833             break;
834         case AUTH_LINK_TYPE_BLE:
835             Anonymize(info->connInfo.info.bleInfo.bleMac, &anonyBleMac);
836             if (strcpy_s((char *)lnnAuditExtra->peerBleMac, BT_MAC_LEN, AnonymizeWrapper(anonyBleMac)) != EOK) {
837                 AUTH_LOGE(AUTH_FSM, "BLE MAC COPY ERROR");
838             }
839             AnonymizeFree(anonyBleMac);
840             break;
841         case AUTH_LINK_TYPE_SLE:
842             Anonymize(info->connInfo.info.sleInfo.sleMac, &anonySleMac);
843             if (strcpy_s((char *)lnnAuditExtra->peerSleMac, BT_MAC_LEN, AnonymizeWrapper(anonySleMac)) != EOK) {
844                 AUTH_LOGE(AUTH_FSM, "SLE MAC COPY ERROR");
845             }
846             AnonymizeFree(anonySleMac);
847             break;
848         case AUTH_LINK_TYPE_WIFI:
849         case AUTH_LINK_TYPE_P2P:
850         case AUTH_LINK_TYPE_ENHANCED_P2P:
851         case AUTH_LINK_TYPE_SESSION_KEY:
852             Anonymize(info->connInfo.info.ipInfo.ip, &anonyIp);
853             if (strcpy_s((char *)lnnAuditExtra->peerIp, IP_STR_MAX_LEN, AnonymizeWrapper(anonyIp)) != EOK) {
854                 AUTH_LOGE(AUTH_FSM, "IP COPY ERROR");
855             }
856             AnonymizeFree(anonyIp);
857             lnnAuditExtra->peerAuthPort = info->connInfo.info.ipInfo.port;
858             break;
859         default:
860             AUTH_LOGW(AUTH_FSM, "unknow param type!");
861             break;
862     }
863 }
864 
GetLocalDevReportInfo(AuditReportDevInfo * reportInfo,LnnAuditExtra * lnnAuditExtra)865 static void GetLocalDevReportInfo(AuditReportDevInfo *reportInfo, LnnAuditExtra *lnnAuditExtra)
866 {
867     (void)LnnGetLocalStrInfoByIfnameIdx(STRING_KEY_IP, reportInfo->localIp, IP_LEN, WLAN_IF);
868     char *anonyLocalIp = NULL;
869     Anonymize(reportInfo->localIp, &anonyLocalIp);
870     if (strcpy_s((char *)lnnAuditExtra->localIp, IP_LEN, AnonymizeWrapper(anonyLocalIp)) != EOK) {
871         AUTH_LOGE(AUTH_FSM, "LOCAL IP COPY ERROR");
872     }
873     AnonymizeFree(anonyLocalIp);
874 
875     (void)LnnGetLocalStrInfo(STRING_KEY_BT_MAC, reportInfo->localBrMac, MAC_LEN);
876     char *anonyLocalBrMac = NULL;
877     Anonymize(reportInfo->localBrMac, &anonyLocalBrMac);
878     if (strcpy_s((char *)lnnAuditExtra->localBrMac, MAC_LEN, AnonymizeWrapper(anonyLocalBrMac)) != EOK) {
879         AUTH_LOGE(AUTH_FSM, "LOCAL BR MAC COPY ERROR");
880     }
881     AnonymizeFree(anonyLocalBrMac);
882 
883     (void)LnnGetLocalStrInfo(STRING_KEY_BLE_MAC, reportInfo->localBleMac, MAC_LEN);
884     char *anonyLocalBleMac = NULL;
885     Anonymize(reportInfo->localBleMac, &anonyLocalBleMac);
886     if (strcpy_s((char *)lnnAuditExtra->localBleMac, MAC_LEN, AnonymizeWrapper(anonyLocalBleMac)) != EOK) {
887         AUTH_LOGE(AUTH_FSM, "LOCAL BLE MAC COPY ERROR");
888     }
889     AnonymizeFree(anonyLocalBleMac);
890 
891     (void)LnnGetLocalStrInfo(STRING_KEY_NETWORKID, reportInfo->localNetworkId, NETWORK_ID_BUF_LEN);
892     char *anonyLocalNetworkId = NULL;
893     Anonymize(reportInfo->localNetworkId, &anonyLocalNetworkId);
894     if (strcpy_s((char *)lnnAuditExtra->localNetworkId, NETWORK_ID_BUF_LEN, AnonymizeWrapper(anonyLocalNetworkId)) !=
895         EOK) {
896         AUTH_LOGE(AUTH_FSM, "LOCAL NETWORKID COPY ERROR");
897     }
898     AnonymizeFree(anonyLocalNetworkId);
899 
900     (void)LnnGetLocalStrInfo(STRING_KEY_DEV_NAME, reportInfo->localDevName, DEVICE_NAME_BUF_LEN);
901     char *anonyLocalDevName = NULL;
902     AnonymizeDeviceName(reportInfo->localDevName, &anonyLocalDevName);
903     if (strcpy_s((char *)lnnAuditExtra->localDevName, DEVICE_NAME_BUF_LEN, AnonymizeWrapper(anonyLocalDevName)) !=
904         EOK) {
905         AUTH_LOGE(AUTH_FSM, "LOCAL DEVICE NAME COPY ERROR");
906     }
907     AnonymizeFree(anonyLocalDevName);
908 }
909 
AuditReportSetLocalDevInfo(LnnAuditExtra * lnnAuditExtra)910 static void AuditReportSetLocalDevInfo(LnnAuditExtra *lnnAuditExtra)
911 {
912     if (lnnAuditExtra == NULL) {
913         AUTH_LOGE(AUTH_FSM, "lnnAuditExtra is null");
914         return;
915     }
916     AuditReportDevInfo reportInfo;
917     (void)memset_s(&reportInfo, sizeof(AuditReportDevInfo), 0, sizeof(AuditReportDevInfo));
918     GetLocalDevReportInfo(&reportInfo, lnnAuditExtra);
919     (void)LnnGetLocalNumInfoByIfnameIdx(NUM_KEY_AUTH_PORT, &lnnAuditExtra->localAuthPort, WLAN_IF);
920     (void)LnnGetLocalNumInfoByIfnameIdx(NUM_KEY_PROXY_PORT, &lnnAuditExtra->localProxyPort, WLAN_IF);
921     (void)LnnGetLocalNumInfoByIfnameIdx(NUM_KEY_SESSION_PORT, &lnnAuditExtra->localSessionPort, WLAN_IF);
922     (void)LnnGetLocalNumInfo(NUM_KEY_DEV_TYPE_ID, &lnnAuditExtra->localDevType);
923     char udid[UDID_BUF_LEN] = { 0 };
924     uint8_t udidHash[SHA_256_HASH_LEN] = { 0 };
925     if (LnnGetLocalStrInfo(STRING_KEY_DEV_UDID, udid, UUID_BUF_LEN) != SOFTBUS_OK) {
926         AUTH_LOGE(AUTH_FSM, "get local udid fail");
927         return;
928     }
929     int32_t ret = SoftBusGenerateStrHash((const unsigned char *)udid, strlen(udid), udidHash);
930     if (ret != SOFTBUS_OK) {
931         AUTH_LOGE(AUTH_FSM, "generate udid hash fail");
932         return;
933     }
934     if (ConvertBytesToUpperCaseHexString(reportInfo.localUdid, SHA_256_HEX_HASH_LEN, udidHash, SHA_256_HASH_LEN) !=
935         SOFTBUS_OK) {
936         AUTH_LOGE(AUTH_FSM, "convert hash to upper hex str fail");
937     }
938     char *anonyLocalUdid = NULL;
939     Anonymize(reportInfo.localUdid, &anonyLocalUdid);
940     if (strcpy_s((char *)lnnAuditExtra->localUdid, SHA_256_HEX_HASH_LEN, AnonymizeWrapper(anonyLocalUdid)) != EOK) {
941         AUTH_LOGE(AUTH_FSM, "LOCAL UDID COPY ERROR");
942     }
943     AnonymizeFree(anonyLocalUdid);
944 }
945 
BuildLnnAuditEvent(LnnAuditExtra * lnnAuditExtra,AuthSessionInfo * info,int32_t result,int32_t errCode,SoftbusAuditType auditType)946 static void BuildLnnAuditEvent(
947     LnnAuditExtra *lnnAuditExtra, AuthSessionInfo *info, int32_t result, int32_t errCode, SoftbusAuditType auditType)
948 {
949     if (lnnAuditExtra == NULL || info == NULL) {
950         AUTH_LOGE(AUTH_FSM, "lnnAuditExtra or info is null");
951         return;
952     }
953     (void)AuditReportSetPeerDevInfo(lnnAuditExtra, info);
954     (void)AuditReportSetLocalDevInfo(lnnAuditExtra);
955     lnnAuditExtra->result = result;
956     lnnAuditExtra->errCode = errCode;
957     lnnAuditExtra->auditType = auditType;
958     lnnAuditExtra->connId = info->connId;
959     lnnAuditExtra->authLinkType = info->connInfo.type;
960     lnnAuditExtra->authRequestId = info->requestId;
961     (void)LnnGetAllOnlineNodeNum(&(lnnAuditExtra->onlineNum));
962 }
963 
ClientSetExchangeIdType(AuthFsm * authFsm)964 static int32_t ClientSetExchangeIdType(AuthFsm *authFsm)
965 {
966     AuthSessionInfo *info = &authFsm->info;
967     if (info->idType == EXCHANGE_FAIL) {
968         AUTH_LOGE(AUTH_FSM, "fsm switch to reauth due to not find networkId");
969         info->idType = EXCHANGE_UDID;
970         LnnFsmTransactState(&authFsm->fsm, g_states + STATE_SYNC_DEVICE_ID);
971         return SOFTBUS_AUTH_NOT_FOUND;
972     }
973     return SOFTBUS_OK;
974 }
975 
UpdateUdidHashIfEmpty(AuthFsm * authFsm,AuthSessionInfo * info)976 static void UpdateUdidHashIfEmpty(AuthFsm *authFsm, AuthSessionInfo *info)
977 {
978     if (info->connInfo.type == AUTH_LINK_TYPE_BLE && strlen(info->udid) != 0 &&
979         authFsm->info.connInfo.info.bleInfo.deviceIdHash[0] == '\0') {
980         char *anonyUdid = NULL;
981         Anonymize(info->udid, &anonyUdid);
982         AUTH_LOGW(AUTH_FSM, "udidhash is empty, udid=%{public}s", AnonymizeWrapper(anonyUdid));
983         AnonymizeFree(anonyUdid);
984         if (SoftBusGenerateStrHash((unsigned char *)info->udid, strlen(info->udid),
985             (unsigned char *)authFsm->info.connInfo.info.bleInfo.deviceIdHash) != SOFTBUS_OK) {
986             AUTH_LOGE(AUTH_FSM, "generate udidhash fail");
987         }
988     }
989 }
990 
HandleMsgRecvDeviceId(AuthFsm * authFsm,const MessagePara * para)991 static void HandleMsgRecvDeviceId(AuthFsm *authFsm, const MessagePara *para)
992 {
993     int32_t ret = SOFTBUS_OK;
994     AuthSessionInfo *info = &authFsm->info;
995     do {
996         if (ProcessDeviceIdMessage(info, para->data, para->len, authFsm->authSeq) != SOFTBUS_OK) {
997             ret = SOFTBUS_AUTH_SYNC_DEVID_FAIL;
998             LnnAuditExtra lnnAuditExtra = { 0 };
999             BuildLnnAuditEvent(&lnnAuditExtra, info, AUDIT_HANDLE_MSG_FAIL_END_AUTH, ret, AUDIT_EVENT_PACKETS_ERROR);
1000             LNN_AUDIT(AUDIT_SCENE_HANDLE_MSG_DEV_ID, lnnAuditExtra);
1001             break;
1002         }
1003         if (info->connInfo.type == AUTH_LINK_TYPE_BLE && LnnIsNeedInterceptBroadcast(false)) {
1004             ret = SOFTBUS_FUNC_NOT_SUPPORT;
1005             AUTH_LOGI(AUTH_FSM, "not support ble online");
1006             break;
1007         }
1008         UpdateUdidHashIfEmpty(authFsm, info);
1009         if (info->isServer) {
1010             if (PostDeviceIdMessage(authFsm->authSeq, info) != SOFTBUS_OK) {
1011                 ret = SOFTBUS_AUTH_SYNC_DEVID_FAIL;
1012                 break;
1013             }
1014         } else {
1015             if (info->normalizedType == NORMALIZED_NOT_SUPPORT || info->peerState == AUTH_STATE_COMPATIBLE) {
1016                 NotifyNormalizeRequestSuccess(authFsm->authSeq, false);
1017             }
1018         }
1019         LnnFsmTransactState(&authFsm->fsm, g_states + STATE_DEVICE_AUTH);
1020     } while (false);
1021 
1022     if (ret != SOFTBUS_OK) {
1023         AUTH_LOGE(AUTH_FSM, "handle devId msg fail, ret=%{public}d", ret);
1024         CompleteAuthSession(authFsm, ret);
1025     }
1026 }
1027 
LocalAuthStateProc(AuthFsm * authFsm,AuthSessionInfo * info,int32_t * result)1028 static void LocalAuthStateProc(AuthFsm *authFsm, AuthSessionInfo *info, int32_t *result)
1029 {
1030     if (info->localState == AUTH_STATE_START) {
1031         info->isServer = false;
1032         LnnFsmTransactState(&authFsm->fsm, g_states + STATE_SYNC_DEVICE_ID);
1033     } else if (info->localState == AUTH_STATE_ACK) {
1034         info->isServer = true;
1035         *result = PostDeviceIdMessage(authFsm->authSeq, info);
1036         LnnFsmTransactState(&authFsm->fsm, g_states + STATE_DEVICE_AUTH);
1037     } else if (info->localState == AUTH_STATE_WAIT) {
1038         info->isServer = true;
1039         *result = PostDeviceIdMessage(authFsm->authSeq, info);
1040     } else if (info->localState == AUTH_STATE_COMPATIBLE) {
1041         if (info->isServer) {
1042             *result = PostDeviceIdMessage(authFsm->authSeq, info);
1043         }
1044         LnnFsmTransactState(&authFsm->fsm, g_states + STATE_DEVICE_AUTH);
1045     } else if (info->localState == AUTH_STATE_UNKNOW) {
1046         *result = PostDeviceIdMessage(authFsm->authSeq, info);
1047     } else {
1048         AUTH_LOGE(AUTH_FSM, "local auth state error");
1049         *result = SOFTBUS_AUTH_SYNC_DEVID_FAIL;
1050     }
1051 }
1052 
HandleMsgRecvDeviceIdNego(AuthFsm * authFsm,const MessagePara * para)1053 static void HandleMsgRecvDeviceIdNego(AuthFsm *authFsm, const MessagePara *para)
1054 {
1055     int32_t ret = SOFTBUS_OK;
1056     AuthSessionInfo *info = &authFsm->info;
1057     do {
1058         if (ProcessDeviceIdMessage(info, para->data, para->len, authFsm->authSeq) != SOFTBUS_OK) {
1059             ret = SOFTBUS_AUTH_SYNC_DEVID_FAIL;
1060             LnnAuditExtra lnnAuditExtra = { 0 };
1061             BuildLnnAuditEvent(&lnnAuditExtra, info, AUDIT_HANDLE_MSG_FAIL_END_AUTH, ret, AUDIT_EVENT_PACKETS_ERROR);
1062             LNN_AUDIT(AUDIT_SCENE_HANDLE_MSG_DEV_ID, lnnAuditExtra);
1063             break;
1064         }
1065         if (info->connInfo.type == AUTH_LINK_TYPE_BLE && LnnIsNeedInterceptBroadcast(false)) {
1066             ret = SOFTBUS_FUNC_NOT_SUPPORT;
1067             AUTH_LOGI(AUTH_FSM, "not support ble online");
1068             break;
1069         }
1070         UpdateUdidHashIfEmpty(authFsm, info);
1071         if (UpdateLocalAuthState(authFsm->authSeq, &authFsm->info) != SOFTBUS_OK) {
1072             AUTH_LOGE(AUTH_FSM, "update auth state fail, authSeq=%{public}" PRId64, authFsm->authSeq);
1073             return;
1074         }
1075         if (info->peerState == AUTH_STATE_COMPATIBLE) {
1076             NotifyNormalizeRequestSuccess(authFsm->authSeq, false);
1077         }
1078         LocalAuthStateProc(authFsm, info, &ret);
1079     } while (false);
1080     if (ret != SOFTBUS_OK) {
1081         AUTH_LOGE(AUTH_FSM, "handle devId msg fail, ret=%{public}d", ret);
1082         CompleteAuthSession(authFsm, ret);
1083     }
1084 }
1085 
SyncNegotiationStateProcess(FsmStateMachine * fsm,int32_t msgType,void * para)1086 static bool SyncNegotiationStateProcess(FsmStateMachine *fsm, int32_t msgType, void *para)
1087 {
1088     MessagePara *msgPara = (MessagePara *)para;
1089     AuthFsm *authFsm = TranslateToAuthFsm(fsm, msgType, msgPara);
1090     if (authFsm == NULL) {
1091         FreeMessagePara(msgPara);
1092         return false;
1093     }
1094     SoftbusHitraceStart(SOFTBUS_HITRACE_ID_VALID, (uint64_t)authFsm->authSeq);
1095     AUTH_LOGI(AUTH_FSM, "auth fsm process. authSeq=%{public}" PRId64 ", message=%{public}s", authFsm->authSeq,
1096         FsmMsgTypeToStr(msgType));
1097     switch (msgType) {
1098         case FSM_MSG_RECV_DEVICE_ID:
1099             HandleMsgRecvDeviceIdNego(authFsm, msgPara);
1100             break;
1101         case FSM_MSG_DEVICE_POST_DEVICEID:
1102             HandleMsgPostDeviceId(authFsm, msgPara);
1103             break;
1104         default:
1105             HandleCommonMsg(authFsm, msgType, msgPara);
1106             break;
1107     }
1108     FreeMessagePara(msgPara);
1109     SoftbusHitraceStop();
1110     return true;
1111 }
1112 
SyncDevIdStateProcess(FsmStateMachine * fsm,int32_t msgType,void * para)1113 static bool SyncDevIdStateProcess(FsmStateMachine *fsm, int32_t msgType, void *para)
1114 {
1115     MessagePara *msgPara = (MessagePara *)para;
1116     AuthFsm *authFsm = TranslateToAuthFsm(fsm, msgType, msgPara);
1117     if (authFsm == NULL) {
1118         FreeMessagePara(msgPara);
1119         return false;
1120     }
1121     SoftbusHitraceStart(SOFTBUS_HITRACE_ID_VALID, (uint64_t)authFsm->authSeq);
1122     AUTH_LOGI(AUTH_FSM, "auth fsm process. authSeq=%{public}" PRId64 ", message=%{public}s", authFsm->authSeq,
1123         FsmMsgTypeToStr(msgType));
1124     switch (msgType) {
1125         case FSM_MSG_RECV_DEVICE_ID:
1126             HandleMsgRecvDeviceId(authFsm, msgPara);
1127             break;
1128         case FSM_MSG_DEVICE_POST_DEVICEID:
1129             HandleMsgPostDeviceId(authFsm, msgPara);
1130             break;
1131         default:
1132             HandleCommonMsg(authFsm, msgType, msgPara);
1133             break;
1134     }
1135     FreeMessagePara(msgPara);
1136     SoftbusHitraceStop();
1137     return true;
1138 }
1139 
HandleMsgRecvAuthData(AuthFsm * authFsm,const MessagePara * para)1140 static void HandleMsgRecvAuthData(AuthFsm *authFsm, const MessagePara *para)
1141 {
1142     HiChainAuthMode authMode = (authFsm->info.authVersion < AUTH_VERSION_V2) ?
1143         HICHAIN_AUTH_DEVICE : HICHAIN_AUTH_IDENTITY_SERVICE;
1144 
1145 #ifdef DISABLE_IDENTITY_SERVICE
1146     authMode = HICHAIN_AUTH_DEVICE;
1147 #endif
1148     int32_t ret = HichainProcessData(authFsm->authSeq, para->data, para->len, authMode);
1149     if (ret != SOFTBUS_OK) {
1150         LnnAuditExtra lnnAuditExtra = { 0 };
1151         BuildLnnAuditEvent(
1152             &lnnAuditExtra, &authFsm->info, AUDIT_HANDLE_MSG_FAIL_END_AUTH, ret, AUDIT_EVENT_PACKETS_ERROR);
1153         LNN_AUDIT(AUDIT_SCENE_HANDLE_MSG_AUTH_DATA, lnnAuditExtra);
1154         AUTH_LOGE(AUTH_FSM, "process hichain data fail");
1155         if (!authFsm->info.isAuthFinished) {
1156             CompleteAuthSession(authFsm, ret);
1157         } else {
1158             AUTH_LOGD(AUTH_FSM, "auth has finished, ignore this processing failure");
1159         }
1160     }
1161 }
1162 
SoftbusCertChainParallel(const AuthSessionInfo * info)1163 static int32_t SoftbusCertChainParallel(const AuthSessionInfo *info)
1164 {
1165     if (info == NULL || !IsSupportUDIDAbatementPacked() || !info->isNeedPackCert) {
1166         AUTH_LOGI(AUTH_FSM, "device not support udid abatement or no need");
1167         return SOFTBUS_OK;
1168     }
1169     SoftbusCertChain *softbusCertChain = (SoftbusCertChain *)SoftBusCalloc(sizeof(SoftbusCertChain));
1170     if (softbusCertChain == NULL) {
1171         AUTH_LOGI(AUTH_FSM, "malloc gencert parallel node failed. skip");
1172         return SOFTBUS_OK;
1173     }
1174     if (AddAuthGenCertParaNode(info->requestId) != SOFTBUS_OK) {
1175         AUTH_LOGI(AUTH_FSM, "add gencert parallel node failed. skip");
1176     }
1177     if (GenerateCertificatePacked(softbusCertChain, info) != SOFTBUS_OK) {
1178         AUTH_LOGI(AUTH_FSM, "GenerateCertificate fail");
1179         if (UpdateAuthGenCertParaNode(info->requestId, false, softbusCertChain) != SOFTBUS_OK) {
1180             AUTH_LOGI(AUTH_FSM, "update gencert parallel node failed. skip");
1181             FreeSoftbusChainPacked(softbusCertChain);
1182             SoftBusFree(softbusCertChain);
1183         }
1184         return SOFTBUS_OK;
1185     }
1186     if (UpdateAuthGenCertParaNode(info->requestId, true, softbusCertChain) != SOFTBUS_OK) {
1187         AUTH_LOGI(AUTH_FSM, "update gencert parallel node failed. skip");
1188         FreeSoftbusChainPacked(softbusCertChain);
1189         SoftBusFree(softbusCertChain);
1190     }
1191     return SOFTBUS_OK;
1192 }
1193 
TrySyncDeviceInfo(int64_t authSeq,const AuthSessionInfo * info)1194 static int32_t TrySyncDeviceInfo(int64_t authSeq, const AuthSessionInfo *info)
1195 {
1196     switch (info->connInfo.type) {
1197         case AUTH_LINK_TYPE_WIFI:
1198         case AUTH_LINK_TYPE_SESSION_KEY:
1199         case AUTH_LINK_TYPE_USB:
1200             /* WIFI: client firstly send device info, server just reponse it. */
1201             if (!info->isServer) {
1202                 return PostDeviceInfoMessage(authSeq, info);
1203             } else {
1204                 return SoftbusCertChainParallel(info);
1205             }
1206             return SOFTBUS_OK;
1207         case AUTH_LINK_TYPE_BR:
1208         case AUTH_LINK_TYPE_BLE:
1209         case AUTH_LINK_TYPE_SLE:
1210         case AUTH_LINK_TYPE_P2P:
1211         case AUTH_LINK_TYPE_ENHANCED_P2P:
1212         case AUTH_LINK_TYPE_SESSION:
1213             return PostDeviceInfoMessage(authSeq, info);
1214         default:
1215             break;
1216     }
1217     return SOFTBUS_AUTH_CONN_TYPE_INVALID;
1218 }
1219 
HandleMsgAuthError(AuthFsm * authFsm,const MessagePara * para)1220 static void HandleMsgAuthError(AuthFsm *authFsm, const MessagePara *para)
1221 {
1222     int32_t result = *((int32_t *)(para->data));
1223     AUTH_LOGE(AUTH_FSM, "auth fsm handle hichain error, authSeq=%{public}" PRId64 ", reason=%{public}d",
1224         authFsm->authSeq, result);
1225     if (result == HICHAIN_RETURN_NOT_TRUSTED) {
1226         AUTH_LOGE(AUTH_FSM, "device not has trust relation, begin to offline");
1227         AuthDeviceNotTrust(authFsm->info.udid);
1228     }
1229     CompleteAuthSession(authFsm, result);
1230 }
1231 
HandleMsgRecvDevInfoEarly(AuthFsm * authFsm,const MessagePara * para)1232 static void HandleMsgRecvDevInfoEarly(AuthFsm *authFsm, const MessagePara *para)
1233 {
1234     AUTH_LOGI(AUTH_FSM, "auth fsm recv device info early, save it. authSeq=%{public}" PRId64 "", authFsm->authSeq);
1235     AuthSessionInfo *info = &authFsm->info;
1236     if (info->deviceInfoData != NULL) {
1237         SoftBusFree(info->deviceInfoData);
1238         info->deviceInfoData = NULL;
1239     }
1240     info->deviceInfoData = DupMemBuffer(para->data, para->len);
1241     if (info->deviceInfoData == NULL) {
1242         AUTH_LOGE(AUTH_FSM, "dup device info fail.");
1243         return;
1244     }
1245     info->deviceInfoDataLen = para->len;
1246 }
1247 
TryFinishAuthSession(AuthFsm * authFsm)1248 static void TryFinishAuthSession(AuthFsm *authFsm)
1249 {
1250     AuthSessionInfo *info = &authFsm->info;
1251     AUTH_LOGI(AUTH_FSM,
1252         "Try finish auth fsm session, authSeq=%{public}" PRId64", devInfo=%{public}d, closeAck=%{public}d, "
1253         "authFinish=%{public}d",
1254         authFsm->authSeq, info->isNodeInfoReceived, info->isCloseAckReceived, info->isAuthFinished);
1255     if (info->isNodeInfoReceived && info->isCloseAckReceived && info->isAuthFinished) {
1256         CompleteAuthSession(authFsm, SOFTBUS_OK);
1257     }
1258 }
1259 
HandleMsgAuthFinish(AuthFsm * authFsm,MessagePara * para)1260 static void HandleMsgAuthFinish(AuthFsm *authFsm, MessagePara *para)
1261 {
1262     AclWriteState aclState = *((AclWriteState *)(para->data));
1263     AuthSessionInfo *info = &authFsm->info;
1264     AUTH_LOGI(AUTH_FSM,
1265         "auth fsm hichain finished, authSeq=%{public}" PRId64", devInfo=%{public}d, closeAck=%{public}d, "
1266         "aclState=%{public}d",
1267         authFsm->authSeq, info->isNodeInfoReceived, info->isCloseAckReceived, aclState);
1268     info->isAuthFinished = true;
1269     info->nodeInfo.aclState = aclState;
1270     TryFinishAuthSession(authFsm);
1271 }
1272 
TryRecoveryKey(AuthFsm * authFsm)1273 static int32_t TryRecoveryKey(AuthFsm *authFsm)
1274 {
1275     int32_t ret = SOFTBUS_OK;
1276     if (authFsm->info.normalizedType == NORMALIZED_SUPPORT) {
1277         AUTH_LOGI(AUTH_FSM, "normalized auth succ");
1278         if (RecoveryNormalizedDeviceKey(authFsm) != SOFTBUS_OK) {
1279             AUTH_LOGE(AUTH_FSM, "normalized auth recovery device key fail");
1280             ret = SOFTBUS_AUTH_SYNC_DEVID_FAIL;
1281         }
1282         return ret;
1283     }
1284     if (authFsm->info.isSupportFastAuth) {
1285         AUTH_LOGI(AUTH_FSM, "fast auth succ");
1286         if (RecoveryFastAuthKey(authFsm) != SOFTBUS_OK) {
1287             AUTH_LOGE(AUTH_FSM, "fast auth recovery device key fail");
1288             ret = SOFTBUS_AUTH_SYNC_DEVID_FAIL;
1289         }
1290     }
1291     return ret;
1292 }
1293 
PopulateDeviceTypeId(HiChainAuthParam * authParam,uint32_t requestId)1294 static void PopulateDeviceTypeId(HiChainAuthParam *authParam, uint32_t requestId)
1295 {
1296     AuthRequest request;
1297     (void)memset_s(&request, sizeof(AuthRequest), 0, sizeof(AuthRequest));
1298     if (GetAuthRequest(requestId, &request) == SOFTBUS_OK) {
1299         if (request.deviceTypeId == TYPE_PC_ID) {
1300             authParam->deviceTypeId = request.deviceTypeId;
1301             AUTH_LOGI(AUTH_FSM, "get deviceTypeId from auth request success");
1302             return;
1303         }
1304     }
1305     NodeInfo nodeInfoLedger;
1306     (void)memset_s(&nodeInfoLedger, sizeof(NodeInfo), 0, sizeof(NodeInfo));
1307     if (LnnGetRemoteNodeInfoById(authParam->udid, CATEGORY_UDID, &nodeInfoLedger) == SOFTBUS_OK) {
1308         if (nodeInfoLedger.deviceInfo.deviceTypeId == TYPE_PC_ID) {
1309             authParam->deviceTypeId = nodeInfoLedger.deviceInfo.deviceTypeId;
1310             AUTH_LOGI(AUTH_FSM, "get deviceTypeId from deviceInfo success");
1311             return;
1312         }
1313     }
1314     NodeInfo nodeInfoPersistent;
1315     (void)memset_s(&nodeInfoPersistent, sizeof(NodeInfo), 0, sizeof(NodeInfo));
1316     if (LnnRetrieveDeviceInfoByUdidPacked(authParam->udid, &nodeInfoPersistent) == SOFTBUS_OK) {
1317         if (nodeInfoPersistent.deviceInfo.deviceTypeId == TYPE_PC_ID) {
1318             authParam->deviceTypeId = nodeInfoPersistent.deviceInfo.deviceTypeId;
1319             AUTH_LOGI(AUTH_FSM, "get deviceTypeId from persistent deviceInfo success");
1320             return;
1321         }
1322     }
1323     AUTH_LOGI(AUTH_FSM, "not setting deviceTypeId");
1324 }
1325 
ProcessClientAuthState(AuthFsm * authFsm)1326 static int32_t ProcessClientAuthState(AuthFsm *authFsm)
1327 {
1328     HiChainAuthParam authParam;
1329     HiChainAuthMode authMode = (authFsm->info.authVersion < AUTH_VERSION_V2) ?
1330         HICHAIN_AUTH_DEVICE : HICHAIN_AUTH_IDENTITY_SERVICE;
1331 
1332 #ifdef DISABLE_IDENTITY_SERVICE
1333     authMode = HICHAIN_AUTH_DEVICE;
1334 #endif
1335     (void)memset_s(&authParam, sizeof(HiChainAuthParam), 0, sizeof(HiChainAuthParam));
1336     /* just client need start authDevice */
1337     if (ClientSetExchangeIdType(authFsm) != SOFTBUS_OK) {
1338         return SOFTBUS_OK;
1339     }
1340     char *anonyUdid = NULL;
1341     Anonymize(authFsm->info.udid, &anonyUdid);
1342     AUTH_LOGI(AUTH_FSM, "start auth send udid=%{public}s peerUserId=%{public}d", AnonymizeWrapper(anonyUdid),
1343         authFsm->info.userId);
1344     AnonymizeFree(anonyUdid);
1345     if (strcpy_s(authParam.udid, UDID_BUF_LEN, authFsm->info.udid) != EOK ||
1346         strcpy_s(authParam.uid, MAX_ACCOUNT_HASH_LEN, authFsm->info.connInfo.peerUid) != EOK ||
1347         (authFsm->info.credId != NULL && strcpy_s(authParam.credId, MAX_CRED_ID_SIZE, authFsm->info.credId) != EOK)) {
1348         AUTH_LOGE(AUTH_FSM, "copy authParam fail");
1349         return SOFTBUS_STRCPY_ERR;
1350     }
1351     authParam.userId = authFsm->info.userId;
1352     authParam.cb = NULL;
1353     PopulateDeviceTypeId(&authParam, authFsm->info.requestId);
1354     return HichainStartAuth(authFsm->authSeq, &authParam, authMode);
1355 }
1356 
DeviceAuthStateEnter(FsmStateMachine * fsm)1357 static void DeviceAuthStateEnter(FsmStateMachine *fsm)
1358 {
1359     if (fsm == NULL) {
1360         AUTH_LOGE(AUTH_FSM, "fsm is null");
1361         return;
1362     }
1363     int32_t ret = SOFTBUS_OK;
1364     AuthFsm *authFsm = TO_AUTH_FSM(fsm);
1365     if (authFsm == NULL) {
1366         AUTH_LOGE(AUTH_FSM, "authFsm is null");
1367         return;
1368     }
1369     AUTH_LOGI(AUTH_FSM, "auth state enter, authSeq=%{public}" PRId64, authFsm->authSeq);
1370     authFsm->curState = STATE_DEVICE_AUTH;
1371     AuthSessionInfo *info = &authFsm->info;
1372     if (info->normalizedType == NORMALIZED_SUPPORT || info->isSupportFastAuth) {
1373         ret = TryRecoveryKey(authFsm);
1374         if (ret != SOFTBUS_OK) {
1375             goto ERR_EXIT;
1376         }
1377         return;
1378     }
1379     if (!info->isServer) {
1380         ret = ProcessClientAuthState(authFsm);
1381     }
1382     if (ret != SOFTBUS_OK) {
1383         goto ERR_EXIT;
1384     }
1385     return;
1386 ERR_EXIT:
1387     AUTH_LOGE(AUTH_FSM, "auth state enter, fail ret=%{public}d", ret);
1388     CompleteAuthSession(authFsm, ret);
1389 }
1390 
DeviceAuthStateProcess(FsmStateMachine * fsm,int32_t msgType,void * para)1391 static bool DeviceAuthStateProcess(FsmStateMachine *fsm, int32_t msgType, void *para)
1392 {
1393     MessagePara *msgPara = (MessagePara *)para;
1394     AuthFsm *authFsm = TranslateToAuthFsm(fsm, msgType, msgPara);
1395     if (authFsm == NULL) {
1396         FreeMessagePara(msgPara);
1397         return false;
1398     }
1399     SoftbusHitraceStart(SOFTBUS_HITRACE_ID_VALID, (uint64_t)authFsm->authSeq);
1400     AUTH_LOGI(AUTH_FSM, "auth fsm process. authSeq=%{public}" PRId64 ", message=%{public}s", authFsm->authSeq,
1401         FsmMsgTypeToStr(msgType));
1402     switch (msgType) {
1403         case FSM_MSG_RECV_DEVICE_ID:
1404             HandleMsgRecvDeviceId(authFsm, msgPara);
1405             break;
1406         case FSM_MSG_RECV_AUTH_DATA:
1407             HandleMsgRecvAuthData(authFsm, msgPara);
1408             break;
1409         case FSM_MSG_SAVE_SESSION_KEY:
1410             HandleMsgSaveSessionKey(authFsm, msgPara);
1411             break;
1412         case FSM_MSG_AUTH_ERROR:
1413             HandleMsgAuthError(authFsm, msgPara);
1414             break;
1415         case FSM_MSG_RECV_DEVICE_INFO:
1416             HandleMsgRecvDevInfoEarly(authFsm, msgPara);
1417             break;
1418         case FSM_MSG_AUTH_FINISH:
1419             HandleMsgAuthFinish(authFsm, msgPara);
1420             break;
1421         default:
1422             HandleCommonMsg(authFsm, msgType, msgPara);
1423             break;
1424     }
1425     FreeMessagePara(msgPara);
1426     SoftbusHitraceStop();
1427     return true;
1428 }
1429 
HandleCloseAckMessage(AuthFsm * authFsm,const AuthSessionInfo * info)1430 static int32_t HandleCloseAckMessage(AuthFsm *authFsm, const AuthSessionInfo *info)
1431 {
1432     if ((info->connInfo.type == AUTH_LINK_TYPE_BLE) && (SoftBusGetBrState() == BR_DISABLE) &&
1433         (info->nodeInfo.feature & 1 << BIT_SUPPORT_THREE_STATE) == 0) {
1434         AUTH_LOGE(AUTH_FSM, "peer not support three state");
1435         CompleteAuthSession(authFsm, SOFTBUS_AUTH_NOT_SUPPORT_THREE_STATE);
1436         return SOFTBUS_NETWORK_NOT_SUPPORT;
1437     }
1438     if (PostCloseAckMessage(authFsm->authSeq, info) != SOFTBUS_OK) {
1439         AUTH_LOGE(AUTH_FSM, "post close ack fail");
1440         CompleteAuthSession(authFsm, SOFTBUS_AUTH_SEND_FAIL);
1441         return SOFTBUS_AUTH_SYNC_DEVINFO_ACK_FAIL;
1442     }
1443     return SOFTBUS_OK;
1444 }
1445 
GetAuthFsmByRequestId(uint64_t requestId)1446 static AuthFsm *GetAuthFsmByRequestId(uint64_t requestId)
1447 {
1448     AuthFsm *item = NULL;
1449     LIST_FOR_EACH_ENTRY(item, &g_authFsmList, AuthFsm, node) {
1450         if (item->info.requestId == requestId) {
1451             return item;
1452         }
1453     }
1454     AUTH_LOGE(AUTH_FSM, "auth fsm not found. ");
1455     return NULL;
1456 }
1457 
OnPtkSyncCallBackLooper(void * voidPtkCbParam)1458 static void OnPtkSyncCallBackLooper(void *voidPtkCbParam)
1459 {
1460     if (voidPtkCbParam == NULL) {
1461         AUTH_LOGE(AUTH_FSM, "get invalid param");
1462         return;
1463     }
1464     OnPtkSyncCallBackParam *ptkCbParam = (OnPtkSyncCallBackParam *)voidPtkCbParam;
1465     if (!RequireAuthLock()) {
1466         SoftBusFree(ptkCbParam);
1467         AUTH_LOGE(AUTH_FSM, "require auth lock fail");
1468         return;
1469     }
1470     AuthPreLinkNode reuseKeyNode;
1471     (void)memset_s(&reuseKeyNode, sizeof(AuthPreLinkNode), 0, sizeof(AuthPreLinkNode));
1472     if (FindAuthPreLinkNodeByUuid(ptkCbParam->uuid, &reuseKeyNode) != SOFTBUS_OK) {
1473         ReleaseAuthLock();
1474         SoftBusFree(ptkCbParam);
1475         AUTH_LOGE(AUTH_FSM, "auth reuse devicekey not found");
1476         return;
1477     }
1478     AuthFsm *authFsm = GetAuthFsmByRequestId(reuseKeyNode.requestId);
1479     if (authFsm == NULL) {
1480         ReleaseAuthLock();
1481         SoftBusFree(ptkCbParam);
1482         AUTH_LOGE(AUTH_FSM, "auth fsm not found");
1483         return;
1484     }
1485     AuthSessionInfo *info = &authFsm->info;
1486     if (ptkCbParam->result != SOFTBUS_OK) {
1487         AUTH_LOGE(AUTH_FSM, "sync ptk fail");
1488         ReleaseAuthLock();
1489         SoftBusFree(ptkCbParam);
1490         CompleteAuthSession(authFsm, SOFTBUS_AUTH_SYNC_PTK_ERR);
1491         return;
1492     }
1493     ReleaseAuthLock();
1494     SoftBusFree(ptkCbParam);
1495     AuthManagerSetAuthPassed(authFsm->authSeq, info);
1496     TryFinishAuthSession(authFsm);
1497 }
1498 
OnPtkSyncCallBack(const char * uuid,int32_t result)1499 static void OnPtkSyncCallBack(const char *uuid, int32_t result)
1500 {
1501     if (uuid == NULL) {
1502         AUTH_LOGE(AUTH_FSM, "get invalid param");
1503         return;
1504     }
1505     OnPtkSyncCallBackParam *ptkCbParam = (OnPtkSyncCallBackParam *)SoftBusCalloc(sizeof(OnPtkSyncCallBackParam));
1506     if (ptkCbParam == NULL) {
1507         AUTH_LOGE(AUTH_FSM, "malloc ptkCbParam fail");
1508         return;
1509     }
1510     if (memcpy_s(ptkCbParam->uuid, UUID_BUF_LEN, uuid, UUID_BUF_LEN) != EOK) {
1511         AUTH_LOGE(AUTH_FSM, "memcpy uuid fail");
1512         SoftBusFree(ptkCbParam);
1513         return;
1514     }
1515     ptkCbParam->result = result;
1516     int32_t ret = LnnAsyncCallbackHelper(GetLooper(LOOP_TYPE_DEFAULT), OnPtkSyncCallBackLooper, (void *)ptkCbParam);
1517     if (ret != SOFTBUS_OK) {
1518         AUTH_LOGE(AUTH_FSM, "LnnAsyncCallbackHelper call error");
1519         SoftBusFree(ptkCbParam);
1520     }
1521 }
1522 
TrySyncPtkClient(AuthSessionInfo * info)1523 static void TrySyncPtkClient(AuthSessionInfo *info)
1524 {
1525     struct WifiDirectManager *wdMgr = GetWifiDirectManager();
1526     if (wdMgr == NULL) {
1527         AUTH_LOGE(AUTH_FSM, "get wifiDirect mgr fail");
1528         return;
1529     }
1530     char localPtk[PTK_DEFAULT_LEN] = { 0 };
1531     char ptk[PTK_STR_LEN] = { 0 };
1532     if (LnnGetLocalPtkByUuidPacked(info->uuid, localPtk, PTK_DEFAULT_LEN) != SOFTBUS_OK) {
1533         AUTH_LOGE(AUTH_FSM, "get ptk by uuid fail");
1534         (void)memset_s(localPtk, PTK_DEFAULT_LEN, 0, PTK_DEFAULT_LEN);
1535         return;
1536     }
1537     if (ConvertBytesToHexString(ptk, PTK_STR_LEN, (unsigned char *)localPtk,
1538         PTK_32_BIT_LEN) != SOFTBUS_OK) {
1539         AUTH_LOGE(AUTH_FSM, "convert ptk fail");
1540         (void)memset_s(localPtk, PTK_DEFAULT_LEN, 0, PTK_DEFAULT_LEN);
1541         (void)memset_s(ptk, PTK_STR_LEN, 0, PTK_STR_LEN);
1542     }
1543     SyncPtkListener listener = OnPtkSyncCallBack;
1544     wdMgr->addSyncPtkListener(listener);
1545     if (wdMgr->savePTK(info->uuid, ptk) != SOFTBUS_OK) {
1546         AUTH_LOGE(AUTH_FSM, "client save ptk fail");
1547         (void)memset_s(localPtk, PTK_DEFAULT_LEN, 0, PTK_DEFAULT_LEN);
1548         (void)memset_s(ptk, PTK_STR_LEN, 0, PTK_STR_LEN);
1549         return;
1550     }
1551     AUTH_LOGI(AUTH_FSM, "try sync ptk");
1552     (void)memset_s(localPtk, PTK_DEFAULT_LEN, 0, PTK_DEFAULT_LEN);
1553     (void)memset_s(ptk, PTK_STR_LEN, 0, PTK_STR_LEN);
1554     if (wdMgr->syncPTK(info->uuid) != SOFTBUS_OK) {
1555         AUTH_LOGE(AUTH_FSM, "client sync ptk fail");
1556     }
1557 }
1558 
TrySavePtkServer(AuthSessionInfo * info)1559 static void TrySavePtkServer(AuthSessionInfo *info)
1560 {
1561     char ptk[PTK_STR_LEN] = { 0 };
1562     struct WifiDirectManager *wdMgr = GetWifiDirectManager();
1563     if (wdMgr == NULL) {
1564         AUTH_LOGE(AUTH_FSM, "get wifiDirect mgr fail");
1565         return;
1566     }
1567     if (ConvertBytesToHexString(ptk, PTK_STR_LEN, (unsigned char *)info->nodeInfo.remotePtk,
1568         PTK_32_BIT_LEN) != SOFTBUS_OK) {
1569         AUTH_LOGE(AUTH_FSM, "client save ptk fail");
1570         (void)memset_s(ptk, PTK_STR_LEN, 0, PTK_STR_LEN);
1571     }
1572     if (wdMgr->savePTK(info->uuid, ptk) != SOFTBUS_OK) {
1573         AUTH_LOGE(AUTH_FSM, "server save ptk fail");
1574     }
1575     (void)memset_s(ptk, PTK_STR_LEN, 0, PTK_STR_LEN);
1576 }
1577 
TryAddSyncPtkListenerServer(void)1578 static void TryAddSyncPtkListenerServer(void)
1579 {
1580     struct WifiDirectManager *wdMgr = GetWifiDirectManager();
1581     if (wdMgr == NULL) {
1582         AUTH_LOGE(AUTH_FSM, "get wifiDirect mgr fail");
1583         return;
1584     }
1585     AUTH_LOGI(AUTH_FSM, "wait to ptk sync");
1586     SyncPtkListener listener = OnPtkSyncCallBack;
1587     wdMgr->addSyncPtkListener(listener);
1588 }
1589 
TryCompleteAuthSessionForError(AuthFsm * authFsm,AuthSessionInfo * info)1590 static void TryCompleteAuthSessionForError(AuthFsm *authFsm, AuthSessionInfo *info)
1591 {
1592     LnnAuditExtra lnnAuditExtra = { 0 };
1593     BuildLnnAuditEvent(&lnnAuditExtra, info, AUDIT_HANDLE_MSG_FAIL_END_AUTH, SOFTBUS_AUTH_UNPACK_DEVINFO_FAIL,
1594         AUDIT_EVENT_PACKETS_ERROR);
1595     LNN_AUDIT(AUDIT_SCENE_HANDLE_MSG_DEV_INFO, lnnAuditExtra);
1596     AUTH_LOGE(AUTH_FSM, "process device info msg fail");
1597     CompleteAuthSession(authFsm, SOFTBUS_AUTH_UNPACK_DEVINFO_FAIL);
1598 }
1599 
ClientTryCompleteAuthSession(AuthFsm * authFsm,AuthSessionInfo * info)1600 static void ClientTryCompleteAuthSession(AuthFsm *authFsm, AuthSessionInfo *info)
1601 {
1602     LnnFsmRemoveMessage(&authFsm->fsm, FSM_MSG_AUTH_TIMEOUT);
1603     if (IsAuthPreLinkNodeExist(info->requestId)) {
1604         TrySyncPtkClient(info);
1605         return;
1606     }
1607     AuthManagerSetAuthPassed(authFsm->authSeq, info);
1608     TryFinishAuthSession(authFsm);
1609 }
1610 
TryRefreshAuthPreLinkInfo(AuthSessionInfo * info)1611 static void TryRefreshAuthPreLinkInfo(AuthSessionInfo *info)
1612 {
1613     if (IsAuthPreLinkNodeExist(info->requestId)) {
1614         GetWifiDirectManager()->refreshRelationShip(info->uuid, info->nodeInfo.wifiDirectAddr);
1615         if (TryUpdateLaneResourceLaneId(info) != SOFTBUS_OK) {
1616             AUTH_LOGE(AUTH_FSM, "update lane resource laneid fail");
1617         }
1618         UpdateAuthPreLinkUuidById(info->requestId, info->uuid);
1619     }
1620 }
1621 
HandleMsgRecvDeviceInfo(AuthFsm * authFsm,const MessagePara * para)1622 static void HandleMsgRecvDeviceInfo(AuthFsm *authFsm, const MessagePara *para)
1623 {
1624     AuthSessionInfo *info = &authFsm->info;
1625     if (ProcessDeviceInfoMessage(authFsm->authSeq, info, para->data, para->len) != SOFTBUS_OK) {
1626         TryCompleteAuthSessionForError(authFsm, info);
1627         return;
1628     }
1629     TryRefreshAuthPreLinkInfo(info);
1630     info->isNodeInfoReceived = true;
1631     if (strcpy_s(info->nodeInfo.uuid, UUID_BUF_LEN, info->uuid) != EOK) {
1632         AUTH_LOGE(AUTH_FSM, "copy uuid fail.");
1633         return;
1634     }
1635     if (info->connInfo.type == AUTH_LINK_TYPE_WIFI || info->connInfo.type == AUTH_LINK_TYPE_SESSION_KEY ||
1636         info->connInfo.type == AUTH_LINK_TYPE_USB) {
1637         info->isCloseAckReceived = true; /* WiFi auth no need close ack, set true directly */
1638         if (!info->isServer) {
1639             ClientTryCompleteAuthSession(authFsm, info);
1640             return;
1641         }
1642         if (IsAuthPreLinkNodeExist(info->requestId)) {
1643             TrySavePtkServer(info);
1644         }
1645         /* WIFI: server should response device info */
1646         if (PostDeviceInfoMessage(authFsm->authSeq, info) != SOFTBUS_OK) {
1647             AUTH_LOGE(AUTH_FSM, "server: response device info fail");
1648             CompleteAuthSession(authFsm, SOFTBUS_AUTH_SYNC_DEVINFO_FAIL);
1649             return;
1650         }
1651         LnnFsmRemoveMessage(&authFsm->fsm, FSM_MSG_AUTH_TIMEOUT);
1652         if (IsAuthPreLinkNodeExist(info->requestId)) {
1653             TryAddSyncPtkListenerServer();
1654             return;
1655         }
1656         AuthManagerSetAuthPassed(authFsm->authSeq, info);
1657         TryFinishAuthSession(authFsm);
1658         return;
1659     }
1660     if (HandleCloseAckMessage(authFsm, info) != SOFTBUS_OK) {
1661         AUTH_LOGE(AUTH_FSM, "handle close ack fail");
1662         return;
1663     }
1664     if (info->isCloseAckReceived) {
1665         LnnFsmRemoveMessage(&authFsm->fsm, FSM_MSG_AUTH_TIMEOUT);
1666         AuthManagerSetAuthPassed(authFsm->authSeq, info);
1667         TryFinishAuthSession(authFsm);
1668     }
1669 }
1670 
HandleMsgRecvCloseAck(AuthFsm * authFsm,MessagePara * para)1671 static void HandleMsgRecvCloseAck(AuthFsm *authFsm, MessagePara *para)
1672 {
1673     (void)para;
1674     AuthSessionInfo *info = &authFsm->info;
1675     AUTH_LOGI(AUTH_FSM, "auth fsm recv close ack, fsm=%{public}" PRId64 ", isNodeInfoReceived=%{public}d",
1676         authFsm->authSeq, info->isNodeInfoReceived);
1677     info->isCloseAckReceived = true;
1678     if (info->isNodeInfoReceived) {
1679         LnnFsmRemoveMessage(&authFsm->fsm, FSM_MSG_AUTH_TIMEOUT);
1680         AuthManagerSetAuthPassed(authFsm->authSeq, info);
1681     } else {
1682         AUTH_LOGI(AUTH_FSM, "close ack received before device info");
1683     }
1684     TryFinishAuthSession(authFsm);
1685 }
1686 
SyncDevInfoStateProcess(FsmStateMachine * fsm,int32_t msgType,void * para)1687 static bool SyncDevInfoStateProcess(FsmStateMachine *fsm, int32_t msgType, void *para)
1688 {
1689     MessagePara *msgPara = (MessagePara *)para;
1690     AuthFsm *authFsm = TranslateToAuthFsm(fsm, msgType, msgPara);
1691     if (authFsm == NULL) {
1692         FreeMessagePara(msgPara);
1693         return false;
1694     }
1695     SoftbusHitraceStart(SOFTBUS_HITRACE_ID_VALID, (uint64_t)authFsm->authSeq);
1696     AUTH_LOGI(AUTH_FSM, "auth fsm process. authSeq=%{public}" PRId64", message=%{public}s",
1697         authFsm->authSeq, FsmMsgTypeToStr(msgType));
1698     switch (msgType) {
1699         case FSM_MSG_RECV_DEVICE_INFO:
1700             HandleMsgRecvDeviceInfo(authFsm, msgPara);
1701             break;
1702         case FSM_MSG_RECV_CLOSE_ACK:
1703             HandleMsgRecvCloseAck(authFsm, msgPara);
1704             break;
1705         case FSM_MSG_RECV_AUTH_DATA:
1706             HandleMsgRecvAuthData(authFsm, msgPara);
1707             break;
1708         case FSM_MSG_AUTH_FINISH:
1709             HandleMsgAuthFinish(authFsm, msgPara);
1710             break;
1711         default:
1712             HandleCommonMsg(authFsm, msgType, msgPara);
1713             break;
1714     }
1715     FreeMessagePara(msgPara);
1716     SoftbusHitraceStop();
1717     return true;
1718 }
1719 
GetAuthFsmByAuthSeq(int64_t authSeq)1720 AuthFsm *GetAuthFsmByAuthSeq(int64_t authSeq)
1721 {
1722     AuthFsm *item = NULL;
1723     LIST_FOR_EACH_ENTRY(item, &g_authFsmList, AuthFsm, node) {
1724         if (item->authSeq != authSeq) {
1725             continue;
1726         }
1727         if (item->isDead) {
1728             AUTH_LOGE(AUTH_FSM, "auth fsm has dead. authSeq=%{public}" PRId64 "", item->authSeq);
1729             break;
1730         }
1731         return item;
1732     }
1733     AUTH_LOGE(AUTH_FSM, "auth fsm not found. authSeq=%{public}" PRId64 "", authSeq);
1734     return NULL;
1735 }
1736 
GetAuthFsmByConnId(uint64_t connId,bool isServer,bool isConnectSide)1737 AuthFsm *GetAuthFsmByConnId(uint64_t connId, bool isServer, bool isConnectSide)
1738 {
1739     AuthFsm *item = NULL;
1740     LIST_FOR_EACH_ENTRY(item, &g_authFsmList, AuthFsm, node) {
1741         if (isConnectSide && (item->info.connId != connId || item->info.isConnectServer != isServer)) {
1742             continue;
1743         }
1744         if (!isConnectSide && (item->info.connId != connId || item->info.isServer != isServer)) {
1745             continue;
1746         }
1747         if (item->isDead) {
1748             AUTH_LOGE(AUTH_FSM, "auth fsm has dead. authSeq=%{public}" PRId64 "", item->authSeq);
1749             break;
1750         }
1751         return item;
1752     }
1753     AUTH_LOGE(AUTH_FSM, "auth fsm not found. " CONN_INFO, CONN_DATA(connId));
1754     return NULL;
1755 }
1756 
GetSessionInfoFromAuthFsm(int64_t authSeq,AuthSessionInfo * info)1757 static int32_t GetSessionInfoFromAuthFsm(int64_t authSeq, AuthSessionInfo *info)
1758 {
1759     if (!RequireAuthLock()) {
1760         return SOFTBUS_LOCK_ERR;
1761     }
1762     AuthFsm *authFsm = GetAuthFsmByAuthSeq(authSeq);
1763     if (authFsm == NULL) {
1764         AUTH_LOGE(AUTH_FSM, "auth fsm not found. authSeq=%{public}" PRId64 "", authSeq);
1765         ReleaseAuthLock();
1766         return SOFTBUS_AUTH_NOT_FOUND;
1767     }
1768     *info = authFsm->info;
1769     info->deviceInfoData = NULL;
1770     info->deviceInfoDataLen = 0;
1771     ReleaseAuthLock();
1772     return SOFTBUS_OK;
1773 }
1774 
PostMessageToAuthFsm(int32_t msgType,int64_t authSeq,const uint8_t * data,uint32_t len)1775 static int32_t PostMessageToAuthFsm(int32_t msgType, int64_t authSeq, const uint8_t *data, uint32_t len)
1776 {
1777     MessagePara *para = NewMessagePara(data, len);
1778     if (para == NULL) {
1779         return SOFTBUS_MALLOC_ERR;
1780     }
1781     if (!RequireAuthLock()) {
1782         SoftBusFree(para);
1783         return SOFTBUS_LOCK_ERR;
1784     }
1785     AuthFsm *authFsm = GetAuthFsmByAuthSeq(authSeq);
1786     if (authFsm == NULL) {
1787         ReleaseAuthLock();
1788         SoftBusFree(para);
1789         return SOFTBUS_AUTH_GET_FSM_FAIL;
1790     }
1791     if (LnnFsmPostMessage(&authFsm->fsm, msgType, para) != SOFTBUS_OK) {
1792         AUTH_LOGE(AUTH_FSM, "post message to auth fsm fail");
1793         ReleaseAuthLock();
1794         SoftBusFree(para);
1795         return SOFTBUS_AUTH_SEND_FAIL;
1796     }
1797     ReleaseAuthLock();
1798     return SOFTBUS_OK;
1799 }
1800 
PostMessageToAuthFsmByConnId(int32_t msgType,uint64_t connId,bool isServer,const uint8_t * data,uint32_t len)1801 static int32_t PostMessageToAuthFsmByConnId(
1802     int32_t msgType, uint64_t connId, bool isServer, const uint8_t *data, uint32_t len)
1803 {
1804     MessagePara *para = NewMessagePara(data, len);
1805     if (para == NULL) {
1806         return SOFTBUS_MALLOC_ERR;
1807     }
1808     if (!RequireAuthLock()) {
1809         SoftBusFree(para);
1810         return SOFTBUS_LOCK_ERR;
1811     }
1812     AuthFsm *authFsm = GetAuthFsmByConnId(connId, isServer, false);
1813     if (authFsm == NULL) {
1814         ReleaseAuthLock();
1815         SoftBusFree(para);
1816         return SOFTBUS_AUTH_GET_FSM_FAIL;
1817     }
1818     if (LnnFsmPostMessage(&authFsm->fsm, msgType, para) != SOFTBUS_OK) {
1819         AUTH_LOGE(AUTH_FSM, "post message to auth fsm by connId fail");
1820         ReleaseAuthLock();
1821         SoftBusFree(para);
1822         return SOFTBUS_AUTH_SEND_FAIL;
1823     }
1824     ReleaseAuthLock();
1825     return SOFTBUS_OK;
1826 }
1827 
SetAuthStartTime(AuthFsm * authFsm)1828 static void SetAuthStartTime(AuthFsm *authFsm)
1829 {
1830     authFsm->statisticData.startAuthTime = (uint64_t)LnnUpTimeMs();
1831 }
1832 
IsPeerSupportNegoAuth(AuthSessionInfo * info)1833 static bool IsPeerSupportNegoAuth(AuthSessionInfo *info)
1834 {
1835     char udidHash[SHORT_UDID_HASH_HEX_LEN + 1] = { 0 };
1836     if (!GetUdidShortHash(info, udidHash, SHORT_UDID_HASH_HEX_LEN + 1)) {
1837         return true;
1838     }
1839     NodeInfo nodeInfo;
1840     (void)memset_s(&nodeInfo, sizeof(nodeInfo), 0, sizeof(nodeInfo));
1841     if (LnnRetrieveDeviceInfoPacked((const char *)udidHash, &nodeInfo) != SOFTBUS_OK) {
1842         AUTH_LOGE(AUTH_FSM, "retrive deviceInfo fail");
1843         return true;
1844     }
1845     if (IsSupportFeatureByCapaBit(nodeInfo.authCapacity, BIT_SUPPORT_NEGOTIATION_AUTH)) {
1846         return true;
1847     }
1848     return false;
1849 }
1850 
GetFirstFsmState(AuthSessionInfo * info,int64_t authSeq,AuthFsmStateIndex * state)1851 static int32_t GetFirstFsmState(AuthSessionInfo *info, int64_t authSeq, AuthFsmStateIndex *state)
1852 {
1853     CHECK_NULL_PTR_RETURN_VALUE(info, SOFTBUS_INVALID_PARAM);
1854     CHECK_NULL_PTR_RETURN_VALUE(state, SOFTBUS_INVALID_PARAM);
1855     if (info->isConnectServer) {
1856         *state = STATE_SYNC_NEGOTIATION;
1857     } else {
1858         if (!IsPeerSupportNegoAuth(info)) {
1859             info->localState = AUTH_STATE_COMPATIBLE;
1860             AUTH_LOGI(AUTH_FSM, "peer not support nego, localState change, authSeq=%{public}" PRId64, authSeq);
1861         }
1862         if (info->localState == AUTH_STATE_START || info->localState == AUTH_STATE_COMPATIBLE) {
1863             *state = STATE_SYNC_DEVICE_ID;
1864         } else {
1865             *state = STATE_SYNC_NEGOTIATION;
1866         }
1867     }
1868     return SOFTBUS_OK;
1869 }
1870 
AuthSessionStartAuth(const AuthParam * authParam,const AuthConnInfo * connInfo,const DeviceKeyId * deviceKeyId)1871 int32_t AuthSessionStartAuth(const AuthParam *authParam, const AuthConnInfo *connInfo, const DeviceKeyId *deviceKeyId)
1872 {
1873     AUTH_CHECK_AND_RETURN_RET_LOGE(connInfo != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "connInfo is NULL");
1874     AUTH_CHECK_AND_RETURN_RET_LOGE(authParam != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "authParam is NULL");
1875     if (!RequireAuthLock()) {
1876         return SOFTBUS_LOCK_ERR;
1877     }
1878     AuthFsmParam authFsmParam;
1879     (void)memset_s(&authFsmParam, sizeof(authFsmParam), 0, sizeof(authFsmParam));
1880     authFsmParam.authSeq = authParam->authSeq;
1881     authFsmParam.requestId = authParam->requestId;
1882     authFsmParam.connId = authParam->connId;
1883     authFsmParam.isServer = authParam->isServer;
1884     authFsmParam.deviceKeyId = *deviceKeyId;
1885     AuthFsm *authFsm =
1886         CreateAuthFsm(&authFsmParam, connInfo);
1887     if (authFsm == NULL) {
1888         ReleaseAuthLock();
1889         return SOFTBUS_MEM_ERR;
1890     }
1891     authFsm->info.isNeedFastAuth = authParam->isFastAuth;
1892     (void)UpdateLocalAuthState(authFsm->authSeq, &authFsm->info);
1893     AuthFsmStateIndex nextState = STATE_SYNC_DEVICE_ID;
1894     if (GetFirstFsmState(&authFsm->info, authFsm->authSeq, &nextState) != SOFTBUS_OK ||
1895         LnnFsmStart(&authFsm->fsm, g_states + nextState) != SOFTBUS_OK) {
1896         AUTH_LOGE(AUTH_FSM, "start auth fsm fail. authSeq=%{public}" PRId64 "", authFsm->authSeq);
1897         DestroyAuthFsm(authFsm);
1898         ReleaseAuthLock();
1899         return SOFTBUS_AUTH_START_FSM_FAIL;
1900     }
1901     SetAuthStartTime(authFsm);
1902     LnnFsmPostMessageDelay(&authFsm->fsm, FSM_MSG_AUTH_TIMEOUT, NULL, AUTH_TIMEOUT_MS);
1903     ReleaseAuthLock();
1904     return SOFTBUS_OK;
1905 }
1906 
AuthSessionProcessDevIdData(int64_t authSeq,const uint8_t * data,uint32_t len)1907 int32_t AuthSessionProcessDevIdData(int64_t authSeq, const uint8_t *data, uint32_t len)
1908 {
1909     if (data == NULL) {
1910         AUTH_LOGE(AUTH_FSM, "data is null");
1911         return SOFTBUS_INVALID_PARAM;
1912     }
1913     return PostMessageToAuthFsm(FSM_MSG_RECV_DEVICE_ID, authSeq, data, len);
1914 }
1915 
AuthSessionPostAuthData(int64_t authSeq,const uint8_t * data,uint32_t len)1916 int32_t AuthSessionPostAuthData(int64_t authSeq, const uint8_t *data, uint32_t len)
1917 {
1918     AuthSessionInfo info;
1919     if (GetSessionInfoFromAuthFsm(authSeq, &info) != SOFTBUS_OK) {
1920         return SOFTBUS_AUTH_GET_SESSION_INFO_FAIL;
1921     }
1922     if (PostHichainAuthMessage(authSeq, &info, data, len) != SOFTBUS_OK) {
1923         return SOFTBUS_AUTH_SYNC_DEVID_FAIL;
1924     }
1925     return SOFTBUS_OK;
1926 }
1927 
AuthSessionProcessAuthData(int64_t authSeq,const uint8_t * data,uint32_t len)1928 int32_t AuthSessionProcessAuthData(int64_t authSeq, const uint8_t *data, uint32_t len)
1929 {
1930     if (data == NULL) {
1931         AUTH_LOGE(AUTH_FSM, "data is null");
1932         return SOFTBUS_INVALID_PARAM;
1933     }
1934     return PostMessageToAuthFsm(FSM_MSG_RECV_AUTH_DATA, authSeq, data, len);
1935 }
1936 
AuthSessionGetUdid(int64_t authSeq,char * udid,uint32_t size)1937 int32_t AuthSessionGetUdid(int64_t authSeq, char *udid, uint32_t size)
1938 {
1939     if (udid == NULL) {
1940         AUTH_LOGE(AUTH_FSM, "udid is null");
1941         return SOFTBUS_INVALID_PARAM;
1942     }
1943     AuthSessionInfo info = { 0 };
1944     if (GetSessionInfoFromAuthFsm(authSeq, &info) != SOFTBUS_OK) {
1945         return SOFTBUS_AUTH_GET_SESSION_INFO_FAIL;
1946     }
1947     if (memcpy_s(udid, size, info.udid, sizeof(info.udid)) != EOK) {
1948         AUTH_LOGE(AUTH_FSM, "copy udid fail");
1949         return SOFTBUS_MEM_ERR;
1950     }
1951     return SOFTBUS_OK;
1952 }
1953 
AuthSessionGetCredId(int64_t authSeq)1954 char *AuthSessionGetCredId(int64_t authSeq)
1955 {
1956     AuthSessionInfo info = { 0 };
1957     if (GetSessionInfoFromAuthFsm(authSeq, &info) != SOFTBUS_OK) {
1958         AUTH_LOGE(AUTH_FSM, "get auth fsm session info fail");
1959         return NULL;
1960     }
1961 
1962     return info.credId;
1963 }
1964 
AuthSessionGetAuthVersion(int64_t authSeq,int32_t * version)1965 int32_t AuthSessionGetAuthVersion(int64_t authSeq, int32_t *version)
1966 {
1967     if (version == NULL) {
1968         AUTH_LOGE(AUTH_FSM, "version is null");
1969         return SOFTBUS_INVALID_PARAM;
1970     }
1971 
1972     AuthSessionInfo info = { 0 };
1973     if (GetSessionInfoFromAuthFsm(authSeq, &info) != SOFTBUS_OK) {
1974         AUTH_LOGE(AUTH_FSM, "get auth fsm session info fail");
1975         return SOFTBUS_AUTH_GET_SESSION_INFO_FAIL;
1976     }
1977 
1978     *version = info.authVersion;
1979     return SOFTBUS_OK;
1980 }
1981 
AuthSessionGetIsSameAccount(int64_t authSeq)1982 bool AuthSessionGetIsSameAccount(int64_t authSeq)
1983 {
1984     AuthSessionInfo info = { 0 };
1985     if (GetSessionInfoFromAuthFsm(authSeq, &info) != SOFTBUS_OK) {
1986         AUTH_LOGE(AUTH_FSM, "get auth fsm session info fail");
1987         return false;
1988     }
1989 
1990     return info.isSameAccount;
1991 }
1992 
AuthSessionGetUserId(int64_t authSeq)1993 int32_t AuthSessionGetUserId(int64_t authSeq)
1994 {
1995     AuthSessionInfo info = { 0 };
1996     if (GetSessionInfoFromAuthFsm(authSeq, &info) != SOFTBUS_OK) {
1997         AUTH_LOGE(AUTH_FSM, "get auth fsm session info fail");
1998         return DEFAULT_USERID;
1999     }
2000     return info.userId;
2001 }
2002 
AuthSessionSaveSessionKey(int64_t authSeq,const uint8_t * key,uint32_t len)2003 int32_t AuthSessionSaveSessionKey(int64_t authSeq, const uint8_t *key, uint32_t len)
2004 {
2005     if (key == NULL) {
2006         AUTH_LOGE(AUTH_FSM, "key is null");
2007         return SOFTBUS_INVALID_PARAM;
2008     }
2009     return PostMessageToAuthFsm(FSM_MSG_SAVE_SESSION_KEY, authSeq, key, len);
2010 }
2011 
AuthSessionHandleAuthFinish(int64_t authSeq,AclWriteState aclState)2012 int32_t AuthSessionHandleAuthFinish(int64_t authSeq, AclWriteState aclState)
2013 {
2014     return PostMessageToAuthFsm(FSM_MSG_AUTH_FINISH, authSeq, (uint8_t *)&aclState, sizeof(aclState));
2015 }
2016 
AuthSessionHandleAuthError(int64_t authSeq,int32_t reason)2017 int32_t AuthSessionHandleAuthError(int64_t authSeq, int32_t reason)
2018 {
2019     return PostMessageToAuthFsm(FSM_MSG_AUTH_ERROR, authSeq, (uint8_t *)&reason, sizeof(reason));
2020 }
2021 
AuthSessionProcessDevInfoData(int64_t authSeq,const uint8_t * data,uint32_t len)2022 int32_t AuthSessionProcessDevInfoData(int64_t authSeq, const uint8_t *data, uint32_t len)
2023 {
2024     if (data == NULL) {
2025         AUTH_LOGE(AUTH_FSM, "data is null");
2026         return SOFTBUS_INVALID_PARAM;
2027     }
2028     return PostMessageToAuthFsm(FSM_MSG_RECV_DEVICE_INFO, authSeq, data, len);
2029 }
2030 
AuthSessionProcessCloseAck(int64_t authSeq,const uint8_t * data,uint32_t len)2031 int32_t AuthSessionProcessCloseAck(int64_t authSeq, const uint8_t *data, uint32_t len)
2032 {
2033     if (data == NULL) {
2034         AUTH_LOGE(AUTH_FSM, "data is null");
2035         return SOFTBUS_INVALID_PARAM;
2036     }
2037     return PostMessageToAuthFsm(FSM_MSG_RECV_CLOSE_ACK, authSeq, data, len);
2038 }
2039 
AuthSessionProcessDevInfoDataByConnId(uint64_t connId,bool isServer,const uint8_t * data,uint32_t len)2040 int32_t AuthSessionProcessDevInfoDataByConnId(uint64_t connId, bool isServer, const uint8_t *data, uint32_t len)
2041 {
2042     if (data == NULL) {
2043         AUTH_LOGE(AUTH_FSM, "data is null");
2044         return SOFTBUS_INVALID_PARAM;
2045     }
2046     return PostMessageToAuthFsmByConnId(FSM_MSG_RECV_DEVICE_INFO, connId, isServer, data, len);
2047 }
2048 
AuthSessionProcessCloseAckByConnId(uint64_t connId,bool isServer,const uint8_t * data,uint32_t len)2049 int32_t AuthSessionProcessCloseAckByConnId(uint64_t connId, bool isServer, const uint8_t *data, uint32_t len)
2050 {
2051     if (data == NULL) {
2052         AUTH_LOGE(AUTH_FSM, "data is null");
2053         return SOFTBUS_INVALID_PARAM;
2054     }
2055     return PostMessageToAuthFsmByConnId(FSM_MSG_RECV_CLOSE_ACK, connId, isServer, data, len);
2056 }
2057 
AuthSessionProcessCancelAuthByConnId(uint64_t connId,bool isConnectServer,const uint8_t * data,uint32_t len)2058 int32_t AuthSessionProcessCancelAuthByConnId(uint64_t connId, bool isConnectServer, const uint8_t *data, uint32_t len)
2059 {
2060     if (!RequireAuthLock()) {
2061         return SOFTBUS_LOCK_ERR;
2062     }
2063     AuthFsm *authFsm = GetAuthFsmByConnId(connId, isConnectServer, true);
2064     if (authFsm == NULL) {
2065         ReleaseAuthLock();
2066         return SOFTBUS_AUTH_GET_FSM_FAIL;
2067     }
2068     if (LnnFsmPostMessage(&authFsm->fsm, FSM_MSG_DEVICE_DISCONNECTED, NULL) != SOFTBUS_OK) {
2069         AUTH_LOGE(AUTH_FSM, "post message to auth fsm by connId fail");
2070         ReleaseAuthLock();
2071         return SOFTBUS_AUTH_SEND_FAIL;
2072     }
2073     ReleaseAuthLock();
2074     return SOFTBUS_OK;
2075 }
2076 
AuthSessionHandleDeviceNotTrusted(const char * udid)2077 int32_t AuthSessionHandleDeviceNotTrusted(const char *udid)
2078 {
2079     if (udid == NULL || udid[0] == '\0') {
2080         AUTH_LOGE(AUTH_FSM, "invalid udid");
2081         return SOFTBUS_INVALID_PARAM;
2082     }
2083     if (!RequireAuthLock()) {
2084         return SOFTBUS_LOCK_ERR;
2085     }
2086     AuthFsm *item = NULL;
2087     LIST_FOR_EACH_ENTRY(item, &g_authFsmList, AuthFsm, node) {
2088         if (strcmp(item->info.udid, udid) != 0) {
2089             continue;
2090         }
2091         if (item->isDead) {
2092             AUTH_LOGE(AUTH_FSM, "auth fsm has dead. authSeq=%{public}" PRId64 "", item->authSeq);
2093             continue;
2094         }
2095         LnnFsmPostMessage(&item->fsm, FSM_MSG_DEVICE_NOT_TRUSTED, NULL);
2096     }
2097     ReleaseAuthLock();
2098     return SOFTBUS_OK;
2099 }
2100 
AuthSessionHandleDeviceDisconnected(uint64_t connId,bool isNeedDisconnect)2101 int32_t AuthSessionHandleDeviceDisconnected(uint64_t connId, bool isNeedDisconnect)
2102 {
2103     if (!RequireAuthLock()) {
2104         AUTH_LOGE(AUTH_FSM, "get auth lock fail");
2105         return SOFTBUS_LOCK_ERR;
2106     }
2107     AuthFsm *item = NULL;
2108     bool isDisconnected = false;
2109     LIST_FOR_EACH_ENTRY(item, &g_authFsmList, AuthFsm, node) {
2110         if (item->info.connId != connId) {
2111             continue;
2112         }
2113         if (item->isDead) {
2114             AUTH_LOGE(AUTH_FSM, "auth fsm has dead. authSeq=%{public}" PRId64 "", item->authSeq);
2115             continue;
2116         }
2117         if (GetConnType(item->info.connId) == AUTH_LINK_TYPE_WIFI ||
2118             GetConnType(item->info.connId) == AUTH_LINK_TYPE_P2P ||
2119             GetConnType(item->info.connId) == AUTH_LINK_TYPE_USB) {
2120             if (isNeedDisconnect) {
2121                 DisconnectAuthDevice(&item->info.connId);
2122                 isDisconnected = true;
2123             } else {
2124                 UpdateFd(&item->info.connId, AUTH_INVALID_FD);
2125             }
2126         }
2127         LnnFsmPostMessage(&item->fsm, FSM_MSG_DEVICE_DISCONNECTED, NULL);
2128     }
2129     ReleaseAuthLock();
2130     if (isNeedDisconnect && !isDisconnected &&
2131         (GetConnType(connId) == AUTH_LINK_TYPE_WIFI || GetConnType(connId) == AUTH_LINK_TYPE_USB) &&
2132         IsExistAuthTcpConnFdItemByConnId(GetConnId(connId))) {
2133         DisconnectAuthDevice(&connId);
2134     }
2135     return SOFTBUS_OK;
2136 }
2137 
AuthNotifyRequestVerify(int64_t authSeq)2138 int32_t AuthNotifyRequestVerify(int64_t authSeq)
2139 {
2140     return PostMessageToAuthFsm(FSM_MSG_DEVICE_POST_DEVICEID, authSeq, NULL, 0);
2141 }
2142 
AuthSessionFsmExit(void)2143 void AuthSessionFsmExit(void)
2144 {
2145     HichainDestroy();
2146     if (!RequireAuthLock()) {
2147         return;
2148     }
2149     AuthFsm *item = NULL;
2150     AuthFsm *next = NULL;
2151     LIST_FOR_EACH_ENTRY_SAFE(item, next, &g_authFsmList, AuthFsm, node) {
2152         DestroyAuthFsm(item);
2153     }
2154     ListInit(&g_authFsmList);
2155     ReleaseAuthLock();
2156 }
2157 
HandleMsgSaveSessionKey(AuthFsm * authFsm,const MessagePara * para)2158 static void HandleMsgSaveSessionKey(AuthFsm *authFsm, const MessagePara *para)
2159 {
2160     SessionKey sessionKey = { .len = para->len };
2161     if (memcpy_s(sessionKey.value, sizeof(sessionKey.value), para->data, para->len) != EOK) {
2162         AUTH_LOGE(AUTH_FSM, "copy session key fail.");
2163         (void)memset_s(&sessionKey, sizeof(sessionKey), 0, sizeof(sessionKey));
2164         return;
2165     }
2166     if (AuthManagerSetSessionKey(authFsm->authSeq, &authFsm->info, &sessionKey, true, false) != SOFTBUS_OK) {
2167         AUTH_LOGE(AUTH_FSM, "auth fsm save session key fail. authSeq=%{public}" PRId64 "", authFsm->authSeq);
2168     }
2169 
2170     (void)CalcHKDFPacked((uint8_t *)(&sessionKey.value), sessionKey.len, (uint8_t *)(&authFsm->info.sessionKeyRandomNum),
2171         sizeof(authFsm->info.sessionKeyRandomNum));
2172     (void)memset_s(&sessionKey, sizeof(sessionKey), 0, sizeof(sessionKey));
2173     if (LnnGenerateLocalPtkPacked(authFsm->info.udid, authFsm->info.uuid) != SOFTBUS_OK) {
2174         AUTH_LOGE(AUTH_FSM, "generate ptk fail");
2175     }
2176     authFsm->info.nodeInfo.isNeedReSyncDeviceName = false;
2177     if (TrySyncDeviceInfo(authFsm->authSeq, &authFsm->info) != SOFTBUS_OK) {
2178         AUTH_LOGE(AUTH_FSM, "auth fsm sync device info fail. authSeq=%{public}" PRId64 "", authFsm->authSeq);
2179         CompleteAuthSession(authFsm, SOFTBUS_AUTH_SYNC_DEVINFO_FAIL);
2180         return;
2181     }
2182     if (authFsm->info.deviceInfoData != NULL) {
2183         AUTH_LOGE(AUTH_FSM, "auth fsm dispatch device info to next state. authSeq=%{public}" PRId64, authFsm->authSeq);
2184         (void)AuthSessionProcessDevInfoData(
2185             authFsm->authSeq, authFsm->info.deviceInfoData, authFsm->info.deviceInfoDataLen);
2186         SoftBusFree(authFsm->info.deviceInfoData);
2187         authFsm->info.deviceInfoData = NULL;
2188     }
2189     LnnFsmTransactState(&authFsm->fsm, g_states + STATE_SYNC_DEVICE_INFO);
2190     authFsm->curState = STATE_SYNC_DEVICE_INFO;
2191 }
AuthSessionSetReSyncDeviceName(void)2192 void AuthSessionSetReSyncDeviceName(void)
2193 {
2194     if (!RequireAuthLock()) {
2195         AUTH_LOGE(AUTH_FSM, "get auth lock fail");
2196         return;
2197     }
2198     AuthFsm *item = NULL;
2199     AuthFsm *next = NULL;
2200     LIST_FOR_EACH_ENTRY_SAFE(item, next, &g_authFsmList, AuthFsm, node) {
2201         if (item->curState >= STATE_SYNC_DEVICE_INFO) {
2202             AUTH_LOGI(AUTH_FSM, "need resync latest device name authSeq=%{public}" PRId64, item->authSeq);
2203             item->info.nodeInfo.isNeedReSyncDeviceName = true;
2204         }
2205     }
2206     ReleaseAuthLock();
2207 }
2208