1 /*
2  * Copyright (c) 2021 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_sync_info_manager.h"
58 #include "lnn_sync_item_info.h"
59 #include "lnn_topo_manager.h"
60 #include "softbus_adapter_bt_common.h"
61 #include "softbus_adapter_crypto.h"
62 #include "softbus_adapter_json.h"
63 #include "softbus_adapter_mem.h"
64 #include "softbus_errcode.h"
65 #include "softbus_feature_config.h"
66 #include "softbus_hisysevt_bus_center.h"
67 #include "softbus_json_utils.h"
68 #include "softbus_adapter_json.h"
69 #include "softbus_utils.h"
70 #include "softbus_wifi_api_adapter.h"
71 #include "trans_channel_manager.h"
72 #include "lnn_net_builder.h"
73 #include "lnn_net_builder_process.h"
74 
75 
76 #define DEFAULT_PKG_NAME                 "com.huawei.nearby"
77 #define DEFAULT_MAX_LNN_CONNECTION_COUNT 10
78 #define NOT_TRUSTED_DEVICE_MSG_DELAY     5000
79 
80 
SetBeginJoinLnnTime(LnnConnectionFsm * connFsm)81 void SetBeginJoinLnnTime(LnnConnectionFsm *connFsm)
82 {
83     connFsm->statisticData.beginJoinLnnTime = LnnUpTimeMs();
84 }
85 
OnReAuthVerifyPassed(uint32_t requestId,AuthHandle authHandle,const NodeInfo * info)86 static void OnReAuthVerifyPassed(uint32_t requestId, AuthHandle authHandle, const NodeInfo *info)
87 {
88     LNN_LOGI(LNN_BUILDER, "reAuth verify passed: requestId=%{public}u, authId=%{public}" PRId64,
89         requestId, authHandle.authId);
90     if (info == NULL) {
91         LNN_LOGE(LNN_BUILDER, "reAuth verify result error");
92         return;
93     }
94     AuthRequest authRequest = { 0 };
95     if (GetAuthRequest(requestId, &authRequest) != SOFTBUS_OK) {
96         LNN_LOGE(LNN_BUILDER, "auth request not found");
97         return;
98     }
99     ConnectionAddr addr;
100     (void)memset_s(&addr, sizeof(ConnectionAddr), 0, sizeof(ConnectionAddr));
101     if (!LnnConvertAuthConnInfoToAddr(&addr, &authRequest.connInfo, GetCurrentConnectType())) {
102         LNN_LOGE(LNN_BUILDER, "ConvertToConnectionAddr failed");
103         return;
104     }
105     int32_t ret = SoftBusGenerateStrHash((unsigned char *)info->deviceInfo.deviceUdid,
106         strlen(info->deviceInfo.deviceUdid), (unsigned char *)addr.info.ble.udidHash);
107     if (ret != SOFTBUS_OK) {
108         LNN_LOGE(LNN_BUILDER, "gen udidHash fail");
109         return;
110     }
111     LnnConnectionFsm *connFsm = FindConnectionFsmByAddr(&addr, true);
112     if (connFsm != NULL && !connFsm->isDead && !LnnIsNeedCleanConnectionFsm(info, addr.type)) {
113         if (info != NULL && LnnUpdateGroupType(info) == SOFTBUS_OK && LnnUpdateAccountInfo(info) == SOFTBUS_OK) {
114             UpdateProfile(info);
115             NodeInfo nodeInfo;
116             (void)memset_s(&nodeInfo, sizeof(NodeInfo), 0, sizeof(NodeInfo));
117             (void)LnnGetRemoteNodeInfoById(info->deviceInfo.deviceUdid, CATEGORY_UDID, &nodeInfo);
118             UpdateDpSameAccount(nodeInfo.accountId, nodeInfo.deviceInfo.deviceUdid);
119         }
120     } else {
121         connFsm = StartNewConnectionFsm(&addr, DEFAULT_PKG_NAME, true);
122         if (connFsm == NULL) {
123             return;
124         }
125         connFsm->connInfo.authHandle = authHandle;
126         connFsm->connInfo.nodeInfo = DupNodeInfo(info);
127         connFsm->connInfo.flag |= LNN_CONN_INFO_FLAG_JOIN_AUTO;
128         LNN_LOGI(LNN_BUILDER, "fsmId=%{public}u start a connection fsm, authId=%{public}" PRId64,
129             connFsm->id, authHandle.authId);
130         if (LnnSendAuthResultMsgToConnFsm(connFsm, SOFTBUS_OK) != SOFTBUS_OK) {
131             SoftBusFree(connFsm->connInfo.nodeInfo);
132             connFsm->connInfo.nodeInfo = NULL;
133             StopConnectionFsm(connFsm);
134         }
135     }
136 }
137 
OnReAuthVerifyFailed(uint32_t requestId,int32_t reason)138 static void OnReAuthVerifyFailed(uint32_t requestId, int32_t reason)
139 {
140     LNN_LOGI(LNN_BUILDER, "verify failed. requestId=%{public}u, reason=%{public}d", requestId, reason);
141     if (reason >= SOFTBUS_HICHAIN_MIN && reason <= SOFTBUS_HICHAIN_MAX) {
142         AuthHandle authHandle = { .authId = AUTH_INVALID_ID };
143         PostVerifyResult(requestId, reason, authHandle, NULL);
144     }
145 }
146 
147 static AuthVerifyCallback g_reAuthVerifyCallback = {
148     .onVerifyPassed = OnReAuthVerifyPassed,
149     .onVerifyFailed = OnReAuthVerifyFailed,
150 };
151 
LnnGetReAuthVerifyCallback(void)152 AuthVerifyCallback *LnnGetReAuthVerifyCallback(void)
153 {
154     return &g_reAuthVerifyCallback;
155 }
156 
PostJoinRequestToConnFsm(LnnConnectionFsm * connFsm,const JoinLnnMsgPara * para,bool needReportFailure)157 int32_t PostJoinRequestToConnFsm(LnnConnectionFsm *connFsm, const JoinLnnMsgPara *para, bool needReportFailure)
158 {
159     if (para == NULL) {
160         LNN_LOGE(LNN_BUILDER, "JoinLnnMsgPara is null");
161         return SOFTBUS_INVALID_PARAM;
162     }
163     int32_t rc = SOFTBUS_OK;
164     bool isCreate = false;
165 
166     if (connFsm == NULL) {
167         connFsm = FindConnectionFsmByAddr(&para->addr, false);
168     }
169     if (connFsm == NULL || connFsm->isDead || CheckRemoteBasicInfoChanged(para->dupInfo)) {
170         connFsm = StartNewConnectionFsm(&para->addr, para->pkgName, para->isNeedConnect);
171         if (connFsm != NULL) {
172             connFsm->connInfo.dupInfo = (para->dupInfo == NULL) ? NULL : DupNodeInfo(para->dupInfo);
173         }
174         isCreate = true;
175     }
176     if (connFsm == NULL || LnnSendJoinRequestToConnFsm(connFsm) != SOFTBUS_OK) {
177         LNN_LOGE(LNN_BUILDER, "process join lnn request failed");
178         if (needReportFailure) {
179             LnnNotifyJoinResult((ConnectionAddr *)&para->addr, NULL, SOFTBUS_ERR);
180         }
181         if (connFsm != NULL && isCreate) {
182             LnnFsmRemoveMessageByType(&connFsm->fsm, FSM_CTRL_MSG_START);
183             ListDelete(&connFsm->node);
184             --LnnGetNetBuilder()->connCount;
185             LnnDestroyConnectionFsm(connFsm);
186         }
187         rc = SOFTBUS_ERR;
188     }
189     if (rc == SOFTBUS_OK) {
190         connFsm->connInfo.infoReport = para->infoReport;
191         connFsm->connInfo.flag |=
192             (needReportFailure ? LNN_CONN_INFO_FLAG_JOIN_REQUEST : LNN_CONN_INFO_FLAG_JOIN_AUTO);
193         LNN_LOGI(LNN_BUILDER, "infoReport.osType=%{public}d, infoReport.type=%{public}X",
194             connFsm->connInfo.infoReport.osType, connFsm->connInfo.infoReport.type);
195     }
196     return rc;
197 }
198 
TryRemovePendingJoinRequest(void)199 void TryRemovePendingJoinRequest(void)
200 {
201     PendingJoinRequestNode *item = NULL;
202     PendingJoinRequestNode *next = NULL;
203     JoinLnnMsgPara para;
204 
205     LIST_FOR_EACH_ENTRY_SAFE(item, next, &LnnGetNetBuilder()->pendingList, PendingJoinRequestNode, node) {
206         if (NeedPendingJoinRequest()) {
207             return;
208         }
209         ListDelete(&item->node);
210         (void)memset_s(&para, sizeof(JoinLnnMsgPara), 0, sizeof(JoinLnnMsgPara));
211         para.isNeedConnect = true;
212         para.addr = item->addr;
213         if (strcpy_s(para.pkgName, PKG_NAME_SIZE_MAX, DEFAULT_PKG_NAME) != EOK) {
214             LNN_LOGE(LNN_BUILDER, "strcpy_s pkgName failed");
215             SoftBusFree(item);
216             continue;
217         }
218         if (PostJoinRequestToConnFsm(NULL, &para, item->needReportFailure) != SOFTBUS_OK) {
219             LNN_LOGE(LNN_BUILDER, "post pending join request failed");
220         }
221         LNN_LOGI(
222             LNN_BUILDER, "remove a pending join request, peerAddr=%{public}s", LnnPrintConnectionAddr(&item->addr));
223         SoftBusFree(item);
224         break;
225     }
226 }
227 
InitiateNewNetworkOnline(ConnectionAddrType addrType,const char * networkId)228 void InitiateNewNetworkOnline(ConnectionAddrType addrType, const char *networkId)
229 {
230     LnnConnectionFsm *item = NULL;
231     int32_t rc;
232 
233     // find target connfsm, then notify it online
234     LIST_FOR_EACH_ENTRY(item, &LnnGetNetBuilder()->fsmList, LnnConnectionFsm, node) {
235         if (strcmp(networkId, item->connInfo.peerNetworkId) != 0) {
236             continue;
237         }
238         if (item->isDead) {
239             continue;
240         }
241         if (addrType != CONNECTION_ADDR_MAX && addrType != item->connInfo.addr.type) {
242             continue;
243         }
244         rc = LnnSendNewNetworkOnlineToConnFsm(item);
245         LNN_LOGI(LNN_INIT, "initiate new network online to connection. fsmId=%{public}u, rc=%{public}d", item->id, rc);
246     }
247 }
248 
TryInitiateNewNetworkOnline(const LnnConnectionFsm * connFsm)249 void TryInitiateNewNetworkOnline(const LnnConnectionFsm *connFsm)
250 {
251     LnnConnectionFsm *item = NULL;
252     LnnInvalidCleanInfo *cleanInfo = connFsm->connInfo.cleanInfo;
253 
254     if ((connFsm->connInfo.flag & LNN_CONN_INFO_FLAG_INITIATE_ONLINE) == 0) {
255         LNN_LOGI(LNN_INIT, "no need initiate new network online. fsmId=%{public}u", connFsm->id);
256         return;
257     }
258     // let last invalid connfsm notify new network online after it clean
259     LIST_FOR_EACH_ENTRY(item, &LnnGetNetBuilder()->fsmList, LnnConnectionFsm, node) {
260         if (strcmp(connFsm->connInfo.peerNetworkId, item->connInfo.peerNetworkId) != 0) {
261             continue;
262         }
263         if ((item->connInfo.flag & LNN_CONN_INFO_FLAG_INITIATE_ONLINE) == 0) {
264             continue;
265         }
266         LNN_LOGI(LNN_INIT, "wait last connfsm clean, then initiate new network online. fsmId=%{public}u", connFsm->id);
267         return;
268     }
269     InitiateNewNetworkOnline(cleanInfo->addrType, cleanInfo->networkId);
270 }
271 
TryDisconnectAllConnection(const LnnConnectionFsm * connFsm)272 void TryDisconnectAllConnection(const LnnConnectionFsm *connFsm)
273 {
274     LnnConnectionFsm *item = NULL;
275     const ConnectionAddr *addr1 = &connFsm->connInfo.addr;
276     const ConnectionAddr *addr2 = NULL;
277     ConnectOption option;
278 
279     // Not really leaving lnn
280     if ((connFsm->connInfo.flag & LNN_CONN_INFO_FLAG_ONLINE) == 0) {
281         return;
282     }
283     LIST_FOR_EACH_ENTRY(item, &LnnGetNetBuilder()->fsmList, LnnConnectionFsm, node) {
284         addr2 = &item->connInfo.addr;
285         if (addr1->type != addr2->type) {
286             continue;
287         }
288         if (addr1->type == CONNECTION_ADDR_BR || addr1->type == CONNECTION_ADDR_BLE) {
289             if (strncmp(item->connInfo.addr.info.br.brMac, addr2->info.br.brMac, BT_MAC_LEN) == 0) {
290                 return;
291             }
292         } else if (addr1->type == CONNECTION_ADDR_WLAN || addr1->type == CONNECTION_ADDR_ETH) {
293             if (strncmp(addr1->info.ip.ip, addr2->info.ip.ip, strlen(addr1->info.ip.ip)) == 0) {
294                 return;
295             }
296         }
297     }
298     if (addr1->type == CONNECTION_ADDR_BR) {
299         LNN_LOGI(
300             LNN_BUILDER, "not disconnect all connection. fsmId=%{public}u, type=%{public}d", connFsm->id, addr1->type);
301         return;
302     }
303     LNN_LOGI(LNN_BUILDER, "disconnect all connection. fsmId=%{public}u, type=%{public}d", connFsm->id, addr1->type);
304     if (LnnConvertAddrToOption(addr1, &option) && CheckAuthChannelIsExit(&option) != SOFTBUS_OK) {
305         ConnDisconnectDeviceAllConn(&option);
306     }
307 }
308 
TryNotifyAllTypeOffline(const LnnConnectionFsm * connFsm)309 void TryNotifyAllTypeOffline(const LnnConnectionFsm *connFsm)
310 {
311     LnnConnectionFsm *item = NULL;
312     const ConnectionAddr *addr1 = &connFsm->connInfo.addr;
313     const ConnectionAddr *addr2 = NULL;
314 
315     LIST_FOR_EACH_ENTRY(item, &LnnGetNetBuilder()->fsmList, LnnConnectionFsm, node) {
316         addr2 = &item->connInfo.addr;
317         if (addr1->type == addr2->type) {
318             return;
319         }
320     }
321     LNN_LOGI(LNN_BUILDER, "notify all connection offline. fsmId=%{public}u, type=%{public}d", connFsm->id, addr1->type);
322     (void)LnnNotifyAllTypeOffline(addr1->type);
323 }
324 
FindConnectionFsmByConnFsmId(uint16_t connFsmId)325 LnnConnectionFsm *FindConnectionFsmByConnFsmId(uint16_t connFsmId)
326 {
327     LnnConnectionFsm *item = NULL;
328 
329     LIST_FOR_EACH_ENTRY(item, &LnnGetNetBuilder()->fsmList, LnnConnectionFsm, node) {
330         if (connFsmId == item->id) {
331             return item;
332         }
333     }
334     return NULL;
335 }
336 
TryElectMasterNodeOnline(const LnnConnectionFsm * connFsm)337 int32_t TryElectMasterNodeOnline(const LnnConnectionFsm *connFsm)
338 {
339     char peerMasterUdid[UDID_BUF_LEN] = { 0 };
340     char localMasterUdid[UDID_BUF_LEN] = { 0 };
341     int32_t localMasterWeight;
342     int32_t peerMasterWeight;
343     int32_t rc;
344 
345     // get local master node info
346     if (LnnGetLocalStrInfo(STRING_KEY_MASTER_NODE_UDID, localMasterUdid, UDID_BUF_LEN) != SOFTBUS_OK ||
347         LnnGetLocalNumInfo(NUM_KEY_MASTER_NODE_WEIGHT, &localMasterWeight) != SOFTBUS_OK) {
348         LNN_LOGE(LNN_BUILDER, "get local master node info from ledger failed");
349         return SOFTBUS_NETWORK_GET_NODE_INFO_ERR;
350     }
351     LNN_LOGI(LNN_BUILDER, "local master fsmId=%{public}u, weight=%{public}d", connFsm->id, localMasterWeight);
352     if (LnnGetRemoteStrInfo(connFsm->connInfo.peerNetworkId, STRING_KEY_MASTER_NODE_UDID,
353         peerMasterUdid, UDID_BUF_LEN) != SOFTBUS_OK ||
354         LnnGetRemoteNumInfo(connFsm->connInfo.peerNetworkId, NUM_KEY_MASTER_NODE_WEIGHT,
355             &peerMasterWeight) != SOFTBUS_OK) {
356         LNN_LOGE(LNN_BUILDER, "peer node info is not found. fsmId=%{public}u", connFsm->id);
357         return SOFTBUS_NETWORK_NOT_FOUND;
358     }
359     LNN_LOGI(LNN_BUILDER, "peer master fsmId=%{public}u, weight=%{public}d", connFsm->id, peerMasterWeight);
360     rc = LnnCompareNodeWeight(localMasterWeight, localMasterUdid, peerMasterWeight, peerMasterUdid);
361     if (rc >= 0) {
362         LNN_LOGI(LNN_BUILDER,
363             "online node  weight less than current, no need elect again. fsmId=%{public}u, compareResult=%{public}d",
364             connFsm->id, rc);
365         return SOFTBUS_OK;
366     }
367     UpdateLocalMasterNode(false, peerMasterUdid, peerMasterWeight);
368     SendElectMessageToAll(connFsm->connInfo.peerNetworkId);
369     return SOFTBUS_OK;
370 }
371 
TryElectMasterNodeOffline(const LnnConnectionFsm * connFsm)372 int32_t TryElectMasterNodeOffline(const LnnConnectionFsm *connFsm)
373 {
374     char localUdid[UDID_BUF_LEN] = { 0 };
375     char localMasterUdid[UDID_BUF_LEN] = { 0 };
376 
377     if (LnnGetLocalStrInfo(STRING_KEY_MASTER_NODE_UDID, localMasterUdid, UDID_BUF_LEN) != SOFTBUS_OK) {
378         LNN_LOGE(LNN_BUILDER, "get local master node info from ledger failed");
379         return SOFTBUS_NETWORK_GET_NODE_INFO_ERR;
380     }
381     LnnGetLocalStrInfo(STRING_KEY_DEV_UDID, localUdid, UDID_BUF_LEN);
382     if (strcmp(localMasterUdid, localUdid) == 0) {
383         LNN_LOGI(LNN_BUILDER, "local is master node, no need elect again. fsmId=%{public}u", connFsm->id);
384     } else {
385         LNN_LOGI(LNN_BUILDER, "maybe master node offline, elect again. fsmId=%{public}u", connFsm->id);
386         UpdateLocalMasterNode(true, localUdid, LnnGetLocalWeight());
387         SendElectMessageToAll(connFsm->connInfo.peerNetworkId);
388     }
389     return SOFTBUS_OK;
390 }
391 
IsSupportMasterNodeElect(SoftBusVersion version)392 bool IsSupportMasterNodeElect(SoftBusVersion version)
393 {
394     LNN_LOGD(LNN_BUILDER, "SoftBusVersion=%{public}d", version);
395     return version >= SOFTBUS_NEW_V1;
396 }
397 
TryElectAsMasterState(const char * networkId,bool isOnline)398 void TryElectAsMasterState(const char *networkId, bool isOnline)
399 {
400     if (networkId == NULL) {
401         LNN_LOGW(LNN_BUILDER, "invalid networkId");
402         return;
403     }
404     if (isOnline) {
405         LNN_LOGD(LNN_BUILDER, "restore master state ignore online process");
406         return;
407     }
408     char masterUdid[UDID_BUF_LEN] = { 0 };
409     char localUdid[UDID_BUF_LEN] = { 0 };
410     if (LnnGetLocalStrInfo(STRING_KEY_MASTER_NODE_UDID, masterUdid, UDID_BUF_LEN) != SOFTBUS_OK) {
411         LNN_LOGE(LNN_BUILDER, "get local master node info from ledger failed");
412         return;
413     }
414     const char *peerUdid = LnnConvertDLidToUdid(networkId, CATEGORY_NETWORK_ID);
415     if (peerUdid == NULL) {
416         char *anonyNetworkId = NULL;
417         Anonymize(networkId, &anonyNetworkId);
418         LNN_LOGE(LNN_BUILDER, "get invalid peerUdid, networkId=%{public}s", anonyNetworkId);
419         AnonymizeFree(anonyNetworkId);
420         return;
421     }
422     if (strcmp(masterUdid, peerUdid) != 0) {
423         char *anonyPeerUdid = NULL;
424         char *anonyMasterUdid = NULL;
425         Anonymize(peerUdid, &anonyPeerUdid);
426         Anonymize(masterUdid, &anonyMasterUdid);
427         LNN_LOGD(LNN_BUILDER, "offline node is not master node. peerUdid=%{public}s, masterUdid=%{public}s",
428             anonyPeerUdid, anonyMasterUdid);
429         AnonymizeFree(anonyPeerUdid);
430         AnonymizeFree(anonyMasterUdid);
431         return;
432     }
433     if (LnnGetLocalStrInfo(STRING_KEY_DEV_UDID, localUdid, UDID_BUF_LEN) != SOFTBUS_OK) {
434         LNN_LOGE(LNN_BUILDER, "get local udid failed");
435         return;
436     }
437     UpdateLocalMasterNode(true, localUdid, LnnGetLocalWeight());
438 }
439 
DeinitNodeInfoSync(void)440 static void DeinitNodeInfoSync(void)
441 {
442     LnnDeinitP2p();
443     LnnDeinitNetworkInfo();
444     LnnDeinitDevicename();
445     LnnDeinitOffline();
446     LnnDeinitBatteryInfo();
447     LnnDeinitWifiDirect();
448 }
449 
NetBuilderConfigInit(void)450 static void NetBuilderConfigInit(void)
451 {
452     if (SoftbusGetConfig(SOFTBUS_INT_MAX_LNN_CONNECTION_CNT, (unsigned char *)&LnnGetNetBuilder()->maxConnCount,
453         sizeof(LnnGetNetBuilder()->maxConnCount)) != SOFTBUS_OK) {
454         LNN_LOGE(LNN_INIT, "get lnn max connection count fail, use default value");
455         LnnGetNetBuilder()->maxConnCount = DEFAULT_MAX_LNN_CONNECTION_COUNT;
456     }
457     if (SoftbusGetConfig(SOFTBUS_INT_LNN_MAX_CONCURRENT_NUM, (unsigned char *)&LnnGetNetBuilder()->maxConcurrentCount,
458         sizeof(LnnGetNetBuilder()->maxConcurrentCount)) != SOFTBUS_OK) {
459         LNN_LOGE(LNN_INIT, "get lnn max conncurent count fail, use default value");
460         LnnGetNetBuilder()->maxConcurrentCount = 0;
461     }
462     LNN_LOGD(LNN_INIT, "lnn config count: maxConnCount=%{public}d, maxConcurrentCount=%{public}d",
463         LnnGetNetBuilder()->maxConnCount, LnnGetNetBuilder()->maxConcurrentCount);
464 }
465 
InitNodeInfoSync(void)466 static int32_t InitNodeInfoSync(void)
467 {
468     if (LnnInitP2p() != SOFTBUS_OK) {
469         LNN_LOGE(LNN_INIT, "init lnn p2p fail");
470         return SOFTBUS_ERR;
471     }
472     if (LnnInitNetworkInfo() != SOFTBUS_OK) {
473         LNN_LOGE(LNN_INIT, "LnnInitNetworkInfo fail");
474         return SOFTBUS_ERR;
475     }
476     if (LnnInitDevicename() != SOFTBUS_OK) {
477         LNN_LOGE(LNN_INIT, "LnnInitDeviceName fail");
478         return SOFTBUS_ERR;
479     }
480     if (LnnInitOffline() != SOFTBUS_OK) {
481         LNN_LOGE(LNN_INIT, "LnnInitOffline fail");
482         return SOFTBUS_ERR;
483     }
484     if (LnnInitBatteryInfo() != SOFTBUS_OK) {
485         LNN_LOGE(LNN_INIT, "LnnInitBatteryInfo fail");
486         return SOFTBUS_ERR;
487     }
488     if (LnnInitCipherKeyManager() != SOFTBUS_OK) {
489         LNN_LOGE(LNN_INIT, "LnnInitCipherKeyManager fail");
490         return SOFTBUS_ERR;
491     }
492     if (LnnInitWifiDirect() != SOFTBUS_OK) {
493         LNN_LOGE(LNN_INIT, "init lnn wifidirect addr fail");
494         return SOFTBUS_ERR;
495     }
496     return SOFTBUS_OK;
497 }
498 
UpdatePCInfoWithoutSoftbus(void)499 static void UpdatePCInfoWithoutSoftbus(void)
500 {
501     int32_t onlineNum = 0;
502     NodeBasicInfo *info = NULL;
503     if (LnnGetAllOnlineNodeInfo(&info, &onlineNum) != 0) {
504         LNN_LOGE(LNN_BUILDER, "LnnGetAllOnlineNodeInfo failed!");
505         return;
506     }
507     if (info == NULL || onlineNum == 0) {
508         LNN_LOGW(LNN_BUILDER, "not online node");
509         return;
510     }
511     // mark-- remove pc offline
512     SoftBusFree(info);
513 }
514 
AccountStateChangeHandler(const LnnEventBasicInfo * info)515 static void AccountStateChangeHandler(const LnnEventBasicInfo *info)
516 {
517     if (info == NULL || info->event != LNN_EVENT_ACCOUNT_CHANGED) {
518         LNN_LOGW(LNN_BUILDER, "invalid param");
519         return;
520     }
521     const LnnMonitorHbStateChangedEvent *event = (const LnnMonitorHbStateChangedEvent *)info;
522     SoftBusAccountState accountState = (SoftBusAccountState)event->status;
523     switch (accountState) {
524         case SOFTBUS_ACCOUNT_LOG_IN:
525             LNN_LOGI(LNN_BUILDER, "ignore SOFTBUS_ACCOUNT_LOG_IN");
526             break;
527         case SOFTBUS_ACCOUNT_LOG_OUT:
528             LNN_LOGI(LNN_BUILDER, "handle SOFTBUS_ACCOUNT_LOG_OUT");
529             UpdatePCInfoWithoutSoftbus();
530             break;
531         default:
532             return;
533     }
534 }
535 
OnDeviceVerifyPass(AuthHandle authHandle,const NodeInfo * info)536 static void OnDeviceVerifyPass(AuthHandle authHandle, const NodeInfo *info)
537 {
538     AuthConnInfo connInfo;
539     DeviceVerifyPassMsgPara *para = NULL;
540     LNN_LOGI(LNN_BUILDER, "verify passed passively, authId=%{public}" PRId64, authHandle.authId);
541     if (authHandle.type < AUTH_LINK_TYPE_WIFI || authHandle.type >= AUTH_LINK_TYPE_MAX) {
542         LNN_LOGE(LNN_BUILDER, "authHandle type error");
543         return;
544     }
545     if (AuthGetConnInfo(authHandle, &connInfo) != SOFTBUS_OK) {
546         LNN_LOGE(LNN_BUILDER, "get AuthConnInfo fail, authId=%{public}" PRId64, authHandle.authId);
547         return;
548     }
549     para = (DeviceVerifyPassMsgPara *)SoftBusMalloc(sizeof(DeviceVerifyPassMsgPara));
550     if (para == NULL) {
551         LNN_LOGE(LNN_BUILDER, "malloc DeviceVerifyPassMsgPara fail");
552         return;
553     }
554     if (!LnnConvertAuthConnInfoToAddr(&para->addr, &connInfo, GetCurrentConnectType())) {
555         LNN_LOGE(LNN_BUILDER, "convert connInfo to addr fail");
556         SoftBusFree(para);
557         return;
558     }
559     para->authHandle = authHandle;
560     para->nodeInfo = DupNodeInfo(info);
561     if (para->nodeInfo == NULL) {
562         LNN_LOGE(LNN_BUILDER, "dup NodeInfo fail");
563         SoftBusFree(para);
564         return;
565     }
566     if (PostBuildMessageToHandler(MSG_TYPE_DEVICE_VERIFY_PASS, para) != SOFTBUS_OK) {
567         LNN_LOGE(LNN_BUILDER, "post DEVICE_VERIFY_PASS msg fail");
568         SoftBusFree(para->nodeInfo);
569         SoftBusFree(para);
570     }
571     if (info != NULL) {
572         LnnNotifyDeviceVerified(info->deviceInfo.deviceUdid);
573     }
574 }
575 
OnDeviceDisconnect(AuthHandle authHandle)576 static void OnDeviceDisconnect(AuthHandle authHandle)
577 {
578     if (authHandle.type < AUTH_LINK_TYPE_WIFI || authHandle.type >= AUTH_LINK_TYPE_MAX) {
579         LNN_LOGE(LNN_BUILDER, "authHandle type error");
580         return;
581     }
582     AuthHandle *para = NULL;
583     para = (AuthHandle *)SoftBusMalloc(sizeof(AuthHandle));
584     if (para == NULL) {
585         LNN_LOGE(LNN_BUILDER, "malloc DeviceDisconnect para fail");
586         return;
587     }
588     LNN_LOGI(LNN_BUILDER, "auth device disconnect, authId=%{public}" PRId64, authHandle.authId);
589     para->authId = authHandle.authId;
590     para->type = authHandle.type;
591     if (PostBuildMessageToHandler(MSG_TYPE_DEVICE_DISCONNECT, para) != SOFTBUS_OK) {
592         LNN_LOGE(LNN_BUILDER, "post DEVICE_DISCONNECT msg fail");
593         SoftBusFree(para);
594     }
595 }
596 
OnDeviceNotTrusted(const char * peerUdid)597 static void OnDeviceNotTrusted(const char *peerUdid)
598 {
599     if (peerUdid == NULL) {
600         LNN_LOGE(LNN_BUILDER, "invalid udid");
601         return;
602     }
603     uint32_t udidLen = strlen(peerUdid) + 1;
604     if (udidLen > UDID_BUF_LEN) {
605         LNN_LOGE(LNN_BUILDER, "udid is too long");
606         return;
607     }
608     if (DeletePcNodeInfo(peerUdid)) {
609         LNN_LOGI(LNN_BUILDER, "pc without softbus, handle offline");
610         return;
611     }
612     const char *useUdid = NULL;
613     char udid[UDID_BUF_LEN] = { 0 };
614     if (StringToLowerCase(peerUdid, udid, UDID_BUF_LEN) != SOFTBUS_OK) {
615         return;
616     }
617     useUdid = SelectUseUdid(peerUdid, udid);
618     if (useUdid == NULL) {
619         return;
620     }
621     LnnDeleteLinkFinderInfo(peerUdid);
622     NotTrustedDelayInfo *info = (NotTrustedDelayInfo *)SoftBusCalloc(sizeof(NotTrustedDelayInfo));
623     if (info == NULL) {
624         LNN_LOGE(LNN_BUILDER, "malloc NotTrustedDelayInfo fail");
625         return;
626     }
627     if (AuthGetLatestAuthSeqList(useUdid, info->authSeq, DISCOVERY_TYPE_COUNT) != SOFTBUS_OK) {
628         LNN_LOGE(LNN_BUILDER, "get latest AuthSeq list fail");
629         SoftBusFree(info);
630         return;
631     }
632     if (strcpy_s(info->udid, UDID_BUF_LEN, useUdid) != EOK) {
633         LNN_LOGE(LNN_BUILDER, "copy udid fail");
634         SoftBusFree(info);
635         return;
636     }
637     if (LnnSendNotTrustedInfo(info, DISCOVERY_TYPE_COUNT, LnnProcessCompleteNotTrustedMsg) != SOFTBUS_OK) {
638         LNN_LOGE(LNN_BUILDER, "send NotTrustedInfo fail");
639         OnLnnProcessNotTrustedMsgDelay((void *)info);
640         return;
641     }
642     if (LnnAsyncCallbackDelayHelper(GetLooper(LOOP_TYPE_DEFAULT), OnLnnProcessNotTrustedMsgDelay,
643         (void *)info, NOT_TRUSTED_DEVICE_MSG_DELAY) != SOFTBUS_OK) {
644         LNN_LOGE(LNN_BUILDER, "async not trusted msg delay fail");
645         SoftBusFree(info);
646     }
647 }
648 
649 AuthVerifyListener g_verifyListener = {
650     .onDeviceVerifyPass = OnDeviceVerifyPass,
651     .onDeviceNotTrusted = OnDeviceNotTrusted,
652     .onDeviceDisconnect = OnDeviceDisconnect,
653 };
654 
UserSwitchedHandler(const LnnEventBasicInfo * info)655 static void UserSwitchedHandler(const LnnEventBasicInfo *info)
656 {
657     if (info == NULL || info->event != LNN_EVENT_USER_SWITCHED) {
658         LNN_LOGW(LNN_BUILDER, "invalid param");
659         return;
660     }
661     const LnnMonitorHbStateChangedEvent *event = (const LnnMonitorHbStateChangedEvent *)info;
662     SoftBusUserSwitchState userSwitchState = (SoftBusUserSwitchState)event->status;
663     switch (userSwitchState) {
664         case SOFTBUS_USER_SWITCHED:
665             LNN_LOGI(LNN_BUILDER, "SOFTBUS_USER_SWITCHED");
666             RegisterOOBEMonitor(NULL);
667             LnnSetUnlockState();
668             break;
669         default:
670             return;
671     }
672 }
673 
InitNetBuilderLooper(void)674 static int32_t InitNetBuilderLooper(void)
675 {
676     ListInit(&LnnGetNetBuilder()->fsmList);
677     ListInit(&LnnGetNetBuilder()->pendingList);
678     LnnGetNetBuilder()->nodeType = NODE_TYPE_L;
679     LnnGetNetBuilder()->looper = GetLooper(LOOP_TYPE_DEFAULT);
680     if (LnnGetNetBuilder()->looper == NULL) {
681         LNN_LOGE(LNN_INIT, "get default looper fail");
682         return SOFTBUS_LOOPER_ERR;
683     }
684     LnnGetNetBuilder()->handler.name = (char *)"NetBuilderHandler";
685     LnnGetNetBuilder()->handler.looper = LnnGetNetBuilder()->looper;
686     LnnGetNetBuilder()->handler.HandleMessage = NetBuilderMessageHandler;
687     LnnGetNetBuilder()->isInit = true;
688     LNN_LOGI(LNN_INIT, "init net builder looper success");
689     return SOFTBUS_OK;
690 }
691 
LnnInitNetBuilder(void)692 int32_t LnnInitNetBuilder(void)
693 {
694     if (LnnGetNetBuilder()->isInit == true) {
695         LNN_LOGI(LNN_INIT, "init net builder repeatly");
696         return SOFTBUS_OK;
697     }
698     if (LnnInitSyncInfoManager() != SOFTBUS_OK) {
699         LNN_LOGE(LNN_INIT, "init sync info manager fail");
700         return SOFTBUS_ERR;
701     }
702     LnnInitTopoManager();
703     UpdateLocalNetCapability();
704     InitNodeInfoSync();
705     NetBuilderConfigInit();
706     // link finder init fail will not cause softbus init fail
707     if (LnnLinkFinderInit() != SOFTBUS_OK) {
708         LNN_LOGE(LNN_INIT, "link finder init fail");
709     }
710     if (RegAuthVerifyListener(&g_verifyListener) != SOFTBUS_OK) {
711         LNN_LOGE(LNN_INIT, "register auth verify listener fail");
712         return SOFTBUS_ERR;
713     }
714     if (LnnRegSyncInfoHandler(LNN_INFO_TYPE_MASTER_ELECT, OnReceiveMasterElectMsg) != SOFTBUS_OK) {
715         LNN_LOGE(LNN_INIT, "register sync master elect msg fail");
716         return SOFTBUS_ERR;
717     }
718     if (LnnRegSyncInfoHandler(LNN_INFO_TYPE_NODE_ADDR, OnReceiveNodeAddrChangedMsg) != SOFTBUS_OK) {
719         LNN_LOGE(LNN_INIT, "register node addr changed msg fail");
720         return SOFTBUS_ERR;
721     }
722     if (ConifgLocalLedger() != SOFTBUS_OK) {
723         LNN_LOGE(LNN_INIT, "config local ledger fail");
724         return SOFTBUS_ERR;
725     }
726     if (LnnRegisterEventHandler(LNN_EVENT_ACCOUNT_CHANGED, AccountStateChangeHandler) != SOFTBUS_OK) {
727         LNN_LOGE(LNN_INIT, "regist account change evt handler fail!");
728         return SOFTBUS_ERR;
729     }
730     if (LnnRegisterEventHandler(LNN_EVENT_USER_SWITCHED, UserSwitchedHandler) != SOFTBUS_OK) {
731         LNN_LOGE(LNN_INIT, "regist user switch evt handler fail!");
732         return SOFTBUS_ERR;
733     }
734     if (!LnnSubcribeKvStoreService()) {
735         LNN_LOGE(LNN_INIT, "regist kv store service fail!");
736     }
737     return InitNetBuilderLooper();
738 }
739 
740 
LnnInitNetBuilderDelay(void)741 int32_t LnnInitNetBuilderDelay(void)
742 {
743     char udid[UDID_BUF_LEN] = { 0 };
744     // set master weight and master udid
745     int32_t ret = LnnGetLocalStrInfo(STRING_KEY_DEV_UDID, udid, UDID_BUF_LEN);
746     if (ret != SOFTBUS_OK) {
747         LNN_LOGE(LNN_INIT, "get local udid error!");
748         return ret;
749     }
750     LnnSetLocalStrInfo(STRING_KEY_MASTER_NODE_UDID, udid);
751     LnnSetLocalNumInfo(NUM_KEY_MASTER_NODE_WEIGHT, LnnGetLocalWeight());
752     if (LnnInitFastOffline() != SOFTBUS_OK) {
753         LNN_LOGE(LNN_INIT, "fast offline init fail!");
754         return SOFTBUS_ERR;
755     }
756     return SOFTBUS_OK;
757 }
758 
LnnDeinitNetBuilder(void)759 void LnnDeinitNetBuilder(void)
760 {
761     LnnConnectionFsm *item = NULL;
762     LnnConnectionFsm *nextItem = NULL;
763 
764     if (!LnnGetNetBuilder()->isInit) {
765         return;
766     }
767     LIST_FOR_EACH_ENTRY_SAFE(item, nextItem, &LnnGetNetBuilder()->fsmList, LnnConnectionFsm, node) {
768         StopConnectionFsm(item);
769     }
770     LnnUnregSyncInfoHandler(LNN_INFO_TYPE_MASTER_ELECT, OnReceiveMasterElectMsg);
771     LnnUnregSyncInfoHandler(LNN_INFO_TYPE_NODE_ADDR, OnReceiveNodeAddrChangedMsg);
772     LnnUnregisterEventHandler(LNN_EVENT_ACCOUNT_CHANGED, AccountStateChangeHandler);
773     UnregAuthVerifyListener();
774     LnnDeinitTopoManager();
775     DeinitNodeInfoSync();
776     LnnDeinitFastOffline();
777     LnnDeinitSyncInfoManager();
778     LnnGetNetBuilder()->isInit = false;
779 }