Merge branch 'master' of gitee.com:openharmony/communication_dsoftbus into syspara_0801

This commit is contained in:
Mupceet 2022-08-08 14:07:36 +00:00 committed by Gitee
commit fde9abac3f
246 changed files with 7824 additions and 960 deletions

View File

@ -37,6 +37,8 @@ if (defined(ohos_lite)) {
"$dsoftbus_root_path/interfaces/kits/common",
"//utils/native/base/include",
"//base/startup/init/interfaces/innerkits/include/syspara",
"//commonlibrary/c_utils/base/include",
"//base/startup/syspara_lite/interfaces/innerkits/native/syspara/include",
"//third_party/bounds_checking_function/include",
]
@ -142,7 +144,7 @@ if (defined(ohos_lite)) {
"$dsoftbus_root_path/interfaces/kits",
"$dsoftbus_root_path/interfaces/kits/common",
"//base/startup/init/interfaces/innerkits/include/syspara",
"//utils/native/base/include",
"//commonlibrary/c_utils/base/include",
"//third_party/bounds_checking_function/include",
]
sources = [
@ -160,7 +162,6 @@ if (defined(ohos_lite)) {
public_deps = [
"//base/startup/init/interfaces/innerkits:libbegetutil",
"//third_party/bounds_checking_function:libsec_static",
"//utils/native/base:utils",
]
native_source_path = rebase_path("$dsoftbus_root_path")
@ -192,6 +193,7 @@ if (defined(ohos_lite)) {
public_configs = [ ":config_adapter_common" ]
if (is_standard_system) {
external_deps = [
"c_utils:utils",
"hisysevent_native:libhisysevent",
"hiviewdfx_hilog_native:libhilog",
]

View File

@ -18,6 +18,14 @@ adapter_bus_center_path = "$softbus_adapter_common/bus_center"
bus_center_adapter_src = []
bus_center_adapter_inc = [ "$softbus_adapter_common/bus_center/include" ]
bus_center_adapter_deps = []
if (!defined(global_parts_info) ||
defined(global_parts_info.notification_common_event_service)) {
has_ces_part = true
} else {
has_ces_part = false
}
if (defined(ohos_lite)) {
if (ohos_kernel_type == "liteos_m") {
if (dsoftbus_feature_lnn_net) {
@ -28,6 +36,7 @@ if (defined(ohos_lite)) {
"$adapter_bus_center_path/network/lnn_lwip_monitor.c",
"$adapter_bus_center_path/network/lnn_netlink_monitor_virtual.c",
"$adapter_bus_center_path/platform/lnn_product_monitor_virtual.c",
"$adapter_bus_center_path/screenstate/lnn_screenstate_monitor_virtual.cpp",
"$adapter_bus_center_path/wlan/lnn_wifiservice_monitor_virtual.cpp",
]
}
@ -40,6 +49,7 @@ if (defined(ohos_lite)) {
"$adapter_bus_center_path/network/lnn_lwip_monitor_virtual.c",
"$adapter_bus_center_path/network/lnn_netlink_monitor.c",
"$adapter_bus_center_path/platform/lnn_product_monitor_virtual.c",
"$adapter_bus_center_path/screenstate/lnn_screenstate_monitor_virtual.cpp",
"$adapter_bus_center_path/wlan/lnn_wifiservice_monitor_virtual.cpp",
]
}
@ -58,6 +68,7 @@ if (defined(ohos_lite)) {
"$adapter_bus_center_path/network/lnn_lwip_monitor_virtual.c",
"$adapter_bus_center_path/network/lnn_netlink_monitor_virtual.c",
"$adapter_bus_center_path/platform/lnn_product_monitor.c",
"$adapter_bus_center_path/screenstate/lnn_screenstate_monitor_virtual.cpp",
"$adapter_bus_center_path/wlan/lnn_wifiservice_monitor_virtual.cpp",
]
bus_center_adapter_inc += [
@ -72,8 +83,15 @@ if (defined(ohos_lite)) {
}
}
} else {
bus_center_adapter_inc += [ "//utils/native/base/include" ]
bus_center_adapter_external_deps = []
if (has_ces_part) {
bus_center_adapter_src +=
[ "$adapter_bus_center_path/screenstate/lnn_screenstate_monitor.cpp" ]
bus_center_adapter_external_deps +=
[ "common_event_service:cesfwk_innerkits" ]
} else {
bus_center_adapter_src += [ "$adapter_bus_center_path/screenstate/lnn_screenstate_monitor_virtual.cpp" ]
}
if (dsoftbus_feature_lnn_net) {
bus_center_adapter_src += [
"$adapter_bus_center_path/driver/lnn_driver_monitor_virtual.c",
@ -83,7 +101,6 @@ if (defined(ohos_lite)) {
"$adapter_bus_center_path/network/lnn_netlink_monitor.c",
"$adapter_bus_center_path/platform/lnn_product_monitor_virtual.c",
]
if (dsoftbus_feature_lnn_wifiservice_dependence) {
bus_center_adapter_src +=
[ "$adapter_bus_center_path/wlan/lnn_wifiservice_monitor.cpp" ]
@ -92,8 +109,6 @@ if (defined(ohos_lite)) {
"//foundation/communication/wifi/wifi/services/wifi_standard/wifi_framework/common/net_helper",
]
bus_center_adapter_deps += []
bus_center_adapter_external_deps +=
[ "common_event_service:cesfwk_innerkits" ]
} else {
bus_center_adapter_src += [
"$adapter_bus_center_path/wlan/lnn_wifiservice_monitor_virtual.cpp",
@ -101,3 +116,15 @@ if (defined(ohos_lite)) {
}
}
}
if (dsoftbus_feature_lnn_net) {
if (dsoftbus_feature_conn_br || dsoftbus_feature_conn_ble) {
bus_center_adapter_src +=
[ "$adapter_bus_center_path/network/lnn_bt_monitor.c" ]
bus_center_adapter_inc +=
[ "$softbus_adapter_common/net/bluetooth/include" ]
} else {
bus_center_adapter_src +=
[ "$adapter_bus_center_path/network/lnn_bt_monitor_virtual.c" ]
}
}

View File

@ -16,7 +16,6 @@
#include "lnn_event_monitor_impl.h"
#include "softbus_errcode.h"
int32_t LnnInitDriverMonitorImpl(void)
{
return SOFTBUS_OK;

View File

@ -80,7 +80,7 @@ static void ProcessLwipEvent(struct HdfSBuf *data)
static void ProcessWlanEvent(struct HdfSBuf *data)
{
LnnNotifyWlanStateChangeEvent(SOFTBUS_UNKNOWN);
LnnNotifyWlanStateChangeEvent(SOFTBUS_WIFI_UNKNOWN);
}
static int32_t OnReceiveDriverEvent(

View File

@ -24,6 +24,7 @@ extern "C" {
#endif
typedef int32_t (*LnnInitEventMonitorImpl)(void);
typedef void (*LnnDeinitEventMonitorImpl)(void);
int32_t LnnInitNetlinkMonitorImpl(void);
@ -34,7 +35,14 @@ int32_t LnnInitLwipMonitorImpl(void);
int32_t LnnInitWifiServiceMonitorImpl(void);
int32_t LnnInitDriverMonitorImpl(void);
int32_t LnnInitScreenStateMonitorImpl(void);
int32_t LnnInitBtStateMonitorImpl(void);
void LnnDeinitBtStateMonitorImpl(void);
#ifdef __cplusplus
}
#endif
#endif /* LNN_EVENT_MONITOR_IMPL_H */
#endif /* LNN_EVENT_MONITOR_IMPL_H */

View File

@ -0,0 +1,94 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "lnn_event_monitor_impl.h"
#include <securec.h>
#include "bus_center_event.h"
#include "lnn_async_callback_utils.h"
#include "softbus_adapter_bt_common.h"
#include "softbus_adapter_mem.h"
#include "softbus_errcode.h"
#include "softbus_log.h"
static int32_t g_btStateListenerId = -1;
static void LnnOnBtStateChanged(int32_t listenerId, int32_t state);
static SoftBusBtStateListener g_btStateListener = {
.OnBtStateChanged = LnnOnBtStateChanged
};
static void LnnOnBtStateChanged(int32_t listenerId, int32_t state)
{
if (listenerId < 0 || state < 0) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "bt monitor get invalid param");
return;
}
SoftBusBtStackState btState = (SoftBusBtStackState)state;
SoftBusBtState *notifyState = (SoftBusBtState *)SoftBusMalloc(sizeof(SoftBusBtState));
if (notifyState == NULL) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "bt monitor malloc err");
return;
}
*notifyState = SOFTBUS_BT_UNKNOWN;
switch (btState) {
case SOFTBUS_BT_STATE_TURN_ON:
*notifyState = SOFTBUS_BLE_TURN_ON;
break;
case SOFTBUS_BT_STATE_TURN_OFF:
*notifyState = SOFTBUS_BLE_TURN_OFF;
break;
case SOFTBUS_BR_STATE_TURN_ON:
*notifyState = SOFTBUS_BR_TURN_ON;
break;
case SOFTBUS_BR_STATE_TURN_OFF:
*notifyState = SOFTBUS_BR_TURN_OFF;
break;
default:
break;
}
if (*notifyState == SOFTBUS_BT_UNKNOWN) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_DBG, "lnn bt state changed but no need notify, btState:%d", btState);
SoftBusFree(notifyState);
return;
}
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "lnn async notify bt state changed, listenerId:%d, notifyState:%d",
listenerId, *notifyState);
int32_t ret = LnnAsyncCallbackHelper(GetLooper(LOOP_TYPE_DEFAULT), LnnNotifyBtStateChangeEvent, notifyState);
if (ret != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "lnn async notify bt state err, ret:%d", ret);
SoftBusFree(notifyState);
return;
}
}
int32_t LnnInitBtStateMonitorImpl(void)
{
g_btStateListenerId = SoftBusAddBtStateListener(&g_btStateListener);
if (g_btStateListenerId < 0) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "monitor add bt state listener fail");
return SOFTBUS_ERR;
}
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "lnn bt state monitor impl start success");
return SOFTBUS_OK;
}
void LnnDeinitBtStateMonitorImpl(void)
{
(void)SoftBusRemoveBtStateListener(g_btStateListenerId);
}

View File

@ -0,0 +1,27 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "lnn_event_monitor_impl.h"
#include "softbus_errcode.h"
int32_t LnnInitBtStateMonitorImpl(void)
{
return SOFTBUS_OK;
}
void LnnDeinitBtStateMonitorImpl(void)
{
}

View File

@ -106,8 +106,9 @@ static int32_t RtNetlinkTalk(struct nlmsghdr *nlMsgHdr, struct nlmsghdr *answer,
while (true) {
status = SoftBusSocketRecv(fd, answer, maxlen, 0);
if (status < 0) {
if (status == SOFTBUS_ADAPTER_SOCKET_EINTR || status == SOFTBUS_ADAPTER_SOCKET_EAGAIN)
if (status == SOFTBUS_ADAPTER_SOCKET_EINTR || status == SOFTBUS_ADAPTER_SOCKET_EAGAIN) {
continue;
}
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "netlink receive error (%d)", status);
SoftBusSocketClose(fd);
return SOFTBUS_ERR;

View File

@ -0,0 +1,122 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "lnn_event_monitor_impl.h"
#include <securec.h>
#include "bus_center_event.h"
#include "common_event_data.h"
#include "common_event_manager.h"
#include "common_event_subscriber.h"
#include "common_event_support.h"
#include "lnn_async_callback_utils.h"
#include "want.h"
#include "softbus_adapter_mem.h"
#include "softbus_errcode.h"
#include "softbus_log.h"
static const int32_t DELAY_LEN = 1000;
static const int32_t RETRY_MAX = 10;
namespace OHOS {
namespace EventFwk {
class ScreenStateMonitor : public CommonEventSubscriber {
public:
explicit ScreenStateMonitor(const CommonEventSubscribeInfo &subscriberInfo);
virtual ~ScreenStateMonitor() {}
virtual void OnReceiveEvent(const CommonEventData &data);
};
ScreenStateMonitor::ScreenStateMonitor(const CommonEventSubscribeInfo &subscriberInfo)
:CommonEventSubscriber(subscriberInfo)
{
}
void ScreenStateMonitor::OnReceiveEvent(const CommonEventData &data)
{
std::string action = data.GetWant().GetAction();
SoftBusScreenState state = SOFTBUS_SCREEN_UNKNOWN;
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "notify ScreenState event %s", action.c_str());
if (action == CommonEventSupport::COMMON_EVENT_SCREEN_OFF) {
state = SOFTBUS_SCREEN_OFF;
} else if (action == CommonEventSupport::COMMON_EVENT_SCREEN_ON) {
state = SOFTBUS_SCREEN_ON;
}
if (state != SOFTBUS_SCREEN_UNKNOWN) {
LnnNotifyScreenStateChangeEvent(state);
}
}
class SubscribeEvent {
public:
int32_t SubscribeScreenStateEvent();
private:
std::shared_ptr<ScreenStateMonitor> subscriber_ = nullptr;
};
int32_t SubscribeEvent::SubscribeScreenStateEvent()
{
MatchingSkills matchingSkills;
matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_SCREEN_OFF);
matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_SCREEN_ON);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
subscriber_ = std::make_shared<ScreenStateMonitor>(subscriberInfo);
if (!CommonEventManager::SubscribeCommonEvent(subscriber_)) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "SubscribeScreenStateEvent: subscribe ScreenState event err");
return SOFTBUS_ERR;
}
return SOFTBUS_OK;
}
} // namespace EventFwk
} // namespace OHOS
static void LnnSubscribeScreenState(void *para)
{
(void)para;
static int32_t retry = 0;
if (retry > RETRY_MAX) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "try subscribe ScreenState event max times");
return;
}
OHOS::EventFwk::SubscribeEvent *subscriberPtr = new OHOS::EventFwk::SubscribeEvent();
if (subscriberPtr == nullptr) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "SubscribeEvent init fail");
return;
}
if (subscriberPtr->SubscribeScreenStateEvent() == SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "subscribe ScreenState on or off state success");
} else {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "subscribe ScreenState event fail");
retry++;
SoftBusLooper *looper = GetLooper(LOOP_TYPE_DEFAULT);
if (LnnAsyncCallbackDelayHelper(looper, LnnSubscribeScreenState, NULL, DELAY_LEN) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "async call subscribe screen state fail");
}
}
delete subscriberPtr;
}
int32_t LnnInitScreenStateMonitorImpl(void)
{
SoftBusLooper *looper = GetLooper(LOOP_TYPE_DEFAULT);
int32_t ret = LnnAsyncCallbackDelayHelper(looper, LnnSubscribeScreenState, NULL, DELAY_LEN);
if (ret != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "init ScreenState LnnAsyncCallbackDelayHelper fail");
}
return ret;
}

View File

@ -0,0 +1,23 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "lnn_event_monitor_impl.h"
#include "softbus_errcode.h"
int32_t LnnInitScreenStateMonitorImpl(void)
{
return SOFTBUS_OK;
}

View File

@ -52,7 +52,7 @@ void WifiServiceMonitor::OnReceiveEvent(const CommonEventData &data)
{
int code = data.GetCode();
std::string action = data.GetWant().GetAction();
SoftBusWifiState state = SOFTBUS_UNKNOWN;
SoftBusWifiState state = SOFTBUS_WIFI_UNKNOWN;
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "notify wifiservice event %s, code(%d)", action.c_str(), code);
if (action == CommonEventSupport::COMMON_EVENT_WIFI_CONN_STATE) {
@ -78,7 +78,7 @@ void WifiServiceMonitor::OnReceiveEvent(const CommonEventData &data)
}
}
}
if (state != SOFTBUS_UNKNOWN) {
if (state != SOFTBUS_WIFI_UNKNOWN) {
LnnNotifyWlanStateChangeEvent(state);
}
}

View File

@ -16,6 +16,7 @@
#include <sstream>
#include <securec.h>
#include "softbus_error_code.h"
#include "softbus_adapter_log.h"
#include "softbus_adapter_mem.h"
#include "message_handler.h"
@ -40,63 +41,58 @@ static const char* g_evtTypeTable[SOFTBUS_EVT_TYPE_BUTT] = {
"BEHAVIOR"
};
static void AppendParamValue(std::stringstream& strStream, SoftBusEvtParam& evtParam)
static void ReportParamValue(SoftBusEvtParam& evtParam)
{
switch (evtParam.paramType) {
case SOFTBUS_EVT_PARAMTYPE_BOOL:
strStream << (unsigned int)evtParam.paramValue.b;
HILOG_INFO(SOFTBUS_HILOG_ID, "ParamName: %{public}s; ParamNum: %{public}s; ParamValue: %{public}u",
evtParam.paramName, g_paramTypeTable[evtParam.paramType], (unsigned int)evtParam.paramValue.b);
break;
case SOFTBUS_EVT_PARAMTYPE_UINT8:
strStream << (unsigned int)evtParam.paramValue.u8v;
HILOG_INFO(SOFTBUS_HILOG_ID, "ParamName: %{public}s; ParamNum: %{public}s; ParamValue: %{public}u",
evtParam.paramName, g_paramTypeTable[evtParam.paramType], (unsigned int)evtParam.paramValue.u8v);
break;
case SOFTBUS_EVT_PARAMTYPE_UINT16:
strStream << (unsigned int)evtParam.paramValue.u16v;
HILOG_INFO(SOFTBUS_HILOG_ID, "ParamName: %{public}s; ParamNum: %{public}s; ParamValue: %{public}u",
evtParam.paramName, g_paramTypeTable[evtParam.paramType], (unsigned int)evtParam.paramValue.u16v);
break;
case SOFTBUS_EVT_PARAMTYPE_INT32:
strStream << (int)evtParam.paramValue.i32v;
HILOG_INFO(SOFTBUS_HILOG_ID, "ParamName: %{public}s; ParamNum: %{public}s; ParamValue: %{public}d",
evtParam.paramName, g_paramTypeTable[evtParam.paramType], (int)evtParam.paramValue.i32v);
break;
case SOFTBUS_EVT_PARAMTYPE_UINT32:
strStream << (unsigned long)evtParam.paramValue.u32v;
HILOG_INFO(SOFTBUS_HILOG_ID, "ParamName: %{public}s; ParamNum: %{public}s; ParamValue: %{public}u",
evtParam.paramName, g_paramTypeTable[evtParam.paramType], (unsigned int)evtParam.paramValue.u32v);
break;
case SOFTBUS_EVT_PARAMTYPE_UINT64:
strStream << (unsigned long long)evtParam.paramValue.u64v;
HILOG_INFO(SOFTBUS_HILOG_ID, "ParamName: %{public}s; ParamNum: %{public}s; ParamValue: %{public}llu",
evtParam.paramName, g_paramTypeTable[evtParam.paramType], (unsigned long long)evtParam.paramValue.u64v);
break;
case SOFTBUS_EVT_PARAMTYPE_FLOAT:
strStream << evtParam.paramValue.f;
HILOG_INFO(SOFTBUS_HILOG_ID, "ParamName: %{public}s; ParamNum: %{public}s; ParamValue: %{public}f",
evtParam.paramName, g_paramTypeTable[evtParam.paramType], evtParam.paramValue.f);
break;
case SOFTBUS_EVT_PARAMTYPE_DOUBLE:
strStream << evtParam.paramValue.d;
HILOG_INFO(SOFTBUS_HILOG_ID, "ParamName: %{public}s; ParamNum: %{public}s; ParamValue: %{public}lf",
evtParam.paramName, g_paramTypeTable[evtParam.paramType], evtParam.paramValue.d);
break;
case SOFTBUS_EVT_PARAMTYPE_STRING:
strStream << (const char*)evtParam.paramValue.str;
HILOG_INFO(SOFTBUS_HILOG_ID, "ParamName: %{public}s; ParamNum: %{public}s; ParamValue: %{public}s",
evtParam.paramName, g_paramTypeTable[evtParam.paramType], evtParam.paramValue.str);
break;
default:
break;
}
}
static char* ConvertReportMsgToStr(SoftBusEvtReportMsg* reportMsg)
static void ConvertReportMsgToStr(SoftBusEvtReportMsg* reportMsg)
{
std::string outStr;
std::stringstream strStream(outStr);
strStream << "EvtName: " << (const char*)reportMsg->evtName <<" And EvtType: ";
strStream << (const char*)g_evtTypeTable[reportMsg->evtType];
strStream << " ParamNum: " << (unsigned long)reportMsg->paramNum << " ";
HILOG_INFO(SOFTBUS_HILOG_ID, "EvtName: %{public}s; EvtType: %{public}s; ParamNum: %{public}d",
reportMsg->evtName, g_evtTypeTable[reportMsg->evtType], reportMsg->paramNum);
for (uint32_t i = 0; i < reportMsg->paramNum; i++) {
strStream << "ParamName: " << (const char*)reportMsg->paramArray[i].paramName;
strStream << " ParamType: " << (const char*)g_paramTypeTable[reportMsg->paramArray[i].paramType];
AppendParamValue(strStream, reportMsg->paramArray[i]);
ReportParamValue(reportMsg->paramArray[i]);
}
unsigned int strlen = outStr.length();
char* msgStr = (char*)SoftBusMalloc(strlen + 1);
if (msgStr != nullptr) {
strcpy_s(msgStr, strlen + 1, outStr.c_str());
}
return msgStr;
}
#ifdef __cplusplus
@ -111,13 +107,7 @@ int32_t SoftbusWriteHisEvt(SoftBusEvtReportMsg* reportMsg)
return SOFTBUS_ERR;
}
char* reportMsgStr = ConvertReportMsgToStr(reportMsg);
if (reportMsgStr == nullptr) {
return SOFTBUS_ERR;
}
HILOG_INFO(SOFTBUS_HILOG_ID, "[COMM]%{public}s", reportMsgStr);
SoftBusFree((void*)reportMsgStr);
ConvertReportMsgToStr(reportMsg);
return SOFTBUS_OK;
}

View File

@ -25,8 +25,8 @@ extern "C" {
#endif
#endif
#define SOFTBUS_HISYSEVT_NAME_LEN 48
#define SOFTBUS_HISYSEVT_PARAM_LEN 16
#define SOFTBUS_HISYSEVT_NAME_LEN 32
#define SOFTBUS_HISYSEVT_PARAM_LEN 32
typedef enum {
SOFTBUS_EVT_PARAM_ZERO = 0,
@ -42,10 +42,10 @@ typedef enum {
} SoftBusEvtParamNum;
typedef enum {
SOFTBUS_EVT_TYPE_FAULT = 1,
SOFTBUS_EVT_TYPE_STATISTIC = 2,
SOFTBUS_EVT_TYPE_SECURITY = 3,
SOFTBUS_EVT_TYPE_BEHAVIOR = 4,
SOFTBUS_EVT_TYPE_FAULT = 0,
SOFTBUS_EVT_TYPE_STATISTIC = 1,
SOFTBUS_EVT_TYPE_SECURITY = 2,
SOFTBUS_EVT_TYPE_BEHAVIOR = 3,
SOFTBUS_EVT_TYPE_BUTT
} SoftBusEvtType;

View File

@ -105,7 +105,6 @@ int32_t SoftBusSocketGetError(int32_t socketFd)
{
int err = 0;
socklen_t errSize = sizeof(err);
int32_t ret = getsockopt(socketFd, SOL_SOCKET, SO_ERROR, &err, &errSize);
if (ret < 0) {
HILOG_ERROR(SOFTBUS_HILOG_ID, "getsockopt fd=%{public}d, ret=%{public}d", socketFd, ret);

View File

@ -165,7 +165,6 @@ int32_t SoftBusThreadAttrInit(SoftBusThreadAttr *threadAttr)
threadAttr->detachState = SOFTBUS_THREAD_JOINABLE;
threadAttr->stackSize = 0;
threadAttr->prior = SOFTBUS_PRIORITY_DEFAULT;
threadAttr->taskName = NULL;
return SOFTBUS_OK;

View File

@ -27,7 +27,7 @@
#define APP_UUID_LEN 2
#define INVALID_ID (-1)
static BtGattClientCallbacks g_btGattClientCallbacks = { 0 };
static BtGattClientCallbacks g_btGattClientCallbacks = {0};
static SoftBusGattcCallback *g_softBusGattcCallback = NULL;
static void GattcConnectionStateChangedCallback(int clientId, int connectionState, int status)

View File

@ -34,7 +34,7 @@ static const char SOFTBUS_APP_UUID[BT_UUID_LEN] = {
};
SoftBusGattsCallback *g_gattsCallback = NULL;
static BtGattServerCallbacks g_bleGattsHalCallback = { 0 };
static BtGattServerCallbacks g_bleGattsHalCallback = {0};
static int g_halServerId = -1;
static int g_halRegFlag = -1; // -1:not registered or register failed; 0:registerring; 1:registered

View File

@ -37,26 +37,36 @@
"ram": "28MB",
"deps": {
"components": [
"libhilog",
"libipc_single",
"libsystem_ability_fwk",
"libsyspara",
"samgr_proxy",
"utils_base"
"ability_base",
"ability_runtime",
"bluetooth",
"drivers_interface_wlan",
"hiviewdfx_hilog_native",
"ipc",
"os_account",
"relational_store",
"utils_base",
"wifi"
],
"third_party": [
"bounds_checking_function",
"cJSON",
"libcoap",
"libmbedtls",
"bounds_checking_function"
"thirdparty_mbedtls"
]
},
"build": {
"sub_component": [
"//foundation/communication/dsoftbus/core:softbus_server",
"//foundation/communication/dsoftbus/sdk:softbus_client",
"//foundation/communication/dsoftbus/core/frame/standard/sa_profile:softbus_sa_profile",
"//foundation/communication/dsoftbus/tools:tool"
],
"group_type":{
"base_group":[],
"fwk_group":[
"//foundation/communication/dsoftbus/sdk:softbus_client"
],
"service_group":[
"//foundation/communication/dsoftbus/core:softbus_server",
"//foundation/communication/dsoftbus/core/frame/standard/sa_profile:softbus_sa_profile",
"//foundation/communication/dsoftbus/tools:tool"
]
},
"inner_kits": [
{
"name": "//foundation/communication/dsoftbus/sdk:softbus_client",
@ -82,6 +92,7 @@
"//foundation/communication/dsoftbus/tests/core/authentication:unittest",
"//foundation/communication/dsoftbus/tests/core/bus_center/lnn:unittest",
"//foundation/communication/dsoftbus/tests/core/common/utils:unittest",
"//foundation/communication/dsoftbus/tests/core/common/dfx:unittest",
"//foundation/communication/dsoftbus/tests/core/connection:connectionTest",
"//foundation/communication/dsoftbus/tests/core/discovery/manager:unittest",
"//foundation/communication/dsoftbus/tests/core/transmission/trans_channel/tcp_direct:unittest",

View File

@ -13,6 +13,7 @@
import("//foundation/communication/dsoftbus/dsoftbus.gni")
NSTACKX_ROOT = "//foundation/communication/dsoftbus/components/nstackx"
fillp_source = [
"src/app_lib/src/api.c",
"src/app_lib/src/epoll_app.c",
@ -21,6 +22,7 @@ fillp_source = [
"src/app_lib/src/socket_app.c",
"src/app_lib/src/spunge_app.c",
"src/app_lib/src/socket_opt.c",
"src/app_lib/src/fillp_dfx.c",
"src/fillp_lib/src/fillp_buf_item.c",
"src/fillp_lib/src/fillp_cookie.c",
"src/fillp_lib/src/fillp_stack_config.c",
@ -75,6 +77,7 @@ fillp_cflags = [
"-DFILLP_LINUX",
"-DFILLP_POWER_SAVE",
"-DFILLP_POWER_SAVING_LINUX",
"-DFILLP_ENABLE_DFX_HIDUMPER",
]
if (defined(ohos_lite)) {
@ -85,7 +88,10 @@ if (defined(ohos_lite)) {
include_dirs = fillp_include
include_dirs += [ "//third_party/bounds_checking_function/include/" ]
sources = fillp_source
deps = [ "//third_party/bounds_checking_function:libsec_shared" ]
deps = [
"$NSTACKX_ROOT/nstackx_util:nstackx_util.open",
"//third_party/bounds_checking_function:libsec_shared",
]
if (ohos_kernel_type == "liteos_a") {
cflags += [ "-DNSTACKX_WITH_LITEOS" ]
@ -104,11 +110,14 @@ if (defined(ohos_lite)) {
include_dirs = fillp_include
include_dirs += [
"//utils/native/base/include/",
"//commonlibrary/c_utils/base/include/",
"//third_party/bounds_checking_function/include",
]
sources = fillp_source
deps = [ "//third_party/bounds_checking_function:libsec_shared" ]
deps = [
"$NSTACKX_ROOT/nstackx_util:nstackx_util.open",
"//third_party/bounds_checking_function:libsec_shared",
]
part_name = "dsoftbus"
subsystem_name = "communication"

View File

@ -397,7 +397,7 @@ typedef struct FillpTraceDescriptStruct {
#define FILLP_TRACE_DESC_INIT(dir) \
{ \
(dir), \
{ 0 }, \
{0}, \
}
/**
@ -1375,6 +1375,33 @@ struct FillpCurrentSendCacheInf {
*/
FILLP_INT DLL_API FtApiEventInfoGet(IN FILLP_INT fd, IO FtEventCbkInfo *info);
/**
* @ingroup fillpevt
* @brief register dfx event callback function
*
* @param[in] softObj any usefull message to evtCb
* @param[in] func event callback function
* @return
* On Success : returns 0
* On Failure : returns -1
*/
extern FILLP_INT DLL_API FtSetDfxEventCb(void *softObj, FillpDfxEventCb evtCb);
/**
* @ingroup fillpevt
* @brief deal with HiDumper cmd
*
* @param[in] argc arg number
* @param[in] argv arg value
* @param[in] softObj any usefull message to dump
* @param[in] dump function to printf data
* @return
* On Success : returns 0
* On Failure : returns -1
*/
extern FILLP_INT DLL_API FtDfxHiDumper(FILLP_UINT32 argc, const FILLP_CHAR **argv,
void *softObj, FillpDfxDumpFunc dump);
#pragma pack(pop)
#ifdef __cplusplus

View File

@ -618,6 +618,74 @@ typedef struct {
} info;
} FtEventCbkInfo;
#define FILLP_DFX_EVENT_NAME_LEN 128
typedef enum {
FILLP_DFX_EVENT_TYPE_FAULT,
FILLP_DFX_EVENT_TYPE_STATISTIC,
FILLP_DFX_EVENT_TYPE_SECURITY,
FILLP_DFX_EVENT_TYPE_BEHAVIOR,
} FillpDfxEvtType;
typedef enum {
FILLP_DFX_EVENT_LEVEL_CRITICAL,
FILLP_DFX_EVENT_LEVEL_MINOR,
} FillpDfxEventLevel;
typedef enum {
FILLP_DFX_PARAM_TYPE_BOOL,
FILLP_DFX_PARAM_TYPE_UINT8,
FILLP_DFX_PARAM_TYPE_UINT16,
FILLP_DFX_PARAM_TYPE_INT32,
FILLP_DFX_PARAM_TYPE_UINT32,
FILLP_DFX_PARAM_TYPE_UINT64,
FILLP_DFX_PARAM_TYPE_FLOAT,
FILLP_DFX_PARAM_TYPE_DOUBLE,
FILLP_DFX_PARAM_TYPE_STRING
} FillpDfxEventParamType;
typedef struct {
FillpDfxEventParamType type;
FILLP_CHAR paramName[FILLP_DFX_EVENT_NAME_LEN];
union {
FILLP_UINT8 u8v;
FILLP_UINT16 u16v;
FILLP_INT32 i32v;
FILLP_UINT32 u32v;
FILLP_ULLONG u64v;
float f;
double d;
FILLP_CHAR str[FILLP_DFX_EVENT_NAME_LEN];
} val;
} FillpDfxEventParam;
typedef struct {
FILLP_CHAR eventName[FILLP_DFX_EVENT_NAME_LEN];
FillpDfxEvtType type;
FillpDfxEventLevel level;
FILLP_UINT32 paramNum;
FillpDfxEventParam *paramArray;
} FillpDfxEvent;
/**
* @ingroup fillpevt
* @brief report dstream event
*
* @param[in] softObj any usefull message to FillpDfxEventCb
* @param[in] info event detail
*/
typedef void (*FillpDfxEventCb)(void *softObj, const FillpDfxEvent *info);
/**
* @ingroup fillpevt
* @brief function to printf data.
*
* @param[in] softObj any usefull message to FillpDfxDumpFunc
* @param[in] data dump string to print
* @param[in] len lenth of data
*/
typedef void (*FillpDfxDumpFunc)(void *softObj, const FILLP_CHAR *data, FILLP_UINT32 len);
#ifdef __cplusplus
}
#endif

View File

@ -0,0 +1,53 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FILLP_DFX_H
#define FILLP_DFX_H
#include "fillptypes.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
FILLP_DFX_LINK_VERSION_MISMATCH,
FILLP_DFX_LINK_RETRANSMIT_OUT,
FILLP_DFX_LINK_KEEPALIVE_TIMEOUT,
FILLP_DFX_LINK_IP_REMOVED,
FILLP_DFX_LINK_CLOSE,
FILLP_DFX_LINK_FIN_INPUT,
FILLP_DFX_LINK_EVT_MAX,
} FillpDfxLinkEvtType;
typedef enum {
FILLP_DFX_PKT_PARSE_FAIL,
FILLP_DFX_PKT_SEMI_RELIABLE_DROP,
FILLP_DFX_PKT_EVT_MAX,
} FillpDfxPktEvtType;
void FillpDfxEvtCbSet(void *softObj, FillpDfxEventCb evtCb);
void FillpDfxSockLinkAndQosNotify(FILLP_INT sockIdx, FillpDfxLinkEvtType evtType);
void FillpDfxPktNotify(FILLP_INT sockIdx, FillpDfxPktEvtType evtType, FILLP_UINT32 dropCnt);
#ifdef FILLP_ENABLE_DFX_HIDUMPER
FILLP_INT FillpDfxDump(FILLP_UINT32 argc, const FILLP_CHAR **argv, void *softObj, FillpDfxDumpFunc dump);
#endif /* FILLP_ENABLE_DFX_HIDUMPER */
#ifdef __cplusplus
}
#endif
#endif /* FILLP_DFX_H */

View File

@ -20,7 +20,7 @@
#include "res.h"
#include "callbacks.h"
#include "epoll_app.h"
#include "fillp_dfx.h"
#ifdef __cplusplus
extern "C" {
#endif
@ -1554,6 +1554,30 @@ FILLP_INT DLL_API FtApiEventInfoGet(IN FILLP_INT fd, IO FtEventCbkInfo *info)
return SockEventInfoGet(fd, info);
}
FILLP_INT DLL_API FtSetDfxEventCb(void *softObj, FillpDfxEventCb evtCb)
{
if (evtCb == NULL) {
FILLP_LOGERR("evtCb is null");
return -1;
}
FillpDfxEvtCbSet(softObj, evtCb);
return 0;
}
FILLP_INT FtDfxHiDumper(FILLP_UINT32 argc, const FILLP_CHAR **argv, void *softObj, FillpDfxDumpFunc dump)
{
#ifdef FILLP_ENABLE_DFX_HIDUMPER
return FillpDfxDump(argc, argv, softObj, dump);
#else
(void)argc;
(void)argv;
(void)softObj;
(void)dump;
FILLP_LOGERR("unsupport FtFillpDfxDump");
return -1;
#endif /* FILLP_ENABLE_DFX_HIDUMPER */
}
#ifdef __cplusplus
}
#endif

View File

@ -0,0 +1,702 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "fillp_dfx.h"
#include "sockets.h"
#include "socket_common.h"
#include "log.h"
#include "res.h"
#include "spunge.h"
#include "securec.h"
#include "nstackx_getopt.h"
#include "log.h"
#define FILLP_DFX_PKT_EVT_DROP_THRESHOLD 1000
static struct Hlist g_fillpDfxPktPraseFailList = {
{
.pprev = (struct HlistNode **)&g_fillpDfxPktPraseFailList,
},
.size = 0,
};
static FillpDfxEventCb g_fillpDfxEvtCb = FILLP_NULL_PTR;
static void *g_fillpDfxSoftObj = FILLP_NULL_PTR;
typedef struct {
struct HlistNode node;
FILLP_INT sockIdx;
FILLP_UINT32 dropCnt;
FILLP_UINT32 lastReportCnt;
} FillpDfxPktParseFailNode;
typedef union {
struct {
FILLP_UINT32 sockIdx;
FillpDfxLinkEvtType linkEvtType;
} linkEvt;
struct {
FILLP_UINT32 sockIdx;
FillpDfxPktEvtType pktEvtType;
/* FILLP_DFX_PKT_PARSE_FAIL: dropCnt means pkt count */
/* FILLP_DFX_PKT_SEMI_RELIABLE_DROP: dropCnt means frame count */
FILLP_UINT32 dropCnt;
} pktEvt;
struct {
FILLP_UINT32 sockIdx;
FILLP_UINT32 rtt;
FILLP_UINT32 recvPktLoss; /* 0.01% */
FILLP_LLONG recvRateBps; /* bps */
FILLP_UINT32 sendPktLoss; /* 0.01% */
FILLP_LLONG sendRateBps; /* bps */
FILLP_LLONG jitter; /* ms */
} sockQos;
} FillpDfxEvtArgs;
#define FILLP_DFX_LINK_EVT_PARA_NUM 2
#define FILLP_DFX_PKT_EVT_PARA_NUM 3
#define FILLP_DFX_SOCK_QOS_EVT_PARA_NUM 7
#define FILLP_EVT_MAX_PARA_NUM FILLP_DFX_SOCK_QOS_EVT_PARA_NUM
typedef enum {
FILLP_DFX_EVT_LINK_EXCEPTION,
FILLP_DFX_EVT_PKT_EXCEPTION,
FILLP_DFX_EVT_SOCK_QOS_STATUS,
FILLP_DFX_EVT_DFX_MAX,
} FillpDfxEvt;
static const FillpDfxEvent g_fillpDfxEvtMsg[FILLP_DFX_EVT_DFX_MAX] = {
[FILLP_DFX_EVT_LINK_EXCEPTION] = {
.eventName = "FILLP_LINK_EVT",
.type = FILLP_DFX_EVENT_TYPE_FAULT,
.level = FILLP_DFX_EVENT_LEVEL_CRITICAL,
.paramNum = FILLP_DFX_LINK_EVT_PARA_NUM,
},
[FILLP_DFX_EVT_PKT_EXCEPTION] = {
.eventName = "FILLP_PKT_EVT",
.type = FILLP_DFX_EVENT_TYPE_STATISTIC,
.level = FILLP_DFX_EVENT_LEVEL_MINOR,
.paramNum = FILLP_DFX_PKT_EVT_PARA_NUM,
},
[FILLP_DFX_EVT_SOCK_QOS_STATUS] = {
.eventName = "FILLP_SOCK_PKT_EVT",
.type = FILLP_DFX_EVENT_TYPE_STATISTIC,
.level = FILLP_DFX_EVENT_LEVEL_MINOR,
.paramNum = FILLP_DFX_SOCK_QOS_EVT_PARA_NUM,
},
};
static const FillpDfxEventParam g_fillpDfxEvtParam[FILLP_DFX_EVT_DFX_MAX][FILLP_EVT_MAX_PARA_NUM] = {
[FILLP_DFX_EVT_LINK_EXCEPTION] = {
{
.type = FILLP_DFX_PARAM_TYPE_UINT32,
.paramName = "sockIdx",
},
{
.type = FILLP_DFX_PARAM_TYPE_UINT8,
.paramName = "linkEvtType",
},
},
[FILLP_DFX_EVT_PKT_EXCEPTION] = {
{
.type = FILLP_DFX_PARAM_TYPE_UINT32,
.paramName = "sockIdx",
},
{
.type = FILLP_DFX_PARAM_TYPE_UINT8,
.paramName = "pktEvtType",
},
{
.type = FILLP_DFX_PARAM_TYPE_UINT32,
.paramName = "dropCnt",
},
},
[FILLP_DFX_EVT_SOCK_QOS_STATUS] = {
{
.type = FILLP_DFX_PARAM_TYPE_UINT32,
.paramName = "sockIdx",
},
{
.type = FILLP_DFX_PARAM_TYPE_UINT32,
.paramName = "rtt",
},
{
.type = FILLP_DFX_PARAM_TYPE_UINT32,
.paramName = "recvPktLoss",
},
{
.type = FILLP_DFX_PARAM_TYPE_UINT64,
.paramName = "recvRateBps",
},
{
.type = FILLP_DFX_PARAM_TYPE_UINT32,
.paramName = "sendPktLoss",
},
{
.type = FILLP_DFX_PARAM_TYPE_UINT64,
.paramName = "sendRateBps",
},
{
.type = FILLP_DFX_PARAM_TYPE_UINT64,
.paramName = "jitter",
},
},
};
static void DfxEvtGetParamAddr(FillpDfxEvtArgs *args, FillpDfxEvt evt, void *paramVal[])
{
void *paramValTmp[FILLP_DFX_EVT_DFX_MAX][FILLP_EVT_MAX_PARA_NUM] = {
[FILLP_DFX_EVT_LINK_EXCEPTION] = {
&args->linkEvt.sockIdx,
&args->linkEvt.linkEvtType,
},
[FILLP_DFX_EVT_PKT_EXCEPTION] = {
&args->pktEvt.sockIdx,
&args->pktEvt.pktEvtType,
&args->pktEvt.dropCnt,
},
[FILLP_DFX_EVT_SOCK_QOS_STATUS] = {
&args->sockQos.sockIdx,
&args->sockQos.rtt,
&args->sockQos.recvPktLoss,
&args->sockQos.recvRateBps,
&args->sockQos.sendPktLoss,
&args->sockQos.sendRateBps,
&args->sockQos.jitter,
},
};
(void)memcpy_s((void *)paramVal, sizeof(void *) * FILLP_EVT_MAX_PARA_NUM,
(void *)paramValTmp[evt], sizeof(void *) * FILLP_EVT_MAX_PARA_NUM);
}
void FillpDfxEvtCbSet(void *softObj, FillpDfxEventCb evtCb)
{
if (g_fillpDfxEvtCb != FILLP_NULL_PTR) {
FILLP_LOGERR("fillp dfx event callback already set!");
return;
}
g_fillpDfxEvtCb = evtCb;
g_fillpDfxSoftObj = softObj;
}
static void DfxEvtParamValCpy(void *dstVal, void * srcVal, FillpDfxEventParamType type)
{
switch (type) {
case FILLP_DFX_PARAM_TYPE_BOOL:
case FILLP_DFX_PARAM_TYPE_UINT8:
*(FILLP_UINT8 *)dstVal = *(FILLP_UINT8 *)srcVal;
break;
case FILLP_DFX_PARAM_TYPE_UINT16:
*(FILLP_UINT16 *)dstVal = *(FILLP_UINT16 *)srcVal;
break;
case FILLP_DFX_PARAM_TYPE_INT32:
case FILLP_DFX_PARAM_TYPE_UINT32:
case FILLP_DFX_PARAM_TYPE_FLOAT:
*(FILLP_UINT32 *)dstVal = *(FILLP_UINT32 *)srcVal;
break;
case FILLP_DFX_PARAM_TYPE_UINT64:
case FILLP_DFX_PARAM_TYPE_DOUBLE:
*(FILLP_ULLONG *)dstVal = *(FILLP_ULLONG *)srcVal;
break;
case FILLP_DFX_PARAM_TYPE_STRING:
if (strcpy_s(dstVal, FILLP_DFX_EVENT_NAME_LEN, srcVal) != EOK) {
FILLP_LOGERR("strcpy_s failed");
}
break;
default:
FILLP_LOGERR("unknow param type!");
break;
}
}
static FillpDfxEventParam *FillpCreateDfxEvtParam(FillpDfxEvtArgs *args, FillpDfxEvt evt, FILLP_UINT32 paramNum)
{
FILLP_UINT8 i;
void *paramVal[FILLP_EVT_MAX_PARA_NUM];
(void)memset_s(paramVal, sizeof(paramVal), 0, sizeof(paramVal));
DfxEvtGetParamAddr(args, evt, &paramVal[0]);
FillpDfxEventParam *param = (FillpDfxEventParam *)calloc(paramNum, sizeof(FillpDfxEventParam));
if (param == FILLP_NULL_PTR) {
FILLP_LOGERR("calloc param failed!");
return FILLP_NULL_PTR;
}
(void)memcpy_s(param, paramNum * sizeof(FillpDfxEventParam),
&g_fillpDfxEvtParam[evt], paramNum * sizeof(FillpDfxEventParam));
for (i = 0; i < paramNum; i++) {
DfxEvtParamValCpy(&param[i].val, paramVal[i], param[i].type);
}
return param;
}
static void FillpDfxEvtNotify(FillpDfxEvtArgs *args, FillpDfxEvt evt)
{
if (g_fillpDfxEvtCb == FILLP_NULL_PTR) {
return;
}
FillpDfxEvent msg;
(void)memcpy_s(&msg, sizeof(FillpDfxEvent), &g_fillpDfxEvtMsg[evt], sizeof(FillpDfxEvent));
msg.paramArray = FillpCreateDfxEvtParam(args, evt, msg.paramNum);
if (msg.paramArray == FILLP_NULL_PTR) {
return;
}
g_fillpDfxEvtCb(g_fillpDfxSoftObj, &msg);
free(msg.paramArray);
}
static void FillpDfxSockQosNotify(FILLP_INT sockIdx)
{
FillpDfxEvtArgs args;
(void)memset_s(&args, sizeof(args), 0, sizeof(args));
args.sockQos.sockIdx = sockIdx;
struct FtSocket *sock = SockApiGetAndCheck(sockIdx);
if (sock == FILLP_NULL_PTR) {
return;
}
if (sock->netconn == FILLP_NULL_PTR || sock->netconn->pcb == FILLP_NULL_PTR) {
(void)SYS_ARCH_RWSEM_RDPOST(&sock->sockConnSem);
return;
}
struct FtNetconn *netconn = (struct FtNetconn *)(sock->netconn);
struct FillAppFcStastics *appFcStastics = &(netconn->pcb->fpcb.statistics.appFcStastics);
args.sockQos.rtt = appFcStastics->periodRtt;
args.sockQos.recvPktLoss = appFcStastics->periodRecvPktLossHighPrecision;
args.sockQos.recvRateBps = appFcStastics->periodRecvRateBps;
args.sockQos.sendPktLoss = appFcStastics->periodSendPktLossHighPrecision;
args.sockQos.sendRateBps = appFcStastics->periodSendRateBps;
args.sockQos.jitter = FILLP_UTILS_US2MS(sock->jitter);
(void)SYS_ARCH_RWSEM_RDPOST(&sock->sockConnSem);
FillpDfxEvtNotify(&args, FILLP_DFX_EVT_SOCK_QOS_STATUS);
}
static FillpDfxPktParseFailNode *DfxGetPktPraseFailNode(FILLP_INT sockIdx)
{
struct HlistNode *pos = FILLP_NULL_PTR;
struct HlistNode *next = FILLP_NULL_PTR;
HLIST_FOREACH_SAFE(pos, next, &g_fillpDfxPktPraseFailList) {
FillpDfxPktParseFailNode *node = (FillpDfxPktParseFailNode *)pos;
if (node->sockIdx == sockIdx) {
return node;
}
}
return FILLP_NULL_PTR;
}
void FillpDfxSockLinkAndQosNotify(FILLP_INT sockIdx, FillpDfxLinkEvtType evtType)
{
FillpDfxEvtArgs args;
(void)memset_s(&args, sizeof(args), 0, sizeof(args));
args.linkEvt.sockIdx = sockIdx;
args.linkEvt.linkEvtType = evtType;
FillpDfxEvtNotify(&args, FILLP_DFX_EVT_LINK_EXCEPTION);
if (evtType == FILLP_DFX_LINK_VERSION_MISMATCH) {
return;
}
FillpDfxSockQosNotify(sockIdx);
FillpDfxPktParseFailNode *node = DfxGetPktPraseFailNode(sockIdx);
if (node == FILLP_NULL_PTR) {
return;
}
if (node->dropCnt == node->lastReportCnt) {
HlistDelNode(&node->node);
free(node);
return;
}
(void)memset_s(&args, sizeof(args), 0, sizeof(args));
args.pktEvt.sockIdx = sockIdx;
args.pktEvt.pktEvtType = FILLP_DFX_PKT_PARSE_FAIL;
args.pktEvt.dropCnt = node->dropCnt;
HlistDelNode(&node->node);
free(node);
FillpDfxEvtNotify(&args, FILLP_DFX_EVT_PKT_EXCEPTION);
}
void FillpDfxPktNotify(FILLP_INT sockIdx, FillpDfxPktEvtType evtType, FILLP_UINT32 dropCnt)
{
FillpDfxPktParseFailNode *node = FILLP_NULL_PTR;
if (evtType == FILLP_DFX_PKT_PARSE_FAIL) {
node = DfxGetPktPraseFailNode(sockIdx);
if (node == FILLP_NULL_PTR) {
node = (FillpDfxPktParseFailNode *)calloc(1U, sizeof(FillpDfxPktParseFailNode));
if (node == FILLP_NULL_PTR) {
FILLP_LOGERR("calloc node failed!");
return;
}
HlistAddTail(&g_fillpDfxPktPraseFailList, &node->node);
}
node->dropCnt += dropCnt;
if (node->dropCnt - node->lastReportCnt < FILLP_DFX_PKT_EVT_DROP_THRESHOLD) {
return;
}
}
FillpDfxEvtArgs args;
(void)memset_s(&args, sizeof(args), 0, sizeof(args));
args.pktEvt.sockIdx = sockIdx;
args.pktEvt.pktEvtType = evtType;
if (evtType == FILLP_DFX_PKT_PARSE_FAIL) {
args.pktEvt.dropCnt = node->dropCnt;
node->lastReportCnt = node->dropCnt;
} else {
args.pktEvt.dropCnt = dropCnt;
}
FillpDfxEvtNotify(&args, FILLP_DFX_EVT_PKT_EXCEPTION);
}
#ifdef FILLP_ENABLE_DFX_HIDUMPER
#define CRLF "\r\n"
#define FILLP_DFX_DUMP_BUF_LEN (2048U)
#define FILLP_DFX_DUMP_ONE_SOCK_BUF (102U)
#define FILLP_DFX_DUMP_MAX_ARGC (20U)
#define FILLP_DFX_DUMP_STRTOL_BASE (10)
#define FUZZY_IN_ADDR(addr) ((uint8_t *)(addr))[0], ((uint8_t *)(addr))[1], ((uint8_t *)(addr))[2]
#define FILLP_DFX_DUMP_IP_PROT_LEN (10)
#define FILLP_DUMP_MSG_ADD_CHECK(data, len, fmt, ...) do { \
FILLP_INT ret = sprintf_s(data + len, FILLP_DFX_DUMP_BUF_LEN - len, fmt, ##__VA_ARGS__); \
if (ret < 0) { \
FILLP_LOGERR("dumper buffer over %u bytes", FILLP_DFX_DUMP_BUF_LEN); \
return FILLP_FAILURE; \
} \
len += ret; \
} while (0)
static FILLP_INT DoShowHelp(FILLP_CHAR *data, FILLP_UINT32 *len)
{
FILLP_DUMP_MSG_ADD_CHECK(data, *len, CRLF"Usage: dstream <opt>"CRLF);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, " -h show this help"CRLF);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, " -V show version"CRLF);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, " -l show debug log level"CRLF);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, " -n show socket list, and info of socket"CRLF);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, " -s <fd> show socket <fd> common config and flow config"CRLF);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, " -q <fd> show socket <fd> qos"CRLF);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, " -f <fd> show socket <fd> frame info"CRLF);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, " -m <0/1> disable/enable management message"CRLF);
return FILLP_SUCCESS;
}
static void FillpDumpShowHelp(void *softObj, FillpDfxDumpFunc dump)
{
FILLP_CHAR data[FILLP_DFX_DUMP_BUF_LEN];
FILLP_UINT32 len = 0;
if (DoShowHelp(data, &len) != FILLP_SUCCESS) {
return;
}
dump(softObj, data, len);
}
static inline FILLP_INT DoShowVersion(FILLP_CHAR *data, FILLP_UINT32 *len)
{
FILLP_DUMP_MSG_ADD_CHECK(data, *len, CRLF FILLP_VERSION CRLF);
return FILLP_SUCCESS;
}
static void FillpDumpShowVer(void *softObj, FillpDfxDumpFunc dump)
{
FILLP_CHAR data[FILLP_DFX_DUMP_BUF_LEN];
FILLP_UINT32 len = 0;
if (DoShowVersion(data, &len) != FILLP_SUCCESS) {
return;
}
dump(softObj, data, len);
}
static inline FILLP_INT DoShowLogLevel(FILLP_CHAR *data, FILLP_UINT32 *len)
{
FILLP_DUMP_MSG_ADD_CHECK(data, *len, CRLF"Current log level: %hhu"CRLF, g_fillpLmGlobal.debugLevel);
return FILLP_SUCCESS;
}
static void FillpDumpShowLogLevel(void *softObj, FillpDfxDumpFunc dump)
{
FILLP_CHAR data[FILLP_DFX_DUMP_BUF_LEN];
FILLP_UINT32 len = 0;
if (DoShowLogLevel(data, &len) != FILLP_SUCCESS) {
return;
}
dump(softObj, data, len);
}
static FILLP_INT32 DoShowSockConfigRes(FILLP_INT sockIndex, FILLP_CONST struct GlobalAppResource *resource,
FILLP_CHAR *data, FILLP_UINT32 *len)
{
FILLP_CONST struct GlobalAppCommon *common = &resource->common;
FILLP_CONST struct GlobalAppFlowControl *fc = &resource->flowControl;
FILLP_DUMP_MSG_ADD_CHECK(data, *len, CRLF"Following are config resource data for socket %d:"CRLF, sockIndex);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, "Max udp tx burst number: %u"CRLF, resource->udp.txBurst);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, "Keep alive timeout: %u"CRLF, common->keepAliveTime);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, "Max server allow send cache: %u"CRLF, common->maxServerAllowSendCache);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, "Max server allow receive cache: %u"CRLF, common->maxServerAllowRecvCache);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, "Max send cache: %u"CRLF, common->sendCache);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, "Max receive cache: %u"CRLF, common->recvCache);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, "Max send buffer size: %u"CRLF, common->udpSendBufSize);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, "Enable nack delay flag: %hhu"CRLF, common->enableNackDelay);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, "Nack delay timeout: %lld"CRLF, common->nackDelayTimeout);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, "Enlarge pack interval falg: %hhu"CRLF, common->enlargePackIntervalFlag);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, "Max receive buffer size: %u"CRLF, common->recvBufSize);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, "Flow control: opposite set rate: %u"CRLF, fc->oppositeSetRate);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, " use const stack send rate: %u"CRLF, fc->constRateEnbale);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, " max send rate: %u Kbps"CRLF, fc->maxRate);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, " max recv rate: %u Kbps"CRLF, fc->maxRecvRate);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, " packet size: %u"CRLF, fc->pktSize);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, " slow start: %u"CRLF, fc->slowStart);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, "Timer config: connection timeout: %u(s)"CRLF, common->connectTimeout);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, " retry timeout: %u(s)"CRLF, common->connRetryTimeout);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, " disconnect retry timeout: %u(s)"CRLF,
common->disconnectRetryTimeout);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, "------- End of socket config resource data -------"CRLF);
return FILLP_SUCCESS;
}
static inline FILLP_INT DumpInvalidSock(FILLP_INT sockIndex, FILLP_CHAR *data, FILLP_UINT32 *len)
{
FILLP_DUMP_MSG_ADD_CHECK(data, *len, "Invalid socket index %d"CRLF, sockIndex);
return FILLP_SUCCESS;
}
static void FillpDumpShowSockResource(FILLP_INT sockIndex, void *softObj, FillpDfxDumpFunc dump)
{
FILLP_CHAR data[FILLP_DFX_DUMP_BUF_LEN];
FILLP_UINT32 len = 0;
struct FtSocket *sock = SockApiGetAndCheck(sockIndex);
if (sock == FILLP_NULL_PTR) {
if (DumpInvalidSock(sockIndex, data, &len) == FILLP_SUCCESS) {
dump(softObj, data, len);
}
return;
}
FILLP_INT32 isOk = DoShowSockConfigRes(sockIndex, &sock->resConf, data, &len);
(void)SYS_ARCH_RWSEM_RDPOST(&sock->sockConnSem);
if (isOk != FILLP_SUCCESS) {
return;
}
dump(softObj, data, len);
}
static inline FILLP_INT32 DoShowSockListTitle(FILLP_CHAR *data, FILLP_UINT32 *len)
{
FILLP_DUMP_MSG_ADD_CHECK(data, *len, CRLF"%5s\t %6s\t %6s\t %6s\t %6s\t %20s\t %20s\t %5s"CRLF,
"Sock", "Unsend", "Unack", "Redun", "Unrecv", "LocalIP", "PeerIP", "State");
return FILLP_SUCCESS;
}
static FILLP_INT32 DoShowSockList(FILLP_CONST struct FtSocket *sock, FILLP_CHAR *data, FILLP_UINT32 *len)
{
struct sockaddr_in *local = (struct sockaddr_in *)&sock->netconn->pcb->localAddr;
struct sockaddr_in *peer = (struct sockaddr_in *)&sock->netconn->pcb->remoteAddr;
const struct FillpSendPcb *sendPcb = &sock->netconn->pcb->fpcb.send;
FILLP_CHAR localAddr[INET_ADDRSTRLEN + FILLP_DFX_DUMP_IP_PROT_LEN];
FILLP_CHAR peerAddr[INET_ADDRSTRLEN + FILLP_DFX_DUMP_IP_PROT_LEN];
FILLP_UINT32 addrLen = 0;
FILLP_DUMP_MSG_ADD_CHECK(localAddr, addrLen, "%hhu.%hhu.%hhu.***:%hu",
FUZZY_IN_ADDR(&local->sin_addr), ntohs(local->sin_port));
addrLen = 0;
FILLP_DUMP_MSG_ADD_CHECK(peerAddr, addrLen, "%hhu.%hhu.%hhu.***:%hu",
FUZZY_IN_ADDR(&peer->sin_addr), ntohs(peer->sin_port));
FILLP_DUMP_MSG_ADD_CHECK(data, *len, "%5d\t %6u\t %6u\t %6u\t %6u\t %20s\t %20s\t %5hhu"CRLF,
sock->index, sendPcb->unSendList.size, sendPcb->unackList.size, sendPcb->redunList.nodeNum,
sendPcb->unrecvList.nodeNum, localAddr, peerAddr, sock->netconn->state);
return FILLP_SUCCESS;
}
static void FillpDumpShowSockList(void *softObj, FillpDfxDumpFunc dump)
{
struct FtSocket *sock = FILLP_NULL_PTR;
FILLP_UINT32 len = 0;
FILLP_CHAR *data = (FILLP_CHAR *)calloc(1U, g_spunge->resConf.maxSockNum * FILLP_DFX_DUMP_ONE_SOCK_BUF);
if (data == FILLP_NULL_PTR) {
const FILLP_CHAR *errMsg = "socket list dump buffer calloc failed!";
dump(softObj, errMsg, strlen(errMsg) + 1);
return;
}
if (DoShowSockListTitle(data, &len) != FILLP_SUCCESS) {
free(data);
return;
}
FILLP_UINT16 i;
for (i = 0; i < SYS_ARCH_ATOMIC_READ(&g_spunge->sockTable->used); i++) {
sock = SockApiGetAndCheck(i);
if (sock == FILLP_NULL_PTR) {
continue;
}
if (sock->netconn == FILLP_NULL_PTR || sock->netconn->pcb == FILLP_NULL_PTR) {
(void)SYS_ARCH_RWSEM_RDPOST(&sock->sockConnSem);
continue;
}
FILLP_INT isOk = DoShowSockList(sock, data, &len);
(void)SYS_ARCH_RWSEM_RDPOST(&sock->sockConnSem);
if (isOk != FILLP_SUCCESS) {
free(data);
return;
}
}
dump(softObj, data, len);
free(data);
}
static FILLP_INT DoShowSockQos(FILLP_CONST struct FtSocket *sock, FILLP_CHAR *data, FILLP_UINT32 *len)
{
struct FillAppFcStastics *appFcStastics = &(sock->netconn->pcb->fpcb.statistics.appFcStastics);
FILLP_DUMP_MSG_ADD_CHECK(data, *len, CRLF"%8s\t %18s\t %18s\t %16s\t %16s\t %10s"CRLF,
"Rtt(ms)", "RecvPktLoss(0.01%%)", "SendPktLoss(0.01%%)", "RecvRateBps(bps)", "SendRateBps(bps)", "Jetter(us)");
FILLP_DUMP_MSG_ADD_CHECK(data, *len, "%8u\t %18u\t %18u\t %16llu\t %16llu\t %10lld"CRLF,
appFcStastics->periodRtt,
appFcStastics->periodRecvPktLossHighPrecision,
appFcStastics->periodSendPktLossHighPrecision,
appFcStastics->periodRecvRateBps,
appFcStastics->periodSendRateBps,
sock->jitter);
return FILLP_SUCCESS;
}
static void FillpDumpShowSockQos(FILLP_INT sockIndex, void *softObj, FillpDfxDumpFunc dump)
{
FILLP_CHAR data[FILLP_DFX_DUMP_BUF_LEN];
FILLP_UINT32 len = 0;
struct FtSocket *sock = SockApiGetAndCheck(sockIndex);
if (sock == FILLP_NULL_PTR || sock->netconn == FILLP_NULL_PTR || sock->netconn->pcb == FILLP_NULL_PTR) {
if (sock != FILLP_NULL_PTR) {
(void)SYS_ARCH_RWSEM_RDPOST(&sock->sockConnSem);
}
if (DumpInvalidSock(sockIndex, data, &len) == FILLP_SUCCESS) {
dump(softObj, data, len);
}
return;
}
FILLP_INT isOk = DoShowSockQos(sock, data, &len);
(void)SYS_ARCH_RWSEM_RDPOST(&sock->sockConnSem);
if (isOk != FILLP_SUCCESS) {
return;
}
dump(softObj, data, len);
}
static FILLP_INT DoShowFrameStats(FILLP_CONST struct FtSocket *sock, FILLP_CHAR *data, FILLP_UINT32 *len)
{
struct FillpFrameStats *stats = &sock->netconn->pcb->fpcb.frameHandle.stats;
FILLP_DUMP_MSG_ADD_CHECK(data, *len, CRLF"%20s\t %20s\t %20s\t %20s"CRLF,
"iFrameCount", "iFrameTotalSize", "pFrameCount", "pFrameTotalSize");
FILLP_DUMP_MSG_ADD_CHECK(data, *len, "%20u\t %20llu\t %20u\t %20llu"CRLF,
stats->iFrameCount, stats->iFrameTotalSize, stats->pFrameCount, stats->pFrameTotalSize);
return FILLP_SUCCESS;
}
static void FillpDumpShowFrameStats(FILLP_INT sockIndex, void *softObj, FillpDfxDumpFunc dump)
{
FILLP_CHAR data[FILLP_DFX_DUMP_BUF_LEN];
FILLP_UINT32 len = 0;
struct FtSocket *sock = SockApiGetAndCheck(sockIndex);
if (sock == FILLP_NULL_PTR || sock->netconn == FILLP_NULL_PTR || sock->netconn->pcb == FILLP_NULL_PTR) {
if (sock != FILLP_NULL_PTR) {
(void)SYS_ARCH_RWSEM_RDPOST(&sock->sockConnSem);
}
if (DumpInvalidSock(sockIndex, data, &len) == FILLP_SUCCESS) {
dump(softObj, data, len);
}
return;
}
FILLP_INT isOk = DoShowFrameStats(sock, data, &len);
(void)SYS_ARCH_RWSEM_RDPOST(&sock->sockConnSem);
if (isOk != FILLP_SUCCESS) {
return;
}
dump(softObj, data, len);
}
static const FILLP_CHAR *g_optString = "hlmns:q:f:V";
static FILLP_INT FillpDfxCheckArg(FILLP_UINT32 argc, const FILLP_CHAR **argv, FillpDfxDumpFunc dump)
{
if (dump == NULL) {
FILLP_LOGERR("dump is null");
return FILLP_FAILURE;
}
if (argc == 0 || argc > FILLP_DFX_DUMP_MAX_ARGC) {
FILLP_LOGERR("argc is invalid %u", argc);
return FILLP_FAILURE;
}
if (argv == FILLP_NULL_PTR) {
FILLP_LOGERR("argv is NULL");
return FILLP_FAILURE;
}
FILLP_UINT32 i;
for (i = 0; i < argc; i++) {
if (argv[i] == FILLP_NULL_PTR) {
FILLP_LOGERR("argv[%d] is NULL", i);
return FILLP_FAILURE;
}
}
return FILLP_SUCCESS;
}
FILLP_INT FillpDfxDump(FILLP_UINT32 argc, const FILLP_CHAR **argv, void *softObj, FillpDfxDumpFunc dump)
{
FILLP_INT opt = 0;
FILLP_INT ret = 0;
const FILLP_CHAR *errMsg = "Parse option fail, please check your option!";
if (FillpDfxCheckArg(argc, argv, dump) != FILLP_SUCCESS) {
goto FAIL;
}
NstackGetOptMsg optMsg;
(void)NstackInitGetOptMsg(&optMsg);
while ((opt = NstackGetOpt(&optMsg, argc, argv, g_optString)) != NSTACK_GETOPT_END_OF_STR) {
switch (opt) {
case 'h':
FillpDumpShowHelp(softObj, dump);
break;
case 'l':
FillpDumpShowLogLevel(softObj, dump);
break;
case 'n':
FillpDumpShowSockList(softObj, dump);
break;
case 's':
ret = strtol(NstackGetOptArgs(&optMsg), FILLP_NULL_PTR, FILLP_DFX_DUMP_STRTOL_BASE);
FillpDumpShowSockResource(ret, softObj, dump);
break;
case 'q':
ret = strtol(NstackGetOptArgs(&optMsg), FILLP_NULL_PTR, FILLP_DFX_DUMP_STRTOL_BASE);
FillpDumpShowSockQos(ret, softObj, dump);
break;
case 'f':
ret = strtol(NstackGetOptArgs(&optMsg), FILLP_NULL_PTR, FILLP_DFX_DUMP_STRTOL_BASE);
FillpDumpShowFrameStats(ret, softObj, dump);
break;
case 'V':
FillpDumpShowVer(softObj, dump);
break;
default:
goto FAIL;
}
}
return 0;
FAIL:
if (dump != NULL) {
dump(softObj, errMsg, strlen(errMsg) + 1);
FillpDumpShowHelp(softObj, dump);
}
return -1;
}
#endif /* FILLP_ENABLE_DFX_HIDUMPER */

View File

@ -14,6 +14,7 @@
*/
#include "fillp_common.h"
#include "fillp_dfx.h"
#ifdef __cplusplus
extern "C" {
@ -1080,6 +1081,7 @@ static void ConnectingHandleFinInput(struct FillpPcb *pcb, struct FtSocket *sock
FillpDisableConnRetryCheckTimer(&conn->pcb->fpcb);
if (flags->verSet) {
FillpDfxSockLinkAndQosNotify(sock->index, FILLP_DFX_LINK_VERSION_MISMATCH);
sock->coreErrType[MSG_TYPE_DO_CONNECT] = ERR_REMOTE_REJECT_VERSION;
} else {
sock->coreErrType[MSG_TYPE_DO_CONNECT] = ERR_REMOTE_REJECT_OR_CLOSE;
@ -1255,6 +1257,7 @@ static void FillpHandleFin(struct FillpPcb *pcb, FILLP_CONST struct NetBuf *p, F
}
/* RST case */
FillpDfxSockLinkAndQosNotify(sock->index, FILLP_DFX_LINK_FIN_INPUT);
if (flags.wrSet && flags.rdSet) {
FillpHandleFinRst(conn, sock);
return;

View File

@ -19,6 +19,7 @@
#include "fillp_algorithm.h"
#include "fillp_common.h"
#include "fillp_output.h"
#include "fillp_dfx.h"
#ifdef __cplusplus
extern "C" {
@ -391,6 +392,7 @@ void FillpFcCycle(void *arg)
FILLP_LOGERR("Keep alive timeout, fillp_sock_id:%d,detaTime:%lld,keepAliveTime:%u(ms)",
sock->index, detaTime, sock->resConf.common.keepAliveTime);
FillpDfxSockLinkAndQosNotify(sock->index, FILLP_DFX_LINK_KEEPALIVE_TIMEOUT);
SpungeShutdownSock(sock, SPUNGE_SHUT_RDWR);
sock->errEvent |= SPUNGE_EPOLLERR;
SpungeEpollEventCallback(sock, (FILLP_INT)SPUNGE_EPOLLIN | (FILLP_INT)SPUNGE_EPOLLERR, 1);

View File

@ -21,6 +21,7 @@
#include "net.h"
#include "fillp_common.h"
#include "fillp_output.h"
#include "fillp_dfx.h"
#ifdef __cplusplus
extern "C" {
@ -274,6 +275,7 @@ static void FillpHdlDataInput(struct FillpPcb *pcb, FILLP_CONST struct NetBuf *b
if ((netconnState != CONN_STATE_CLOSING) && (netconnState != CONN_STATE_CONNECTED)) {
// Drop it silently
FILLP_LOGDBG("not connected or connecting, drop it !!!!!");
FillpDfxPktNotify(FILLP_GET_SOCKET(pcb)->index, FILLP_DFX_PKT_PARSE_FAIL, 1U);
return;
}
@ -447,6 +449,7 @@ static void FillpNackInput(struct FillpPcb *pcb, FILLP_CONST struct NetBuf *p)
struct FillpSeqPktNum seqPktNum;
if (FillpCheckNackPacket(pcb, p) != 0) {
FillpDfxPktNotify(ftSock->index, FILLP_DFX_PKT_PARSE_FAIL, 1U);
return;
}
@ -929,6 +932,7 @@ void FillpDoInput(struct FillpPcb *pcb, FILLP_CONST struct NetBuf *buf, struct S
FILLP_LOGINF("FillpDoInput: recv buffer length incorrect, dataLen = %d is greater than pktSize = %zu,"
"flag:%u, pktNum:%u, seqNum:%u",
buf->len, pcb->pktSize, head->flag, head->pktNum, head->seqNum);
FillpDfxPktNotify(ftSock->index, FILLP_DFX_PKT_PARSE_FAIL, 1U);
return;
}
@ -936,7 +940,7 @@ void FillpDoInput(struct FillpPcb *pcb, FILLP_CONST struct NetBuf *buf, struct S
FILLP_LOGINF("FillpDoInput: fillp_sock_id:%d protocol head incorrect. "
"dataLen = %u greater than buflen = %d, flag:%u, pktNum:%u, seqNum:%u",
ftSock->index, head->dataLen, buf->len, head->flag, head->pktNum, head->seqNum);
FillpDfxPktNotify(ftSock->index, FILLP_DFX_PKT_PARSE_FAIL, 1U);
return;
}
FillpDoInputPktType(pcb, buf, inst, (FILLP_UINT16)FILLP_PKT_GET_TYPE(head->flag));

View File

@ -17,6 +17,7 @@
#include "spunge_app.h"
#include "res.h"
#include "socket_common.h"
#include "fillp_dfx.h"
#include "spunge_message.h"
#ifdef __cplusplus
@ -585,6 +586,7 @@ static void SpungeHandleMsgDoShutdown(void *value, struct SpungeInstance *inst)
goto FINISH;
}
FillpDfxSockLinkAndQosNotify(sock->index, FILLP_DFX_LINK_CLOSE);
SpungeShutdownSock(sock, howValue);
if (readShut && writeShut) {
@ -687,6 +689,7 @@ static void SpungeHandleMsgClose(void *value, struct SpungeInstance *inst)
conn->closeSet = 1;
sock->allocState = SOCK_ALLOC_STATE_WAIT_TO_CLOSE;
FillpDfxSockLinkAndQosNotify(sock->index, FILLP_DFX_LINK_CLOSE);
SpungeShutdownSock(sock, SPUNGE_SHUT_RDWR);
SpungeCloseMsgFreeSrc(conn, sock);

View File

@ -82,7 +82,7 @@ if (defined(ohos_lite)) {
include_dirs = [
"$NSTACKX_ROOT/nstackx_util/interface",
"$NSTACKX_ROOT/nstackx_util/platform/unix",
"//utils/native/base/include/",
"//commonlibrary/c_utils/base/include/",
"//third_party/bounds_checking_function/include",
"interface",
"platform/unix",

View File

@ -134,7 +134,7 @@ int32_t RecvNetlinkResponse(int32_t nlSockFd, struct NlmsgCallback *nlcb)
};
int32_t recvLen;
char buf[MAX_NETLINK_BUFFER_LEN] = { 0 };
char buf[MAX_NETLINK_BUFFER_LEN] = {0};
iovRecv.iov_base = buf;
iovRecv.iov_len = MAX_NETLINK_BUFFER_LEN;

View File

@ -30,7 +30,7 @@
static int32_t ProcessQdiscInfoInner(struct rtattr *tb[], int32_t parent)
{
struct rtattr *tbs[TCA_STATS_MAX + 1] = { 0 };
struct rtattr *tbs[TCA_STATS_MAX + 1] = {0};
(void)parent;
struct rtattr *rta = RTA_DATA(tb[TCA_STATS2]); // tb is trusted
@ -69,7 +69,7 @@ static void ProcessQdiscInfo(struct nlmsghdr *h, void *arg, void *value)
return;
}
struct tcmsg *tcMsgRecv = NLMSG_DATA(h); // h is trusted
struct rtattr *tb[TCA_MAX + 1] = { 0 };
struct rtattr *tb[TCA_MAX + 1] = {0};
int32_t len = (int32_t)(h->nlmsg_len);
len -= NLMSG_LENGTH(sizeof(*tcMsgRecv));
if (len < 0) {
@ -101,7 +101,7 @@ static int32_t GetQdiscUsedLength(const char *devName, int32_t protocol, int32_t
int32_t sendNetlinkRequestCount = SEND_NETLINK_REQUEST_COUNT;
struct NlmsgCallback nlcb;
QdiscArg qdiscArg;
QdiscValue qdiscValue = { 0 };
QdiscValue qdiscValue = {0};
qdiscArg.ifIndex = (int32_t)if_nametoindex(devName);
qdiscArg.protocol = protocol;
@ -145,7 +145,7 @@ static inline int32_t CheckQdiscAllLen(int32_t qdiscAllLen)
static int32_t GetQdiscAllLengthFromFile(const char *devName)
{
char qdiscFileName[QDISC_FILE_NAME_NAX_LENGTH] = { 0 };
char qdiscFileName[QDISC_FILE_NAME_NAX_LENGTH] = {0};
int32_t ret = sprintf_s(
qdiscFileName, QDISC_FILE_NAME_NAX_LENGTH, "/sys/devices/virtual/net/%s/tx_queue_len", devName);
if (ret <= 0) {
@ -154,7 +154,7 @@ static int32_t GetQdiscAllLengthFromFile(const char *devName)
}
char *fileName = qdiscFileName;
char absolutePath[PATH_MAX + 1] = { 0 }; // +1 is avoiding array out of bound
char absolutePath[PATH_MAX + 1] = {0}; // +1 is avoiding array out of bound
if (realpath(qdiscFileName, absolutePath) == NULL) {
LOGE(TAG, "realpath failed");
} else {

View File

@ -58,8 +58,8 @@ static int32_t GetScanInfo(struct nl_msg *msg, void *arg)
{
struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
struct nlattr *tb[NL80211_ATTR_MAX + 1] = { 0 };
struct nlattr *bss[NL80211_BSS_MAX + 1] = { 0 };
struct nlattr *tb[NL80211_ATTR_MAX + 1] = {0};
struct nlattr *bss[NL80211_BSS_MAX + 1] = {0};
struct nla_policy bssPolicy[NL80211_BSS_MAX + 1] = {
[NL80211_BSS_FREQUENCY] = { .type = NLA_U32 },
[NL80211_BSS_BSSID] = { },
@ -102,7 +102,7 @@ static inline uint32_t ResolveBitrateInfoInner(struct nlattr *rInfo[])
static int32_t ResolveBitrateInfo(struct nlattr *bitrateAttr, WifiRateInfo *rateInfo)
{
struct nlattr *rInfo[NL80211_RATE_INFO_MAX + 1] = { 0 };
struct nlattr *rInfo[NL80211_RATE_INFO_MAX + 1] = {0};
static struct nla_policy ratePolicy[NL80211_RATE_INFO_MAX + 1] = {
[NL80211_RATE_INFO_BITRATE] = { .type = NLA_U16 },
[NL80211_RATE_INFO_BITRATE32] = { .type = NLA_U32 },
@ -155,10 +155,10 @@ static void GetStationInfoRate(WifiStationInfo *wifiStationInfo, struct nlattr *
static int32_t GetStationInfo(struct nl_msg *msg, void *arg)
{
struct nlattr *tb[NL80211_ATTR_MAX + 1] = { 0 };
struct nlattr *tb[NL80211_ATTR_MAX + 1] = {0};
struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
struct nlattr *sinfo[NL80211_STA_INFO_MAX + 1] = { 0 };
struct nlattr *sinfo[NL80211_STA_INFO_MAX + 1] = {0};
static struct nla_policy statsPolicy[NL80211_STA_INFO_MAX + 1] = {
[NL80211_STA_INFO_SIGNAL] = { .type = NLA_U8 },
[NL80211_STA_INFO_RX_BITRATE] = { .type = NLA_NESTED },

View File

@ -25,6 +25,7 @@ if (defined(ohos_lite)) {
"-DLWIP_DONT_PROVIDE_BYTEORDER_FUNCTIONS",
"-DLWIP_LITEOS_A_COMPAT",
"-DMBEDTLS_INCLUDED",
"-DDFILE_ENABLE_HIDUMP",
]
cflags_cc = cflags
}
@ -57,6 +58,7 @@ if (defined(ohos_lite)) {
"core/nstackx_dfile.c",
"core/nstackx_dfile_config.c",
"core/nstackx_dfile_control.c",
"core/nstackx_dfile_dfx.c",
"core/nstackx_dfile_frame.c",
"core/nstackx_dfile_mp.c",
"core/nstackx_dfile_retransmission.c",
@ -90,6 +92,7 @@ if (defined(ohos_lite)) {
"core/nstackx_dfile.c",
"core/nstackx_dfile_config.c",
"core/nstackx_dfile_control.c",
"core/nstackx_dfile_dfx.c",
"core/nstackx_dfile_frame.c",
"core/nstackx_dfile_mp.c",
"core/nstackx_dfile_retransmission.c",
@ -115,6 +118,7 @@ if (defined(ohos_lite)) {
"-Wall",
"-DMBEDTLS_INCLUDED",
"-DNSTACKX_WITH_HMOS_LINUX",
"-DDFILE_ENABLE_HIDUMP",
]
cflags_cc = cflags
include_dirs = [
@ -124,7 +128,7 @@ if (defined(ohos_lite)) {
"$NSTACKX_ROOT/nstackx_core",
"$NSTACKX_ROOT/nstackx_util/interface",
"$NSTACKX_ROOT/nstackx_util/platform/unix",
"//utils/native/base/include/",
"//commonlibrary/c_utils/base/include/",
"//third_party/bounds_checking_function/include",
]
sources = [
@ -134,6 +138,7 @@ if (defined(ohos_lite)) {
"core/nstackx_dfile.c",
"core/nstackx_dfile_config.c",
"core/nstackx_dfile_control.c",
"core/nstackx_dfile_dfx.c",
"core/nstackx_dfile_frame.c",
"core/nstackx_dfile_mp.c",
"core/nstackx_dfile_retransmission.c",

View File

@ -22,6 +22,7 @@
#include "nstackx_dfile_config.h"
#include "nstackx_dfile_mp.h"
#include "nstackx_congestion.h"
#include "nstackx_dfile_dfx.h"
#ifdef MBEDTLS_INCLUDED
#include "nstackx_mbedtls.h"
#else
@ -30,6 +31,9 @@
#include "nstackx_dfile_private.h"
#include "securec.h"
#include "nstackx_socket.h"
#ifdef DFILE_ENABLE_HIDUMP
#include "nstackx_getopt.h"
#endif
#define TAG "nStackXDFile"
#define Coverity_Tainted_Set(pkt)
@ -39,20 +43,14 @@
/* this lock will been destroy only when process exit. */
static pthread_mutex_t g_dFileSessionIdMutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t g_dFileSessionChainMutex = PTHREAD_MUTEX_INITIALIZER;
static List g_dFileSessionChain = {&(g_dFileSessionChain), &(g_dFileSessionChain)};
pthread_mutex_t g_dFileSessionChainMutex = PTHREAD_MUTEX_INITIALIZER;
List g_dFileSessionChain = {&(g_dFileSessionChain), &(g_dFileSessionChain)};
static uint16_t g_dFileSessionId = 0;
/* currently enabled capabilities */
static uint32_t g_capabilities = NSTACKX_CAPS_WLAN_CATAGORY | NSTACKX_CAPS_CHACHA;
/* wlan catagory from APP */
static uint32_t g_wlanCatagory = NSTACKX_WLAN_CAT_TCP;
typedef struct DFileSessionNode {
List list;
uint16_t sessionId;
DFileSession *session;
} DFileSessionNode;
typedef struct {
DFileSession *session;
char *path;
@ -87,7 +85,11 @@ static int32_t GetDFileSessionId(uint16_t *sessionId)
return NSTACKX_EOK;
}
#ifdef DFILE_ENABLE_HIDUMP
DFileSessionNode *GetDFileSessionNodeById(uint16_t sessionId)
#else
static DFileSessionNode *GetDFileSessionNodeById(uint16_t sessionId)
#endif
{
List *pos = NULL;
DFileSessionNode *node = NULL;
@ -470,6 +472,8 @@ static void DFileSendFileInner(void *arg)
DFileSession *session = ctx->session;
DFileMsg data;
DFileSendFileBeginEvent();
(void)memset_s(&data, sizeof(data), 0, sizeof(data));
if (session == NULL) {
data.errorCode = NSTACKX_EINVAL;
@ -913,6 +917,13 @@ static DFileSession *DFileSessionCreate(DFileSessionType type, DFileMsgReceiver
return NULL;
}
if (type == DFILE_SESSION_TYPE_CLIENT) {
DFileClientCreateEvent();
}
if (type == DFILE_SESSION_TYPE_SERVER) {
DFileServerCreateEvent();
}
DFileSessionBaseInit(session, type, msgReceiver, sessionId);
if (InitOutboundQueueWait(session) != NSTACKX_EOK) {
@ -1562,3 +1573,58 @@ int32_t NSTACKX_DFileSetCapabilities(uint32_t capabilities, uint32_t value)
(void)(value);
return NSTACKX_EOK;
}
#ifdef DFILE_ENABLE_HIDUMP
int32_t NSTACKX_DFileDump(uint32_t argc, const char **arg, void *softObj, DFileDumpFunc dump)
{
int32_t ret = 0, c = 0;
char *message = NULL;
char *opt = NULL;
size_t size = 0;
message = (char *)malloc(DUMP_INFO_MAX * sizeof(char));
if (message == NULL) {
LOGE(TAG, "malloc failed");
return NSTACKX_EFAILED;
}
(void)memset_s(message, DUMP_INFO_MAX, 0, DUMP_INFO_MAX);
NstackGetOptMsg optMsg;
(void)NstackInitGetOptMsg(&optMsg);
while ((c = NstackGetOpt(&optMsg, argc, arg, "s:m:hl")) != NSTACK_GETOPT_END_OF_STR) {
switch (c) {
case 'h':
ret = HidumpHelp(message, &size);
break;
case 'l':
ret = HidumpList(message, &size);
break;
case 'm':
opt = (char *)NstackGetOptArgs(&optMsg);
ret = HidumpMessage(message, &size, opt);
break;
case 's':
opt = (char *)NstackGetOptArgs(&optMsg);
ret = HidumpInformation(message, &size, opt);
break;
default:
LOGE(TAG, "unknown option");
ret = HidumpHelp(message, &size);
break;
}
if (ret != NSTACKX_EOK) {
free(message);
return ret;
}
dump(softObj, message, size);
(void)memset_s(message, DUMP_INFO_MAX, 0, DUMP_INFO_MAX);
}
free(message);
return ret;
}
#endif
void NSTACKX_DFileSetEventFunc(void *softObj, DFileEventFunc func)
{
DFileSetEvent(softObj, func);
}

View File

@ -0,0 +1,380 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "nstackx_dfile_dfx.h"
#include "securec.h"
#include "nstackx_dfile_session.h"
#include "nstackx_dfile_transfer.h"
#include "nstackx_log.h"
#define TAG "nStackXDFile"
#ifdef DFILE_ENABLE_HIDUMP
static bool g_dfileDumpFrameSwitch = 0;
int32_t HidumpHelp(char *message, size_t *size)
{
int32_t ret = 0;
ret = sprintf_s(message, DUMP_INFO_MAX,
"\n-h help information about the hidump dfile command.\n"
"-l Displays all session IDs.\n"
"-m signaling packet switch, 1:open, 0:close.\n"
"-s Displays information about the transmit end/receive end.\n"
" transmit end: capability, sending rate, I/O rate, send block number.\n"
" receive end: capability, I/O rate, retransmissions number, recev number, total number\n");
if (ret == -1) {
LOGE(TAG, "write message failed");
return NSTACKX_EFAILED;
}
*size = strlen(message);
return NSTACKX_EOK;
}
int32_t HidumpList(char *message, size_t *size)
{
int32_t ret = 0, retTemp = 0;
uint16_t count = 0;
bool flag = 0;
DFileSessionNode *node = NULL;
if (PthreadMutexLock(&g_dFileSessionChainMutex) != 0) {
LOGE(TAG, "lock g_dFileSessionChainMutex failed");
return 0;
}
List *pos = NULL;
retTemp = sprintf_s(message + ret, DUMP_INFO_MAX - ret, "\nsession id list:\n");
retTemp == -1 ? (flag = 1) : (ret = ret + retTemp);
LIST_FOR_EACH(pos, &g_dFileSessionChain)
{
node = (DFileSessionNode *)pos;
retTemp = sprintf_s(message + ret, DUMP_INFO_MAX - ret, "index %u sessionId: %u \n", count, node->sessionId);
retTemp == -1 ? (flag = 1) : (ret = ret + retTemp);
count++;
}
if (PthreadMutexUnlock(&g_dFileSessionChainMutex) != 0) {
LOGE(TAG, "unlock g_dFileSessionChainMutex failed");
return 0;
}
*size = strlen(message);
if (flag == 1) {
LOGE(TAG, "write message failed");
return NSTACKX_EFAILED;
}
return NSTACKX_EOK;
}
static int32_t HidumpInfoClient(char *message, size_t *size, DFileSession *session)
{
int32_t ret = 0, retTemp = 0;
bool flag = 0;
List *pos = NULL;
PeerInfo *peerInfoTemp = NULL;
retTemp = sprintf_s(message + ret, DUMP_INFO_MAX - ret, "\ncapability: %x\n", session->capability);
retTemp == -1 ? (flag = 1) : (ret = ret + retTemp);
retTemp = sprintf_s(message + ret, DUMP_INFO_MAX - ret, "amendSendRate: ");
retTemp == -1 ? (flag = 1) : (ret = ret + retTemp);
LIST_FOR_EACH(pos, &session->peerInfoChain)
{
peerInfoTemp = (PeerInfo *)pos;
retTemp = sprintf_s(message + ret, DUMP_INFO_MAX - ret, "%d ", peerInfoTemp->amendSendRate);
retTemp == -1 ? (flag = 1) : (ret = ret + retTemp);
}
retTemp = sprintf_s(message + ret, DUMP_INFO_MAX - ret, "\nIO read rate: %u KB/s\n", session->fileManager->iorRate);
retTemp == -1 ? (flag = 1) : (ret = ret + retTemp);
retTemp = sprintf_s(message + ret, DUMP_INFO_MAX - ret, "total send block num: %llu\n",
NSTACKX_ATOM_FETCH(&(session->totalSendBlocks)));
retTemp == -1 ? (flag = 1) : (ret = ret + retTemp);
*size = strlen(message);
if (flag == 1) {
return NSTACKX_EFAILED;
}
return NSTACKX_EOK;
}
static int32_t HidumpInfoServer(char *message, size_t *size, DFileSession *session)
{
int32_t ret = 0, retTemp = 0;
bool flag = 0;
List *pos = NULL;
DFileTrans *transTemp = NULL;
retTemp = sprintf_s(message + ret, DUMP_INFO_MAX - ret, "\ncapability: %x\n", session->capability);
retTemp == -1 ? (flag = 1) : (ret = ret + retTemp);
retTemp = sprintf_s(message + ret, DUMP_INFO_MAX - ret, "IO write rate: %u KB/s\n", session->fileManager->iowRate);
retTemp == -1 ? (flag = 1) : (ret = ret + retTemp);
LIST_FOR_EACH(pos, &session->dFileTransChain)
{
transTemp = (DFileTrans *)pos;
retTemp = sprintf_s(message + ret, DUMP_INFO_MAX - ret, "trans id: %d\n", transTemp->transId);
retTemp == -1 ? (flag = 1) : (ret = ret + retTemp);
retTemp = sprintf_s(message + ret, DUMP_INFO_MAX - ret, "allRetrySendCount:%u recev:%d all:%llu\n",
transTemp->allRetrySendCount, transTemp->receivedDataFrameCnt, transTemp->totalDataFrameCnt);
retTemp == -1 ? (flag = 1) : (ret = ret + retTemp);
}
*size = strlen(message);
if (flag == 1) {
return NSTACKX_EFAILED;
}
return NSTACKX_EOK;
}
int32_t HidumpInformation(char *message, size_t *size, char *opt)
{
int32_t ret = 0;
int64_t sessionId = 0;
DFileSession *session = NULL;
DFileSessionNode *node = NULL;
sessionId = (int64_t)strtol(opt, NULL, DUMP_DECIMAL);
if (sessionId > USHRT_MAX) {
(void)sprintf_s(message, DUMP_INFO_MAX, "session id is overflowing");
*size = strlen(message);
return NSTACKX_EOK;
}
node = GetDFileSessionNodeById(sessionId);
if (node == NULL) {
ret = sprintf_s(message, DUMP_INFO_MAX, "find session by session id failed");
return NSTACKX_EOK;
}
session = node->session;
if (session->sessionType == DFILE_SESSION_TYPE_CLIENT) {
ret = HidumpInfoClient(message, size, session);
} else {
ret = HidumpInfoServer(message, size, session);
}
if (ret != NSTACKX_EOK) {
LOGE(TAG, "write message failed");
return NSTACKX_EFAILED;
}
return NSTACKX_EOK;
}
static void SetDfileDumpFrameSwitch(bool status)
{
g_dfileDumpFrameSwitch = status;
}
bool GetDfileDumpFrameSwitch()
{
return g_dfileDumpFrameSwitch;
}
int32_t HidumpMessage(char *message, size_t *size, char *opt)
{
int ret = 0;
int64_t input;
input = (int64_t)strtol(opt, NULL, DUMP_DECIMAL);
if (input == 1) {
SetDfileDumpFrameSwitch(1);
ret = sprintf_s(message, DUMP_INFO_MAX, "Signaling packet switch is open");
} else if (input == 0) {
SetDfileDumpFrameSwitch(0);
ret = sprintf_s(message, DUMP_INFO_MAX, "Signaling packet switch is close");
} else {
ret = sprintf_s(message, DUMP_INFO_MAX, "Invalid input");
}
if (ret == -1) {
LOGE(TAG, "write message failed");
return NSTACKX_EFAILED;
}
*size = strlen(message);
return NSTACKX_EOK;
}
#endif
static void EventAssemble(char *eventName, DFileEventType eventType, DFileEventLevel eventLevel, uint32_t eventNum,
DFileEventParam *transParam)
{
DFileEvent temp;
DFileEvent *msg = &temp;
if (strcpy_s(msg->eventName, DFile_EVENT_NAME_LEN, eventName) != NSTACKX_EOK) {
LOGE(TAG, "string copy failed", 0);
return;
}
msg->type = eventType;
msg->level = eventLevel;
msg->paramNum = eventNum;
msg->params = transParam;
NSTACKX_DFileAssembleFunc(NULL, msg);
}
void WaitFileHeaderTimeoutEvent(DFileTransErrorCode errorCode)
{
char valueStr[DFile_EVENT_NAME_LEN];
char eventName[DFile_EVENT_NAME_LEN] = "Header confirm timeout";
DFileEventParam temp;
DFileEventParam *transParam = &temp;
(void)sprintf_s(valueStr, DFile_EVENT_NAME_LEN, "Errorcode: %u", errorCode);
transParam->type = DFile_PARAM_TYPE_STRING;
if (strcpy_s(transParam->name, DFile_EVENT_NAME_LEN, "Errorcode") != NSTACKX_EOK) {
LOGE(TAG, "string copy failed");
return;
}
if (strcpy_s(transParam->value.str, DFile_EVENT_NAME_LEN, valueStr) != NSTACKX_EOK) {
LOGE(TAG, "string copy failed");
return;
}
EventAssemble(eventName, DFile_EVENT_TYPE_FAULT, DFile_EVENT_LEVEL_CRITICAL, 1, transParam);
}
void DFileServerCreateEvent(void)
{
char valueStr[DFile_EVENT_NAME_LEN];
char eventName[DFile_EVENT_NAME_LEN] = "Server created";
DFileEventParam temp;
DFileEventParam *transParam = &temp;
transParam->type = DFile_PARAM_TYPE_STRING;
if (strcpy_s(transParam->name, DFile_EVENT_NAME_LEN, "NA") != NSTACKX_EOK) {
LOGE(TAG, "string copy failed");
return;
}
if (strcpy_s(transParam->value.str, DFile_EVENT_NAME_LEN, valueStr) != NSTACKX_EOK) {
LOGE(TAG, "string copy failed");
return;
}
EventAssemble(eventName, DFile_EVENT_TYPE_BEHAVIOR, DFile_EVENT_LEVEL_MINOR, 0, transParam);
}
void DFileClientCreateEvent(void)
{
char valueStr[DFile_EVENT_NAME_LEN];
char eventName[DFile_EVENT_NAME_LEN] = "Client created";
DFileEventParam temp;
DFileEventParam *transParam = &temp;
(void)sprintf_s(valueStr, DFile_EVENT_NAME_LEN, "");
transParam->type = DFile_PARAM_TYPE_STRING;
if (strcpy_s(transParam->name, DFile_EVENT_NAME_LEN, "NA") != NSTACKX_EOK) {
LOGE(TAG, "string copy failed");
return;
}
if (strcpy_s(transParam->value.str, DFile_EVENT_NAME_LEN, valueStr) != NSTACKX_EOK) {
LOGE(TAG, "string copy failed");
return;
}
EventAssemble(eventName, DFile_EVENT_TYPE_BEHAVIOR, DFile_EVENT_LEVEL_MINOR, 0, transParam);
}
void DFileSendFileBeginEvent(void)
{
char valueStr[DFile_EVENT_NAME_LEN];
char eventName[DFile_EVENT_NAME_LEN] = "Send file begin";
DFileEventParam temp;
DFileEventParam *transParam = &temp;
(void)sprintf_s(valueStr, DFile_EVENT_NAME_LEN, "");
transParam->type = DFile_PARAM_TYPE_STRING;
if (strcpy_s(transParam->name, DFile_EVENT_NAME_LEN, "NA") != NSTACKX_EOK) {
LOGE(TAG, "string copy failed", 0);
return;
}
if (strcpy_s(transParam->value.str, DFile_EVENT_NAME_LEN, valueStr) != NSTACKX_EOK) {
LOGE(TAG, "string copy failed", 0);
return;
}
EventAssemble(eventName, DFile_EVENT_TYPE_BEHAVIOR, DFile_EVENT_LEVEL_MINOR, 0, transParam);
}
void PeerShuttedEvent(void)
{
char valueStr[DFile_EVENT_NAME_LEN];
char eventName[DFile_EVENT_NAME_LEN] = "Peer shutted down";
DFileEventParam temp;
DFileEventParam *transParam = &temp;
(void)sprintf_s(valueStr, DFile_EVENT_NAME_LEN, "");
transParam->type = DFile_PARAM_TYPE_STRING;
if (strcpy_s(transParam->name, DFile_EVENT_NAME_LEN, "SocketIndex") != NSTACKX_EOK) {
LOGE(TAG, "string copy failed", 0);
return;
}
if (strcpy_s(transParam->value.str, DFile_EVENT_NAME_LEN, valueStr) != NSTACKX_EOK) {
LOGE(TAG, "string copy failed", 0);
return;
}
EventAssemble(eventName, DFile_EVENT_TYPE_FAULT, DFile_EVENT_LEVEL_CRITICAL, 1, transParam);
}
void TransferCompleteEvent(const double rate)
{
char valueStr[DFile_EVENT_NAME_LEN];
char eventName[DFile_EVENT_NAME_LEN] = "transferring completed";
DFileEventParam temp;
DFileEventParam *transParam = &temp;
(void)sprintf_s(valueStr, DFile_EVENT_NAME_LEN, "rate: %.2f MB/s", rate);
transParam->type = DFile_PARAM_TYPE_STRING;
if (strcpy_s(transParam->name, DFile_EVENT_NAME_LEN, "transrate") != NSTACKX_EOK) {
LOGE(TAG, "string copy failed", 0);
return;
}
if (strcpy_s(transParam->value.str, DFile_EVENT_NAME_LEN, valueStr) != NSTACKX_EOK) {
LOGE(TAG, "string copy failed", 0);
return;
}
EventAssemble(eventName, DFile_EVENT_TYPE_STATISTIC, DFile_EVENT_LEVEL_MINOR, 0, transParam);
}
void AcceptSocketEvent(void)
{
char valueStr[DFile_EVENT_NAME_LEN];
char eventName[DFile_EVENT_NAME_LEN] = "Accept socket success";
DFileEventParam temp;
DFileEventParam *transParam = &temp;
(void)sprintf_s(valueStr, DFile_EVENT_NAME_LEN, "");
transParam->type = DFile_PARAM_TYPE_STRING;
if (strcpy_s(transParam->name, DFile_EVENT_NAME_LEN, "NA") != NSTACKX_EOK) {
LOGE(TAG, "string copy failed", 0);
return;
}
if (strcpy_s(transParam->value.str, DFile_EVENT_NAME_LEN, valueStr) != NSTACKX_EOK) {
LOGE(TAG, "string copy failed", 0);
return;
}
EventAssemble(eventName, DFile_EVENT_TYPE_BEHAVIOR, DFile_EVENT_LEVEL_MINOR, 0, transParam);
}

View File

@ -18,6 +18,7 @@
#include "nstackx_dfile_transfer.h"
#include "nstackx_file_manager.h"
#include "nstackx_log.h"
#include "nstackx_dfile_dfx.h"
#include "securec.h"
#define TAG "nStackXDfileMp"

View File

@ -49,10 +49,10 @@ static void SendBackPressureFrame(DFileTrans *dFileTrans)
allSize = recvListAllSize + recvInnerAllSize;
uint32_t recvListWindowSize = (dFileTrans->fileManager->iowMaxRate * DFILE_KILOBYTES / NSTACKX_MILLI_TICKS)
* NSTACKX_ACK_INTERVAL * FILE_RECV_LIST_SLOW_START_RATE;
if ((allSize >= dFileTrans->fileManager->iowCount * FILE_RECV_LIST_IO_WRITE_THRESHOLD
|| allSize >= dFileTrans->fileManager->maxRecvBlockListSize * FILE_RECV_LIST_IO_WRITE_THRESHOLD
|| allSize * blockFrameSize >= recvListWindowSize)
&& allSize > 0) {
if (((allSize >= dFileTrans->fileManager->iowCount * FILE_RECV_LIST_IO_WRITE_THRESHOLD) ||
(allSize >= dFileTrans->fileManager->maxRecvBlockListSize * FILE_RECV_LIST_IO_WRITE_THRESHOLD) ||
(allSize * blockFrameSize >= recvListWindowSize)) &&
allSize > 0) {
dFileTrans->fileManager->recvListOverIo = 1;
} else {
dFileTrans->fileManager->recvListOverIo = 0;

View File

@ -34,6 +34,7 @@
#include "nstackx_dfile_mp.h"
#include "securec.h"
#include "nstackx_util.h"
#include "nstackx_dfile_dfx.h"
#define TAG "nStackXDFile"
@ -49,6 +50,7 @@
static void ReadEventHandle(void *arg);
static void ProcessSessionTrans(const DFileSession *session, uint16_t exceptTransId);
DFileEventFunc g_dfileEventFunc;
static QueueNode *CreateQueueNode(const uint8_t *frame, size_t length,
const struct sockaddr_in *peerAddr, uint8_t socketIndex)
@ -208,10 +210,10 @@ void NoticeSessionProgress(DFileSession *session)
{
DFileMsg data;
(void)memset_s(&data, sizeof(data), 0, sizeof(data));
if (FileManagerGetTotalBytes(session->fileManager, &data.transferUpdate.totalBytes) == NSTACKX_EOK &&
FileManagerGetBytesTransferred(session->fileManager, &data.transferUpdate.bytesTransferred) == NSTACKX_EOK
&& data.transferUpdate.bytesTransferred <= data.transferUpdate.totalBytes
&& data.transferUpdate.bytesTransferred > 0) {
if ((FileManagerGetTotalBytes(session->fileManager, &data.transferUpdate.totalBytes) == NSTACKX_EOK) &&
(FileManagerGetBytesTransferred(session->fileManager, &data.transferUpdate.bytesTransferred) == NSTACKX_EOK) &&
(data.transferUpdate.bytesTransferred <= data.transferUpdate.totalBytes) &&
(data.transferUpdate.bytesTransferred > 0)) {
NotifyMsgRecver(session, DFILE_ON_SESSION_IN_PROGRESS, &data);
}
}
@ -303,6 +305,8 @@ static void CalculateSessionTransferRate(DFileSession *session, uint64_t totalBy
(void)memset_s(&msgData, sizeof(msgData), 0, sizeof(msgData));
msgData.rate = (uint32_t)rate;
NotifyMsgRecver(session, DFILE_ON_SESSION_TRANSFER_RATE, &msgData);
TransferCompleteEvent(rate);
}
static void CheckTransDone(DFileSession *session, struct DFileTrans *dFileTrans, DFileTransMsgType msgType)
@ -1532,6 +1536,7 @@ void *DFileSenderHandle(void *arg)
}
ret = DFileSessionSendFrame(session, &queueNode, &unsent, &before, socketIndex);
if (ret < 0 && ret != NSTACKX_EAGAIN) {
PeerShuttedEvent();
PostFatalEvent(session);
break;
}
@ -1781,6 +1786,8 @@ int32_t DFileAcceptSocket(DFileSession *session)
SetTcpKeepAlive(session->acceptSocket->sockfd);
}
AcceptSocketEvent();
return NSTACKX_EOK;
}
@ -1810,6 +1817,7 @@ void *DFileReceiverHandle(void *arg)
ret = DFileSocketRecv(session);
if (ret != NSTACKX_EAGAIN && ret != NSTACKX_EOK) {
PeerShuttedEvent();
break;
}
}
@ -2036,3 +2044,15 @@ void DestroyReceiverPipe(DFileSession *session)
}
}
void DFileSetEvent(void *softObj, DFileEventFunc func)
{
g_dfileEventFunc = func;
(void)softObj;
}
void NSTACKX_DFileAssembleFunc(void *softObj, const DFileEvent *info)
{
if (g_dfileEventFunc != NULL) {
g_dfileEventFunc(softObj, info);
}
}

View File

@ -27,6 +27,7 @@
#include "nstackx_log.h"
#include "nstackx_timer.h"
#include "nstackx_util.h"
#include "nstackx_dfile_dfx.h"
#include "securec.h"
#define TAG "nStackXDFile"
@ -491,6 +492,7 @@ static void WaitForFileHeaderConfirm(DFileTrans *dFileTrans, DFileSendState *nex
if (dFileTrans->headerRetryCnt > dFileTrans->config.maxCtrlFrameRetryCnt) {
*nextState = STATE_SEND_FILE_FAIL;
dFileTrans->errorCode = DFILE_TRANS_FILE_HEADER_CONFIRM_TIMEOUT;
WaitFileHeaderTimeoutEvent(dFileTrans->errorCode);
return;
}
dFileTrans->headerRetryCnt++;

View File

@ -0,0 +1,59 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NSTACKX_DFILE_DFX_H
#define NSTACKX_DFILE_DFX_H
#include <limits.h>
#include "nstackx_dfile.h"
#include "nstackx_list.h"
#include "nstackx_dfile_session.h"
typedef struct DFileSessionNode {
List list;
uint16_t sessionId;
DFileSession *session;
} DFileSessionNode;
#ifdef __cplusplus
extern "C" {
#endif
#ifdef DFILE_ENABLE_HIDUMP
DFileSessionNode *GetDFileSessionNodeById(uint16_t sessionId);
#define DUMP_INFO_MAX 1000
#define DUMP_DECIMAL 10
extern pthread_mutex_t g_dFileSessionChainMutex;
extern List g_dFileSessionChain;
int32_t HidumpHelp(char *message, size_t *size);
int32_t HidumpList(char *message, size_t *size);
int32_t HidumpInformation(char *message, size_t *size, char *opt);
int32_t HidumpMessage(char *message, size_t *size, char *opt);
bool GetDfileHiDumpStatus();
#endif
void WaitFileHeaderTimeoutEvent(DFileTransErrorCode errorCode);
void DFileServerCreateEvent(void);
void DFileClientCreateEvent(void);
void DFileSendFileBeginEvent(void);
void PeerShuttedEvent(void);
void TransferCompleteEvent(const double rate);
void AcceptSocketEvent(void);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -241,6 +241,9 @@ static inline bool CapsChaCha(const struct DFileSession *session)
return (session->fileManager->keyLen == CHACHA20_KEY_LENGTH) && (session->capability & NSTACKX_CAPS_CHACHA);
}
void NSTACKX_DFileAssembleFunc(void *softObj, const DFileEvent *info);
void DFileSetEvent(void *softObj, DFileEventFunc func);
#ifdef __cplusplus
}
#endif

View File

@ -30,7 +30,6 @@
#endif
#include "nstackx_error.h"
#ifdef __cplusplus
extern "C" {
#endif
@ -190,6 +189,57 @@ typedef struct {
socklen_t addrLen;
} NSTACKX_ServerParaMp;
/* nStack HIEVENT接口设计 */
typedef enum {
DFile_EVENT_TYPE_FAULT,
DFile_EVENT_TYPE_STATISTIC,
DFile_EVENT_TYPE_SECURITY,
DFile_EVENT_TYPE_BEHAVIOR,
} DFileEventType;
typedef enum {
DFile_EVENT_LEVEL_CRITICAL,
DFile_EVENT_LEVEL_MINOR,
} DFileEventLevel;
typedef enum {
DFile_PARAM_TYPE_BOOL,
DFile_PARAM_TYPE_UINT8,
DFile_PARAM_TYPE_UINT16,
DFile_PARAM_TYPE_INT32,
DFile_PARAM_TYPE_UINT32,
DFile_PARAM_TYPE_UINT64,
DFile_PARAM_TYPE_FLOAT,
DFile_PARAM_TYPE_DOUBLE,
DFile_PARAM_TYPE_STRING
} DFileEventParamType;
#define DFile_EVENT_NAME_LEN 128
#define DFile_EVENT_TAG_LEN 16
typedef struct {
DFileEventParamType type;
char name[DFile_EVENT_NAME_LEN];
union {
uint8_t u8v;
uint16_t u16v;
int32_t i32v;
uint32_t u32v;
uint64_t u64v;
float f;
double d;
char str[DFile_EVENT_NAME_LEN];
} value;
} DFileEventParam;
typedef struct {
char eventName[DFile_EVENT_NAME_LEN];
DFileEventType type;
DFileEventLevel level;
uint32_t paramNum;
DFileEventParam *params;
} DFileEvent;
/*
* Create DFile server session.
* param: localAddr - filled with local ip addr, port and family for socket binding
@ -313,6 +363,15 @@ NSTACKX_EXPORT uint32_t NSTACKX_DFileGetCapabilities(void);
NSTACKX_EXPORT int32_t NSTACKX_DFileSetCapabilities(uint32_t capabilities, uint32_t value);
typedef void (*DFileDumpFunc)(void *softObj, const char *data, uint32_t len);
NSTACKX_EXPORT int32_t NSTACKX_DFileDump(uint32_t argc, const char **arg, void *softObj, DFileDumpFunc dump);
/* 软总线提供的回调支持多线程调用,事件的触发频率要求(表格整理出来,什么时候触发,触发频率) */
typedef void (*DFileEventFunc)(void *softObj, const DFileEvent *info);
NSTACKX_EXPORT void NSTACKX_DFileSetEventFunc(void *softObj, DFileEventFunc func);
#ifdef __cplusplus
}
#endif

View File

@ -17,6 +17,7 @@ cflags = [
"-DENABLE_USER_LOG",
"-DDFINDER_SAVE_DEVICE_LIST",
"-DNSTACKX_EXTEND_BUSINESSDATA",
"-DNSTACKX_DFINDER_HIDUMP",
]
if (defined(board_toolchain_type)) {
@ -48,7 +49,10 @@ if (defined(ohos_lite)) {
"core/nstackx_common.c",
"core/nstackx_database.c",
"core/nstackx_device.c",
"core/nstackx_dfinder_hidump.c",
"core/nstackx_dfinder_hievent.c",
"core/nstackx_dfinder_log.c",
"core/nstackx_statistics.c",
]
include_dirs = [
"include",
@ -94,8 +98,11 @@ if (defined(ohos_lite)) {
"core/nstackx_common.c",
"core/nstackx_database.c",
"core/nstackx_device.c",
"core/nstackx_dfinder_hidump.c",
"core/nstackx_dfinder_hievent.c",
"core/nstackx_dfinder_log.c",
"core/nstackx_smartgenius.c",
"core/nstackx_statistics.c",
]
ctrl_include = [
"../nstackx_util/interface",
@ -150,8 +157,11 @@ if (defined(ohos_lite)) {
"core/nstackx_common.c",
"core/nstackx_database.c",
"core/nstackx_device.c",
"core/nstackx_dfinder_hidump.c",
"core/nstackx_dfinder_hievent.c",
"core/nstackx_dfinder_log.c",
"core/nstackx_smartgenius.c",
"core/nstackx_statistics.c",
]
include_dirs += [
"//third_party/bounds_checking_function/include",

View File

@ -32,6 +32,7 @@
#include "nstackx_error.h"
#include "nstackx_dfinder_log.h"
#include "nstackx_event.h"
#include "nstackx_statistics.h"
#define TAG "nStackXCoAP"
@ -152,6 +153,7 @@ static void CoAPEpollErrorHandle(void *data)
if (socket == NULL) {
return;
}
IncStatistics(STATS_SOCKET_ERROR);
g_socketEventNum[SOCKET_ERROR_EVENT]++;
EpollTask *currEpollTask = NULL;
@ -185,6 +187,7 @@ static void CoAPEpollErrorHandle(void *data)
return;
}
coap_socket_t *socket = task->ptr;
IncStatistics(STATS_SOCKET_ERROR);
g_socketEventNum[SOCKET_ERROR_EVENT]++;
if (socket == NULL) {
return;
@ -440,6 +443,7 @@ int32_t CoapSelectWait(TaskListInfo *taskListInfo)
if (ret < 0) {
int lastError = WSAGetLastError();
if (lastError != WSAEINVAL) {
IncStatistics(STATS_SOCKET_ERROR);
DFINDER_LOGE(TAG, "select error ret lastError: %d", lastError);
return NSTACKX_EFAILED;
}
@ -494,6 +498,7 @@ static void *CoapIoMonitorLoop(void *arg)
break;
}
if (CoapSelectWait(&taskListInfo) == NSTACKX_EFAILED) {
IncStatistics(STATS_SOCKET_ERROR);
DFINDER_LOGE(TAG, "Coap select failure");
break;
}
@ -542,7 +547,7 @@ void CoapThreadDestory(void)
#endif
#ifdef DFINDER_SUPPORT_MULTI_NIF
int32_t CoapServerInitWithIdx(const struct in_addr *ip, uint32_t idx, const char *networkName)
static int32_t CoapServerInitWithIdxEx(const struct in_addr *ip, uint32_t idx, const char *networkName)
{
DFINDER_LOGI(TAG, "CoapServerInitWithIdx, idx-%u", idx);
@ -569,8 +574,17 @@ int32_t CoapServerInitWithIdx(const struct in_addr *ip, uint32_t idx, const char
return NSTACKX_EOK;
}
int32_t CoapServerInitWithIdx(const struct in_addr *ip, uint32_t idx, const char *networkName)
{
int32_t ret = CoapServerInitWithIdxEx(ip, idx, networkName);
if (ret != NSTACKX_EOK) {
IncStatistics(STATS_CREATE_SERVER_FAILED);
}
return ret;
}
#else
int32_t CoapServerInit(const struct in_addr *ip)
static int32_t CoapServerInitEx(const struct in_addr *ip)
{
DFINDER_LOGD(TAG, "CoapServerInit is called");
@ -600,7 +614,16 @@ int32_t CoapServerInit(const struct in_addr *ip)
return NSTACKX_EOK;
}
int32_t CoapP2pServerInit(const struct in_addr *ip)
int32_t CoapServerInit(const struct in_addr *ip)
{
int32_t ret = CoapServerInitEx(ip);
if (ret != NSTACKX_EOK) {
IncStatistics(STATS_CREATE_SERVER_FAILED);
}
return ret;
}
static int32_t CoapP2pServerInitEx(const struct in_addr *ip)
{
DFINDER_LOGD(TAG, "CoapP2pServerInit is called");
@ -635,7 +658,16 @@ int32_t CoapP2pServerInit(const struct in_addr *ip)
return NSTACKX_EOK;
}
int32_t CoapUsbServerInit(const struct in_addr *ip)
int32_t CoapP2pServerInit(const struct in_addr *ip)
{
int32_t ret = CoapP2pServerInitEx(ip);
if (ret != NSTACKX_EOK) {
IncStatistics(STATS_CREATE_SERVER_FAILED);
}
return ret;
}
static int32_t CoapUsbServerInitEx(const struct in_addr *ip)
{
DFINDER_LOGD(TAG, "CoapUsbServerInit is called");
@ -669,6 +701,15 @@ int32_t CoapUsbServerInit(const struct in_addr *ip)
return NSTACKX_EOK;
}
int32_t CoapUsbServerInit(const struct in_addr *ip)
{
int32_t ret = CoapUsbServerInitEx(ip);
if (ret != NSTACKX_EOK) {
IncStatistics(STATS_CREATE_SERVER_FAILED);
}
return ret;
}
#endif /* END OF DFINDER_SUPPORT_MULTI_NIF */
#ifdef DFINDER_SUPPORT_MULTI_NIF

View File

@ -33,6 +33,7 @@
#include "nstackx_error.h"
#include "nstackx_dfinder_log.h"
#include "nstackx_util.h"
#include "nstackx_statistics.h"
#define TAG "nStackXCoAP"
@ -121,7 +122,7 @@ coap_response_t CoapMessageHandler(coap_session_t *session,
{
if (received == NULL) {
DFINDER_LOGE(TAG, "received error");
return COAP_RESPONSE_FAIL;
goto FAIL;
}
(void)session;
(void)sent;
@ -133,22 +134,26 @@ coap_response_t CoapMessageHandler(coap_session_t *session,
(void)memset_s(&optIter, sizeof(optIter), 0, sizeof(optIter));
if (coap_pdu_get_type(received) == COAP_MESSAGE_RST) {
DFINDER_LOGD(TAG, "got RST");
return COAP_RESPONSE_FAIL;
goto FAIL;
}
if (coap_check_option(received, COAP_OPTION_OBSERVE, &optIter)) {
DFINDER_LOGE(TAG, "observe not support.");
return COAP_RESPONSE_FAIL;
goto FAIL;
}
blockOpt2 = coap_check_option(received, COAP_OPTION_BLOCK2, &optIter);
blockOpt1 = coap_check_option(received, COAP_OPTION_BLOCK1, &optIter);
if ((blockOpt1 != NULL) || (blockOpt2 != NULL)) {
DFINDER_LOGE(TAG, "block not support.");
return COAP_RESPONSE_FAIL;
goto FAIL;
}
coap_pdu_code_t rcv_code = coap_pdu_get_code(received);
DFINDER_LOGD(TAG, "%d.%02d", COAP_RESPONSE_CLASS(rcv_code), rcv_code & 0x1F);
return COAP_RESPONSE_OK;
FAIL:
IncStatistics(STATS_INVALID_RESPONSE_MSG);
return COAP_RESPONSE_FAIL;
}
static void InitAddrinfo(struct addrinfo *hints)
@ -162,7 +167,8 @@ static void InitAddrinfo(struct addrinfo *hints)
hints->ai_flags = AI_PASSIVE | AI_NUMERICHOST;
}
coap_context_t *CoapGetContext(const char *node, const char *port, uint8_t needBind, const struct in_addr *ip)
static coap_context_t *CoapGetContextEx(const char *node, const char *port,
uint8_t needBind, const struct in_addr *ip)
{
struct addrinfo hints;
struct addrinfo *result = NULL;
@ -215,6 +221,15 @@ coap_context_t *CoapGetContext(const char *node, const char *port, uint8_t needB
return ctx;
}
coap_context_t *CoapGetContext(const char *node, const char *port, uint8_t needBind, const struct in_addr *ip)
{
coap_context_t *context = CoapGetContextEx(node, port, needBind, ip);
if (context == NULL) {
IncStatistics(STATS_CREATE_CONTEX_FAILED);
}
return context;
}
static coap_session_t *CoapGetSessionInner(struct addrinfo *result, coap_context_t *ctx,
const CoapServerParameter *coapServerParameter)
{
@ -256,7 +271,7 @@ static void CoapSetAckTimeOut(coap_session_t *session)
coap_session_set_ack_random_factor(session, COAP_ACK_RANDOM_FACTOR);
}
coap_session_t *CoapGetSession(coap_context_t *ctx, const char *localAddr, const char *localPort,
static coap_session_t *CoapGetSessionEx(coap_context_t *ctx, const char *localAddr, const char *localPort,
const CoapServerParameter *coapServerParameter)
{
coap_session_t *session = NULL;
@ -308,6 +323,16 @@ coap_session_t *CoapGetSession(coap_context_t *ctx, const char *localAddr, const
return session;
}
coap_session_t *CoapGetSession(coap_context_t *ctx, const char *localAddr, const char *localPort,
const CoapServerParameter *coapServerParameter)
{
coap_session_t *session = CoapGetSessionEx(ctx, localAddr, localPort, coapServerParameter);
if (session == NULL) {
IncStatistics(STATS_CREATE_SESSION_FAILED);
}
return session;
}
uint8_t IsCoapCtxEndpointSocket(const coap_context_t *ctx, int fd)
{
coap_endpoint_t *iterator = NULL;

View File

@ -26,6 +26,7 @@
#include "nstackx_error.h"
#include "nstackx_device.h"
#include "json_payload.h"
#include "nstackx_statistics.h"
#define TAG "nStackXCoAP"
@ -264,7 +265,7 @@ DATA_FREE:
}
// Caller must make sure that reqeustPara, reqeustPara->serverType/context are all valid.
static int32_t CoapSendRequest(uint8_t coapType, const char *url, char *data, size_t dataLen,
static int32_t CoapSendRequestEx(uint8_t coapType, const char *url, char *data, size_t dataLen,
const CoapRequestPara *reqeustPara)
{
CoapContextWrapper wrapper = {
@ -292,6 +293,16 @@ static int32_t CoapSendRequest(uint8_t coapType, const char *url, char *data, si
return CoapSendRequestInner(coapType, url, data, dataLen, &wrapper);
}
static int32_t CoapSendRequest(uint8_t coapType, const char *url, char *data, size_t dataLen,
const CoapRequestPara *reqeustPara)
{
int32_t ret = CoapSendRequestEx(coapType, url, data, dataLen, reqeustPara);
if (ret != NSTACKX_EOK) {
IncStatistics(STATS_SEND_REQUEST_FAILED);
}
return ret;
}
static int32_t CoapResponseService(const char *remoteUrl, coap_context_t *context)
{
CoapRequestPara para = {
@ -368,22 +379,17 @@ static int32_t HndPostServiceDiscoverInner(const coap_pdu_t *request, char **rem
return NSTACKX_EOK;
}
static void HndPostServiceDiscover(coap_resource_t *resource, coap_session_t *session,
const coap_pdu_t *request, const coap_string_t *query, coap_pdu_t *response)
static int32_t HndPostServiceDiscoverEx(coap_session_t *session, const coap_pdu_t *request, coap_pdu_t *response)
{
(void)resource;
(void)query;
if (request == NULL || response == NULL) {
return;
}
int32_t ret = NSTACKX_EFAILED;
coap_context_t *currCtx = coap_session_get_context(session);
if (currCtx == NULL) {
return;
return ret;
}
char *remoteUrl = NULL;
DeviceInfo *deviceInfo = malloc(sizeof(DeviceInfo));
if (deviceInfo == NULL) {
return;
return ret;
}
if (HndPostServiceDiscoverInner(request, &remoteUrl, deviceInfo) != NSTACKX_EOK) {
goto L_ERR;
@ -418,9 +424,25 @@ static void HndPostServiceDiscover(coap_resource_t *resource, coap_session_t *se
} else {
coap_pdu_set_code(response, COAP_RESPONSE_CODE_CREATED);
}
ret = NSTACKX_EOK;
L_ERR:
free(deviceInfo);
free(remoteUrl);
return ret;
}
static void HndPostServiceDiscover(coap_resource_t *resource, coap_session_t *session,
const coap_pdu_t *request, const coap_string_t *query, coap_pdu_t *response)
{
(void)resource;
(void)query;
if (request == NULL || response == NULL) {
return;
}
if (HndPostServiceDiscoverEx(session, request, response) != NSTACKX_EOK) {
IncStatistics(STATS_HANDLE_DEVICE_DISCOVER_MSG_FAILED);
}
}
static void DeleteOverTimeMsgIdRecord(MsgIdList *msgIdList, struct timespec *curTime)
@ -442,6 +464,7 @@ static void DeleteOverTimeMsgIdRecord(MsgIdList *msgIdList, struct timespec *cur
msgIdList->startIdx = (msgIdList->startIdx + 1) % COAP_MAX_MSGID_RESERVE_NUM;
i = msgIdList->startIdx;
if (cycleTimes > COAP_MAX_MSGID_RESERVE_NUM) {
IncStatistics(STATS_DROP_MSG_ID);
DFINDER_LOGE(TAG, "cycle too many times, error must occurred and init msgList");
msgIdList->startIdx = COAP_MAX_MSGID_RESERVE_NUM;
msgIdList->endIdx = COAP_MAX_MSGID_RESERVE_NUM;
@ -500,6 +523,7 @@ static uint8_t RefreshMsgIdList(coap_mid_t msgId)
}
i = (i + 1) % COAP_MAX_MSGID_RESERVE_NUM;
if (cycleTimes > COAP_MAX_MSGID_RESERVE_NUM) {
IncStatistics(STATS_DROP_MSG_ID);
DFINDER_LOGE(TAG, "cycle too many times, error must occurred and init msgList");
g_msgIdList->startIdx = COAP_MAX_MSGID_RESERVE_NUM;
g_msgIdList->endIdx = COAP_MAX_MSGID_RESERVE_NUM;
@ -601,14 +625,14 @@ static uint16_t ParseServiceMsgFrame(const uint8_t *frame, uint16_t size, char *
return msgLen;
}
static void HndPostServiceMsg(coap_resource_t *resource, coap_session_t *session,
const coap_pdu_t *request, const coap_string_t *query, coap_pdu_t *response)
static int32_t HndPostServiceMsgEx(coap_resource_t *resource, coap_session_t *session,
const coap_pdu_t *request, const coap_string_t *query, coap_pdu_t *response)
{
(void)resource;
(void)session;
(void)query;
if (request == NULL || response == NULL) {
return;
return NSTACKX_EFAILED;
}
char deviceId[NSTACKX_MAX_DEVICE_ID_LEN] = {0};
char moduleName[NSTACKX_MAX_MODULE_NAME_LEN] = {0};
@ -618,30 +642,38 @@ static void HndPostServiceMsg(coap_resource_t *resource, coap_session_t *session
size_t size;
if (coap_get_data(request, &size, &buf) == 0 || size == 0 || size > COAP_RXBUFFER_SIZE) {
return;
return NSTACKX_EFAILED;
}
if (!RefreshMsgIdList(coap_pdu_get_mid(request))) {
DFINDER_LOGE(TAG, "repeated msg id");
return;
return NSTACKX_EFAILED;
}
DFINDER_LOGD(TAG, "handling post service msg request");
msgLen = ParseServiceMsgFrame(buf, size, moduleName, deviceId, &msg);
if (msgLen == 0) {
DFINDER_LOGD(TAG, "parse service msg frame error");
return;
return NSTACKX_EFAILED;
}
NotifyMsgReceived(moduleName, deviceId, msg, msgLen);
coap_pdu_set_code(response, COAP_RESPONSE_CODE_CREATED);
free(msg);
return;
return NSTACKX_EOK;
}
static void HndPostServiceMsg(coap_resource_t *resource, coap_session_t *session,
const coap_pdu_t *request, const coap_string_t *query, coap_pdu_t *response)
{
if (HndPostServiceMsgEx(resource, session, request, query, response) != NSTACKX_EOK) {
IncStatistics(STATS_HANDLE_SERVICE_MSG_FAILED);
}
}
#ifdef DFINDER_SUPPORT_MULTI_NIF
static int32_t CoapPostServiceDiscover(void)
static int32_t CoapPostServiceDiscoverEx(void)
{
char ifName[NSTACKX_MAX_INTERFACE_NAME_LEN] = {0};
char ipString[NSTACKX_MAX_IP_STRING_LEN] = {0};
@ -696,7 +728,7 @@ static int32_t CoapPostServiceDiscover(void)
return NSTACKX_EOK;
}
#else
static int32_t CoapPostServiceDiscover(void)
static int32_t CoapPostServiceDiscoverEx(void)
{
char ipString[NSTACKX_MAX_IP_STRING_LEN] = {0};
char discoverUri[COAP_URI_BUFFER_LENGTH] = {0};
@ -747,6 +779,15 @@ static int32_t CoapPostServiceDiscover(void)
}
#endif /* END OF DFINDER_SUPPORT_MULTI_NIF */
static int32_t CoapPostServiceDiscover(void)
{
int32_t ret = CoapPostServiceDiscoverEx();
if (ret != NSTACKX_EOK) {
IncStatistics(STATS_POST_SD_REQUEST_FAILED);
}
return ret;
}
static uint32_t GetDiscoverInterval(uint32_t discoverCount)
{
switch (g_coapDiscoverType) {
@ -782,11 +823,13 @@ static void CoapServiceDiscoverTimerHandle(void *argument)
#ifdef DFINDER_SUPPORT_MULTI_NIF
if (g_discoverCount >= g_coapDiscoverTargetCount || !IsApConnected()) {
IncStatistics(STATS_ABORT_SD);
CoapServiceDiscoverStop();
return;
}
#else
if (g_discoverCount >= g_coapDiscoverTargetCount || !IsWifiApConnected()) {
IncStatistics(STATS_ABORT_SD);
/* Discover done, or wifi AP disconnected. */
CoapServiceDiscoverStop();
return;
@ -810,6 +853,7 @@ static void CoapServiceDiscoverTimerHandle(void *argument)
return;
L_ERR_DISCOVER:
IncStatistics(STATS_ABORT_SD);
/* Abort service discover by not starting timer. */
DFINDER_LOGE(TAG, "abort service discovery, have tried %u request", g_discoverCount);
/* Reset g_discoverCount to allow new request from user. */
@ -908,6 +952,7 @@ static uint8_t NetworkIsConnected()
void CoapServiceDiscoverInner(uint8_t userRequest)
{
if (!NetworkIsConnected()) {
IncStatistics(STATS_START_SD_FAILED);
LOGI(TAG, "Network not connected when discovery inner");
return;
}
@ -935,6 +980,7 @@ void CoapServiceDiscoverInner(uint8_t userRequest)
#ifdef DFINDER_SAVE_DEVICE_LIST
/* First discover */
if (BackupDeviceDB() != NSTACKX_EOK) {
IncStatistics(STATS_START_SD_FAILED);
DFINDER_LOGE(TAG, "backup device list fail when discovery inner");
return;
}
@ -949,6 +995,7 @@ void CoapServiceDiscoverInner(uint8_t userRequest)
void CoapServiceDiscoverInnerAn(uint8_t userRequest)
{
if (!NetworkIsConnected()) {
IncStatistics(STATS_START_SD_FAILED);
LOGI(TAG, "Network not connected when discovery inner AN");
return;
}
@ -970,6 +1017,7 @@ void CoapServiceDiscoverInnerAn(uint8_t userRequest)
void CoapServiceDiscoverInnerConfigurable(uint8_t userRequest)
{
if (!NetworkIsConnected()) {
IncStatistics(STATS_START_SD_FAILED);
LOGI(TAG, "Network not connected when discovery configurable");
return;
}
@ -996,6 +1044,7 @@ void CoapServiceDiscoverInnerConfigurable(uint8_t userRequest)
/* First discover */
#ifdef DFINDER_SAVE_DEVICE_LIST
if (BackupDeviceDB() != NSTACKX_EOK) {
IncStatistics(STATS_START_SD_FAILED);
DFINDER_LOGE(TAG, "backup device list fail when discovery configurable");
return;
}
@ -1036,9 +1085,9 @@ static uint8_t *CreateServiceMsgFrame(const char *moduleName, const char *device
frame = (uint8_t *)calloc(1U, bufferLen);
if (frame == NULL) {
IncStatistics(STATS_CREATE_SERVICE_MSG_FAILED);
return NULL;
}
if (memcpy_s(frame, bufferLen, &frameLen, sizeof(frameLen)) != EOK) {
goto L_ERR_SEND_MSG;
}
@ -1069,6 +1118,7 @@ static uint8_t *CreateServiceMsgFrame(const char *moduleName, const char *device
*dataLen = bufferLen;
return frame;
L_ERR_SEND_MSG:
IncStatistics(STATS_CREATE_SERVICE_MSG_FAILED);
free(frame);
return NULL;
}
@ -1381,29 +1431,29 @@ void SetCoapUserDiscoverInfo(uint32_t advCount, uint32_t advDuration)
}
}
void SendDiscoveryRsp(const NSTACKX_ResponseSettings *responseSettings)
static int32_t SendDiscoveryRspEx(const NSTACKX_ResponseSettings *responseSettings)
{
char remoteUrl[NSTACKX_MAX_URI_BUFFER_LENGTH] = {0};
char host[NSTACKX_MAX_IP_STRING_LEN] = {0};
if (responseSettings == NULL) {
return;
return NSTACKX_EFAILED;
}
if (responseSettings->businessData == NULL) {
DFINDER_LOGE(TAG, "businessData is null");
return;
return NSTACKX_EFAILED;
}
if (SetLocalDeviceBusinessDataUnicast(responseSettings->businessData, responseSettings->length) != NSTACKX_EOK) {
return;
return NSTACKX_EFAILED;
}
if (strncpy_s(host, sizeof(host), responseSettings->remoteIp, strlen(responseSettings->remoteIp)) != EOK) {
DFINDER_LOGE(TAG, "discoveryRsp remoteIp copy error");
return;
return NSTACKX_EFAILED;
}
if (sprintf_s(remoteUrl, sizeof(remoteUrl), "coap://%s/" COAP_DEVICE_DISCOVER_URI, host) < 0) {
DFINDER_LOGE(TAG, "failed to get discoveryRsp remoteUrl");
return;
return NSTACKX_EFAILED;
}
#ifdef DFINDER_SUPPORT_MULTI_NIF
uint32_t i;
@ -1413,20 +1463,25 @@ void SendDiscoveryRsp(const NSTACKX_ResponseSettings *responseSettings)
}
if (strcmp(responseSettings->localNetworkName, g_discoverCtxList[i].networkName) == 0) {
DFINDER_LOGD(TAG, "find right discover context to call CoapResponseService with idx-%u", i);
(void)CoapResponseService(remoteUrl, g_discoverCtxList[i].context);
break;
return CoapResponseService(remoteUrl, g_discoverCtxList[i].context);
}
}
if (i == NSTACKX_MAX_LISTENED_NIF_NUM) {
DFINDER_LOGE(TAG, "can not find right discover context to call CoapResponseService");
return;
}
DFINDER_LOGE(TAG, "can not find right discover context to call CoapResponseService");
return NSTACKX_EFAILED;
#else
coap_context_t *context = GetContext(SERVER_TYPE_WLANORETH);
if (context == NULL) {
DFINDER_LOGE(TAG, "can not find right discover context to call CoapResponseService");
return;
return NSTACKX_EFAILED;
}
(void)CoapResponseService(remoteUrl, context);
return CoapResponseService(remoteUrl, context);
#endif
}
void SendDiscoveryRsp(const NSTACKX_ResponseSettings *responseSettings)
{
if (SendDiscoveryRspEx(responseSettings) != NSTACKX_EOK) {
IncStatistics(STATS_SEND_SD_RESPONSE_FAILED);
}
}

View File

@ -23,6 +23,7 @@
#include "nstackx_dfinder_log.h"
#include "nstackx_error.h"
#include "nstackx_device.h"
#include "nstackx_statistics.h"
#define TAG "nStackXCoAP"
@ -421,9 +422,9 @@ static void ParseBusinessDataJsonData(const cJSON *data, DeviceInfo *dev, uint8_
* }
*/
#ifdef DFINDER_SUPPORT_MULTI_NIF
char *PrepareServiceDiscoverWithIdx(uint8_t isBroadcast, uint32_t idx)
static char *PrepareServiceDiscoverWithIdxEx(uint8_t isBroadcast, uint32_t idx)
#else
char *PrepareServiceDiscover(uint8_t isBroadcast)
static char *PrepareServiceDiscoverEx(uint8_t isBroadcast)
#endif /* #ifdef DFINDER_SUPPORT_MULTI_NIF */
{
char coapUriBuffer[NSTACKX_MAX_URI_BUFFER_LENGTH] = {0};
@ -482,7 +483,27 @@ L_END_JSON:
return formatString;
}
int32_t ParseServiceDiscover(const uint8_t *buf, DeviceInfo *deviceInfo, char **remoteUrlPtr)
#ifdef DFINDER_SUPPORT_MULTI_NIF
char *PrepareServiceDiscoverWithIdx(uint8_t isBroadcast, uint32_t idx)
{
char *str = PrepareServiceDiscoverWithIdxEx(isBroadcast, idx);
if (str == NULL) {
IncStatistics(STATS_PREPARE_SD_MSG_FAILED);
}
return str;
}
#else
char *PrepareServiceDiscover(uint8_t isBroadcast)
{
char *str = PrepareServiceDiscoverEx(isBroadcast);
if (str == NULL) {
IncStatistics(STATS_PREPARE_SD_MSG_FAILED);
}
return str;
}
#endif
static int32_t ParseServiceDiscoverEx(const uint8_t *buf, DeviceInfo *deviceInfo, char **remoteUrlPtr)
{
char *remoteUrl = NULL;
cJSON *data = NULL;
@ -532,3 +553,12 @@ int32_t ParseServiceDiscover(const uint8_t *buf, DeviceInfo *deviceInfo, char **
cJSON_Delete(data);
return NSTACKX_EOK;
}
int32_t ParseServiceDiscover(const uint8_t *buf, DeviceInfo *deviceInfo, char **remoteUrlPtr)
{
int32_t ret = ParseServiceDiscoverEx(buf, deviceInfo, remoteUrlPtr);
if (ret != NSTACKX_EOK) {
IncStatistics(STATS_PARSE_SD_MSG_FAILED);
}
return ret;
}

View File

@ -16,6 +16,7 @@
#include "coap_adapter.h"
#include "nstackx_dfinder_log.h"
#include "securec.h"
#include "nstackx_statistics.h"
#define COAP_MAX_ENDPOINTS_NUM 64
#define COAP_LOW_DELTA_NUM 13
@ -126,7 +127,7 @@ static int32_t CoapParseOption(CoapOption *option, uint16_t *runningDelta, const
return DISCOVERY_ERR_SUCCESS;
}
static int32_t CoapParseOptionsAndPayload(CoapPacket *pkt, const uint8_t *buf, uint32_t buflen)
static int32_t CoapParseOptionsAndPayloadEx(CoapPacket *pkt, const uint8_t *buf, uint32_t buflen)
{
uint8_t optionIndex = 0;
uint16_t delta = 0;
@ -167,6 +168,15 @@ static int32_t CoapParseOptionsAndPayload(CoapPacket *pkt, const uint8_t *buf, u
return DISCOVERY_ERR_SUCCESS;
}
static int32_t CoapParseOptionsAndPayload(CoapPacket *pkt, const uint8_t *buf, uint32_t buflen)
{
int32_t ret = CoapParseOptionsAndPayloadEx(pkt, buf, buflen);
if (ret != DISCOVERY_ERR_SUCCESS) {
IncStatistics(STATS_INVALID_OPT_AND_PAYLOAD);
}
return ret;
}
static int32_t CoapParseHeader(CoapPacket *pkt, const uint8_t *buf, uint32_t bufLen)
{
if (bufLen < HEADER_LEN) {
@ -183,7 +193,7 @@ static int32_t CoapParseHeader(CoapPacket *pkt, const uint8_t *buf, uint32_t buf
return DISCOVERY_ERR_SUCCESS;
}
int32_t CoapSoftBusDecode(CoapPacket *pkt, const uint8_t *buf, uint32_t bufLen)
static int32_t CoapSoftBusDecodeEx(CoapPacket *pkt, const uint8_t *buf, uint32_t bufLen)
{
int32_t ret;
if (pkt == NULL || buf == NULL) {
@ -241,7 +251,16 @@ int32_t CoapSoftBusDecode(CoapPacket *pkt, const uint8_t *buf, uint32_t bufLen)
return DISCOVERY_ERR_SUCCESS;
}
static int32_t CoapCreateHeader(CoapPacket *pkt, const CoapPacketParam *pktParam, CoapReadWriteBuffer *buf)
int32_t CoapSoftBusDecode(CoapPacket *pkt, const uint8_t *buf, uint32_t bufLen)
{
int32_t ret = CoapSoftBusDecodeEx(pkt, buf, bufLen);
if (ret != DISCOVERY_ERR_SUCCESS) {
IncStatistics(STATS_DECODE_FAILED);
}
return ret;
}
static int32_t CoapCreateHeaderEx(CoapPacket *pkt, const CoapPacketParam *pktParam, CoapReadWriteBuffer *buf)
{
if (buf->len != 0) {
DFINDER_LOGE(TAG, "CoapCreateHeader invalid argument");
@ -284,6 +303,15 @@ static int32_t CoapCreateHeader(CoapPacket *pkt, const CoapPacketParam *pktParam
return DISCOVERY_ERR_SUCCESS;
}
static int32_t CoapCreateHeader(CoapPacket *pkt, const CoapPacketParam *pktParam, CoapReadWriteBuffer *buf)
{
int32_t ret = CoapCreateHeaderEx(pkt, pktParam, buf);
if (ret != DISCOVERY_ERR_SUCCESS) {
IncStatistics(STATS_CREATE_HEADER_FAILED);
}
return ret;
}
static int32_t CoapAddData(CoapPacket *pkt, const CoapBuffer *payload, CoapReadWriteBuffer *buf)
{
if ((payload->len == 0) && (payload->buffer == NULL)) {
@ -527,7 +555,7 @@ static int32_t CoapCreateBody(CoapPacket *pkt, const CoapPacketParam *param, con
return DISCOVERY_ERR_SUCCESS;
}
int32_t CoapSoftBusEncode(CoapPacket *pkt, const CoapPacketParam *param, const CoapBuffer *payload,
static int32_t CoapSoftBusEncodeEx(CoapPacket *pkt, const CoapPacketParam *param, const CoapBuffer *payload,
CoapReadWriteBuffer *buf)
{
int32_t ret;
@ -555,6 +583,16 @@ int32_t CoapSoftBusEncode(CoapPacket *pkt, const CoapPacketParam *param, const C
return DISCOVERY_ERR_SUCCESS;
}
static int32_t CoapSoftBusEncode(CoapPacket *pkt, const CoapPacketParam *param, const CoapBuffer *payload,
CoapReadWriteBuffer *buf)
{
int32_t ret = CoapSoftBusEncodeEx(pkt, param, payload, buf);
if (ret != DISCOVERY_ERR_SUCCESS) {
IncStatistics(STATS_ENCODE_FAILED);
}
return ret;
}
void CoapSoftBusInitMsgId(void)
{
g_msgId = (uint16_t)(RAND_DIVISOR);
@ -617,7 +655,8 @@ static void BuildCoapPktParam(const CoapBuildParam *buildParam, CoapPacketParam
outParam->msgId = buildParam->msgId;
}
int32_t BuildCoapPkt(const CoapBuildParam *param, const char *pktPayload, CoapReadWriteBuffer *sndPktBuff, bool isAck)
static int32_t BuildCoapPktEx(const CoapBuildParam *param, const char *pktPayload,
CoapReadWriteBuffer *sndPktBuff, bool isAck)
{
if (param == NULL || sndPktBuff == NULL || sndPktBuff->readWriteBuf == NULL) {
DFINDER_LOGE(TAG, "BuildCoapPkt invalid");
@ -661,3 +700,12 @@ int32_t BuildCoapPkt(const CoapBuildParam *param, const char *pktPayload, CoapRe
return DISCOVERY_ERR_SUCCESS;
}
int32_t BuildCoapPkt(const CoapBuildParam *param, const char *pktPayload, CoapReadWriteBuffer *sndPktBuff, bool isAck)
{
int32_t ret = BuildCoapPktEx(param, pktPayload, sndPktBuff, isAck);
if (ret != DISCOVERY_ERR_SUCCESS) {
IncStatistics(STATS_BUILD_PKT_FAILED);
}
return ret;
}

View File

@ -31,6 +31,7 @@
#include "nstackx_error.h"
#include "nstackx_dfinder_log.h"
#include "sys_util.h"
#include "nstackx_statistics.h"
#define TAG "nStackXCoAP"
@ -87,12 +88,14 @@ static void HandleReadEvent(int32_t fd)
socklen_t len = sizeof(struct sockaddr_in);
ssize_t nRead = recvfrom(fd, recvBuffer, COAP_MAX_PDU_SIZE, 0, (struct sockaddr *)&remoteAddr, &len);
if ((nRead == 0) || (nRead < 0 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)) {
IncStatistics(STATS_SOCKET_ERROR);
free(recvBuffer);
DFINDER_LOGE(TAG, "receive from remote packet failed");
return;
}
if (IsLoopBackPacket(&remoteAddr)) {
IncStatistics(STATS_DROP_LOOPBACK_PKT);
free(recvBuffer);
return;
}
@ -105,7 +108,7 @@ static void HandleReadEvent(int32_t fd)
free(recvBuffer);
}
static int32_t CoapCreateUdpClient(const struct sockaddr_in *sockAddr, uint8_t isBroadCast)
static int32_t CoapCreateUdpClientEx(const struct sockaddr_in *sockAddr, uint8_t isBroadCast)
{
(void)sockAddr;
int32_t fd = socket(AF_INET, SOCK_DGRAM, 0);
@ -148,6 +151,15 @@ CLOSE_FD:
return NSTACKX_EFAILED;
}
static int32_t CoapCreateUdpClient(const struct sockaddr_in *sockAddr, uint8_t isBroadCast)
{
int32_t ret = CoapCreateUdpClientEx(sockAddr, isBroadCast);
if (ret == NSTACKX_EFAILED) {
IncStatistics(STATS_CREATE_CLIENT_FAILED);
}
return ret;
}
static int32_t CoapSocketSend(const SocketInfo *socket, const uint8_t *buffer, size_t length)
{
if (buffer == NULL || socket == NULL) {
@ -157,6 +169,7 @@ static int32_t CoapSocketSend(const SocketInfo *socket, const uint8_t *buffer, s
socklen_t dstAddrLen = sizeof(struct sockaddr_in);
int32_t ret = sendto(socket->cliendFd, buffer, length, 0, (struct sockaddr *)&socket->dstAddr, dstAddrLen);
if (ret != length) {
IncStatistics(STATS_SOCKET_ERROR);
DFINDER_LOGE(TAG, "sendto failed, ret = %d, errno = %d", ret, errno);
}
return ret;
@ -190,7 +203,7 @@ static int32_t CoapSendMsg(const CoapRequest *coapRequest, uint8_t isBroadcast)
return NSTACKX_EOK;
}
int32_t CoapSendMessage(const CoapBuildParam *param, uint8_t isBroadcast, bool isAckMsg)
static int32_t CoapSendMessageEx(const CoapBuildParam *param, uint8_t isBroadcast, bool isAckMsg)
{
if (param == NULL) {
DFINDER_LOGE(TAG, "coap build param is null");
@ -237,6 +250,15 @@ int32_t CoapSendMessage(const CoapBuildParam *param, uint8_t isBroadcast, bool i
return ret;
}
int32_t CoapSendMessage(const CoapBuildParam *param, uint8_t isBroadcast, bool isAckMsg)
{
int32_t ret = CoapSendMessageEx(param, isBroadcast, isAckMsg);
if (ret != DISCOVERY_ERR_SUCCESS) {
IncStatistics(STATS_SEND_MSG_FAILED);
}
return ret;
}
static void DeRegisteCoAPEpollTaskCtx(void)
{
DeRegisterEpollTask(&g_task);
@ -277,6 +299,7 @@ static void CoAPEpollErrorHandle(void *data)
if (task->taskfd < 0) {
return;
}
IncStatistics(STATS_SOCKET_ERROR);
g_socketEventNum[SOCKET_ERROR_EVENT]++;
g_ctxSocketErrFlag = NSTACKX_TRUE;
DFINDER_LOGE(TAG, "coap socket error occurred and close it");
@ -352,7 +375,7 @@ static int32_t CoapGetContext(const char *node, int32_t port, uint8_t needBind,
return coapListenFd;
}
int32_t CoapServerInit(const struct in_addr *ip)
static int32_t CoapServerInitEx(const struct in_addr *ip)
{
DFINDER_LOGD(TAG, "CoapServerInit is called");
EpollDesc epollFd;
@ -388,6 +411,15 @@ int32_t CoapServerInit(const struct in_addr *ip)
return NSTACKX_EOK;
}
int32_t CoapServerInit(const struct in_addr *ip)
{
int32_t ret = CoapServerInitEx(ip);
if (ret != NSTACKX_EOK) {
IncStatistics(STATS_CREATE_SERVER_FAILED);
}
return ret;
}
void CoapServerDestroy(void)
{
DFINDER_LOGD(TAG, "CoapServerDestroy is called");

View File

@ -27,6 +27,7 @@
#include "nstackx_dfinder_log.h"
#include "nstackx_timer.h"
#include "securec.h"
#include "nstackx_statistics.h"
#define TAG "nStackXCoAP"
@ -125,10 +126,11 @@ static int32_t CreateUnicastCoapParam(const char *remoteUrl, const char *remoteI
return NSTACKX_EOK;
}
void HndPostServiceDiscover(const CoapPacket *pkt)
static int32_t HndPostServiceDiscoverEx(const CoapPacket *pkt)
{
int32_t ret = NSTACKX_EFAILED;
if (pkt == NULL) {
return;
return ret;
}
char *remoteUrl = NULL;
CoapBuildParam param;
@ -137,7 +139,7 @@ void HndPostServiceDiscover(const CoapPacket *pkt)
DeviceInfo *deviceInfo = (DeviceInfo *)malloc(sizeof(DeviceInfo));
if (deviceInfo == NULL) {
DFINDER_LOGE(TAG, "malloc device info failed");
return;
return ret;
}
(void)memset_s(deviceInfo, sizeof(DeviceInfo), 0, sizeof(DeviceInfo));
if (HndPostServiceDiscoverInner(pkt->payload.buffer, pkt->payload.len, &remoteUrl, deviceInfo) != NSTACKX_EOK) {
@ -154,7 +156,6 @@ void HndPostServiceDiscover(const CoapPacket *pkt)
#endif /* END OF DFINDER_SAVE_DEVICE_LIST */
goto FAIL;
}
if (g_forceUpdate) {
g_forceUpdate = NSTACKX_FALSE;
}
@ -165,16 +166,24 @@ void HndPostServiceDiscover(const CoapPacket *pkt)
(void)inet_ntop(AF_INET, &(deviceInfo->netChannelInfo.wifiApInfo.ip), wifiIpAddr, sizeof(wifiIpAddr));
GetBuildCoapParam(pkt, remoteUrl, wifiIpAddr, &param);
if (remoteUrl != NULL) {
/* check if we need to reply a unicast based on businessType. */
if (CheckBusinessTypeReplyUnicast(deviceInfo->businessType) == NSTACKX_EOK) {
(void)CoapSendMessage(&param, NSTACKX_FALSE, false);
}
} else {
(void)CoapSendMessage(&param, NSTACKX_FALSE, true);
}
ret = NSTACKX_EOK;
FAIL:
free(remoteUrl);
free(deviceInfo);
return ret;
}
void HndPostServiceDiscover(const CoapPacket *pkt)
{
if (HndPostServiceDiscoverEx(pkt) != NSTACKX_EOK) {
IncStatistics(STATS_HANDLE_DEVICE_DISCOVER_MSG_FAILED);
}
}
static uint32_t GetDiscoverInterval(uint32_t discoverCount)
@ -204,7 +213,7 @@ static void CoapServiceDiscoverStop(void)
g_userRequest = NSTACKX_FALSE;
}
static int32_t CoapPostServiceDiscover(void)
static int32_t CoapPostServiceDiscoverEx(void)
{
char ipString[NSTACKX_MAX_IP_STRING_LEN] = {0};
char ifName[NSTACKX_MAX_INTERFACE_NAME_LEN] = {0};
@ -246,6 +255,15 @@ static int32_t CoapPostServiceDiscover(void)
return NSTACKX_EOK;
}
static int32_t CoapPostServiceDiscover(void)
{
int32_t ret = CoapPostServiceDiscoverEx();
if (ret != NSTACKX_EOK) {
IncStatistics(STATS_POST_SD_REQUEST_FAILED);
}
return ret;
}
static void CoapServiceDiscoverTimerHandle(void *argument)
{
uint32_t discoverInterval;
@ -317,6 +335,7 @@ static void CoapServiceDiscoverFirstTime(void)
void CoapServiceDiscoverInner(uint8_t userRequest)
{
if (!IsWifiApConnected()) {
IncStatistics(STATS_START_SD_FAILED);
DFINDER_LOGI(TAG, "Network not connected when discovery inner for mini");
return;
}
@ -344,6 +363,7 @@ void CoapServiceDiscoverInner(uint8_t userRequest)
#ifdef DFINDER_SAVE_DEVICE_LIST
/* First discover */
if (BackupDeviceDB() != NSTACKX_EOK) {
IncStatistics(STATS_START_SD_FAILED);
DFINDER_LOGE(TAG, "backup device list fail");
return;
}
@ -357,6 +377,7 @@ void CoapServiceDiscoverInner(uint8_t userRequest)
void CoapServiceDiscoverInnerAn(uint8_t userRequest)
{
if (!IsWifiApConnected()) {
IncStatistics(STATS_START_SD_FAILED);
return;
}
@ -375,6 +396,7 @@ void CoapServiceDiscoverInnerAn(uint8_t userRequest)
void CoapServiceDiscoverInnerConfigurable(uint8_t userRequest)
{
if (!IsWifiApConnected()) {
IncStatistics(STATS_START_SD_FAILED);
DFINDER_LOGI(TAG, "Network not connected when discovery inner for configurable");
return;
}
@ -402,6 +424,7 @@ void CoapServiceDiscoverInnerConfigurable(uint8_t userRequest)
#ifdef DFINDER_SAVE_DEVICE_LIST
/* First discover */
if (BackupDeviceDB() != NSTACKX_EOK) {
IncStatistics(STATS_START_SD_FAILED);
DFINDER_LOGE(TAG, "backup device list fail");
return;
}
@ -463,35 +486,42 @@ void SetCoapDiscoverType(CoapBroadcastType type)
g_coapDiscoverType = (uint32_t)type;
}
void SendDiscoveryRsp(const NSTACKX_ResponseSettings *responseSettings)
static int32_t SendDiscoveryRspEx(const NSTACKX_ResponseSettings *responseSettings)
{
if (responseSettings == NULL) {
return;
return NSTACKX_EFAILED;
}
if (responseSettings->businessData == NULL) {
DFINDER_LOGE(TAG, "businessData is null");
return;
return NSTACKX_EFAILED;
}
if (SetLocalDeviceBusinessDataUnicast(responseSettings->businessData,
responseSettings->length) != NSTACKX_EOK) {
return;
return NSTACKX_EFAILED;
}
char remoteUrl[NSTACKX_MAX_URI_BUFFER_LENGTH] = {0};
char host[NSTACKX_MAX_IP_STRING_LEN] = {0};
if (strncpy_s(host, sizeof(host), responseSettings->remoteIp,
strlen(responseSettings->remoteIp)) != EOK) {
DFINDER_LOGE(TAG, "discoveryRsp remoteIp copy error");
return;
return NSTACKX_EFAILED;
}
if (sprintf_s(remoteUrl, sizeof(remoteUrl), "coap://%s/" COAP_DEVICE_DISCOVER_URI, host) < 0) {
DFINDER_LOGE(TAG, "failed to get discoveryRsp remoteUrl");
return;
return NSTACKX_EFAILED;
}
CoapBuildParam param = {0};
CreateUnicastCoapParam(remoteUrl, host, &param);
(void)CoapSendMessage(&param, NSTACKX_FALSE, false);
return CoapSendMessage(&param, NSTACKX_FALSE, false);
}
void SendDiscoveryRsp(const NSTACKX_ResponseSettings *responseSettings)
{
if (SendDiscoveryRspEx(responseSettings) != NSTACKX_EOK) {
IncStatistics(STATS_SEND_SD_RESPONSE_FAILED);
}
}
void SetCoapUserDiscoverInfo(uint32_t advCount, uint32_t advDuration)

View File

@ -35,6 +35,9 @@
#include "nstackx_timer.h"
#include "nstackx_util.h"
#include "json_payload.h"
#include "nstackx_statistics.h"
#include "nstackx_dfinder_hidump.h"
#include "nstackx_dfinder_hievent.h"
#ifdef DFINDER_USE_MINI_NSTACKX
#include "cmsis_os2.h"
@ -80,6 +83,16 @@ static uint32_t g_continuousBusyIntervals;
static int32_t CheckDiscoverySettings(const NSTACKX_DiscoverySettings *discoverySettings);
List *GetEventNodeChain(void)
{
return &g_eventNodeChain;
}
EpollDesc GetEpollFD(void)
{
return g_epollfd;
}
void NotifyDFinderMsgRecver(DFinderMsgType msgType)
{
if (g_parameter.onDFinderMsgReceived != NULL) {
@ -87,6 +100,7 @@ void NotifyDFinderMsgRecver(DFinderMsgType msgType)
}
}
/* check if we need to reply a unicast based on businessType. */
int32_t CheckBusinessTypeReplyUnicast(uint8_t businessType)
{
switch (businessType) {
@ -231,6 +245,7 @@ static void *NstackMainLoop(void *arg)
ret = EpollLoop(g_epollfd, -1);
#endif /* END OF DFINDER_USE_MINI_NSTACKX */
if (ret == NSTACKX_EFAILED) {
IncStatistics(STATS_EPOLL_ERROR);
DFINDER_LOGE(TAG, "epoll loop failed");
#ifndef DFINDER_USE_MINI_NSTACKX
DeRegisterCoAPEpollTask();
@ -463,7 +478,8 @@ void NSTACKX_Deinit(void)
CloseEpollDesc(g_epollfd);
g_epollfd = INVALID_EPOLL_DESC;
}
ResetStatistics();
ResetEventFunc();
g_nstackInitState = NSTACKX_INIT_STATE_START;
DFINDER_LOGI(TAG, "deinit successfully");
}
@ -511,6 +527,7 @@ static void DeviceDiscoverStopInner(void *argument)
{
(void)argument;
CoapServiceDiscoverStopInner();
NotifyStatisticsEvent();
}
int32_t NSTACKX_StartDeviceFind(void)
@ -1342,3 +1359,64 @@ int32_t NSTACKX_DFinderRegisterLog(DFinderLogCallback userLogCallback)
return ret;
}
#endif
#ifdef NSTACKX_DFINDER_HIDUMP
#define MAX_DUMP_ARGC 10
int NSTACKX_DFinderDump(const char **argv, uint32_t argc, void *softObj, DFinderDumpFunc dump)
{
if (g_nstackInitState != NSTACKX_INIT_STATE_DONE) {
DFINDER_LOGE(TAG, "NSTACKX_Ctrl is not initiated yet");
return NSTACKX_EFAILED;
}
if (dump == NULL) {
DFINDER_LOGE(TAG, "dump is null");
return NSTACKX_EINVAL;
}
if (argc == 0 || argc > MAX_DUMP_ARGC) {
DFINDER_LOGE(TAG, "argc is invalid %u", argc);
return NSTACKX_EINVAL;
}
if (argv == NULL) {
DFINDER_LOGE(TAG, "argv is null");
return NSTACKX_EINVAL;
}
uint32_t i;
for (i = 0; i < argc; i++) {
if (argv[i] == NULL) {
DFINDER_LOGE(TAG, "argv[%u] is null", i);
return NSTACKX_EINVAL;
}
}
return DFinderDump(argv, argc, softObj, dump);
}
#else
int NSTACKX_DFinderDump(const char **argv, uint32_t argc, void *softObj, DFinderDumpFunc dump)
{
(void)argv;
(void)argc;
(void)softObj;
(void)dump;
DFINDER_LOGE(TAG, "Unsupport dfinder dump");
return NSTACKX_NOTSUPPORT;
}
#endif
int NSTACKX_DFinderSetEventFunc(void *softobj, DFinderEventFunc func)
{
if (g_nstackInitState != NSTACKX_INIT_STATE_DONE) {
DFINDER_LOGE(TAG, "NSTACKX_Ctrl is not initiated yet");
return NSTACKX_EFAILED;
}
if (func == NULL) {
DFINDER_LOGE(TAG, "func is null");
return NSTACKX_EINVAL;
}
return SetEventFunc(softobj, func);
}

View File

@ -21,11 +21,22 @@
#include "nstackx_dfinder_log.h"
#include "nstackx_error.h"
#include "nstackx_statistics.h"
#define TAG "nStackXDFinder"
#define NSTACKX_USEDMAP_ROW_SIZE 32U /* Row size suit for uint32_t */
typedef struct {
uint8_t *blk;
uint32_t *usedMap;
uint32_t mapSize;
uint32_t useCount;
uint32_t maxCount;
size_t recSize;
RecCompareCallback cb;
} DatabaseInfo;
static inline int64_t GetRecordIndex(const DatabaseInfo *db, const void *rec)
{
if (db->recSize == 0) {
@ -120,7 +131,7 @@ void *DatabaseGetNextRecord(void *dbptr, int64_t *idx)
return NULL;
}
void *DatabaseAllocRecord(void *dbptr)
static void *DatabaseAllocRecordEx(void *dbptr)
{
DatabaseInfo *db = dbptr;
void *rec = NULL;
@ -156,7 +167,16 @@ void *DatabaseAllocRecord(void *dbptr)
return NULL;
}
void DatabaseFreeRecord(void *dbptr, const void *ptr)
void *DatabaseAllocRecord(void *dbptr)
{
void *record = DatabaseAllocRecordEx(dbptr);
if (record == NULL) {
IncStatistics(STATS_ALLOC_RECORD_FAILED);
}
return record;
}
static int32_t DatabaseFreeRecordEx(void *dbptr, const void *ptr)
{
DatabaseInfo *db = dbptr;
uint32_t i, off;
@ -164,21 +184,29 @@ void DatabaseFreeRecord(void *dbptr, const void *ptr)
if (dbptr == NULL || ptr == NULL || db->useCount == 0) {
DFINDER_LOGE(TAG, "Sanity chk failed");
return;
return -1;
}
recNum = GetRecordIndex(db, ptr);
if (recNum < 0 || recNum >= db->maxCount) {
DFINDER_LOGE(TAG, "Invalid record");
return;
return -1;
}
if (!IsRecordOccupied(db, (uint32_t)recNum, &i, &off)) {
DFINDER_LOGE(TAG, "Unused record");
return;
return -1;
}
db->usedMap[i] &= ~(1U << off);
db->useCount--;
return 0;
}
void DatabaseFreeRecord(void *dbptr, const void *ptr)
{
if (DatabaseFreeRecordEx(dbptr, ptr) != 0) {
IncStatistics(STATS_FREE_RECORD_FAILED);
}
}
void DatabaseClean(void *ptr)

View File

@ -41,6 +41,7 @@
#include "coap_app.h"
#include "coap_discover.h"
#include "json_payload.h"
#include "nstackx_statistics.h"
#define TAG "nStackXDFinder"
@ -731,6 +732,7 @@ static int32_t UpdateWhenDiscoverPassive(const DeviceInfo *deviceInfo, uint8_t i
internalDevice = CreateNewDevice(g_deviceList, deviceInfo);
#endif
if (internalDevice == NULL) {
IncStatistics(STATS_OVER_DEVICE_LIMIT);
return NSTACKX_ENOMEM;
}
updated = NSTACKX_TRUE;
@ -757,7 +759,7 @@ static int32_t UpdateWhenDiscoverPassive(const DeviceInfo *deviceInfo, uint8_t i
return NSTACKX_EOK;
}
int32_t UpdateDeviceDb(const DeviceInfo *deviceInfo, uint8_t forceUpdate)
static int32_t UpdateDeviceDbEx(const DeviceInfo *deviceInfo, uint8_t forceUpdate)
{
if (deviceInfo == NULL) {
return NSTACKX_EINVAL;
@ -776,6 +778,15 @@ int32_t UpdateDeviceDb(const DeviceInfo *deviceInfo, uint8_t forceUpdate)
}
return NSTACKX_EOK;
}
int32_t UpdateDeviceDb(const DeviceInfo *deviceInfo, uint8_t forceUpdate)
{
int32_t ret = UpdateDeviceDbEx(deviceInfo, forceUpdate);
if (ret != NSTACKX_EOK) {
IncStatistics(STATS_UPDATE_DEVICE_DB_FAILED);
}
return ret;
}
#else
int32_t DeviceInfoNotify(const DeviceInfo *deviceInfo, uint8_t forceUpdate)
{
@ -2195,7 +2206,7 @@ L_ERR_DEVICE_DB_BACKUP_LIST:
}
#ifdef DFINDER_SAVE_DEVICE_LIST
int32_t BackupDeviceDB(void)
static int32_t BackupDeviceDBEx(void)
{
void *db = g_deviceList;
void *backupDB = g_deviceListBackup;
@ -2229,6 +2240,15 @@ int32_t BackupDeviceDB(void)
return NSTACKX_EOK;
}
int32_t BackupDeviceDB(void)
{
int32_t ret = BackupDeviceDBEx();
if (ret != NSTACKX_EOK) {
IncStatistics(STATS_BACKUP_DEVICE_DB_FAILED);
}
return ret;
}
void *GetDeviceDB(void)
{
return g_deviceList;

View File

@ -0,0 +1,230 @@
/*
* Copyright (C) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "nstackx_dfinder_hidump.h"
#include <inttypes.h>
#include "nstackx_dfinder_log.h"
#include "nstackx_util.h"
#include "nstackx_getopt.h"
#include "nstackx_statistics.h"
#include "nstackx_common.h"
#include "nstackx_event.h"
#include "nstackx_error.h"
#include "securec.h"
#ifdef NSTACKX_DFINDER_HIDUMP
#define TAG "nStackXDFinder"
#define CRLF "\r\n"
#define DUMP_BUF_LEN (2048U)
#define DUMP_MSG_ADD_CHECK(ret, data, index, size, fmt, ...) do { \
ret = sprintf_s(data + index, size - index, fmt, ##__VA_ARGS__); \
if (ret < 0) { \
DFINDER_LOGE(TAG, "dumper buffer over %u bytes", size); \
return NSTACKX_EFAILED; \
} \
index += ret; \
} while (0)
typedef struct {
char *buf;
uint32_t size;
int err;
sem_t wait;
} DumpMsg;
static DumpMsg *CreateDumpMsg(char *buf, uint32_t size)
{
DumpMsg *msg = (DumpMsg *)malloc(sizeof(DumpMsg));
if (msg == NULL) {
return NULL;
}
if (SemInit(&(msg->wait), 0, 0)) {
free(msg);
return NULL;
}
msg->err = NSTACKX_EOK;
msg->buf = buf;
msg->size = size;
return msg;
}
static void DestroyDumpMsg(DumpMsg *msg)
{
SemDestroy(&(msg->wait));
free(msg);
}
static int PostDumpMsg(char *buf, uint32_t size, EventHandle handle)
{
int ret = NSTACKX_EFAILED;
DumpMsg *msg = CreateDumpMsg(buf, size);
if (msg == NULL) {
return ret;
}
if (PostEvent(GetEventNodeChain(), GetEpollFD(), handle, msg) != NSTACKX_EOK) {
DestroyDumpMsg(msg);
return ret;
}
SemWait(&(msg->wait));
ret = msg->err;
DestroyDumpMsg(msg);
return ret;
}
typedef int (*DumpFunc)(char *buf, uint32_t size);
static int Dump(void *softObj, DFinderDumpFunc dump, DumpFunc func)
{
char *buf = (char *)calloc(DUMP_BUF_LEN, sizeof(char));
if (buf == NULL) {
return NSTACKX_EFAILED;
}
if (func(buf, DUMP_BUF_LEN) != NSTACKX_EOK) {
free(buf);
return NSTACKX_EFAILED;
}
dump(softObj, buf, strlen(buf) + 1);
free(buf);
return NSTACKX_EOK;
}
static int DumpStatisticsInfo(char *buf, uint32_t size)
{
int ret;
uint32_t index = 0;
const uint64_t *stat = GetStatistics();
DUMP_MSG_ADD_CHECK(ret, buf, index, size, CRLF"DFinder statistics:"CRLF);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_INVALID_OPT_AND_PAYLOAD: %" PRIu64 CRLF,
stat[STATS_INVALID_OPT_AND_PAYLOAD]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_DECODE_FAILED: %" PRIu64 CRLF, stat[STATS_DECODE_FAILED]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_ENCODE_FAILED: %" PRIu64 CRLF, stat[STATS_ENCODE_FAILED]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_CREATE_HEADER_FAILED: %" PRIu64 CRLF,
stat[STATS_CREATE_HEADER_FAILED]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_BUILD_PKT_FAILED: %" PRIu64 CRLF, stat[STATS_BUILD_PKT_FAILED]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_SOCKET_ERROR: %" PRIu64 CRLF, stat[STATS_SOCKET_ERROR]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_EPOLL_ERROR: %" PRIu64 CRLF, stat[STATS_EPOLL_ERROR]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_CREATE_SERVER_FAILED: %" PRIu64 CRLF,
stat[STATS_CREATE_SERVER_FAILED]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_CREATE_CLIENT_FAILED: %" PRIu64 CRLF,
stat[STATS_CREATE_CLIENT_FAILED]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_DROP_LOOPBACK_PKT: %" PRIu64 CRLF, stat[STATS_DROP_LOOPBACK_PKT]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_SEND_MSG_FAILED: %" PRIu64 CRLF, stat[STATS_SEND_MSG_FAILED]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_SEND_REQUEST_FAILED: %" PRIu64 CRLF,
stat[STATS_SEND_REQUEST_FAILED]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_DROP_MSG_ID: %" PRIu64 CRLF, stat[STATS_DROP_MSG_ID]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_HANDLE_SERVICE_MSG_FAILED: %" PRIu64 CRLF,
stat[STATS_HANDLE_SERVICE_MSG_FAILED]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_HANDLE_DEVICE_DISCOVER_MSG_FAILED: %" PRIu64 CRLF,
stat[STATS_HANDLE_DEVICE_DISCOVER_MSG_FAILED]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_INVALID_RESPONSE_MSG: %" PRIu64 CRLF,
stat[STATS_INVALID_RESPONSE_MSG]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_POST_SD_REQUEST_FAILED: %" PRIu64 CRLF,
stat[STATS_POST_SD_REQUEST_FAILED]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_ABORT_SD: %" PRIu64 CRLF, stat[STATS_ABORT_SD]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_START_SD_FAILED: %" PRIu64 CRLF, stat[STATS_START_SD_FAILED]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_CREATE_SERVICE_MSG_FAILED: %" PRIu64 CRLF,
stat[STATS_CREATE_SERVICE_MSG_FAILED]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_SEND_SD_RESPONSE_FAILED: %" PRIu64 CRLF,
stat[STATS_SEND_SD_RESPONSE_FAILED]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_BACKUP_DEVICE_DB_FAILED: %" PRIu64 CRLF,
stat[STATS_BACKUP_DEVICE_DB_FAILED]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_UPDATE_DEVICE_DB_FAILED: %" PRIu64 CRLF,
stat[STATS_UPDATE_DEVICE_DB_FAILED]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_CREATE_CONTEX_FAILED: %" PRIu64 CRLF,
stat[STATS_CREATE_CONTEX_FAILED]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_CREATE_SESSION_FAILED: %" PRIu64 CRLF,
stat[STATS_CREATE_SESSION_FAILED]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_PREPARE_SD_MSG_FAILED: %" PRIu64 CRLF,
stat[STATS_PREPARE_SD_MSG_FAILED]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_PARSE_SD_MSG_FAILED: %" PRIu64 CRLF,
stat[STATS_PARSE_SD_MSG_FAILED]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_ALLOC_RECORD_FAILED: %" PRIu64 CRLF,
stat[STATS_ALLOC_RECORD_FAILED]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_FREE_RECORD_FAILED: %" PRIu64 CRLF,
stat[STATS_FREE_RECORD_FAILED]);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, "STATS_OVER_DEVICE_LIMIT: %" PRIu64 CRLF, stat[STATS_OVER_DEVICE_LIMIT]);
return NSTACKX_EOK;
}
static void DumpStatisticsInner(void *arg)
{
DumpMsg *msg = (DumpMsg *)arg;
msg->err = DumpStatisticsInfo(msg->buf, msg->size);
SemPost(&(msg->wait));
}
int DumpStatistics(char *buf, uint32_t size)
{
return PostDumpMsg(buf, size, DumpStatisticsInner);
}
static int DumpHelp(char *buf, uint32_t size)
{
int ret;
int index = 0;
DUMP_MSG_ADD_CHECK(ret, buf, index, size, CRLF"Usage: dfinder <opt>"CRLF);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, " -h show this help"CRLF);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, " -s show statistics info"CRLF);
DUMP_MSG_ADD_CHECK(ret, buf, index, size, " -m <0/1> enable control message log"CRLF);
return NSTACKX_EOK;
}
#define DFINDER_DUMP_STRTOL_BASE 10
static const char *g_dfinderDumpOpts = "hsm:";
int DFinderDump(const char **argv, uint32_t argc, void *softObj, DFinderDumpFunc dump)
{
int32_t opt;
NstackGetOptMsg optMsg;
int32_t ret = NstackInitGetOptMsg(&optMsg);
if (ret != NSTACKX_EOK) {
return ret;
}
while ((opt = NstackGetOpt(&optMsg, argc, argv, g_dfinderDumpOpts)) != NSTACK_GETOPT_END_OF_STR) {
switch (opt) {
case 'h':
ret = Dump(softObj, dump, DumpHelp);
break;
case 's':
ret = Dump(softObj, dump, DumpStatistics);
break;
case 'm':
#ifdef DFINDER_SET_CTRL_MSG_LOG
(void)SetMgtMsgLog((int32_t)strtol(NstackGetOptArgs(&optMsg), NULL, DFINDER_DUMP_STRTOL_BASE));
#endif
break;
default:
ret = NSTACKX_EFAILED;
DFINDER_LOGE(TAG, "Unknown option");
break;
}
if (ret != NSTACKX_EOK) {
break;
}
}
return ret;
}
#endif /* NSTACKX_DFINDER_HIDUMP */

View File

@ -0,0 +1,136 @@
/*
* Copyright (C) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "nstackx_dfinder_hievent.h"
#include "nstackx_dfinder_log.h"
#include "nstackx_statistics.h"
#include "nstackx_error.h"
#include "nstackx_common.h"
#include "nstackx_event.h"
#include "securec.h"
#define TAG "nStackXDFinder"
#define STAT_EVT_PARA_NUM 4
#define STAT_EVT_NAME "dfinderStatistics"
static void *g_softObj;
static DFinderEventFunc g_eventFunc;
static int g_statisticsIdx[STAT_EVT_PARA_NUM] = {
STATS_INVALID_OPT_AND_PAYLOAD,
STATS_BUILD_PKT_FAILED,
STATS_INVALID_RESPONSE_MSG,
STATS_OVER_DEVICE_LIMIT
};
static DFinderEventParam g_statisticsPara[STAT_EVT_PARA_NUM] = {
{
.type = DFINDER_PARAM_TYPE_UINT64,
.name = "invalidOptionCnt"
},
{
.type = DFINDER_PARAM_TYPE_UINT64,
.name = "buildPktFailCnt"
},
{
.type = DFINDER_PARAM_TYPE_UINT64,
.name = "invalidRspCnt"
},
{
.type = DFINDER_PARAM_TYPE_UINT64,
.name = "overDeviceLimitCnt"
}
};
static DFinderEventParam *CreateStatisticsEventParams(void)
{
int i;
const uint64_t *stat = GetStatistics();
DFinderEventParam *para = (DFinderEventParam *)calloc(STAT_EVT_PARA_NUM, sizeof(DFinderEventParam));
if (para == NULL) {
return NULL;
}
for (i = 0; i < STAT_EVT_PARA_NUM; i++) {
para[i] = g_statisticsPara[i];
para[i].value.u64v = stat[g_statisticsIdx[i]];
}
return para;
}
void NotifyStatisticsEvent(void)
{
int ret;
DFinderEvent evt;
if (g_eventFunc == NULL) {
return;
}
(void)memset_s(&evt, sizeof(evt), 0, sizeof(evt));
evt.type = DFINDER_EVENT_TYPE_STATISTIC;
evt.level = DFINDER_EVENT_LEVEL_MINOR;
evt.paramNum = STAT_EVT_PARA_NUM;
ret = memcpy_s(evt.eventName, DFINDER_EVENT_NAME_LEN, STAT_EVT_NAME, strlen(STAT_EVT_NAME));
if (ret != EOK) {
DFINDER_LOGE(TAG, "memcpy_s eventName failed.");
return;
}
evt.params = CreateStatisticsEventParams();
if (evt.params == NULL) {
DFINDER_LOGE(TAG, "SetStatisticsPara failed.");
return;
}
g_eventFunc(g_softObj, &evt);
free(evt.params);
DFINDER_LOGD(TAG, "report the dfinder statistics event.");
}
typedef struct {
void *softobj;
DFinderEventFunc func;
} DFinderEventMsg;
static void SetEventFuncInner(void *arg)
{
DFinderEventMsg *msg = (DFinderEventMsg *)arg;
g_softObj = msg->softobj;
g_eventFunc = msg->func;
free(msg);
}
int SetEventFunc(void *softobj, DFinderEventFunc func)
{
DFinderEventMsg *msg = (DFinderEventMsg *)malloc(sizeof(DFinderEventMsg));
if (msg == NULL) {
return NSTACKX_EFAILED;
}
msg->softobj = softobj;
msg->func = func;
if (PostEvent(GetEventNodeChain(), GetEpollFD(), SetEventFuncInner, msg) != NSTACKX_EOK) {
free(msg);
return NSTACKX_EFAILED;
}
return NSTACKX_EOK;
}
void ResetEventFunc(void)
{
g_softObj = NULL;
g_eventFunc = NULL;
}

View File

@ -33,6 +33,7 @@
#include "nstackx_device.h"
#include "nstackx_timer.h"
#include "coap_discover/coap_discover.h"
#include "nstackx_statistics.h"
#define TAG "nStackXDFinder"
#ifdef SUPPORT_SMARTGENIUS
@ -123,6 +124,7 @@ static void SmartGeniusCallback(void *arg)
socklen = sizeof(struct sockaddr_nl);
len = recvfrom(task->taskfd, innerBuf, BUFLEN, 0, (struct sockaddr *)&peer, &socklen);
if (len <= 0) {
IncStatistics(STATS_SOCKET_ERROR);
DFINDER_LOGE(TAG, "recvfrom error %d", errno);
return;
}

View File

@ -0,0 +1,34 @@
/*
* Copyright (C) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "nstackx_statistics.h"
#include <securec.h>
static uint64_t g_statistics[STATS_MAX];
void ResetStatistics(void)
{
(void)memset_s(&g_statistics[0], sizeof(g_statistics), 0, sizeof(g_statistics));
}
void IncStatistics(StatisticsType type)
{
g_statistics[type]++;
}
const uint64_t *GetStatistics(void)
{
return &g_statistics[0];
}

View File

@ -68,7 +68,6 @@ void CoapDiscoverDeinit(void);
#ifdef DFINDER_SUPPORT_MULTI_NIF
void CoapInitResourcesWithIdx(coap_context_t *ctx, uint32_t idx, const char *networkName);
void CoapDestroyCtxWithIdx(uint32_t ctxIdx);
coap_context_t *GetContextWithIdx(uint8_t serverType, uint32_t idx);
#else
void CoapDestroyCtx(uint8_t serverType);
#endif

View File

@ -43,6 +43,8 @@ List *GetMainLoopEvendChain(void);
uint32_t GetDefaultDiscoverInterval(uint32_t discoverCount);
int32_t CheckBusinessTypeReplyUnicast(uint8_t businessType);
int32_t GetServiceDiscoverInfo(const uint8_t *buf, size_t size, struct DeviceInfo *deviceInfo, char **remoteUrlPtr);
List *GetEventNodeChain(void);
EpollDesc GetEpollFD(void);
#ifdef __cplusplus
};

View File

@ -24,16 +24,6 @@ extern "C" {
typedef uint8_t (*RecCompareCallback)(void *, void *);
typedef struct {
uint8_t *blk;
uint32_t *usedMap;
uint32_t mapSize;
uint32_t useCount;
uint32_t maxCount;
size_t recSize;
RecCompareCallback cb;
} DatabaseInfo;
void *DatabaseInit(uint32_t recnum, size_t recsz, RecCompareCallback cb);
void DatabaseClean(void *ptr);
uint32_t GetDatabaseUseCount(const void *dbptr);

View File

@ -0,0 +1,24 @@
/*
* Copyright (C) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NSTACKX_DFINDER_HIDUMP_H
#define NSTACKX_DFINDER_HIDUMP_H
#include "nstackx.h"
#ifdef NSTACKX_DFINDER_HIDUMP
int DFinderDump(const char **argv, uint32_t argc, void *softObj, DFinderDumpFunc dump);
#endif
#endif

View File

@ -0,0 +1,24 @@
/*
* Copyright (C) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NSTACKX_DFINDER_HIEVENT_H
#define NSTACKX_DFINDER_HIEVENT_H
#include "nstackx.h"
int SetEventFunc(void *softobj, DFinderEventFunc func);
void ResetEventFunc(void);
void NotifyStatisticsEvent(void);
#endif

View File

@ -0,0 +1,57 @@
/*
* Copyright (C) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NSTACKX_STATISTICS_H
#define NSTACKX_STATISTICS_H
#include <stdint.h>
typedef enum {
STATS_INVALID_OPT_AND_PAYLOAD,
STATS_DECODE_FAILED,
STATS_ENCODE_FAILED,
STATS_CREATE_HEADER_FAILED,
STATS_BUILD_PKT_FAILED,
STATS_SOCKET_ERROR,
STATS_EPOLL_ERROR,
STATS_CREATE_SERVER_FAILED,
STATS_CREATE_CLIENT_FAILED,
STATS_DROP_LOOPBACK_PKT,
STATS_SEND_MSG_FAILED,
STATS_SEND_REQUEST_FAILED,
STATS_DROP_MSG_ID,
STATS_HANDLE_SERVICE_MSG_FAILED,
STATS_HANDLE_DEVICE_DISCOVER_MSG_FAILED,
STATS_INVALID_RESPONSE_MSG,
STATS_POST_SD_REQUEST_FAILED,
STATS_ABORT_SD,
STATS_START_SD_FAILED,
STATS_CREATE_SERVICE_MSG_FAILED,
STATS_SEND_SD_RESPONSE_FAILED,
STATS_BACKUP_DEVICE_DB_FAILED,
STATS_UPDATE_DEVICE_DB_FAILED,
STATS_CREATE_CONTEX_FAILED,
STATS_CREATE_SESSION_FAILED,
STATS_PREPARE_SD_MSG_FAILED,
STATS_PARSE_SD_MSG_FAILED,
STATS_ALLOC_RECORD_FAILED,
STATS_FREE_RECORD_FAILED,
STATS_OVER_DEVICE_LIMIT,
STATS_MAX
} StatisticsType;
void ResetStatistics(void);
void IncStatistics(StatisticsType type);
const uint64_t *GetStatistics(void);
#endif

View File

@ -17,6 +17,7 @@
#define NSTACKX_H
#include <stdint.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
@ -193,6 +194,66 @@ enum {
DFINDER_LOG_LEVEL_END,
};
typedef enum {
DFINDER_EVENT_TYPE_FAULT,
DFINDER_EVENT_TYPE_STATISTIC,
DFINDER_EVENT_TYPE_SECURITY,
DFINDER_EVENT_TYPE_BEHAVIOR,
} DFinderEventType;
typedef enum {
DFINDER_EVENT_LEVEL_CRITICAL,
DFINDER_EVENT_LEVEL_MINOR,
} DFinderEventLevel;
typedef enum {
DFINDER_PARAM_TYPE_BOOL,
DFINDER_PARAM_TYPE_UINT8,
DFINDER_PARAM_TYPE_UINT16,
DFINDER_PARAM_TYPE_INT32,
DFINDER_PARAM_TYPE_UINT32,
DFINDER_PARAM_TYPE_UINT64,
DFINDER_PARAM_TYPE_FLOAT,
DFINDER_PARAM_TYPE_DOUBLE,
DFINDER_PARAM_TYPE_STRING,
} DFinderEventParamType;
#define DFINDER_EVENT_NAME_LEN 32
#define DFINDER_EVENT_TAG_LEN 16
typedef struct {
DFinderEventParamType type;
char name[DFINDER_EVENT_NAME_LEN];
union {
bool b;
uint8_t u8v;
uint16_t u16v;
int32_t i32v;
uint32_t u32v;
uint64_t u64v;
float f;
double d;
char str[DFINDER_EVENT_NAME_LEN];
} value;
} DFinderEventParam;
typedef struct {
char eventName[DFINDER_EVENT_NAME_LEN];
DFinderEventType type;
DFinderEventLevel level;
char tag[DFINDER_EVENT_TAG_LEN];
char desc[DFINDER_EVENT_NAME_LEN];
DFinderEventParam *params;
uint32_t paramNum;
} DFinderEvent;
typedef void (*DFinderEventFunc)(void *softObj, const DFinderEvent *info);
DFINDER_EXPORT int NSTACKX_DFinderSetEventFunc(void *softobj, DFinderEventFunc func);
typedef void (*DFinderDumpFunc)(void *softObj, const char *data, uint32_t len);
DFINDER_EXPORT int NSTACKX_DFinderDump(const char **argv, uint32_t argc, void *softObj, DFinderDumpFunc dump);
/*
* NSTACKX Initialization
* return 0 on success, negative value on failure

View File

@ -65,6 +65,7 @@ if (defined(ohos_lite)) {
]
sources += [
"core/nstackx_getopt.c",
"platform/liteos/sys_epoll.c",
"platform/liteos/sys_event.c",
"platform/liteos/sys_log.c",
@ -97,6 +98,7 @@ if (defined(ohos_lite)) {
sources = [
"core/nstackx_dev.c",
"core/nstackx_event.c",
"core/nstackx_getopt.c",
"core/nstackx_log.c",
"core/nstackx_mbedtls.c",
"core/nstackx_socket.c",
@ -132,6 +134,7 @@ if (defined(ohos_lite)) {
sources = [
"core/nstackx_dev.c",
"core/nstackx_event.c",
"core/nstackx_getopt.c",
"core/nstackx_log.c",
"core/nstackx_mbedtls.c",
"core/nstackx_socket.c",
@ -183,13 +186,14 @@ if (defined(ohos_lite)) {
"interface",
"platform/unix",
"$NSTACKX_ROOT/nstackx_core/",
"//utils/native/base/include/",
"//commonlibrary/c_utils/base/include/",
"//third_party/bounds_checking_function/include",
"//base/hiviewdfx/hilog/interfaces/native/innerkits/",
]
sources = [
"core/nstackx_dev.c",
"core/nstackx_event.c",
"core/nstackx_getopt.c",
"core/nstackx_log.c",
"core/nstackx_mbedtls.c",
"core/nstackx_socket.c",

View File

@ -0,0 +1,135 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "nstackx_getopt.h"
#include "nstackx_error.h"
#include "nstackx_log.h"
#include "nstackx_util.h"
#define TAG "nStackXGetOpt"
#define NSTACK_GETOPT_MAX_ARGC 100
int32_t NstackInitGetOptMsg(NstackGetOptMsg *optMsg)
{
if (optMsg == NULL) {
LOGE(TAG, "optMsg is NULL");
return NSTACKX_EFAILED;
}
optMsg->argvIdx = 1;
optMsg->argvOffset = 1;
optMsg->attachArg = NULL;
return NSTACKX_EOK;
}
static int32_t GetOptCheckInputArg(NstackGetOptMsg *optMsg, int argc, const char *const *argv)
{
if (optMsg->argvIdx >= argc || argv[optMsg->argvIdx][0] != '-' || argv[optMsg->argvIdx][1] == '\0') {
return NSTACKX_EFAILED;
} else if (!strcmp(argv[optMsg->argvIdx], "--")) {
optMsg->argvIdx++;
return NSTACKX_EFAILED;
}
return NSTACKX_EOK;
}
static int32_t GetOptCheckCurrentOpt(NstackGetOptMsg *optMsg, int32_t currentOpt,
char *currentOptIdxInOpts, char nextChar)
{
if (currentOpt == ':' || currentOptIdxInOpts == NULL) {
LOGE(TAG, ": illegal option -- %c", currentOpt);
optMsg->argvOffset++;
if (nextChar == '\0') {
optMsg->argvIdx++;
optMsg->argvOffset = 1;
}
return NSTACKX_EFAILED;
}
return NSTACKX_EOK;
}
static int32_t GetOptParseAttachArg(NstackGetOptMsg *optMsg, int32_t argc, const char *const *argv,
char currentOpt, const char *currentOptIdxInOpts)
{
if (*(currentOptIdxInOpts + 1) == ':') {
if (argv[optMsg->argvIdx][optMsg->argvOffset + 1] != '\0') {
optMsg->attachArg = &argv[optMsg->argvIdx++][optMsg->argvOffset + 1];
} else if (++optMsg->argvIdx >= argc) {
LOGE(TAG, ": option requires an argument -- %c", currentOpt);
optMsg->argvOffset = 1;
return NSTACKX_EFAILED;
} else {
optMsg->attachArg = argv[optMsg->argvIdx++];
}
optMsg->argvOffset = 1;
} else {
if (argv[optMsg->argvIdx][++(optMsg->argvOffset)] == '\0') {
optMsg->argvOffset = 1;
optMsg->argvIdx++;
}
optMsg->attachArg = NULL;
}
return NSTACKX_EOK;
}
static int32_t NstackCheckArg(int32_t argc, const char *const *argv)
{
if (argc == 0 || argc > NSTACK_GETOPT_MAX_ARGC) {
LOGE(TAG, "argc is invalid %u", argc);
return NSTACKX_EFAILED;
}
if (argv == NULL) {
LOGE(TAG, "argv is NULL");
return NSTACKX_EFAILED;
}
int32_t i;
for (i = 0; i < argc; i++) {
if (argv[i] == NULL) {
LOGE(TAG, "argv[%d] is NULL", i);
return NSTACKX_EFAILED;
}
}
return NSTACKX_EOK;
}
int32_t NstackGetOpt(NstackGetOptMsg *optMsg, int32_t argc, const char *const *argv, const char *opts)
{
if (NstackCheckArg(argc, argv) != NSTACKX_EOK) {
return NSTACK_GETOPT_END_OF_STR;
}
int32_t currentOpt;
if (optMsg->argvOffset == 1 && GetOptCheckInputArg(optMsg, argc, argv) != NSTACKX_EOK) {
return NSTACK_GETOPT_END_OF_STR;
}
currentOpt = argv[optMsg->argvIdx][optMsg->argvOffset];
char *currentOptIdxInOpts = strchr(opts, currentOpt);
if (GetOptCheckCurrentOpt(optMsg, currentOpt, currentOptIdxInOpts,
argv[optMsg->argvIdx][optMsg->argvOffset + 1]) != NSTACKX_EOK) {
return NSTACK_GETOPT_UNKNOW_OPT;
}
if (GetOptParseAttachArg(optMsg, argc, argv, currentOpt, currentOptIdxInOpts) != NSTACKX_EOK) {
return NSTACK_GETOPT_UNKNOW_OPT;
}
return currentOpt;
}
const char *NstackGetOptArgs(NstackGetOptMsg *optMsg)
{
if (optMsg == NULL) {
LOGE(TAG, "optMsg is NULL");
return NULL;
}
return optMsg->attachArg;
}

View File

@ -25,7 +25,7 @@ static uint32_t g_logLevel = NSTACKX_LOG_LEVEL_INFO;
#ifdef BUILD_FOR_WINDOWS
static void DefaultLogImpl(const char *tag, uint32_t level, const char *format, va_list args)
{
SYSTEMTIME st = { 0 };
SYSTEMTIME st = {0};
GetLocalTime(&st);
printf("%02d-%02d %02d:%02d:%02d.%03d %d %d %d %s: ", st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond,

View File

@ -0,0 +1,41 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NSTACKX_GETOPT_H
#define NSTACKX_GETOPT_H
#include "sys_common_header.h"
#ifdef __cplusplus
extern "C" {
#endif
#define NSTACK_GETOPT_END_OF_STR (-1)
#define NSTACK_GETOPT_UNKNOW_OPT '?'
typedef struct {
int32_t argvIdx;
int32_t argvOffset;
const char *attachArg;
} NstackGetOptMsg;
NSTACKX_EXPORT int32_t NstackInitGetOptMsg(NstackGetOptMsg *optMsg);
NSTACKX_EXPORT int32_t NstackGetOpt(NstackGetOptMsg *optMsg, int32_t argc, const char *const *argv, const char *opts);
NSTACKX_EXPORT const char *NstackGetOptArgs(NstackGetOptMsg *optMsg);
#ifdef __cplusplus
}
#endif
#endif /* NSTACKX_GETOPT_H */

View File

@ -1153,15 +1153,13 @@ static void OnAuthGroupChanged(const char *groupInfo, bool create)
return;
}
cJSON_Delete(msg);
if (groupType == IDENTICAL_ACCOUNT_GROUP) {
SoftBusLog(SOFTBUS_LOG_AUTH, SOFTBUS_LOG_INFO, "auth group account change %d, groupType = %d",
create, groupType);
for (uint32_t monitor = LNN; monitor < VERIFY_MODULE_NUM; ++monitor) {
if (create && g_verifyCallback[monitor].onGroupCreated != NULL) {
g_verifyCallback[monitor].onGroupCreated(groupId);
} else if (!create && g_verifyCallback[monitor].onGroupDeleted != NULL) {
g_verifyCallback[monitor].onGroupDeleted(groupId);
}
SoftBusLog(SOFTBUS_LOG_AUTH, SOFTBUS_LOG_INFO, "auth group account change %d, groupType = %d",
create, groupType);
for (uint32_t monitor = LNN; monitor < VERIFY_MODULE_NUM; ++monitor) {
if (create && g_verifyCallback[monitor].onGroupCreated != NULL) {
g_verifyCallback[monitor].onGroupCreated(groupId);
} else if (!create && g_verifyCallback[monitor].onGroupDeleted != NULL) {
g_verifyCallback[monitor].onGroupDeleted(groupId);
}
}
}

View File

@ -68,6 +68,7 @@ int32_t LnnGetNodeKeyInfo(const char *networkId, int key, uint8_t *info, uint32_
int32_t LnnGetNodeKeyInfoLen(int32_t key);
int32_t LnnGetNetworkIdByUuid(const char *uuid, char *buf, uint32_t len);
bool LnnIsMasterNode(void);
void SoftBusDumpBusCenterPrintInfo(int fd, NodeBasicInfo *nodeInfo);
int32_t LnnServerJoin(ConnectionAddr *addr);
int32_t LnnServerLeave(const char *networkId);

View File

@ -48,6 +48,9 @@ int32_t LnnIpcNotifyOnlineState(bool isOnline, void *info, uint32_t infoTypeLen)
int32_t LnnIpcNotifyBasicInfoChanged(void *info, uint32_t infoTypeLen, int32_t type);
int32_t LnnIpcNotifyTimeSyncResult(const char *pkgName, const void *info, uint32_t infoTypeLen, int32_t retCode);
int32_t LnnIpcShiftLNNGear(const char *pkgName, const char *callerId, const char *targetNetworkId,
const GearMode *mode);
void BusCenterServerDeathCallback(const char *pkgName);
#ifdef __cplusplus

View File

@ -21,6 +21,7 @@
#include "bus_center_manager.h"
#include "client_bus_center_manager.h"
#include "lnn_distributed_net_ledger.h"
#include "lnn_heartbeat_strategy.h"
#include "lnn_ipc_utils.h"
#include "lnn_meta_node_ledger.h"
#include "lnn_time_sync_manager.h"
@ -161,6 +162,11 @@ int32_t LnnIpcGetAllMetaNodeInfo(MetaNodeInfo *infos, int32_t *infoNum)
return LnnGetAllMetaNodeInfo(infos, infoNum);
}
int32_t LnnIpcShiftLNNGear(const char *pkgName, const char *callerId, const char *targetNetworkId, const GearMode *mode)
{
return LnnShiftLNNGear(pkgName, callerId, targetNetworkId, mode);
}
int32_t LnnIpcNotifyJoinResult(void *addr, uint32_t addrTypeLen, const char *networkId, int32_t retCode)
{
(void)addrTypeLen;

View File

@ -23,6 +23,7 @@
#include "bus_center_manager.h"
#include "lnn_connection_addr_utils.h"
#include "lnn_distributed_net_ledger.h"
#include "lnn_heartbeat_strategy.h"
#include "lnn_ipc_utils.h"
#include "lnn_meta_node_ledger.h"
#include "lnn_time_sync_manager.h"
@ -356,6 +357,11 @@ int32_t LnnIpcGetAllMetaNodeInfo(MetaNodeInfo *infos, int32_t *infoNum)
return LnnGetAllMetaNodeInfo(infos, infoNum);
}
int32_t LnnIpcShiftLNNGear(const char *pkgName, const char *callerId, const char *targetNetworkId, const GearMode *mode)
{
return LnnShiftLNNGear(pkgName, callerId, targetNetworkId, mode);
}
int32_t LnnIpcNotifyJoinResult(void *addr, uint32_t addrTypeLen, const char *networkId, int32_t retCode)
{
if (addr == NULL) {

View File

@ -24,6 +24,7 @@
#include "bus_center_manager.h"
#include "lnn_connection_addr_utils.h"
#include "lnn_distributed_net_ledger.h"
#include "lnn_heartbeat_strategy.h"
#include "lnn_ipc_utils.h"
#include "lnn_meta_node_ledger.h"
#include "lnn_time_sync_manager.h"
@ -265,6 +266,11 @@ int32_t LnnIpcGetAllMetaNodeInfo(MetaNodeInfo *infos, int32_t *infoNum)
return LnnGetAllMetaNodeInfo(infos, infoNum);
}
int32_t LnnIpcShiftLNNGear(const char *pkgName, const char *callerId, const char *targetNetworkId, const GearMode *mode)
{
return LnnShiftLNNGear(pkgName, callerId, targetNetworkId, mode);
}
int32_t LnnIpcNotifyJoinResult(void *addr, uint32_t addrTypeLen, const char *networkId, int32_t retCode)
{
if (addr == nullptr) {

View File

@ -16,7 +16,7 @@
#ifndef LNN_HEARTBEAT_FSM_H
#define LNN_HEARTBEAT_FSM_H
#include "softbus_common.h"
#include "lnn_heartbeat_manager.h"
#ifdef __cplusplus
extern "C" {

View File

@ -16,7 +16,6 @@
#ifndef LNN_HEARTBEAT_MANAGER_H
#define LNN_HEARTBEAT_MANAGER_H
#include "softbus_common.h"
#include "lnn_node_info.h"
#ifdef __cplusplus

View File

@ -17,8 +17,9 @@
#define LNN_HEARTBEAT_STRATEGY_H
#include <stdbool.h>
#include "softbus_common.h"
#include "lnn_heartbeat_manager.h"
#include "softbus_common.h"
#ifdef __cplusplus
extern "C" {
@ -30,27 +31,6 @@ extern "C" {
#define HB_CHECK_DELAY_LEN (10 * HB_TIME_FACTOR + HB_ONE_CYCLE_LEN)
#define HB_ENABLE_DELAY_LEN (20 * HB_TIME_FACTOR)
#define HB_UPDATE_INTERVAL_LEN (HB_ENABLE_DELAY_LEN - HB_ONE_CYCLE_LEN)
typedef enum {
/**< Heartbeat cycle ( in sec ). */
HIGH_FREQ_CYCLE = 30,
MID_FREQ_CYCLE = 60,
LOW_FREQ_CYCLE = 5 * 60,
} ModeCycle;
typedef enum {
/**< Heartbeat keep alive duration ( in sec ). */
DEFAULT_DURATION = 60,
NORMAL_DURATION = 10 * 60,
LONG_DURATION = 30 * 60,
} ModeDuration;
typedef struct {
ModeCycle modeCycle;
ModeDuration modeDuration;
bool wakeupFlag;
} GearMode;
typedef struct {
LnnHeartbeatImplType type;
union {
@ -67,12 +47,10 @@ typedef struct {
HeartbeatImplPolicy *implPolicy;
} HeartbeatPolicy;
int32_t ShiftLNNGear(const char *pkgName, int32_t callingUid, const char *targetNetworkId,
GearMode mode, const HeartbeatImplPolicy *implPolicy);
int32_t LnnGetHeartbeatGearMode(GearMode *mode);
int32_t LnnGetHeartbeatImplPolicy(LnnHeartbeatImplType type, HeartbeatImplPolicy *implPolicy);
int32_t LnnOfflineTimingByHeartbeat(const char *networkId, ConnectionAddrType addrType);
int32_t LnnShiftLNNGear(const char *pkgName, const char *callerId, const char *targetNetworkId, const GearMode *mode);
int32_t LnnStartHeartbeatDelay(void);
void LnnStopHeartbeatNow(void);

View File

@ -369,7 +369,7 @@ static int32_t OnTryAsMasterNode(const SoftBusMessage *msg)
if (LnnGetHeartbeatGearMode(&gearMode) != SOFTBUS_OK) {
return SOFTBUS_ERR;
}
uint64_t delayMillis = (uint64_t)gearMode.modeCycle * HB_TIME_FACTOR + HB_ENABLE_DELAY_LEN;
uint64_t delayMillis = (uint64_t)gearMode.cycle * HB_TIME_FACTOR + HB_ENABLE_DELAY_LEN;
if (LnnPostDelayMsgToHbFsm(EVENT_HB_AS_MASTER_NODE, NULL, delayMillis) != SOFTBUS_OK) {
return SOFTBUS_ERR;
}
@ -429,7 +429,7 @@ static int32_t OnRepeatCycle(const SoftBusMessage *msg)
if (LnnGetHeartbeatGearMode(&gearMode) != SOFTBUS_OK) {
return SOFTBUS_ERR;
}
uint64_t delayMillis = (uint64_t)gearMode.modeCycle * HB_TIME_FACTOR;
uint64_t delayMillis = (uint64_t)gearMode.cycle * HB_TIME_FACTOR;
if (LnnPostDelayMsgToHbFsm(EVENT_HB_REPEAT_CYCLE, NULL, delayMillis) != SOFTBUS_OK) {
return SOFTBUS_ERR;
}
@ -666,7 +666,7 @@ static int32_t OnCheckDeviceStatus(const SoftBusMessage *msg)
SoftBusFree(info);
return SOFTBUS_ERR;
}
offlineMillis = (uint64_t)gearMode.modeCycle * HB_TIME_FACTOR;
offlineMillis = (uint64_t)gearMode.cycle * HB_TIME_FACTOR;
nowTime = (uint64_t)times.sec * HB_TIME_FACTOR + (uint64_t)times.usec / HB_TIME_FACTOR;
for (i = 0; i < infoNum; i++) {
NodeInfo *nodeInfo = LnnGetNodeInfoById(info[i].networkId, CATEGORY_NETWORK_ID);

View File

@ -48,8 +48,8 @@ static int32_t HbMonitorInit(void)
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "HB monitor init mutex fail!");
return SOFTBUS_ERR;
}
g_strategy.gearMode.modeCycle = LOW_FREQ_CYCLE;
g_strategy.gearMode.modeDuration = LONG_DURATION;
g_strategy.gearMode.cycle = LOW_FREQ_CYCLE;
g_strategy.gearMode.duration = LONG_DURATION;
g_strategy.gearMode.wakeupFlag = false;
g_strategy.callingUid = HB_INVALID_UID;
return SOFTBUS_OK;
@ -67,56 +67,13 @@ static void HbMonitorDeinit(void)
SoftBusMutexDestroy(&g_strategy.lock);
}
static int32_t ResetHeartbeatParam(int32_t callingUid, GearMode mode, const HeartbeatImplPolicy *implPolicy)
int32_t LnnShiftLNNGear(const char *pkgName, const char *callerId, const char *targetNetworkId, const GearMode *mode)
{
if (SoftBusMutexLock(&g_strategy.lock) != 0) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "HB reset param lock mutex fail!");
return SOFTBUS_ERR;
}
if (g_strategy.callingUid == HB_INVALID_UID || g_strategy.callingUid == callingUid) {
g_strategy.gearMode = mode;
} else {
if (g_strategy.gearMode.modeCycle <= mode.modeCycle) {
g_strategy.gearMode.modeCycle = mode.modeCycle;
}
if (g_strategy.gearMode.modeDuration >= mode.modeDuration) {
g_strategy.gearMode.modeDuration = mode.modeDuration;
}
}
if (implPolicy != NULL) {
HeartbeatImplPolicy *tmpImplPolicy = (HeartbeatImplPolicy *)SoftBusCalloc(sizeof(HeartbeatImplPolicy));
if (tmpImplPolicy == NULL) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "HB calloc tmpImplPolicy err");
(void)SoftBusMutexUnlock(&g_strategy.lock);
return SOFTBUS_MALLOC_ERR;
}
tmpImplPolicy->type = implPolicy->type;
tmpImplPolicy->info = implPolicy->info;
g_strategy.policy[implPolicy->type].implPolicy = tmpImplPolicy;
tmpImplPolicy = NULL;
}
(void)SoftBusMutexUnlock(&g_strategy.lock);
return SOFTBUS_OK;
}
int32_t ShiftLNNGear(const char *pkgName, int32_t callingUid, const char *targetNetworkId, GearMode mode,
const HeartbeatImplPolicy *implPolicy)
{
if (pkgName == NULL || callingUid <= HB_INVALID_UID) {
if (pkgName == NULL || mode == NULL || callerId == NULL) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "HB shift gear get invalid param");
return SOFTBUS_INVALID_PARAM;
}
if (targetNetworkId != NULL && !LnnGetOnlineStateById(targetNetworkId, CATEGORY_NETWORK_ID)) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_WARN, "HB target networkId:%s is offline",
AnonymizesNetworkID(targetNetworkId));
return SOFTBUS_NETWORK_NODE_OFFLINE;
}
if (ResetHeartbeatParam(callingUid, mode, implPolicy) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "HB reset gearMode param fail");
return SOFTBUS_ERR;
}
(void)targetNetworkId;
return SOFTBUS_OK;
}
@ -166,7 +123,7 @@ int32_t LnnOfflineTimingByHeartbeat(const char *networkId, ConnectionAddrType ad
if (LnnGetHeartbeatGearMode(&gearMode) != SOFTBUS_OK) {
return SOFTBUS_ERR;
}
delayMillis = (uint64_t)gearMode.modeCycle * HB_TIME_FACTOR + HB_ENABLE_DELAY_LEN;
delayMillis = (uint64_t)gearMode.cycle * HB_TIME_FACTOR + HB_ENABLE_DELAY_LEN;
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_DBG, "heartbeat(HB) start offline countdown");
if (LnnHbProcessDeviceLost(networkId, addrType, delayMillis) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "HB process dev lost err");
@ -191,6 +148,14 @@ static void LnnHeartbeatMasterNodeChangeEventHandler(const LnnEventBasicInfo *in
}
}
static void LnnHeartbeatScreenStateChangeEventHandler(const LnnEventBasicInfo *info)
{
if (info == NULL || info->event != LNN_EVENT_SCREEN_STATE_CHANGED) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "HB screen state event handler get invalid param");
return;
}
}
static void HbOnGroupChanged(void)
{
int32_t ret = LnnPostMsgToHbFsm(EVENT_HB_UPDATE_DEVICE_INFO, NULL);
@ -216,8 +181,6 @@ static VerifyCallback g_verifyCb = {
int32_t LnnStartHeartbeatDelay(void)
{
uint64_t delayMillis;
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "heartbeat(HB) process start.");
if (LnnRemoveHbFsmMsg(EVENT_HB_START, 0, NULL) != SOFTBUS_OK) {
return SOFTBUS_ERR;
@ -228,10 +191,6 @@ int32_t LnnStartHeartbeatDelay(void)
if (LnnHbFsmStart(STATE_HB_MASTER_NODE_INDEX, 0) != SOFTBUS_OK) {
return SOFTBUS_ERR;
}
delayMillis = (uint64_t)g_strategy.gearMode.modeDuration * HB_TIME_FACTOR;
if (LnnHbFsmStop(delayMillis) != SOFTBUS_OK) {
return SOFTBUS_ERR;
}
AuthRegCallback(HEARTBEAT_MONITOR, &g_verifyCb);
return SOFTBUS_OK;
@ -257,9 +216,14 @@ int32_t LnnInitHeartbeat(void)
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "HB monitor init fail!");
return SOFTBUS_ERR;
}
if (LnnRegisterEventHandler(LNN_EVENT_SCREEN_STATE_CHANGED, LnnHeartbeatScreenStateChangeEventHandler) !=
SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "HB monitor regist screen state event fail!");
return SOFTBUS_ERR;
}
if (LnnRegisterEventHandler(LNN_EVENT_NODE_MASTER_STATE_CHANGED, LnnHeartbeatMasterNodeChangeEventHandler) !=
SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "HB monitor regist event fail!");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "HB monitor regist node master event fail!");
return SOFTBUS_ERR;
}
AuthRegCallback(HEARTBEAT_MONITOR, &g_verifyCb);

View File

@ -18,14 +18,12 @@
#include "softbus_errcode.h"
#include "softbus_log.h"
int32_t ShiftLNNGear(const char *pkgName, int32_t callingUid, const char *targetNetworkId,
GearMode mode, const HeartbeatImplPolicy *implPolicy)
int32_t LnnShiftLNNGear(const char *pkgName, const char *callerId, const char *targetNetworkId, const GearMode *mode)
{
(void)pkgName;
(void)callingUid;
(void)callerId;
(void)targetNetworkId;
(void)mode;
(void)implPolicy;
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "heartbeat stub ShiftLNNGear");
return SOFTBUS_NOT_IMPLEMENT;
}

View File

@ -183,7 +183,7 @@ static ProtocolType LnnLaneSelectProtocol(LnnNetIfType ifType, const char *netWo
(void)LnnVisitPhysicalSubnet(FindBestProtocol, &req);
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "LnnLaneSelectProtocol protocol = %lld", req.selectedProtocol);
return req.selectedProtocol;
return LNN_PROTOCOL_IP;
}
static void FillWlanLinkInfo(

View File

@ -20,6 +20,7 @@
#include "lnn_node_info.h"
#include "lnn_state_machine.h"
#include "softbus_bus_center.h"
#include "softbus_hisysevt_bus_center.h"
#ifndef LNN_CONNECTION_FSM_H
#define LNN_CONNECTION_FSM_H
@ -77,6 +78,7 @@ typedef struct tagLnnConnectionFsm {
LnnConntionInfo connInfo;
LnnConnectionFsmStopCallback stopCallback;
bool isDead;
LnnStatisticData statisticData;
} LnnConnectionFsm;
typedef struct {
@ -102,6 +104,7 @@ int32_t LnnSendDisconnectMsgToConnFsm(LnnConnectionFsm *connFsm);
int32_t LnnSendLeaveRequestToConnFsm(LnnConnectionFsm *connFsm);
int32_t LnnSendSyncOfflineFinishToConnFsm(LnnConnectionFsm *connFsm);
int32_t LnnSendNewNetworkOnlineToConnFsm(LnnConnectionFsm *connFsm);
int64_t LnnUpTimeMs(void);
#ifdef __cplusplus
#if __cplusplus

View File

@ -27,7 +27,8 @@ if (dsoftbus_feature_lnn_net) {
bus_center_builder_src = [ "$dsoftbus_root_path/core/bus_center/lnn/net_builder/src/lnn_net_builder_virtual.c" ]
}
bus_center_builder_inc = [
"$dsoftbus_root_path/core/bus_center/lnn/net_builder/include",
"$dsoftbus_root_path/core/adapter/bus_center/include",
"$dsoftbus_root_path/core/bus_center/lnn/net_builder/include",
"$dsoftbus_root_path/core/common/dfx/hisysevent_adapter/include",
]
bus_center_builder_deps = []

View File

@ -39,6 +39,9 @@
#define STATE_LEAVING_INDEX 4
#define STATE_NUM_MAX (STATE_LEAVING_INDEX + 1)
#define SECOND_TO_MSENC 1000
#define MILLISECOND_TO_MICRO 1000
#define JOIN_LNN_TIMEOUT_LEN (15 * 1000UL)
#define LEAVE_LNN_TIMEOUT_LEN (5 * 1000UL)
@ -180,6 +183,39 @@ static void ReportResult(const char *udid, ReportCategory report)
}
}
int64_t LnnUpTimeMs(void)
{
SoftBusSysTime t;
t.sec = 0;
t.usec = 0;
SoftBusGetTime(&t);
int64_t when = t.sec * SECOND_TO_MSENC + t.usec / MILLISECOND_TO_MICRO;
return when;
}
static void ReportLnnDfx(LnnConnectionFsm *connFsm, int32_t retCode)
{
LnnConntionInfo *connInfo = &connFsm->connInfo;
connFsm->statisticData.type = connInfo->addr.type;
connFsm->statisticData.retCode = retCode;
if (retCode == SOFTBUS_OK) {
connFsm->statisticData.endTime = LnnUpTimeMs();
if (AddStatisticDuration(&connFsm->statisticData) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "add static duration");
}
}
if (AddStatisticRateOfSuccess(&connFsm->statisticData) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "add rate success");
}
if (retCode != SOFTBUS_OK) {
SoftBusEvtReportMsg msg;
(void)memset_s(&msg, sizeof(SoftBusEvtReportMsg), 0, sizeof(SoftBusEvtReportMsg));
if (CreateBusCenterFaultEvt(&msg, retCode, &connInfo->addr) == SOFTBUS_OK && msg.paramArray != NULL) {
(void)ReportBusCenterFaultEvt(&msg);
}
}
}
static void CompleteJoinLNN(LnnConnectionFsm *connFsm, const char *networkId, int32_t retCode)
{
LnnConntionInfo *connInfo = &connFsm->connInfo;
@ -187,6 +223,9 @@ static void CompleteJoinLNN(LnnConnectionFsm *connFsm, const char *networkId, in
uint8_t relation[CONNECTION_ADDR_MAX] = {0};
LnnFsmRemoveMessage(&connFsm->fsm, FSM_MSG_TYPE_JOIN_LNN_TIMEOUT);
if ((connInfo->flag & LNN_CONN_INFO_FLAG_JOIN_AUTO) != 0) { // only report auto network
ReportLnnDfx(connFsm, retCode);
}
if (retCode == SOFTBUS_OK) {
report = LnnAddOnlineNode(connInfo->nodeInfo);
NotifyJoinResult(connFsm, networkId, retCode);
@ -454,7 +493,7 @@ static void ParsePeerConnInfo(LnnConntionInfo *connInfo)
(uint64_t)times.usec / HB_TIME_FACTOR;
connInfo->nodeInfo->discoveryType = 1 << (uint32_t)LnnGetDiscoveryType(connInfo->addr.type);
connInfo->nodeInfo->authSeqNum = connInfo->authId;
connInfo->nodeInfo->authChannelId = (int32_t)connInfo->authId;
connInfo->nodeInfo->authChannelId[connInfo->addr.type] = (int32_t)connInfo->authId;
connInfo->nodeInfo->relation[connInfo->addr.type]++;
}

View File

@ -32,9 +32,9 @@
#include "lnn_local_net_ledger.h"
#include "lnn_network_id.h"
#include "lnn_network_manager.h"
#include "lnn_ip_network_impl.h"
#include "lnn_node_weight.h"
#include "lnn_p2p_info.h"
#include "lnn_physical_subnet_manager.h"
#include "lnn_sync_info_manager.h"
#include "lnn_topo_manager.h"
#include "softbus_adapter_mem.h"
@ -229,6 +229,7 @@ static LnnConnectionFsm *StartNewConnectionFsm(const ConnectionAddr *addr)
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "create connection fsm failed");
return NULL;
}
connFsm->statisticData.beginTime = LnnUpTimeMs();
if (LnnStartConnectionFsm(connFsm) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "start connection fsm[id=%u] failed", connFsm->id);
LnnDestroyConnectionFsm(connFsm);
@ -603,6 +604,7 @@ static int32_t ProcessAuthKeyGenerated(const void *para)
connFsm->connInfo.flag |= LNN_CONN_INFO_FLAG_JOIN_PASSIVE;
}
connFsm->connInfo.peerVersion = msgPara->peerVersion;
connFsm->statisticData.authTime = LnnUpTimeMs();
if (LnnSendAuthKeyGenMsgToConnFsm(connFsm) != SOFTBUS_OK) {
if (isCreate) {
StopConnectionFsm(connFsm);

View File

@ -59,6 +59,8 @@ void LnnNotifyPhysicalSubnetAddressChanged(const char *ifName, ProtocolType type
typedef VisitNextChoice (*LnnVisitPhysicalSubnetCallback)(const LnnPhysicalSubnet *, void *);
bool LnnVisitPhysicalSubnet(LnnVisitPhysicalSubnetCallback callback, void *data);
void LnnNotifyAllTypeOffline(ConnectionAddrType type);
#ifdef __cplusplus
#if __cplusplus
}

View File

@ -26,6 +26,9 @@ bus_center_net_mgr_inc = [
"$dsoftbus_root_path/core/bus_center/lnn/net_buscenter/include",
"$dsoftbus_root_path/core/adapter/bus_center/include",
]
if (dsoftbus_feature_conn_br || dsoftbus_feature_conn_ble) {
bus_center_net_mgr_src += [ "$dsoftbus_root_path/core/bus_center/lnn/net_buscenter/src/lnn_bt_network_impl.c" ]
}
bus_center_net_mgr_deps = []
native_source_path = rebase_path("$dsoftbus_root_path")

View File

@ -0,0 +1,295 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <securec.h>
#include <string.h>
#include "bus_center_event.h"
#include "bus_center_manager.h"
#include "lnn_heartbeat_strategy.h"
#include "lnn_net_builder.h"
#include "lnn_network_manager.h"
#include "lnn_physical_subnet_manager.h"
#include "softbus_adapter_bt_common.h"
#include "softbus_adapter_mem.h"
#include "softbus_errcode.h"
#include "softbus_log.h"
#include "softbus_utils.h"
#define LNN_BT_PROTOCOL_PRI 10
typedef enum {
BT_SUBNET_MANAGER_EVENT_IF_READY, // bluetooth on
BT_SUBNET_MANAGER_EVENT_IF_DOWN, // bluetooth off
BT_SUBNET_MANAGER_EVENT_MAX
} BtSubnetManagerEvent;
typedef enum {
BT_EVENT_RESULT_ACCEPTED = 0,
BT_EVENT_RESULT_REJECTED,
BT_EVENT_RESULT_OPTION_COUNT
} BtSubnetManagerEventResultOptions;
static void TransactBtSubnetState(LnnPhysicalSubnet *subnet, BtSubnetManagerEvent event, bool isAccepted)
{
LnnPhysicalSubnetStatus lastStatus = subnet->status;
LnnPhysicalSubnetStatus transactMap[][BT_EVENT_RESULT_OPTION_COUNT] = {
[BT_SUBNET_MANAGER_EVENT_IF_READY] = {LNN_SUBNET_RUNNING, LNN_SUBNET_IDLE},
[BT_SUBNET_MANAGER_EVENT_IF_DOWN] = {LNN_SUBNET_SHUTDOWN, subnet->status},
};
subnet->status = transactMap[event][isAccepted ? BT_EVENT_RESULT_ACCEPTED : BT_EVENT_RESULT_REJECTED];
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_DBG, "subnet %s trans state from %d to %d", subnet->ifName,
lastStatus, subnet->status);
}
static int32_t EnableBrSubnet(LnnPhysicalSubnet *subnet)
{
int32_t ret;
SoftBusBtAddr mac;
char macStr[BT_MAC_LEN] = {0};
if (subnet->status == LNN_SUBNET_RUNNING) {
return SOFTBUS_OK;
}
ret = SoftBusGetBtMacAddr(&mac);
if (ret != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "get bt mac addr fail");
return ret;
}
ret = ConvertBtMacToStr(macStr, sizeof(macStr), mac.addr, sizeof(mac.addr));
if (ret != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "convert bt mac to str fail");
return ret;
}
ret = LnnSetLocalStrInfo(STRING_KEY_BT_MAC, macStr);
if (ret != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "set bt mac to local ledger fail");
return ret;
}
return SOFTBUS_OK;
}
static int32_t EnableBleSubnet(LnnPhysicalSubnet *subnet)
{
int32_t ret;
if (subnet->status == LNN_SUBNET_RUNNING) {
return SOFTBUS_OK;
}
ret = LnnStartHeartbeatDelay();
if (ret != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "LNN start ble heartbeat fail, ret=%d", ret);
return ret;
}
return SOFTBUS_OK;
}
static int32_t DisableBrSubnet(LnnPhysicalSubnet *subnet)
{
int32_t ret;
bool addrType[CONNECTION_ADDR_MAX] = {
[CONNECTION_ADDR_BR] = true,
};
if (subnet->status != LNN_SUBNET_RUNNING) {
return SOFTBUS_ERR;
}
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "LNN start leave br network");
ret = LnnRequestLeaveByAddrType(addrType, CONNECTION_ADDR_MAX);
if (ret != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "LNN leave br network fail, ret=%d", ret);
return ret;
}
return SOFTBUS_OK;
}
static int32_t DisableBleSubnet(LnnPhysicalSubnet *subnet)
{
int32_t ret;
bool addrType[CONNECTION_ADDR_MAX] = {
[CONNECTION_ADDR_BLE] = true,
};
if (subnet->status != LNN_SUBNET_RUNNING) {
return SOFTBUS_ERR;
}
LnnStopHeartbeatNow();
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "LNN start leave ble network");
ret = LnnRequestLeaveByAddrType(addrType, CONNECTION_ADDR_MAX);
if (ret != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "LNN leave ble network fail, ret=%d", ret);
return ret;
}
return SOFTBUS_OK;
}
static void DestroyBtSubnetManager(LnnPhysicalSubnet *subnet)
{
int32_t ret;
LnnNetIfType type;
LnnGetNetIfTypeByName(subnet->ifName, &type);
if (subnet->status == LNN_SUBNET_RUNNING) {
ret = (type == LNN_NETIF_TYPE_BR) ? DisableBrSubnet(subnet) : DisableBleSubnet(subnet);
TransactBtSubnetState(subnet, BT_SUBNET_MANAGER_EVENT_IF_DOWN, (ret == SOFTBUS_OK));
}
SoftBusFree(subnet);
}
static LnnPhysicalSubnet *CreateBtSubnetManager(struct LnnProtocolManager *self, const char *ifName)
{
LnnNetIfType type;
LnnGetNetIfTypeByName(ifName, &type);
LnnPhysicalSubnet *subnet = (LnnPhysicalSubnet *)SoftBusCalloc(sizeof(LnnPhysicalSubnet));
if (subnet == NULL) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "%s:calloc bt subnet fail", __func__);
return NULL;
}
do {
subnet->Destroy = DestroyBtSubnetManager;
subnet->protocol = self;
subnet->status = LNN_SUBNET_IDLE;
subnet->OnNetifStatusChanged = NULL;
subnet->OnSoftbusNetworkDisconnected = NULL;
int32_t ret = strcpy_s(subnet->ifName, sizeof(subnet->ifName), ifName);
if (ret != EOK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "%s:copy ifName failed! ret=%d", __func__, ret);
break;
}
return subnet;
} while (false);
subnet->Destroy(subnet);
return NULL;
}
static VisitNextChoice NotifyBtStatusChanged(const LnnPhysicalSubnet *subnet, void *data)
{
int32_t ret = SOFTBUS_OK;
LnnNetIfType type;
BtSubnetManagerEvent event;
SoftBusBtState btState = (SoftBusBtState)(*(uint8_t *)data);
LnnGetNetIfTypeByName(subnet->ifName, &type);
switch (type) {
case LNN_NETIF_TYPE_BR:
if (btState == SOFTBUS_BR_TURN_ON) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_DBG, "net_buscenter get br turn on");
ret = EnableBrSubnet(subnet);
event = BT_SUBNET_MANAGER_EVENT_IF_READY;
break;
}
if (btState == SOFTBUS_BR_TURN_OFF) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_DBG, "net_buscenter get br turn off");
ret = DisableBrSubnet(subnet);
event = BT_SUBNET_MANAGER_EVENT_IF_DOWN;
break;
}
return CHOICE_VISIT_NEXT;
case LNN_NETIF_TYPE_BLE:
if (btState == SOFTBUS_BLE_TURN_ON) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_DBG, "net_buscenter get ble turn on");
ret = EnableBleSubnet(subnet);
event = BT_SUBNET_MANAGER_EVENT_IF_READY;
break;
}
if (btState == SOFTBUS_BLE_TURN_OFF) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_DBG, "net_buscenter get ble turn off");
ret = DisableBleSubnet(subnet);
event = BT_SUBNET_MANAGER_EVENT_IF_DOWN;
break;
}
return CHOICE_VISIT_NEXT;
default:
return CHOICE_VISIT_NEXT;
}
TransactBtSubnetState(subnet, event, (ret == SOFTBUS_OK));
return CHOICE_VISIT_NEXT;
}
static void LnnBtStateChangeEventHandler(const LnnEventBasicInfo *info)
{
if (info == NULL || info->event != LNN_EVENT_BT_STATE_CHANGED) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "HB bt state event handler get invalid param");
return;
}
const LnnMonitorBtStateChangedEvent *event = (const LnnMonitorBtStateChangedEvent *)info;
(void)LnnVisitPhysicalSubnet(NotifyBtStatusChanged, &event->status);
}
int32_t LnnInitBtProtocol(struct LnnProtocolManager *self)
{
(void)self;
if (LnnRegisterEventHandler(LNN_EVENT_BT_STATE_CHANGED, LnnBtStateChangeEventHandler) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "register bt state change event handler failed");
return SOFTBUS_ERR;
}
return SOFTBUS_OK;
}
int32_t LnnEnableBtProtocol(struct LnnProtocolManager *self, LnnNetIfMgr *netifMgr)
{
(void)self;
if (netifMgr == NULL) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "%s:netifMgr null ptr!", __func__);
return SOFTBUS_INVALID_PARAM;
}
LnnPhysicalSubnet *manager = CreateBtSubnetManager(self, netifMgr->ifName);
if (manager == NULL) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "%s:create bt subnet mgr fail", __func__);
return SOFTBUS_ERR;
}
int ret = LnnRegistPhysicalSubnet(manager);
if (ret != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "%s:regist subnet manager failed! ret=%d", __func__, ret);
manager->Destroy(manager);
return ret;
}
return SOFTBUS_OK;
}
static ListenerModule LnnGetBtListenerModule(ListenerMode mode)
{
return UNUSE_BUTT;
}
void LnnDeinitBtNetwork(struct LnnProtocolManager *self)
{
(void)self;
LnnUnregisterEventHandler(LNN_EVENT_BT_STATE_CHANGED, LnnBtStateChangeEventHandler);
LnnUnregistPhysicalSubnetByType(LNN_PROTOCOL_BR | LNN_PROTOCOL_BLE);
SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_WARN, "%s:bt network deinited", __func__);
}
static LnnProtocolManager g_btProtocol = {
.id = LNN_PROTOCOL_BR | LNN_PROTOCOL_BLE,
.pri = LNN_BT_PROTOCOL_PRI,
.supportedNetif = LNN_NETIF_TYPE_BR | LNN_NETIF_TYPE_BLE,
.Init = LnnInitBtProtocol,
.Deinit = LnnDeinitBtNetwork,
.Enable = LnnEnableBtProtocol,
.Disable = NULL,
.GetListenerModule = LnnGetBtListenerModule,
};
int32_t RegistBtProtocolManager(void)
{
return LnnRegistProtocol(&g_btProtocol);
}

View File

@ -13,9 +13,8 @@
* limitations under the License.
*/
#include "lnn_ip_network_impl.h"
#include <securec.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
@ -33,6 +32,7 @@
#include "lnn_physical_subnet_manager.h"
#include "softbus_adapter_mem.h"
#include "softbus_adapter_thread.h"
#include "softbus_common.h"
#include "softbus_def.h"
#include "softbus_errcode.h"
#include "softbus_feature_config.h"
@ -41,6 +41,7 @@
#include "trans_tcp_direct_listener.h"
#define IP_DEFAULT_PORT 0
#define LNN_LOOPBACK_IP "127.0.0.1"
static int32_t GetAvailableIpAddr(const char *ifName, char *ip, uint32_t size)
{
@ -64,7 +65,7 @@ static int32_t OpenAuthPort(void)
{
int32_t port = OpenAuthServer();
if (port < 0) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "open auth server failed\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "open auth server failed");
return SOFTBUS_ERR;
}
return LnnSetLocalNumInfo(NUM_KEY_AUTH_PORT, port);
@ -94,7 +95,7 @@ static int32_t OpenSessionPort(void)
}
port = TransTdcStartSessionListener(DIRECT_CHANNEL_SERVER_WIFI, &info);
if (port < 0) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "open session server failed\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "open session server failed");
return SOFTBUS_ERR;
}
return LnnSetLocalNumInfo(NUM_KEY_SESSION_PORT, port);
@ -126,7 +127,7 @@ static void OpenProxyPort(void)
int32_t port = ConnStartLocalListening(&listenerInfo);
if (port < 0) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "open proxy server failed\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "open proxy server failed");
return;
}
(void)LnnSetLocalNumInfo(NUM_KEY_PROXY_PORT, port);
@ -144,7 +145,7 @@ static void CloseProxyPort(void)
}
};
if (ConnStopLocalListening(&listenerInfo) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "ConnStopLocalListening fail!\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "ConnStopLocalListening fail!");
}
(void)LnnSetLocalNumInfo(NUM_KEY_PROXY_PORT, IP_DEFAULT_PORT);
}
@ -153,12 +154,12 @@ static int32_t OpenIpLink(void)
{
int32_t ret = OpenAuthPort();
if (ret != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "OpenAuthPort fail!\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "OpenAuthPort fail!");
return SOFTBUS_ERR;
}
ret = OpenSessionPort();
if (ret != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "OpenSessionPort fail!\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "OpenSessionPort fail!");
CloseAuthPort();
return SOFTBUS_ERR;
}
@ -176,11 +177,11 @@ static void CloseIpLink(void)
static int32_t GetLocalIpInfo(char *ipAddr, uint32_t ipAddrLen, char *ifName, uint32_t ifNameLen)
{
if (LnnGetLocalStrInfo(STRING_KEY_WLAN_IP, ipAddr, ipAddrLen) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "get local ip error!\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "get local ip error!");
return SOFTBUS_ERR;
}
if (LnnGetLocalStrInfo(STRING_KEY_NET_IF_NAME, ifName, ifNameLen) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "get local ifName error!\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "get local ifName error!");
return SOFTBUS_ERR;
}
return SOFTBUS_OK;
@ -189,11 +190,11 @@ static int32_t GetLocalIpInfo(char *ipAddr, uint32_t ipAddrLen, char *ifName, ui
static int32_t SetLocalIpInfo(const char *ipAddr, const char *ifName)
{
if (LnnSetLocalStrInfo(STRING_KEY_WLAN_IP, ipAddr) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "set local ip error!\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "set local ip error!");
return SOFTBUS_ERR;
}
if (LnnSetLocalStrInfo(STRING_KEY_NET_IF_NAME, ifName) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "set local ifName error!\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "set local ifName error!");
return SOFTBUS_ERR;
}
return SOFTBUS_OK;
@ -216,9 +217,9 @@ static void LeaveOldIpNetwork(const char *ifCurrentName)
} else {
addrType[type] = true;
}
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "LNN start leave ip network\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "LNN start leave ip network");
if (LnnRequestLeaveByAddrType(addrType, CONNECTION_ADDR_MAX) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "LNN leave ip network fail\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "LNN leave ip network fail");
}
}
@ -227,18 +228,18 @@ static int32_t ReleaseMainPort(const char *ifName)
char oldMainIf[NET_IF_NAME_LEN] = {0};
do {
if (LnnGetLocalStrInfo(STRING_KEY_NET_IF_NAME, oldMainIf, sizeof(oldMainIf)) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "%s:get local ifName error!\n", __func__);
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "%s:get local ifName error!", __func__);
break;
}
if (strcmp(ifName, oldMainIf) != 0) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "ifName %s is not main port!\n", ifName);
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "ifName %s is not main port!", ifName);
return SOFTBUS_ERR;
}
} while (false);
if (SetLocalIpInfo(LNN_LOOPBACK_IP, LNN_LOOPBACK_IFNAME) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "%s:set local ip info failed\n", __func__);
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "%s:set local ip info failed", __func__);
return SOFTBUS_ERR;
}
return SOFTBUS_OK;
@ -247,27 +248,27 @@ static int32_t ReleaseMainPort(const char *ifName)
static int32_t RequestMainPort(const char *ifName, const char *address)
{
if (strcmp(ifName, LNN_LOOPBACK_IFNAME) == 0) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "loopback ifName not allowed!\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "loopback ifName not allowed!");
return SOFTBUS_ERR;
}
if (strcmp(address, LNN_LOOPBACK_IP) == 0) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "loopback ip not allowed!\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "loopback ip not allowed!");
return SOFTBUS_ERR;
}
char oldMainIf[NET_IF_NAME_LEN] = {0};
if (LnnGetLocalStrInfo(STRING_KEY_NET_IF_NAME, oldMainIf, sizeof(oldMainIf)) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "get local ifName error!\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "get local ifName error!");
return SOFTBUS_ERR;
}
if (strcmp(oldMainIf, ifName) != 0 && strcmp(oldMainIf, LNN_LOOPBACK_IFNAME) != 0) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "Only 1 local subnet is allowed!\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "Only 1 local subnet is allowed!");
return SOFTBUS_ERR;
}
if (SetLocalIpInfo(address, ifName) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "set local ip info failed\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "set local ip info failed");
return SOFTBUS_ERR;
}
@ -290,16 +291,16 @@ static int32_t EnableIpSubnet(LnnPhysicalSubnet *subnet)
return SOFTBUS_ERR;
}
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "open ip link and start discovery\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "open ip link and start discovery");
if (OpenIpLink() != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "open ip link failed\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "open ip link failed");
}
DiscLinkStatusChanged(LINK_STATUS_UP, COAP);
if (LnnStartPublish() != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "start publish failed\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "start publish failed");
}
if (LnnIsAutoNetWorkingEnabled() && LnnStartDiscovery() != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "start discovery failed\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "start discovery failed");
}
SetCallLnnStatus(true);
return SOFTBUS_OK;
@ -341,27 +342,27 @@ typedef enum {
SUBNET_MANAGER_EVENT_IF_DOWN, // addr change from avaliable to
SUBNET_MANAGER_EVENT_IF_CHANGED, // addr changed
SUBNET_MANAGER_EVENT_MAX
} SubnetManagerEvent;
} IpSubnetManagerEvent;
typedef enum {
EVENT_RESULT_ACCEPTED = 0,
EVENT_RESULT_REJECTED,
EVENT_RESULT_OPTION_COUNT
} SubnetManagerEventResultOptions;
} IpSubnetManagerEventResultOptions;
static void TransactIpSubnetState(LnnPhysicalSubnet *subnet, SubnetManagerEvent event, bool isAccepted)
static void TransactIpSubnetState(LnnPhysicalSubnet *subnet, IpSubnetManagerEvent event, bool isAccepted)
{
LnnPhysicalSubnetStatus transactMap[][EVENT_RESULT_OPTION_COUNT] = {
[SUBNET_MANAGER_EVENT_IF_READY] = {LNN_SUBNET_RUNNING, LNN_SUBNET_IDLE},
[SUBNET_MANAGER_EVENT_IF_DOWN] = {LNN_SUBNET_SHUTDOWN, subnet->status },
[SUBNET_MANAGER_EVENT_IF_CHANGED] = {LNN_SUBNET_RESETTING, subnet->status }
[SUBNET_MANAGER_EVENT_IF_DOWN] = {LNN_SUBNET_SHUTDOWN, subnet->status},
[SUBNET_MANAGER_EVENT_IF_CHANGED] = {LNN_SUBNET_RESETTING, subnet->status}
};
subnet->status = transactMap[event][isAccepted ? EVENT_RESULT_ACCEPTED : EVENT_RESULT_REJECTED];
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_DBG, "subnet [%s, %u] state change to %d", subnet->ifName,
subnet->protocol->id, subnet->status);
}
static SubnetManagerEvent GetEventInOther(LnnPhysicalSubnet *subnet)
static IpSubnetManagerEvent GetEventInOther(LnnPhysicalSubnet *subnet)
{
char currentIfAddress[IP_LEN] = {0};
int32_t ret = GetAvailableIpAddr(subnet->ifName, currentIfAddress, sizeof(currentIfAddress));
@ -372,7 +373,7 @@ static SubnetManagerEvent GetEventInOther(LnnPhysicalSubnet *subnet)
}
}
static SubnetManagerEvent GetEventInRunning(LnnPhysicalSubnet *subnet)
static IpSubnetManagerEvent GetEventInRunning(LnnPhysicalSubnet *subnet)
{
char currentIfAddress[IP_LEN] = {0};
int32_t ret = GetAvailableIpAddr(subnet->ifName, currentIfAddress, sizeof(currentIfAddress));
@ -383,7 +384,7 @@ static SubnetManagerEvent GetEventInRunning(LnnPhysicalSubnet *subnet)
char localIpAddr[IP_LEN] = {0};
char localNetifName[NET_IF_NAME_LEN] = {0};
if (GetLocalIpInfo(localIpAddr, sizeof(localIpAddr), localNetifName, sizeof(localNetifName)) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "get main ip info failed\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "get main ip info failed");
return SUBNET_MANAGER_EVENT_IF_READY;
}
@ -398,7 +399,7 @@ static SubnetManagerEvent GetEventInRunning(LnnPhysicalSubnet *subnet)
}
}
static void OnSoftbusNetworkDisconnected(LnnPhysicalSubnet *subnet)
static void OnSoftbusIpNetworkDisconnected(LnnPhysicalSubnet *subnet)
{
if (subnet->status == LNN_SUBNET_RESETTING || subnet->status == LNN_SUBNET_IDLE) {
int32_t ret = EnableIpSubnet(subnet);
@ -408,7 +409,7 @@ static void OnSoftbusNetworkDisconnected(LnnPhysicalSubnet *subnet)
static void OnNetifStatusChanged(LnnPhysicalSubnet *subnet)
{
SubnetManagerEvent event = SUBNET_MANAGER_EVENT_MAX;
IpSubnetManagerEvent event = SUBNET_MANAGER_EVENT_MAX;
if (subnet->status == LNN_SUBNET_RUNNING) {
event = GetEventInRunning(subnet);
@ -432,7 +433,7 @@ static void OnNetifStatusChanged(LnnPhysicalSubnet *subnet)
}
default:
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_WARN, "discard unexpected event %d\n", event);
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_WARN, "discard unexpected event %d", event);
return;
}
@ -443,7 +444,7 @@ static LnnPhysicalSubnet *CreateIpSubnetManager(const struct LnnProtocolManager
{
LnnPhysicalSubnet *subnet = (LnnPhysicalSubnet *)SoftBusCalloc(sizeof(LnnPhysicalSubnet));
if (subnet == NULL) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "%s:oom\n", __func__);
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "%s:oom", __func__);
return NULL;
}
@ -452,11 +453,11 @@ static LnnPhysicalSubnet *CreateIpSubnetManager(const struct LnnProtocolManager
subnet->protocol = self;
subnet->status = LNN_SUBNET_IDLE;
subnet->OnNetifStatusChanged = OnNetifStatusChanged;
subnet->OnSoftbusNetworkDisconnected = OnSoftbusNetworkDisconnected;
subnet->OnSoftbusNetworkDisconnected = OnSoftbusIpNetworkDisconnected;
int32_t ret = strcpy_s(subnet->ifName, sizeof(subnet->ifName), ifName);
if (ret != EOK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "%s:copy ifName failed!ret=%d\n", __func__, ret);
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "%s:copy ifName failed!ret=%d", __func__, ret);
break;
}
return subnet;
@ -512,15 +513,15 @@ int32_t LnnInitIpProtocol(struct LnnProtocolManager *self)
(void)self;
int32_t ret = SOFTBUS_OK;
if (LnnRegisterEventHandler(LNN_EVENT_IP_ADDR_CHANGED, IpAddrChangeEventHandler) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "register ip addr change event handler failed\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "register ip addr change event handler failed");
return SOFTBUS_ERR;
}
if (LnnRegisterEventHandler(LNN_EVENT_WIFI_STATE_CHANGED, WifiStateChangeEventHandler) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "register wifi state change event handler failed\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "register wifi state change event handler failed");
return SOFTBUS_ERR;
}
if (SetLocalIpInfo(LNN_LOOPBACK_IP, LNN_LOOPBACK_IFNAME) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "init local ip as loopback failed!\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "init local ip as loopback failed!");
return SOFTBUS_ERR;
}
DiscLinkStatusChanged(LINK_STATUS_DOWN, COAP);
@ -531,18 +532,18 @@ int32_t LnnEnableIpProtocol(struct LnnProtocolManager *self, LnnNetIfMgr *netifM
{
(void)self;
if (netifMgr == NULL) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "%s:null ptr!\n", __func__);
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "%s:null ptr!", __func__);
return SOFTBUS_ERR;
}
LnnPhysicalSubnet *manager = CreateIpSubnetManager(self, netifMgr->ifName);
if (manager == NULL) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "%s:oom!\n", __func__);
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "%s:oom!", __func__);
return SOFTBUS_ERR;
}
int ret = LnnRegistPhysicalSubnet(manager);
if (ret != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "%s:regist subnet manager failed!ret=%d\n", __func__, ret);
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "%s:regist subnet manager failed!ret=%d", __func__, ret);
manager->Destroy(manager);
return ret;
}
@ -568,7 +569,6 @@ void LnnDeinitIpNetwork(struct LnnProtocolManager *self)
SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_WARN, "%s:ip network deinited", __func__);
}
static LnnProtocolManager g_ipProtocol = {
.id = LNN_PROTOCOL_IP,
.pri = 10,

View File

@ -34,10 +34,14 @@
#define LNN_DEFAULT_IF_NAME_WLAN "wlan0"
#define LNN_DEFAULT_IF_NAME_ETH "eth0"
#define LNN_DEFAULT_IF_NAME_BR "br0"
#define LNN_DEFAULT_IF_NAME_BLE "ble0"
typedef enum {
LNN_ETH_TYPE = 0,
LNN_WLAN_TYPE,
LNN_BR_TYPE,
LNN_BLE_TYPE,
LNN_MAX_NUM_TYPE,
} LnnNetIfNameType;
@ -54,11 +58,17 @@ int32_t __attribute__((weak)) RegistNewIPProtocolManager(void)
return SOFTBUS_OK;
}
int32_t __attribute__ ((weak)) RegistBtProtocolManager(void)
{
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_WARN, "regist virtual bt protocol manager");
return SOFTBUS_OK;
}
static LnnNetIfManagerBuilder g_netifBuilders[LNN_MAX_NUM_TYPE] = {0};
static LnnProtocolManager *g_networkProtocols[LNN_NETWORK_MAX_PROTOCOL_COUNT] = {0};
static LnnNetIfMgr *CreateEthNetifMgr(const char *netIfName)
static LnnNetIfMgr *CreateNetifMgr(const char *netIfName)
{
if (netIfName == NULL) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "parameters invalid!");
@ -160,6 +170,20 @@ static int32_t SetIfNameDefaultVal(void)
return SOFTBUS_ERR;
}
ListTailInsert(&g_netIfNameList, &netIfMgr->node);
netIfMgr = NetifMgrFactory(LNN_BR_TYPE, LNN_DEFAULT_IF_NAME_BR);
if (netIfMgr == NULL) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "add default BR netIfMgr failed!");
return SOFTBUS_ERR;
}
ListTailInsert(&g_netIfNameList, &netIfMgr->node);
netIfMgr = NetifMgrFactory(LNN_BLE_TYPE, LNN_DEFAULT_IF_NAME_BLE);
if (netIfMgr == NULL) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "add default BLE netIfMgr failed!");
return SOFTBUS_ERR;
}
ListTailInsert(&g_netIfNameList, &netIfMgr->node);
return SOFTBUS_OK;
}
@ -211,11 +235,12 @@ int32_t LnnRegistProtocol(LnnProtocolManager *protocolMgr)
if (protocolMgr->Init != NULL) {
ret = protocolMgr->Init(protocolMgr);
if (ret != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "init network protocol failed!ret=%d\n", ret);
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "init network protocol failed! ret=%d", ret);
break;
}
} else {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_WARN, "network protocol have no init\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_WARN, "network protocol (supportedNetif=%u) have no init",
protocolMgr->supportedNetif);
}
g_networkProtocols[i] = protocolMgr;
break;
@ -227,7 +252,7 @@ int32_t UnregistProtocol(LnnProtocolManager *protocolMgr)
{
uint8_t i;
if (protocolMgr == NULL) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "%s:null ptr!\n", __func__);
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "%s:null ptr!", __func__);
return SOFTBUS_ERR;
}
@ -240,7 +265,7 @@ int32_t UnregistProtocol(LnnProtocolManager *protocolMgr)
return SOFTBUS_OK;
}
}
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "%s:no such protocol!\n", __func__);
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "%s:no such protocol!", __func__);
return SOFTBUS_ERR;
}
@ -278,7 +303,7 @@ static void RestartCoapDiscovery(void)
char ifName[NET_IF_NAME_LEN] = {0};
int32_t authPort = 0;
if (LnnGetLocalStrInfo(STRING_KEY_NET_IF_NAME, ifName, NET_IF_NAME_LEN) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "get local ifName error!\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "get local ifName error!");
return;
}
if (strncmp(ifName, LNN_LOOPBACK_IFNAME, strlen(LNN_LOOPBACK_IFNAME)) == 0) {
@ -292,7 +317,7 @@ static void RestartCoapDiscovery(void)
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "open previous discovery again");
LnnStopDiscovery();
if (LnnStartDiscovery() != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "start discovery failed\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "start discovery failed");
}
SetCallLnnStatus(true);
}
@ -349,22 +374,31 @@ static VisitNextChoice GetAllProtocols(const LnnProtocolManager *manager, void *
int32_t LnnInitNetworkManager(void)
{
RegistNetIfMgr(LNN_ETH_TYPE, CreateEthNetifMgr);
RegistNetIfMgr(LNN_WLAN_TYPE, CreateEthNetifMgr);
RegistNetIfMgr(LNN_ETH_TYPE, CreateNetifMgr);
RegistNetIfMgr(LNN_WLAN_TYPE, CreateNetifMgr);
RegistNetIfMgr(LNN_BR_TYPE, CreateNetifMgr);
RegistNetIfMgr(LNN_BLE_TYPE, CreateNetifMgr);
int32_t ret = LnnInitManagerByConfig();
if (ret != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "Read net config failed!ret=%d\n", ret);
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "Read net config failed!ret=%d", ret);
return ret;
}
// Regist default protocols
ret = RegistIPProtocolManager();
if (ret != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "regist ip protocol manager failed,ret=%d\n", ret);
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "regist ip protocol manager failed,ret=%d", ret);
return ret;
}
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "IP protocol registed.\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "IP protocol registed.");
ret = RegistBtProtocolManager();
if (ret != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "regist bt protocol manager failed,ret=%d", ret);
return ret;
}
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "BT protocol registed.");
ret = RegistNewIPProtocolManager();
if (ret != SOFTBUS_OK) {
@ -380,7 +414,7 @@ int32_t LnnInitNetworkManager(void)
ret = LnnInitPhysicalSubnetManager();
if (ret != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "init subnet manager failed!,ret=%d\n", ret);
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "init subnet manager failed!,ret=%d", ret);
return ret;
}
@ -406,13 +440,12 @@ int32_t LnnInitNetworkManagerDelay(void)
char udid[UDID_BUF_LEN] = {0};
if (LnnGetLocalStrInfo(STRING_KEY_DEV_UDID, udid, UDID_BUF_LEN) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "get local udid error!\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "get local udid error!");
return SOFTBUS_ERR;
}
LnnNetIfMgr *item = NULL;
LIST_FOR_EACH_ENTRY(item, &g_netIfNameList, LnnNetIfMgr, node)
{
LIST_FOR_EACH_ENTRY(item, &g_netIfNameList, LnnNetIfMgr, node) {
for (i = 0; i < LNN_NETWORK_MAX_PROTOCOL_COUNT; ++i) {
if (g_networkProtocols[i] == NULL) {
continue;
@ -420,11 +453,11 @@ int32_t LnnInitNetworkManagerDelay(void)
if ((g_networkProtocols[i]->supportedNetif & item->type) != 0) {
int32_t ret = g_networkProtocols[i]->Enable(g_networkProtocols[i], item);
if (ret != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "enable protocol (%d) for netif %s failed\n", i,
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "enable protocol (%d) for netif %s failed", i,
item->ifName);
}
SoftBusLog(
SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "enable protocol (%d) for netif %s success\n", i, item->ifName);
SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "enable protocol (%d) for netif %s success", i, item->ifName);
}
}
}
@ -435,7 +468,7 @@ bool LnnIsAutoNetWorkingEnabled(void)
{
bool isEnabled = false;
if (SoftbusGetConfig(SOFTBUS_INT_AUTO_NETWORKING_SWITCH, (unsigned char *)&isEnabled,
sizeof(LnnIsAutoNetWorkingEnabled())) != SOFTBUS_OK) {
sizeof(isEnabled)) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "Cannot get autoNetworkingSwitch from config file");
return true;
}
@ -446,7 +479,7 @@ void LnnDeinitNetworkManager(void)
{
uint32_t i;
if (LnnClearNetConfigList() != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "deinit network manager failed\n");
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "deinit network manager failed");
}
LnnDeinitPhysicalSubnetManager();
@ -467,8 +500,7 @@ int32_t LnnGetNetIfTypeByName(const char *ifName, LnnNetIfType *type)
return SOFTBUS_ERR;
}
LnnNetIfMgr *netif = NULL;
LIST_FOR_EACH_ENTRY(netif, &g_netIfNameList, LnnNetIfMgr, node)
{
LIST_FOR_EACH_ENTRY(netif, &g_netIfNameList, LnnNetIfMgr, node) {
if (strncmp(ifName, netif->ifName, sizeof(netif->ifName)) == 0) {
*type = netif->type;
return SOFTBUS_OK;
@ -476,6 +508,7 @@ int32_t LnnGetNetIfTypeByName(const char *ifName, LnnNetIfType *type)
}
return SOFTBUS_ERR;
}
int32_t LnnGetAddrTypeByIfName(const char *ifName, ConnectionAddrType *type)
{
if (type == NULL || ifName == NULL) {
@ -494,6 +527,12 @@ int32_t LnnGetAddrTypeByIfName(const char *ifName, ConnectionAddrType *type)
case LNN_NETIF_TYPE_WLAN:
*type = CONNECTION_ADDR_WLAN;
break;
case LNN_NETIF_TYPE_BR:
*type = CONNECTION_ADDR_BR;
break;
case LNN_NETIF_TYPE_BLE:
*type = CONNECTION_ADDR_BLE;
break;
default:
ret = SOFTBUS_ERR;
}

View File

@ -76,11 +76,14 @@ void LnnDeinitPhysicalSubnetManager(void)
static int32_t DoRegistSubnet(LnnPhysicalSubnet *subnet)
{
for (uint8_t i = 0; i < MAX_SUPPORTED_PHYSICAL_SUBNET; i++) {
if (g_physicalSubnets[i] == NULL) {
g_physicalSubnets[i] = subnet;
g_physicalSubnets[i]->OnNetifStatusChanged(g_physicalSubnets[i]);
return SOFTBUS_OK;
if (g_physicalSubnets[i] != NULL) {
continue;
}
g_physicalSubnets[i] = subnet;
if (g_physicalSubnets[i]->OnNetifStatusChanged != NULL) {
g_physicalSubnets[i]->OnNetifStatusChanged(g_physicalSubnets[i]);
}
return SOFTBUS_OK;
}
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "%s: subnet list is full", __func__);
return SOFTBUS_ERR;

View File

@ -81,7 +81,7 @@ typedef struct {
DeviceBasicInfo deviceInfo;
ConnectInfo connectInfo;
int64_t authSeqNum;
int32_t authChannelId;
int32_t authChannelId[CONNECTION_ADDR_MAX];
BssTransInfo bssTransInfo;
bool isBleP2p; // true: this device support connect p2p via ble connection
P2pInfo p2pInfo;
@ -93,6 +93,7 @@ const char *LnnGetDeviceUdid(const NodeInfo *info);
int32_t LnnSetDeviceUdid(NodeInfo *info, const char *udid);
bool LnnHasDiscoveryType(const NodeInfo *info, DiscoveryType type);
int32_t LnnSetDiscoveryType(NodeInfo *info, DiscoveryType type);
int32_t LnnClearDiscoveryType(NodeInfo *info, DiscoveryType type);
bool LnnIsNodeOnline(const NodeInfo *info);
void LnnSetNodeConnStatus(NodeInfo *info, ConnectStatus status);
const char *LnnGetBtMac(const NodeInfo *info);

View File

@ -23,6 +23,8 @@
#include "lnn_meta_node_ledger.h"
#include "softbus_errcode.h"
#include "softbus_log.h"
#include "softbus_utils.h"
#include "softbus_adapter_mem.h"
int32_t LnnInitNetLedger(void)
{
@ -155,3 +157,129 @@ int32_t LnnGetNodeKeyInfoLen(int32_t key)
return SOFTBUS_ERR;
}
}
int32_t SoftbusDumpPrintUdid(int fd, NodeBasicInfo *nodeInfo)
{
NodeDeviceInfoKey key;
key = NODE_KEY_UDID;
char udid[UDID_BUF_LEN] = {0};
if (LnnGetNodeKeyInfo(nodeInfo->networkId, key, (uint8_t *)udid, UDID_BUF_LEN) != 0) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "LnnGetNodeKeyInfo Udid failed!");
return SOFTBUS_ERR;
}
char *anonyOut = DataMasking((char *)udid, strlen(udid), ID_DELIMITER);
dprintf(fd, "Udid = %s\n", anonyOut);
SoftBusFree(anonyOut);
return SOFTBUS_OK;
}
int32_t SoftbusDumpPrintUuid(int fd, NodeBasicInfo *nodeInfo)
{
NodeDeviceInfoKey key;
key = NODE_KEY_UUID;
char uuid[UUID_BUF_LEN] = {0};
if (LnnGetNodeKeyInfo(nodeInfo->networkId, key, (uint8_t *)uuid, UUID_BUF_LEN) != 0) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "LnnGetNodeKeyInfo Uuid failed!");
return SOFTBUS_ERR;
}
char *anonyOut = DataMasking((char *)uuid, strlen(uuid), ID_DELIMITER);
dprintf(fd, "Uuid = %s\n", anonyOut);
SoftBusFree(anonyOut);
return SOFTBUS_OK;
}
int32_t SoftbusDumpPrintMac(int fd, NodeBasicInfo *nodeInfo)
{
NodeDeviceInfoKey key;
key = NODE_KEY_BR_MAC;
char brMac[BT_MAC_LEN] = {0};
if (LnnGetNodeKeyInfo(nodeInfo->networkId, key, (uint8_t *)brMac, BT_MAC_LEN) != 0) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "LnnGetNodeKeyInfo brMac failed!");
return SOFTBUS_ERR;
}
char *anonyOut = DataMasking((char *)brMac, strlen(brMac), MAC_DELIMITER);
dprintf(fd, "BrMac = %s\n", anonyOut);
SoftBusFree(anonyOut);
return SOFTBUS_OK;
}
int32_t SoftbusDumpPrintIp(int fd, NodeBasicInfo *nodeInfo)
{
NodeDeviceInfoKey key;
key = NODE_KEY_IP_ADDRESS;
char ipAddr[IP_STR_MAX_LEN] = {0};
if (LnnGetNodeKeyInfo(nodeInfo->networkId, key, (uint8_t *)ipAddr, IP_STR_MAX_LEN) != 0) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "LnnGetNodeKeyInfo ipAddr failed!");
return SOFTBUS_ERR;
}
char *anonyOut = DataMasking((char *)ipAddr, strlen(ipAddr), IP_DELIMITER);
dprintf(fd, "IpAddr = %s\n", anonyOut);
SoftBusFree(anonyOut);
return SOFTBUS_OK;
}
int32_t SoftbusDumpPrintNetCapacity(int fd, NodeBasicInfo *nodeInfo)
{
NodeDeviceInfoKey key;
key = NODE_KEY_NETWORK_CAPABILITY;
int32_t netCapacity = 0;
if (LnnGetNodeKeyInfo(nodeInfo->networkId, key, (uint8_t *)&netCapacity, NUM_BUF_SIZE) != 0) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "LnnGetNodeKeyInfo netCapacity failed!");
return SOFTBUS_ERR;
}
dprintf(fd, "NetCapacity = %d\n", netCapacity);
return SOFTBUS_OK;
}
int32_t SoftbusDumpPrintNetType(int fd, NodeBasicInfo *nodeInfo)
{
NodeDeviceInfoKey key;
key = NODE_KEY_NETWORK_TYPE;
int32_t netType = 0;
if (LnnGetNodeKeyInfo(nodeInfo->networkId, key, (uint8_t *)&netType, NUM_BUF_SIZE) != 0) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "LnnGetNodeKeyInfo netType failed!");
return SOFTBUS_ERR;
}
dprintf(fd, "NetType = %d\n", netType);
return SOFTBUS_OK;
}
void SoftBusDumpBusCenterPrintInfo(int fd, NodeBasicInfo *nodeInfo)
{
if (fd <= 0 || nodeInfo == NULL) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "param is null");
return;
}
dprintf(fd, "DeviceName = %s\n", nodeInfo->deviceName);
char *anonyOut = DataMasking(nodeInfo->networkId, strlen(nodeInfo->networkId), ID_DELIMITER);
dprintf(fd, "NetworkId = %s\n", anonyOut);
SoftBusFree(anonyOut);
if (SoftbusDumpPrintUdid(fd, nodeInfo) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "SoftbusDumpPrintUdid failed!");
return;
}
if (SoftbusDumpPrintUuid(fd, nodeInfo) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "SoftbusDumpPrintUuid failed!");
return;
}
if (SoftbusDumpPrintMac(fd, nodeInfo) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "SoftbusDumpPrintMac failed!");
return;
}
if (SoftbusDumpPrintIp(fd, nodeInfo) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "SoftbusDumpPrintIp failed!");
return;
}
if (SoftbusDumpPrintNetCapacity(fd, nodeInfo) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "SoftbusDumpPrintNetCapacity failed!");
return;
}
if (SoftbusDumpPrintNetType(fd, nodeInfo) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "SoftbusDumpPrintNetType failed!");
return;
}
}

View File

@ -64,6 +64,16 @@ int32_t LnnSetDiscoveryType(NodeInfo *info, DiscoveryType type)
return SOFTBUS_OK;
}
int32_t LnnClearDiscoveryType(NodeInfo *info, DiscoveryType type)
{
if (info == NULL || type >= DISCOVERY_TYPE_COUNT) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "para error!");
return SOFTBUS_INVALID_PARAM;
}
info->discoveryType = (uint32_t)info->discoveryType & ~(1 << (uint32_t)type);
return SOFTBUS_OK;
}
bool LnnIsNodeOnline(const NodeInfo *info)
{
if (info == NULL) {

View File

@ -21,6 +21,7 @@
#include <securec.h>
#include "lnn_connection_addr_utils.h"
#include "lnn_lane_info.h"
#include "lnn_map.h"
#include "softbus_adapter_mem.h"
@ -29,8 +30,11 @@
#include "softbus_errcode.h"
#include "softbus_log.h"
#include "softbus_utils.h"
#include "softbus_hidumper_buscenter.h"
#include "bus_center_manager.h"
#define NUM_BUF_SIZE 4
#define SOFTBUS_BUSCENTER_DUMP_REMOTEDEVICEINFO "remote_device_info"
#define RETURN_IF_GET_NODE_VALID(networkId, buf, info) do { \
if ((networkId) == NULL || (buf) == NULL) { \
return SOFTBUS_INVALID_PARAM; \
@ -138,34 +142,6 @@ static void InitLaneStatus(void)
(void)memset_s(g_distributedNetLedger.laneCount, len, 0, len);
}
int32_t LnnInitDistributedLedger(void)
{
if (g_distributedNetLedger.status == DL_INIT_SUCCESS) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "Distributed Ledger already init");
return SOFTBUS_OK;
}
if (InitDistributedInfo(&g_distributedNetLedger.distributedInfo) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "InitDistributedInfo ERROR!");
g_distributedNetLedger.status = DL_INIT_FAIL;
return SOFTBUS_ERR;
}
if (InitConnectionCode(&g_distributedNetLedger.cnnCode) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "InitConnectionCode ERROR!");
g_distributedNetLedger.status = DL_INIT_FAIL;
return SOFTBUS_ERR;
}
if (SoftBusMutexInit(&g_distributedNetLedger.lock, NULL) != SOFTBUS_OK) {
g_distributedNetLedger.status = DL_INIT_FAIL;
return SOFTBUS_ERR;
}
InitLaneStatus();
g_distributedNetLedger.status = DL_INIT_SUCCESS;
return SOFTBUS_OK;
}
void LnnDeinitDistributedLedger(void)
{
if (SoftBusMutexLock(&g_distributedNetLedger.lock) != 0) {
@ -768,13 +744,14 @@ short LnnGetCnnCode(const char *uuid, DiscoveryType type)
return (*ptr);
}
static void MergeLnnRelation(const NodeInfo *oldInfo, NodeInfo *info)
static void MergeLnnInfo(const NodeInfo *oldInfo, NodeInfo *info)
{
int32_t i;
for (i = 0; i < CONNECTION_ADDR_MAX; ++i) {
info->relation[i] += oldInfo->relation[i];
info->relation[i] &= LNN_RELATION_MASK;
info->authChannelId[i] = oldInfo->authChannelId[i];
}
}
@ -819,7 +796,9 @@ ReportCategory LnnAddOnlineNode(NodeInfo *info)
} else {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "flag error");
}
MergeLnnRelation(oldInfo, info);
// update lnn discovery type
info->discoveryType |= oldInfo->discoveryType;
MergeLnnInfo(oldInfo, info);
}
LnnSetNodeConnStatus(info, STATUS_ONLINE);
LnnMapSet(&map->udidMap, udid, info, sizeof(NodeInfo));
@ -851,16 +830,21 @@ ReportCategory LnnSetNodeOffline(const char *udid, ConnectionAddrType type, int3
if (type != CONNECTION_ADDR_MAX && info->relation[type] > 0) {
info->relation[type]--;
}
if (LnnHasDiscoveryType(info, DISCOVERY_TYPE_BR)) {
if (LnnHasDiscoveryType(info, DISCOVERY_TYPE_BR) && LnnGetDiscoveryType(type) == DISCOVERY_TYPE_BR) {
RemoveCnnCode(&g_distributedNetLedger.cnnCode.connectionCode, info->uuid, DISCOVERY_TYPE_BR);
}
if (LnnHasDiscoveryType(info, DISCOVERY_TYPE_WIFI)) {
if (info->authChannelId != authId) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "not need to report offline.");
SoftBusMutexUnlock(&g_distributedNetLedger.lock);
return REPORT_NONE;
}
if (LnnHasDiscoveryType(info, DISCOVERY_TYPE_WIFI) && LnnGetDiscoveryType(type) == DISCOVERY_TYPE_WIFI &&
info->authChannelId[type] != authId) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "authChannelId != authId, not need to report offline.");
SoftBusMutexUnlock(&g_distributedNetLedger.lock);
return REPORT_NONE;
}
LnnClearDiscoveryType(info, LnnGetDiscoveryType(type));
if (info->discoveryType != 0) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "discoveryType=%u after clear, not need to report offline.",
info->discoveryType);
SoftBusMutexUnlock(&g_distributedNetLedger.lock);
return REPORT_NONE;
}
LnnSetNodeConnStatus(info, STATUS_OFFLINE);
SoftBusMutexUnlock(&g_distributedNetLedger.lock);
@ -1275,3 +1259,52 @@ int32_t LnnSetDLNodeAddr(const char *id, IdCategory type, const char *addr)
(void)SoftBusMutexUnlock(&g_distributedNetLedger.lock);
return ret == EOK ? SOFTBUS_OK : SOFTBUS_ERR;
}
int SoftBusDumpBusCenterRemoteDeviceInfo(int fd)
{
dprintf(fd, "-----RemoteDeviceInfo-----\n");
NodeBasicInfo *remoteNodeInfo = NULL;
int32_t infoNum = 0;
if (LnnGetAllOnlineNodeInfo(&remoteNodeInfo, &infoNum) != 0) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "LnnGetAllOnlineNodeInfo failed!");
return SOFTBUS_ERR;
}
dprintf(fd, "remote device num = %d\n", infoNum);
for (int i = 0; i < infoNum; i++) {
dprintf(fd, "\n[NO.%d]\n", i+1);
SoftBusDumpBusCenterPrintInfo(fd, remoteNodeInfo + i);
}
return SOFTBUS_OK;
}
int32_t LnnInitDistributedLedger(void)
{
if (g_distributedNetLedger.status == DL_INIT_SUCCESS) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, "Distributed Ledger already init");
return SOFTBUS_OK;
}
if (InitDistributedInfo(&g_distributedNetLedger.distributedInfo) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "InitDistributedInfo ERROR!");
g_distributedNetLedger.status = DL_INIT_FAIL;
return SOFTBUS_ERR;
}
if (InitConnectionCode(&g_distributedNetLedger.cnnCode) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "InitConnectionCode ERROR!");
g_distributedNetLedger.status = DL_INIT_FAIL;
return SOFTBUS_ERR;
}
if (SoftBusMutexInit(&g_distributedNetLedger.lock, NULL) != SOFTBUS_OK) {
g_distributedNetLedger.status = DL_INIT_FAIL;
return SOFTBUS_ERR;
}
if (SoftBusRegBusCenterVarDump(SOFTBUS_BUSCENTER_DUMP_REMOTEDEVICEINFO,
&SoftBusDumpBusCenterRemoteDeviceInfo) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusRegConnVarDump regist fail");
return SOFTBUS_ERR;
}
InitLaneStatus();
g_distributedNetLedger.status = DL_INIT_SUCCESS;
return SOFTBUS_OK;
}

View File

@ -29,12 +29,15 @@
#include "softbus_errcode.h"
#include "softbus_log.h"
#include "softbus_utils.h"
#include "softbus_hidumper_buscenter.h"
#define SOFTBUS_VERSION "hm.1.0.0"
#define VERSION_TYPE_LITE "LITE"
#define VERSION_TYPE_DEFAULT ""
#define NUM_BUF_SIZE 4
#define SOFTBUS_BUSCENTER_DUMP_LOCALDEVICEINFO "local_device_info"
typedef struct {
NodeInfo localInfo;
SoftBusMutex lock;
@ -881,6 +884,18 @@ int32_t LnnGetLocalDeviceInfo(NodeBasicInfo *info)
return LnnConvertDeviceTypeToId(type, &info->deviceTypeId);
}
int SoftBusDumpBusCenterLocalDeviceInfo(int fd)
{
dprintf(fd, "-----LocalDeviceInfo-----\n");
NodeBasicInfo localNodeInfo;
if (LnnGetLocalDeviceInfo(&localNodeInfo) != 0) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "LnnGetLocalDeviceInfo failed!");
return SOFTBUS_ERR;
}
SoftBusDumpBusCenterPrintInfo(fd, &localNodeInfo);
return SOFTBUS_OK;
}
int32_t LnnInitLocalLedger(void)
{
NodeInfo *nodeInfo = NULL;
@ -919,6 +934,11 @@ int32_t LnnInitLocalLedger(void)
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "mutex init fail!");
goto EXIT;
}
if (SoftBusRegBusCenterVarDump(
SOFTBUS_BUSCENTER_DUMP_LOCALDEVICEINFO, &SoftBusDumpBusCenterLocalDeviceInfo) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusRegConnVarDump regist fail");
return SOFTBUS_ERR;
}
g_localNetLedger.status = LL_INIT_SUCCESS;
return SOFTBUS_OK;
EXIT:
@ -934,7 +954,7 @@ int32_t LnnInitLocalLedgerDelay(void)
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "GetCommonDevInfo: COMM_DEVICE_KEY_UDID failed");
return SOFTBUS_ERR;
}
uint8_t accountHash[SHA_256_HASH_LEN] = {0};
if (LnnGetOhosAccountInfo(accountHash, SHA_256_HASH_LEN) != SOFTBUS_OK) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "get local user id hash error!");

View File

@ -34,5 +34,6 @@ bus_center_ledger_inc = [
"$dsoftbus_root_path/core/bus_center/lnn/net_ledger/common/include",
"$dsoftbus_root_path/core/bus_center/lnn/net_ledger/distributed_ledger/include",
"$dsoftbus_root_path/core/bus_center/lnn/net_ledger/local_ledger/include",
"$dsoftbus_root_path/core/bus_center/utils/include",
]
bus_center_ledger_deps = []

View File

@ -29,7 +29,9 @@ typedef enum {
MONITOR_IMPL_PRODUCT_TYPE,
MONITOR_IMPL_LWIP_TYPE,
MONITOR_IMPL_WIFISERVICE_TYPE,
MONITOR_IMPL_BT_STATE_TYPE,
MONITOR_IMPL_DRIVER_TYPE,
MONITOR_IMPL_SCREENSTATE_TYPE,
MONITOR_IMPL_MAX_TYPE,
} MonitorImplType;
@ -38,7 +40,13 @@ static LnnInitEventMonitorImpl g_monitorImplInit[MONITOR_IMPL_MAX_TYPE] = {
LnnInitProductMonitorImpl,
LnnInitLwipMonitorImpl,
LnnInitWifiServiceMonitorImpl,
LnnInitBtStateMonitorImpl,
LnnInitDriverMonitorImpl,
LnnInitScreenStateMonitorImpl,
};
static LnnDeinitEventMonitorImpl g_monitorImplDeinit[MONITOR_IMPL_MAX_TYPE] = {
LnnDeinitBtStateMonitorImpl,
};
int32_t LnnInitEventMonitor(void)
@ -53,4 +61,16 @@ int32_t LnnInitEventMonitor(void)
}
}
return SOFTBUS_OK;
}
void LnnDeinitEventMonitor(void)
{
uint32_t i;
for (i = 0; i < MONITOR_IMPL_MAX_TYPE; ++i) {
if (g_monitorImplDeinit[i] == NULL) {
continue;
}
g_monitorImplDeinit[i]();
}
}

View File

@ -30,7 +30,9 @@ typedef enum {
/* event from system monitor */
LNN_EVENT_IP_ADDR_CHANGED,
LNN_EVENT_WIFI_STATE_CHANGED,
LNN_EVENT_BT_STATE_CHANGED,
LNN_EVENT_WLAN_PARAM,
LNN_EVENT_SCREEN_STATE_CHANGED,
/* event from internal lnn */
LNN_EVENT_NODE_ONLINE_STATE_CHANGED,
LNN_EVENT_RELATION_CHANGED,
@ -52,14 +54,38 @@ typedef enum {
SOFTBUS_WIFI_CONNECTED,
SOFTBUS_WIFI_DISCONNECTED,
SOFTBUS_WIFI_DISABLED,
SOFTBUS_UNKNOWN,
SOFTBUS_WIFI_UNKNOWN,
} SoftBusWifiState;
typedef enum {
SOFTBUS_SCREEN_ON,
SOFTBUS_SCREEN_OFF,
SOFTBUS_SCREEN_UNKNOWN,
} SoftBusScreenState;
typedef enum {
SOFTBUS_BLE_TURN_ON,
SOFTBUS_BLE_TURN_OFF,
SOFTBUS_BR_TURN_ON,
SOFTBUS_BR_TURN_OFF,
SOFTBUS_BT_UNKNOWN,
} SoftBusBtState;
typedef struct {
LnnEventBasicInfo basic;
uint8_t status;
} LnnMonitorWlanStateChangedEvent;
typedef struct {
LnnEventBasicInfo basic;
uint8_t status;
} LnnMonitorScreenStateChangedEvent;
typedef struct {
LnnEventBasicInfo basic;
uint8_t status;
} LnnMonitorBtStateChangedEvent;
typedef struct {
LnnEventBasicInfo basic;
bool isOnline;
@ -103,6 +129,8 @@ void LnnNotifyOnlineState(bool isOnline, NodeBasicInfo *info);
void LnnNotifyBasicInfoChanged(NodeBasicInfo *info, NodeBasicInfoType type);
void LnnNotifyWlanStateChangeEvent(SoftBusWifiState state);
void LnnNotifyScreenStateChangeEvent(SoftBusScreenState state);
void LnnNotifyBtStateChangeEvent(void *state);
void LnnNotifyAddressChangedEvent(const char* ifName);
void LnnNotifyLnnRelationChanged(const char *udid, ConnectionAddrType type, uint8_t relation, bool isJoin);

View File

@ -263,7 +263,7 @@ void LnnNotifyTimeSyncResult(const char *pkgName, const TimeSyncResultInfo *info
void LnnNotifyWlanStateChangeEvent(SoftBusWifiState state)
{
if (state < SOFTBUS_WIFI_CONNECTED || state > SOFTBUS_UNKNOWN) {
if (state < SOFTBUS_WIFI_CONNECTED || state > SOFTBUS_WIFI_UNKNOWN) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "bad state %d", state);
return;
}
@ -271,6 +271,28 @@ void LnnNotifyWlanStateChangeEvent(SoftBusWifiState state)
NotifyEvent((const LnnEventBasicInfo *)&event);
}
void LnnNotifyScreenStateChangeEvent(SoftBusScreenState state)
{
if (state < SOFTBUS_SCREEN_ON || state >= SOFTBUS_SCREEN_UNKNOWN) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "bad state %d", state);
return;
}
LnnMonitorScreenStateChangedEvent event = {.basic.event = LNN_EVENT_SCREEN_STATE_CHANGED, .status = state};
NotifyEvent((const LnnEventBasicInfo *)&event);
}
void LnnNotifyBtStateChangeEvent(void *state)
{
SoftBusBtState *btState = (SoftBusBtState *)state;
if (*btState < SOFTBUS_BLE_TURN_ON || *btState >= SOFTBUS_BT_UNKNOWN) {
SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "bad btState %d", *btState);
return;
}
LnnMonitorBtStateChangedEvent event = {.basic.event = LNN_EVENT_BT_STATE_CHANGED, .status = (uint8_t)(*btState)};
NotifyEvent((const LnnEventBasicInfo *)&event);
SoftBusFree(btState);
}
void LnnNotifyAddressChangedEvent(const char *ifName)
{
LnnMonitorAddressChangedEvent event = {.basic.event = LNN_EVENT_IP_ADDR_CHANGED, .ifName = {0}};

Some files were not shown because too many files have changed in this diff Show More