• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "lnn_net_builder.h"
17 
18 #include <securec.h>
19 #include <stdlib.h>
20 #include <inttypes.h>
21 
22 #include "anonymizer.h"
23 #include "auth_common.h"
24 #include "auth_deviceprofile.h"
25 #include "auth_interface.h"
26 #include "auth_request.h"
27 #include "auth_request.h"
28 #include "auth_hichain_adapter.h"
29 #include "bus_center_event.h"
30 #include "bus_center_manager.h"
31 #include "common_list.h"
32 #include "lnn_async_callback_utils.h"
33 #include "lnn_battery_info.h"
34 #include "lnn_cipherkey_manager.h"
35 #include "lnn_connection_addr_utils.h"
36 #include "lnn_connection_fsm.h"
37 #include "lnn_deviceinfo_to_profile.h"
38 #include "lnn_devicename_info.h"
39 #include "lnn_discovery_manager.h"
40 #include "lnn_distributed_net_ledger.h"
41 #include "lnn_fast_offline.h"
42 #include "lnn_heartbeat_utils.h"
43 #include "lnn_kv_adapter_wrapper.h"
44 #include "lnn_link_finder.h"
45 #include "lnn_local_net_ledger.h"
46 #include "lnn_log.h"
47 #include "lnn_map.h"
48 #include "lnn_network_id.h"
49 #include "lnn_network_info.h"
50 #include "lnn_network_manager.h"
51 #include "lnn_node_info.h"
52 #include "lnn_node_weight.h"
53 #include "lnn_ohos_account.h"
54 #include "lnn_oobe_manager.h"
55 #include "lnn_p2p_info.h"
56 #include "lnn_physical_subnet_manager.h"
57 #include "lnn_sa_status_monitor.h"
58 #include "lnn_sync_info_manager.h"
59 #include "lnn_sync_item_info.h"
60 #include "lnn_topo_manager.h"
61 #include "softbus_adapter_bt_common.h"
62 #include "softbus_adapter_crypto.h"
63 #include "softbus_adapter_json.h"
64 #include "softbus_adapter_mem.h"
65 #include "softbus_error_code.h"
66 #include "softbus_feature_config.h"
67 #include "legacy/softbus_hisysevt_bus_center.h"
68 #include "softbus_json_utils.h"
69 #include "softbus_adapter_json.h"
70 #include "softbus_utils.h"
71 #include "softbus_wifi_api_adapter.h"
72 #include "trans_channel_manager.h"
73 #include "lnn_net_builder.h"
74 #include "lnn_net_builder_process.h"
75 #include "lnn_init_monitor.h"
76 
77 
78 #define DEFAULT_PKG_NAME                 "com.huawei.nearby"
79 #define DEFAULT_MAX_LNN_CONNECTION_COUNT 10
80 #define NOT_TRUSTED_DEVICE_MSG_DELAY     5000
81 #define DELAY_REG_DP_TIME                10000
82 #define RETRY_TIMES                      5
83 
SetBeginJoinLnnTime(LnnConnectionFsm * connFsm)84 void SetBeginJoinLnnTime(LnnConnectionFsm *connFsm)
85 {
86     connFsm->statisticData.beginJoinLnnTime = LnnUpTimeMs();
87 }
88 
DfxRecordDeviceInfoExchangeEndTime(const NodeInfo * info)89 static void DfxRecordDeviceInfoExchangeEndTime(const NodeInfo *info)
90 {
91     int32_t ret = SOFTBUS_OK;
92     uint64_t timeStamp = 0;
93     LnnEventExtra extra = { 0 };
94     (void)LnnEventExtraInit(&extra);
95     LnnTriggerInfo triggerInfo = { 0 };
96     GetLnnTriggerInfo(&triggerInfo);
97     timeStamp = SoftBusGetSysTimeMs();
98     extra.timeLatency = timeStamp - triggerInfo.triggerTime;
99     uint8_t hash[UDID_HASH_LEN] = { 0 };
100     char *udidHash = (char *)SoftBusCalloc(SHORT_UDID_HASH_HEX_LEN + 1);
101     if (udidHash == NULL) {
102         LNN_LOGE(LNN_BUILDER, "udidHash calloc fail");
103         return;
104     }
105     ret = SoftBusGenerateStrHash((uint8_t *)info->deviceInfo.deviceUdid, strlen(info->deviceInfo.deviceUdid),
106         hash);
107     if (ret != SOFTBUS_OK) {
108         LNN_LOGE(LNN_BUILDER, "generate udidhash fail. ret=%{public}d", ret);
109         SoftBusFree(udidHash);
110         return;
111     }
112     ret = ConvertBytesToHexString(udidHash, HB_SHORT_UDID_HASH_HEX_LEN + 1, hash, HB_SHORT_UDID_HASH_LEN);
113     if (ret != SOFTBUS_OK) {
114         LNN_LOGE(LNN_BUILDER, "convert bytes to string fail. ret=%{public}d", ret);
115         SoftBusFree(udidHash);
116         return;
117     }
118     extra.peerUdidHash = udidHash;
119     LNN_EVENT(EVENT_SCENE_JOIN_LNN, EVENT_STAGE_AUTH_DEVICE_INFO_PROCESS, extra);
120     SoftBusFree(udidHash);
121 }
122 
OnReAuthVerifyPassed(uint32_t requestId,AuthHandle authHandle,const NodeInfo * info)123 static void OnReAuthVerifyPassed(uint32_t requestId, AuthHandle authHandle, const NodeInfo *info)
124 {
125     LNN_LOGI(LNN_BUILDER, "reAuth verify passed: requestId=%{public}u, authId=%{public}" PRId64,
126         requestId, authHandle.authId);
127     LNN_CHECK_AND_RETURN_LOGE(info != NULL, LNN_BUILDER, "reAuth verify result error");
128     AuthRequest authRequest = { 0 };
129     if (GetAuthRequest(requestId, &authRequest) != SOFTBUS_OK) {
130         LNN_LOGE(LNN_BUILDER, "auth request not found");
131         return;
132     }
133     ConnectionAddr addr;
134     (void)memset_s(&addr, sizeof(ConnectionAddr), 0, sizeof(ConnectionAddr));
135     if (!LnnConvertAuthConnInfoToAddr(&addr, &authRequest.connInfo, GetCurrentConnectType())) {
136         LNN_LOGE(LNN_BUILDER, "ConvertToConnectionAddr failed");
137         return;
138     }
139     int32_t ret = SoftBusGenerateStrHash((unsigned char *)info->deviceInfo.deviceUdid,
140         strlen(info->deviceInfo.deviceUdid), (unsigned char *)addr.info.ble.udidHash);
141     if (ret != SOFTBUS_OK) {
142         LNN_LOGE(LNN_BUILDER, "gen udidHash fail");
143         return;
144     }
145     LnnConnectionFsm *connFsm = FindConnectionFsmByAddr(&addr, true);
146     if (connFsm != NULL && !connFsm->isDead && !LnnIsNeedCleanConnectionFsm(info, addr.type)) {
147         if (info != NULL && LnnUpdateGroupType(info) == SOFTBUS_OK && LnnUpdateAccountInfo(info) == SOFTBUS_OK) {
148             UpdateProfile(info);
149             LnnUpdateRemoteDeviceName(info);
150             NodeInfo nodeInfo;
151             (void)memset_s(&nodeInfo, sizeof(NodeInfo), 0, sizeof(NodeInfo));
152             (void)LnnGetRemoteNodeInfoById(info->deviceInfo.deviceUdid, CATEGORY_UDID, &nodeInfo);
153             UpdateDpSameAccount(nodeInfo.accountId, nodeInfo.deviceInfo.deviceUdid, nodeInfo.userId);
154         }
155     } else {
156         connFsm = StartNewConnectionFsm(&addr, DEFAULT_PKG_NAME, true);
157         if (connFsm == NULL) {
158             return;
159         }
160         connFsm->connInfo.authHandle = authHandle;
161         connFsm->connInfo.nodeInfo = DupNodeInfo(info);
162         connFsm->connInfo.flag |= LNN_CONN_INFO_FLAG_JOIN_AUTO;
163         LNN_LOGI(LNN_BUILDER, "fsmId=%{public}u start a connection fsm, authId=%{public}" PRId64,
164             connFsm->id, authHandle.authId);
165         if (LnnSendAuthResultMsgToConnFsm(connFsm, SOFTBUS_OK) != SOFTBUS_OK) {
166             SoftBusFree(connFsm->connInfo.nodeInfo);
167             connFsm->connInfo.nodeInfo = NULL;
168             StopConnectionFsm(connFsm);
169         }
170     }
171 }
172 
OnReAuthVerifyFailed(uint32_t requestId,int32_t reason)173 static void OnReAuthVerifyFailed(uint32_t requestId, int32_t reason)
174 {
175     LNN_LOGI(LNN_BUILDER, "verify failed. requestId=%{public}u, reason=%{public}d", requestId, reason);
176     if (reason >= SOFTBUS_HICHAIN_MIN && reason <= SOFTBUS_HICHAIN_MAX) {
177         AuthHandle authHandle = { .authId = AUTH_INVALID_ID };
178         PostVerifyResult(requestId, reason, authHandle, NULL);
179     }
180 }
181 
182 static AuthVerifyCallback g_reAuthVerifyCallback = {
183     .onVerifyPassed = OnReAuthVerifyPassed,
184     .onVerifyFailed = OnReAuthVerifyFailed,
185 };
186 
LnnGetReAuthVerifyCallback(void)187 AuthVerifyCallback *LnnGetReAuthVerifyCallback(void)
188 {
189     return &g_reAuthVerifyCallback;
190 }
191 
NotifyStateForSession(const ConnectionAddr * addr)192 void NotifyStateForSession(const ConnectionAddr *addr)
193 {
194     if (addr == NULL) {
195         LNN_LOGE(LNN_BUILDER, "addr is null.");
196         return;
197     }
198     ConnIdCbInfo connIdCbInfo;
199     (void)memset_s(&connIdCbInfo, sizeof(ConnIdCbInfo), 0, sizeof(ConnIdCbInfo));
200     int32_t ret = GetConnIdCbInfoByAddr(addr, &connIdCbInfo);
201     if (ret != SOFTBUS_OK) {
202         LNN_LOGE(LNN_BUILDER, "get connIdCbInfo fail.");
203         return;
204     }
205     LnnNotifyStateForSession(connIdCbInfo.udid, SOFTBUS_NETWORK_JOIN_REQUEST_ERR);
206 }
207 
PostJoinRequestToConnFsm(LnnConnectionFsm * connFsm,const JoinLnnMsgPara * para,bool needReportFailure)208 int32_t PostJoinRequestToConnFsm(LnnConnectionFsm *connFsm, const JoinLnnMsgPara *para, bool needReportFailure)
209 {
210     if (para == NULL) {
211         LNN_LOGE(LNN_BUILDER, "JoinLnnMsgPara is null");
212         return SOFTBUS_INVALID_PARAM;
213     }
214     int32_t rc = SOFTBUS_OK;
215     bool isCreate = false;
216 
217     if (connFsm == NULL) {
218         connFsm = FindConnectionFsmByAddr(&para->addr, false);
219     }
220     if (connFsm == NULL || connFsm->isDead || CheckRemoteBasicInfoChanged(para->dupInfo)) {
221         connFsm = StartNewConnectionFsm(&para->addr, para->pkgName, para->isNeedConnect);
222         if (connFsm != NULL) {
223             connFsm->connInfo.dupInfo = (para->dupInfo == NULL) ? NULL : DupNodeInfo(para->dupInfo);
224         }
225         isCreate = true;
226     }
227     if (connFsm != NULL && para->isSession) {
228         connFsm->isSession = true;
229     }
230 
231     if (connFsm == NULL || LnnSendJoinRequestToConnFsm(connFsm, false) != SOFTBUS_OK) {
232         LNN_LOGE(LNN_BUILDER, "process join lnn request failed");
233         if (needReportFailure) {
234             LnnNotifyJoinResult((ConnectionAddr *)&para->addr, NULL, SOFTBUS_NETWORK_JOIN_REQUEST_ERR);
235             NotifyStateForSession(&para->addr);
236         }
237         if (connFsm != NULL && isCreate) {
238             LnnFsmRemoveMessageByType(&connFsm->fsm, FSM_CTRL_MSG_START);
239             ListDelete(&connFsm->node);
240             --LnnGetNetBuilder()->connCount;
241             LnnDestroyConnectionFsm(connFsm);
242         }
243         rc = SOFTBUS_NETWORK_JOIN_REQUEST_ERR;
244     }
245     if (rc == SOFTBUS_OK) {
246         connFsm->connInfo.infoReport = para->infoReport;
247         connFsm->connInfo.flag |=
248             (needReportFailure ? LNN_CONN_INFO_FLAG_JOIN_REQUEST : LNN_CONN_INFO_FLAG_JOIN_AUTO);
249         LNN_LOGI(LNN_BUILDER, "infoReport.osType=%{public}d, infoReport.type=%{public}X",
250             connFsm->connInfo.infoReport.osType, connFsm->connInfo.infoReport.type);
251     }
252     return rc;
253 }
254 
TryRemovePendingJoinRequest(void)255 void TryRemovePendingJoinRequest(void)
256 {
257     PendingJoinRequestNode *item = NULL;
258     PendingJoinRequestNode *next = NULL;
259     JoinLnnMsgPara para;
260 
261     LIST_FOR_EACH_ENTRY_SAFE(item, next, &LnnGetNetBuilder()->pendingList, PendingJoinRequestNode, node) {
262         if (NeedPendingJoinRequest()) {
263             return;
264         }
265         ListDelete(&item->node);
266         (void)memset_s(&para, sizeof(JoinLnnMsgPara), 0, sizeof(JoinLnnMsgPara));
267         para.isNeedConnect = true;
268         para.addr = item->addr;
269         if (strcpy_s(para.pkgName, PKG_NAME_SIZE_MAX, DEFAULT_PKG_NAME) != EOK) {
270             LNN_LOGE(LNN_BUILDER, "strcpy_s pkgName failed");
271             SoftBusFree(item);
272             continue;
273         }
274         if (PostJoinRequestToConnFsm(NULL, &para, item->needReportFailure) != SOFTBUS_OK) {
275             LNN_LOGE(LNN_BUILDER, "post pending join request failed");
276         }
277         LNN_LOGI(
278             LNN_BUILDER, "remove a pending join request, peerAddr=%{public}s", LnnPrintConnectionAddr(&item->addr));
279         SoftBusFree(item);
280         break;
281     }
282 }
283 
InitiateNewNetworkOnline(ConnectionAddrType addrType,const char * networkId)284 void InitiateNewNetworkOnline(ConnectionAddrType addrType, const char *networkId)
285 {
286     LnnConnectionFsm *item = NULL;
287     int32_t rc;
288 
289     // find target connfsm, then notify it online
290     LIST_FOR_EACH_ENTRY(item, &LnnGetNetBuilder()->fsmList, LnnConnectionFsm, node) {
291         if (strcmp(networkId, item->connInfo.peerNetworkId) != 0) {
292             continue;
293         }
294         if (item->isDead) {
295             continue;
296         }
297         if (addrType != CONNECTION_ADDR_MAX && addrType != item->connInfo.addr.type) {
298             continue;
299         }
300         rc = LnnSendNewNetworkOnlineToConnFsm(item);
301         LNN_LOGI(LNN_INIT, "initiate new network online to connection. fsmId=%{public}u, rc=%{public}d", item->id, rc);
302     }
303 }
304 
TryInitiateNewNetworkOnline(const LnnConnectionFsm * connFsm)305 void TryInitiateNewNetworkOnline(const LnnConnectionFsm *connFsm)
306 {
307     LnnConnectionFsm *item = NULL;
308     LnnInvalidCleanInfo *cleanInfo = connFsm->connInfo.cleanInfo;
309 
310     if ((connFsm->connInfo.flag & LNN_CONN_INFO_FLAG_INITIATE_ONLINE) == 0) {
311         LNN_LOGI(LNN_INIT, "no need initiate new network online. fsmId=%{public}u", connFsm->id);
312         return;
313     }
314     // let last invalid connfsm notify new network online after it clean
315     LIST_FOR_EACH_ENTRY(item, &LnnGetNetBuilder()->fsmList, LnnConnectionFsm, node) {
316         if (strcmp(connFsm->connInfo.peerNetworkId, item->connInfo.peerNetworkId) != 0) {
317             continue;
318         }
319         if ((item->connInfo.flag & LNN_CONN_INFO_FLAG_INITIATE_ONLINE) == 0) {
320             continue;
321         }
322         LNN_LOGI(LNN_INIT, "wait last connfsm clean, then initiate new network online. fsmId=%{public}u", connFsm->id);
323         return;
324     }
325     InitiateNewNetworkOnline(cleanInfo->addrType, cleanInfo->networkId);
326 }
327 
TryDisconnectAllConnection(const LnnConnectionFsm * connFsm)328 void TryDisconnectAllConnection(const LnnConnectionFsm *connFsm)
329 {
330     LnnConnectionFsm *item = NULL;
331     const ConnectionAddr *addr1 = &connFsm->connInfo.addr;
332     const ConnectionAddr *addr2 = NULL;
333     ConnectOption option;
334 
335     // Not really leaving lnn
336     if ((connFsm->connInfo.flag & LNN_CONN_INFO_FLAG_ONLINE) == 0) {
337         return;
338     }
339     LIST_FOR_EACH_ENTRY(item, &LnnGetNetBuilder()->fsmList, LnnConnectionFsm, node) {
340         addr2 = &item->connInfo.addr;
341         if (addr1->type != addr2->type) {
342             continue;
343         }
344         if (addr1->type == CONNECTION_ADDR_BR || addr1->type == CONNECTION_ADDR_BLE) {
345             if (strncmp(item->connInfo.addr.info.br.brMac, addr2->info.br.brMac, BT_MAC_LEN) == 0) {
346                 return;
347             }
348         } else if (addr1->type == CONNECTION_ADDR_WLAN || addr1->type == CONNECTION_ADDR_ETH) {
349             if (strncmp(addr1->info.ip.ip, addr2->info.ip.ip, strlen(addr1->info.ip.ip)) == 0) {
350                 return;
351             }
352         }
353     }
354     if (addr1->type == CONNECTION_ADDR_BR) {
355         LNN_LOGI(
356             LNN_BUILDER, "not disconnect all connection. fsmId=%{public}u, type=%{public}d", connFsm->id, addr1->type);
357         return;
358     }
359     LNN_LOGI(LNN_BUILDER, "disconnect all connection. fsmId=%{public}u, type=%{public}d", connFsm->id, addr1->type);
360     if (LnnConvertAddrToOption(addr1, &option) && CheckAuthChannelIsExit(&option) != SOFTBUS_OK) {
361         ConnDisconnectDeviceAllConn(&option);
362     }
363 }
364 
TryNotifyAllTypeOffline(const LnnConnectionFsm * connFsm)365 void TryNotifyAllTypeOffline(const LnnConnectionFsm *connFsm)
366 {
367     LnnConnectionFsm *item = NULL;
368     const ConnectionAddr *addr1 = &connFsm->connInfo.addr;
369     const ConnectionAddr *addr2 = NULL;
370 
371     LIST_FOR_EACH_ENTRY(item, &LnnGetNetBuilder()->fsmList, LnnConnectionFsm, node) {
372         addr2 = &item->connInfo.addr;
373         if (addr1->type == addr2->type) {
374             return;
375         }
376     }
377     LNN_LOGI(LNN_BUILDER, "notify all connection offline. fsmId=%{public}u, type=%{public}d", connFsm->id, addr1->type);
378     (void)LnnNotifyAllTypeOffline(addr1->type);
379 }
380 
FindConnectionFsmByConnFsmId(uint16_t connFsmId)381 LnnConnectionFsm *FindConnectionFsmByConnFsmId(uint16_t connFsmId)
382 {
383     LnnConnectionFsm *item = NULL;
384 
385     LIST_FOR_EACH_ENTRY(item, &LnnGetNetBuilder()->fsmList, LnnConnectionFsm, node) {
386         if (connFsmId == item->id) {
387             return item;
388         }
389     }
390     return NULL;
391 }
392 
TryElectMasterNodeOnline(const LnnConnectionFsm * connFsm)393 int32_t TryElectMasterNodeOnline(const LnnConnectionFsm *connFsm)
394 {
395     char peerMasterUdid[UDID_BUF_LEN] = { 0 };
396     char localMasterUdid[UDID_BUF_LEN] = { 0 };
397     int32_t localMasterWeight;
398     int32_t peerMasterWeight;
399     int32_t rc;
400 
401     // get local master node info
402     if (LnnGetLocalStrInfo(STRING_KEY_MASTER_NODE_UDID, localMasterUdid, UDID_BUF_LEN) != SOFTBUS_OK ||
403         LnnGetLocalNumInfo(NUM_KEY_MASTER_NODE_WEIGHT, &localMasterWeight) != SOFTBUS_OK) {
404         LNN_LOGE(LNN_BUILDER, "get local master node info from ledger failed");
405         return SOFTBUS_NETWORK_GET_NODE_INFO_ERR;
406     }
407     LNN_LOGI(LNN_BUILDER, "local master fsmId=%{public}u, weight=%{public}d", connFsm->id, localMasterWeight);
408     if (LnnGetRemoteStrInfo(connFsm->connInfo.peerNetworkId, STRING_KEY_MASTER_NODE_UDID,
409         peerMasterUdid, UDID_BUF_LEN) != SOFTBUS_OK ||
410         LnnGetRemoteNumInfo(connFsm->connInfo.peerNetworkId, NUM_KEY_MASTER_NODE_WEIGHT,
411             &peerMasterWeight) != SOFTBUS_OK) {
412         LNN_LOGE(LNN_BUILDER, "peer node info is not found. fsmId=%{public}u", connFsm->id);
413         return SOFTBUS_NETWORK_NOT_FOUND;
414     }
415     LNN_LOGI(LNN_BUILDER, "peer master fsmId=%{public}u, weight=%{public}d", connFsm->id, peerMasterWeight);
416     rc = LnnCompareNodeWeight(localMasterWeight, localMasterUdid, peerMasterWeight, peerMasterUdid);
417     if (rc >= 0) {
418         LNN_LOGI(LNN_BUILDER,
419             "online node  weight less than current, no need elect again. fsmId=%{public}u, compareResult=%{public}d",
420             connFsm->id, rc);
421         return SOFTBUS_OK;
422     }
423     UpdateLocalMasterNode(false, peerMasterUdid, peerMasterWeight);
424     SendElectMessageToAll(connFsm->connInfo.peerNetworkId);
425     return SOFTBUS_OK;
426 }
427 
TryElectMasterNodeOffline(const LnnConnectionFsm * connFsm)428 int32_t TryElectMasterNodeOffline(const LnnConnectionFsm *connFsm)
429 {
430     char localUdid[UDID_BUF_LEN] = { 0 };
431     char localMasterUdid[UDID_BUF_LEN] = { 0 };
432 
433     if (LnnGetLocalStrInfo(STRING_KEY_MASTER_NODE_UDID, localMasterUdid, UDID_BUF_LEN) != SOFTBUS_OK) {
434         LNN_LOGE(LNN_BUILDER, "get local master node info from ledger failed");
435         return SOFTBUS_NETWORK_GET_NODE_INFO_ERR;
436     }
437     LnnGetLocalStrInfo(STRING_KEY_DEV_UDID, localUdid, UDID_BUF_LEN);
438     if (strcmp(localMasterUdid, localUdid) == 0) {
439         LNN_LOGI(LNN_BUILDER, "local is master node, no need elect again. fsmId=%{public}u", connFsm->id);
440     } else {
441         LNN_LOGI(LNN_BUILDER, "maybe master node offline, elect again. fsmId=%{public}u", connFsm->id);
442         UpdateLocalMasterNode(true, localUdid, LnnGetLocalWeight());
443         SendElectMessageToAll(connFsm->connInfo.peerNetworkId);
444     }
445     return SOFTBUS_OK;
446 }
447 
IsSupportMasterNodeElect(SoftBusVersion version)448 bool IsSupportMasterNodeElect(SoftBusVersion version)
449 {
450     LNN_LOGD(LNN_BUILDER, "SoftBusVersion=%{public}d", version);
451     return version >= SOFTBUS_NEW_V1;
452 }
453 
TryElectAsMasterState(const char * networkId,bool isOnline)454 void TryElectAsMasterState(const char *networkId, bool isOnline)
455 {
456     if (networkId == NULL) {
457         LNN_LOGW(LNN_BUILDER, "invalid networkId");
458         return;
459     }
460     if (isOnline) {
461         LNN_LOGD(LNN_BUILDER, "restore master state ignore online process");
462         return;
463     }
464     char masterUdid[UDID_BUF_LEN] = { 0 };
465     char localUdid[UDID_BUF_LEN] = { 0 };
466     if (LnnGetLocalStrInfo(STRING_KEY_MASTER_NODE_UDID, masterUdid, UDID_BUF_LEN) != SOFTBUS_OK) {
467         LNN_LOGE(LNN_BUILDER, "get local master node info from ledger failed");
468         return;
469     }
470     const char *peerUdid = LnnConvertDLidToUdid(networkId, CATEGORY_NETWORK_ID);
471     if (peerUdid == NULL) {
472         char *anonyNetworkId = NULL;
473         Anonymize(networkId, &anonyNetworkId);
474         LNN_LOGE(LNN_BUILDER, "get invalid peerUdid, networkId=%{public}s", AnonymizeWrapper(anonyNetworkId));
475         AnonymizeFree(anonyNetworkId);
476         return;
477     }
478     if (strcmp(masterUdid, peerUdid) != 0) {
479         char *anonyPeerUdid = NULL;
480         char *anonyMasterUdid = NULL;
481         Anonymize(peerUdid, &anonyPeerUdid);
482         Anonymize(masterUdid, &anonyMasterUdid);
483         LNN_LOGD(LNN_BUILDER, "offline node is not master node. peerUdid=%{public}s, masterUdid=%{public}s",
484             AnonymizeWrapper(anonyPeerUdid), AnonymizeWrapper(anonyMasterUdid));
485         AnonymizeFree(anonyPeerUdid);
486         AnonymizeFree(anonyMasterUdid);
487         return;
488     }
489     if (LnnGetLocalStrInfo(STRING_KEY_DEV_UDID, localUdid, UDID_BUF_LEN) != SOFTBUS_OK) {
490         LNN_LOGE(LNN_BUILDER, "get local udid failed");
491         return;
492     }
493     UpdateLocalMasterNode(true, localUdid, LnnGetLocalWeight());
494 }
495 
DeinitNodeInfoSync(void)496 static void DeinitNodeInfoSync(void)
497 {
498     LnnDeinitP2p();
499     LnnDeinitNetworkInfo();
500     LnnDeinitDevicename();
501     LnnDeinitOffline();
502     LnnDeinitBatteryInfo();
503     LnnDeinitWifiDirect();
504 }
505 
NetBuilderConfigInit(void)506 static void NetBuilderConfigInit(void)
507 {
508     if (SoftbusGetConfig(SOFTBUS_INT_MAX_LNN_CONNECTION_CNT, (unsigned char *)&LnnGetNetBuilder()->maxConnCount,
509         sizeof(LnnGetNetBuilder()->maxConnCount)) != SOFTBUS_OK) {
510         LNN_LOGE(LNN_INIT, "get lnn max connection count fail, use default value");
511         LnnGetNetBuilder()->maxConnCount = DEFAULT_MAX_LNN_CONNECTION_COUNT;
512     }
513     if (SoftbusGetConfig(SOFTBUS_INT_LNN_MAX_CONCURRENT_NUM, (unsigned char *)&LnnGetNetBuilder()->maxConcurrentCount,
514         sizeof(LnnGetNetBuilder()->maxConcurrentCount)) != SOFTBUS_OK) {
515         LNN_LOGE(LNN_INIT, "get lnn max conncurent count fail, use default value");
516         LnnGetNetBuilder()->maxConcurrentCount = 0;
517     }
518     LNN_LOGD(LNN_INIT, "lnn config count: maxConnCount=%{public}d, maxConcurrentCount=%{public}d",
519         LnnGetNetBuilder()->maxConnCount, LnnGetNetBuilder()->maxConcurrentCount);
520 }
521 
InitNodeInfoSync(void)522 static int32_t InitNodeInfoSync(void)
523 {
524     int32_t rc = LnnInitP2p();
525     if (rc != SOFTBUS_OK) {
526         LNN_LOGE(LNN_INIT, "init lnn p2p fail, rc=%{public}d", rc);
527         return rc;
528     }
529     rc = LnnInitNetworkInfo();
530     if (rc != SOFTBUS_OK) {
531         LNN_LOGE(LNN_INIT, "LnnInitNetworkInfo fail, rc=%{public}d", rc);
532         return rc;
533     }
534     rc = LnnInitDevicename();
535     if (rc != SOFTBUS_OK) {
536         LNN_LOGE(LNN_INIT, "LnnInitDeviceName fail, rc=%{public}d", rc);
537         return rc;
538     }
539     rc = LnnInitOffline();
540     if (rc != SOFTBUS_OK) {
541         LNN_LOGE(LNN_INIT, "LnnInitOffline fail, rc=%{public}d", rc);
542         return rc;
543     }
544     rc = LnnInitBatteryInfo();
545     if (rc != SOFTBUS_OK) {
546         LNN_LOGE(LNN_INIT, "LnnInitBatteryInfo fail, rc=%{public}d", rc);
547         return rc;
548     }
549     rc = LnnInitCipherKeyManager();
550     if (rc != SOFTBUS_OK) {
551         LNN_LOGE(LNN_INIT, "LnnInitCipherKeyManager fail, rc=%{public}d", rc);
552         return rc;
553     }
554     rc = LnnInitWifiDirect();
555     if (rc != SOFTBUS_OK) {
556         LNN_LOGE(LNN_INIT, "init lnn wifidirect addr fail, rc=%{public}d", rc);
557         return rc;
558     }
559     return SOFTBUS_OK;
560 }
561 
UpdatePCInfoWithoutSoftbus(void)562 static void UpdatePCInfoWithoutSoftbus(void)
563 {
564     int32_t onlineNum = 0;
565     NodeBasicInfo *info = NULL;
566     if (LnnGetAllOnlineNodeInfo(&info, &onlineNum) != 0) {
567         LNN_LOGE(LNN_BUILDER, "LnnGetAllOnlineNodeInfo failed!");
568         return;
569     }
570     if (info == NULL || onlineNum == 0) {
571         LNN_LOGW(LNN_BUILDER, "not online node");
572         return;
573     }
574     // mark-- remove pc offline
575     SoftBusFree(info);
576 }
577 
AccountStateChangeHandler(const LnnEventBasicInfo * info)578 static void AccountStateChangeHandler(const LnnEventBasicInfo *info)
579 {
580     if (info == NULL || info->event != LNN_EVENT_ACCOUNT_CHANGED) {
581         LNN_LOGW(LNN_BUILDER, "invalid param");
582         return;
583     }
584     const LnnMonitorHbStateChangedEvent *event = (const LnnMonitorHbStateChangedEvent *)info;
585     SoftBusAccountState accountState = (SoftBusAccountState)event->status;
586     switch (accountState) {
587         case SOFTBUS_ACCOUNT_LOG_IN:
588             LNN_LOGI(LNN_BUILDER, "ignore SOFTBUS_ACCOUNT_LOG_IN");
589             break;
590         case SOFTBUS_ACCOUNT_LOG_OUT:
591             LNN_LOGI(LNN_BUILDER, "handle SOFTBUS_ACCOUNT_LOG_OUT");
592             UpdatePCInfoWithoutSoftbus();
593             break;
594         default:
595             return;
596     }
597 }
598 
OnDeviceVerifyPass(AuthHandle authHandle,const NodeInfo * info)599 static void OnDeviceVerifyPass(AuthHandle authHandle, const NodeInfo *info)
600 {
601     LNN_CHECK_AND_RETURN_LOGE(info != NULL, LNN_BUILDER, "NodeInfo is NULL");
602     AuthConnInfo connInfo;
603     DeviceVerifyPassMsgPara *para = NULL;
604     LNN_LOGI(LNN_BUILDER, "verify passed passively, authId=%{public}" PRId64, authHandle.authId);
605     if (authHandle.type < AUTH_LINK_TYPE_WIFI || authHandle.type >= AUTH_LINK_TYPE_MAX) {
606         LNN_LOGE(LNN_BUILDER, "authHandle type error");
607         return;
608     }
609     if (AuthGetConnInfo(authHandle, &connInfo) != SOFTBUS_OK) {
610         LNN_LOGE(LNN_BUILDER, "get AuthConnInfo fail, authId=%{public}" PRId64, authHandle.authId);
611         return;
612     }
613     para = (DeviceVerifyPassMsgPara *)SoftBusMalloc(sizeof(DeviceVerifyPassMsgPara));
614     if (para == NULL) {
615         LNN_LOGE(LNN_BUILDER, "malloc DeviceVerifyPassMsgPara fail");
616         return;
617     }
618 
619     if (authHandle.type != AUTH_LINK_TYPE_ENHANCED_P2P && authHandle.type != AUTH_LINK_TYPE_SESSION) {
620         if (!LnnConvertAuthConnInfoToAddr(&para->addr, &connInfo, GetCurrentConnectType())) {
621             LNN_LOGE(LNN_BUILDER, "convert connInfo to addr fail");
622             SoftBusFree(para);
623             return;
624         }
625     } else {
626         para->addr.type = CONNECTION_ADDR_BR;
627         if (strcpy_s(para->addr.info.br.brMac, BT_MAC_LEN, info->connectInfo.macAddr) != EOK) {
628             LNN_LOGE(LNN_BUILDER, "copy br mac to addr fail");
629         }
630     }
631 
632     para->authHandle = authHandle;
633     para->nodeInfo = DupNodeInfo(info);
634     if (para->nodeInfo == NULL) {
635         LNN_LOGE(LNN_BUILDER, "dup NodeInfo fail");
636         SoftBusFree(para);
637         return;
638     }
639     if (PostBuildMessageToHandler(MSG_TYPE_DEVICE_VERIFY_PASS, para) != SOFTBUS_OK) {
640         LNN_LOGE(LNN_BUILDER, "post DEVICE_VERIFY_PASS msg fail");
641         SoftBusFree(para->nodeInfo);
642         SoftBusFree(para);
643     }
644     LnnNotifyDeviceVerified(info->deviceInfo.deviceUdid);
645     DfxRecordDeviceInfoExchangeEndTime(info);
646 }
647 
OnDeviceDisconnect(AuthHandle authHandle)648 static void OnDeviceDisconnect(AuthHandle authHandle)
649 {
650     if (authHandle.type < AUTH_LINK_TYPE_WIFI || authHandle.type >= AUTH_LINK_TYPE_MAX) {
651         LNN_LOGE(LNN_BUILDER, "authHandle type error");
652         return;
653     }
654     AuthHandle *para = NULL;
655     para = (AuthHandle *)SoftBusMalloc(sizeof(AuthHandle));
656     if (para == NULL) {
657         LNN_LOGE(LNN_BUILDER, "malloc DeviceDisconnect para fail");
658         return;
659     }
660     LNN_LOGI(LNN_BUILDER, "auth device disconnect, authId=%{public}" PRId64, authHandle.authId);
661     para->authId = authHandle.authId;
662     para->type = authHandle.type;
663     if (PostBuildMessageToHandler(MSG_TYPE_DEVICE_DISCONNECT, para) != SOFTBUS_OK) {
664         LNN_LOGE(LNN_BUILDER, "post DEVICE_DISCONNECT msg fail");
665         SoftBusFree(para);
666     }
667 }
668 
IsNeedNotifyOfflineByAdv(const char * udid)669 static bool IsNeedNotifyOfflineByAdv(const char *udid)
670 {
671     NodeInfo info;
672     (void)memset_s(&info, sizeof(NodeInfo), 0, sizeof(NodeInfo));
673     if (LnnGetRemoteNodeInfoByKey(udid, &info) != SOFTBUS_OK) {
674         LNN_LOGE(LNN_BUILDER, "get nodeinfo fail");
675         return false;
676     }
677     if (!IsSupportFeatureByCapaBit(info.authCapacity, BIT_SUPPORT_ADV_OFFLINE)) {
678         LNN_LOGI(LNN_BUILDER, "peer device not support notify offline by adv");
679         return false;
680     }
681     if (LnnHasDiscoveryType(&info, DISCOVERY_TYPE_WIFI)) {
682         LNN_LOGI(LNN_BUILDER, "wifi online, no need notify offline by adv");
683         return false;
684     }
685 
686     uint32_t local = 0;
687     int32_t ret = LnnGetLocalNumU32Info(NUM_KEY_NET_CAP, &local);
688     if (ret != SOFTBUS_OK) {
689         LNN_LOGE(LNN_BUILDER, "lnnGetLocalNumInfo err, ret=%{public}d, local=%{public}u", ret, local);
690         return false;
691     }
692     if (((local & (1 << BIT_BLE)) == 0) || ((info.netCapacity & (1 << BIT_BLE)) == 0)) {
693         LNN_LOGE(LNN_BUILDER, "ble capa disable, local=%{public}u, remote=%{public}u", local, info.netCapacity);
694         return false;
695     }
696     LnnRequestLeaveSpecific(info.networkId, CONNECTION_ADDR_MAX);
697     return true;
698 }
699 
OnDeviceNotTrusted(const char * peerUdid)700 static void OnDeviceNotTrusted(const char *peerUdid)
701 {
702     if (peerUdid == NULL) {
703         LNN_LOGE(LNN_BUILDER, "invalid udid");
704         return;
705     }
706     uint32_t udidLen = strlen(peerUdid) + 1;
707     if (udidLen > UDID_BUF_LEN) {
708         LNN_LOGE(LNN_BUILDER, "udid is too long");
709         return;
710     }
711     if (DeletePcNodeInfo(peerUdid)) {
712         LNN_LOGI(LNN_BUILDER, "pc without softbus, handle offline");
713         return;
714     }
715     const char *useUdid = NULL;
716     char udid[UDID_BUF_LEN] = { 0 };
717     if (StringToLowerCase(peerUdid, udid, UDID_BUF_LEN) != SOFTBUS_OK) {
718         return;
719     }
720     useUdid = SelectUseUdid(peerUdid, udid);
721     if (useUdid == NULL) {
722         return;
723     }
724     LNN_CHECK_AND_RETURN_LOGW(!IsNeedNotifyOfflineByAdv(peerUdid), LNN_BUILDER, "need notify offline by adv");
725     NotTrustedDelayInfo *info = (NotTrustedDelayInfo *)SoftBusCalloc(sizeof(NotTrustedDelayInfo));
726     LNN_CHECK_AND_RETURN_LOGE(info != NULL, LNN_BUILDER, "malloc NotTrustedDelayInfo fail");
727     if (AuthGetLatestAuthSeqList(useUdid, info->authSeq, DISCOVERY_TYPE_COUNT) != SOFTBUS_OK) {
728         LNN_LOGE(LNN_BUILDER, "get latest AuthSeq list fail");
729         SoftBusFree(info);
730         return;
731     }
732     if (strcpy_s(info->udid, UDID_BUF_LEN, useUdid) != EOK) {
733         LNN_LOGE(LNN_BUILDER, "copy udid fail");
734         SoftBusFree(info);
735         return;
736     }
737     if (LnnSendNotTrustedInfo(info, DISCOVERY_TYPE_COUNT, LnnProcessCompleteNotTrustedMsg) != SOFTBUS_OK) {
738         LNN_LOGE(LNN_BUILDER, "send NotTrustedInfo fail");
739         OnLnnProcessNotTrustedMsgDelay((void *)info);
740         return;
741     }
742     if (LnnAsyncCallbackDelayHelper(GetLooper(LOOP_TYPE_DEFAULT), OnLnnProcessNotTrustedMsgDelay,
743         (void *)info, NOT_TRUSTED_DEVICE_MSG_DELAY) != SOFTBUS_OK) {
744         LNN_LOGE(LNN_BUILDER, "async not trusted msg delay fail");
745         SoftBusFree(info);
746     }
747 }
748 
749 AuthVerifyListener g_verifyListener = {
750     .onDeviceVerifyPass = OnDeviceVerifyPass,
751     .onDeviceNotTrusted = OnDeviceNotTrusted,
752     .onDeviceDisconnect = OnDeviceDisconnect,
753 };
754 
UserSwitchedHandler(const LnnEventBasicInfo * info)755 static void UserSwitchedHandler(const LnnEventBasicInfo *info)
756 {
757     if (info == NULL || info->event != LNN_EVENT_USER_SWITCHED) {
758         LNN_LOGW(LNN_BUILDER, "invalid param");
759         return;
760     }
761     const LnnMonitorHbStateChangedEvent *event = (const LnnMonitorHbStateChangedEvent *)info;
762     SoftBusUserSwitchState userSwitchState = (SoftBusUserSwitchState)event->status;
763     bool isDataShareInit = true;
764     switch (userSwitchState) {
765         case SOFTBUS_USER_SWITCHED:
766             LNN_LOGI(LNN_BUILDER, "SOFTBUS_USER_SWITCHED");
767             LnnGetDataShareInitResult(&isDataShareInit);
768             if (isDataShareInit) {
769                 RegisterOOBEMonitor(NULL);
770             }
771             LnnSetUnlockState();
772             break;
773         default:
774             return;
775     }
776 }
777 
InitNetBuilderLooper(void)778 static int32_t InitNetBuilderLooper(void)
779 {
780     ListInit(&LnnGetNetBuilder()->fsmList);
781     ListInit(&LnnGetNetBuilder()->pendingList);
782     LnnGetNetBuilder()->nodeType = NODE_TYPE_L;
783     LnnGetNetBuilder()->looper = GetLooper(LOOP_TYPE_DEFAULT);
784     if (LnnGetNetBuilder()->looper == NULL) {
785         LNN_LOGE(LNN_INIT, "get default looper fail");
786         return SOFTBUS_LOOPER_ERR;
787     }
788     LnnGetNetBuilder()->handler.name = (char *)"NetBuilderHandler";
789     LnnGetNetBuilder()->handler.looper = LnnGetNetBuilder()->looper;
790     LnnGetNetBuilder()->handler.HandleMessage = NetBuilderMessageHandler;
791     LnnGetNetBuilder()->isInit = true;
792     LNN_LOGI(LNN_INIT, "init net builder looper success");
793     return SOFTBUS_OK;
794 }
795 
InitSyncInfoReg(void)796 static int32_t InitSyncInfoReg(void)
797 {
798     int32_t rc = LnnRegSyncInfoHandler(LNN_INFO_TYPE_MASTER_ELECT, OnReceiveMasterElectMsg);
799     if (rc != SOFTBUS_OK) {
800         LNN_LOGE(LNN_INIT, "register sync master elect msg fail, rc=%{public}d", rc);
801         return rc;
802     }
803     rc = LnnRegSyncInfoHandler(LNN_INFO_TYPE_NODE_ADDR, OnReceiveNodeAddrChangedMsg);
804     if (rc != SOFTBUS_OK) {
805         LNN_LOGE(LNN_INIT, "register node addr changed msg fail, rc=%{public}d", rc);
806         return rc;
807     }
808     return SOFTBUS_OK;
809 }
810 
LnnInitNetBuilder(void)811 int32_t LnnInitNetBuilder(void)
812 {
813     if (LnnGetNetBuilder()->isInit == true) {
814         LNN_LOGI(LNN_INIT, "init net builder repeatly");
815         return SOFTBUS_OK;
816     }
817     int32_t rc = LnnInitSyncInfoManager();
818     if (rc != SOFTBUS_OK) {
819         LNN_LOGE(LNN_INIT, "init sync info manager fail, rc=%{public}d", rc);
820         return rc;
821     }
822     LnnInitTopoManager();
823     UpdateLocalNetCapability();
824     InitNodeInfoSync();
825     LnnInitConnIdCallbackManager();
826     NetBuilderConfigInit();
827     // link finder init fail will not cause softbus init fail
828     if (LnnLinkFinderInit() != SOFTBUS_OK) {
829         LNN_LOGE(LNN_INIT, "link finder init fail");
830     }
831     rc = RegAuthVerifyListener(&g_verifyListener);
832     if (rc != SOFTBUS_OK) {
833         LNN_LOGE(LNN_INIT, "register auth verify listener fail, rc=%{public}d", rc);
834         return rc;
835     }
836     rc = InitSyncInfoReg();
837     if (rc != SOFTBUS_OK) {
838         return rc;
839     }
840     rc = ConfigLocalLedger();
841     if (rc != SOFTBUS_OK) {
842         LNN_LOGE(LNN_INIT, "config local ledger fail, rc=%{public}d", rc);
843         return rc;
844     }
845     rc = LnnRegisterEventHandler(LNN_EVENT_ACCOUNT_CHANGED, AccountStateChangeHandler);
846     if (rc != SOFTBUS_OK) {
847         LNN_LOGE(LNN_INIT, "regist account change evt handler fail, rc=%{public}d", rc);
848         return rc;
849     }
850     rc = LnnRegisterEventHandler(LNN_EVENT_USER_SWITCHED, UserSwitchedHandler);
851     if (rc != SOFTBUS_OK) {
852         LNN_LOGE(LNN_INIT, "regist user switch evt handler fail, rc=%{public}d", rc);
853         return rc;
854     }
855     if (LnnInitModuleNotifyWithRetrySync(INIT_DEPS_KVSTORE, LnnSubcribeKvStoreService, RETRY_TIMES,
856         DELAY_REG_DP_TIME) != SOFTBUS_OK) {
857         LNN_LOGE(LNN_INIT, "regist kv store service fail!");
858     }
859     LnnInitSaStatusMonitor();
860     return InitNetBuilderLooper();
861 }
862 
LnnInitNetBuilderDelay(void)863 int32_t LnnInitNetBuilderDelay(void)
864 {
865     char udid[UDID_BUF_LEN] = { 0 };
866     // set master weight and master udid
867     int32_t ret = LnnGetLocalStrInfo(STRING_KEY_DEV_UDID, udid, UDID_BUF_LEN);
868     if (ret != SOFTBUS_OK) {
869         LNN_LOGE(LNN_INIT, "get local udid error!");
870         return ret;
871     }
872     LnnSetLocalStrInfo(STRING_KEY_MASTER_NODE_UDID, udid);
873     LnnSetLocalNumInfo(NUM_KEY_MASTER_NODE_WEIGHT, LnnGetLocalWeight());
874     ret = LnnInitFastOffline();
875     if (ret != SOFTBUS_OK) {
876         LNN_LOGE(LNN_INIT, "fast offline init fail!");
877         return ret;
878     }
879 #ifndef ENABLE_FEATURE_DATAMGR_SERVICE
880     LnnNotifyDataShareStateChangeEvent(SOFTBUS_DATA_SHARE_READY);
881 #endif
882     return SOFTBUS_OK;
883 }
884 
LnnDeinitNetBuilder(void)885 void LnnDeinitNetBuilder(void)
886 {
887     LnnConnectionFsm *item = NULL;
888     LnnConnectionFsm *nextItem = NULL;
889 
890     if (!LnnGetNetBuilder()->isInit) {
891         return;
892     }
893     LIST_FOR_EACH_ENTRY_SAFE(item, nextItem, &LnnGetNetBuilder()->fsmList, LnnConnectionFsm, node) {
894         StopConnectionFsm(item);
895     }
896     LnnUnregSyncInfoHandler(LNN_INFO_TYPE_MASTER_ELECT, OnReceiveMasterElectMsg);
897     LnnUnregSyncInfoHandler(LNN_INFO_TYPE_NODE_ADDR, OnReceiveNodeAddrChangedMsg);
898     LnnUnregisterEventHandler(LNN_EVENT_ACCOUNT_CHANGED, AccountStateChangeHandler);
899     LnnUnregisterEventHandler(LNN_EVENT_USER_SWITCHED, UserSwitchedHandler);
900     UnregAuthVerifyListener();
901     LnnDeinitTopoManager();
902     DeinitNodeInfoSync();
903     LnnDeinitFastOffline();
904     LnnDeinitSyncInfoManager();
905     LnnDeInitSaStatusMonitor();
906     LnnDeinitConnIdCallbackManager();
907     LnnGetNetBuilder()->isInit = false;
908 }