diff --git a/CODEOWNERS b/CODEOWNERS index d7e15f45b..60f1b88d5 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -13,5 +13,119 @@ * limitations under the License. */ +[Arch] +./BUILD.gn zhangchunxin@huawei.com zhangshaojie3@huawei.com +./bundle.json zhangchunxin@huawei.com zhangshaojie3@huawei.com +./dsoftbus.gni zhangchunxin@huawei.com zhangshaojie3@huawei.com + +[Conn] +./adapter/common/net/bluetooth/ songzhengteng@huawei.com wuchunbo1@huawei.com +./core/adapter/br/ songzhengteng@huawei.com wuchunbo1@huawei.com +./core/connection/ songzhengteng@huawei.com wuchunbo1@huawei.com +./tests/adapter/bluetooth/ songzhengteng@huawei.com wuchunbo1@huawei.com +./tests/adapter/fuzztest/softbussocketrecv_fuzzer/ songzhengteng@huawei.com wuchunbo1@huawei.com +./tests/adapter/unittest/softbus_wifi_api_test.cpp songzhengteng@huawei.com wuchunbo1@huawei.com +./tests/adapter/unittest/softbus_socket_test.cpp songzhengteng@huawei.com wuchunbo1@huawei.com +./tests/core/connection/ songzhengteng@huawei.com wuchunbo1@huawei.com + +[Disc] +./adapter/common/range/ liufeihu@huawei.com xudaqing@huawei.com +./core/discovery/ liufeihu@huawei.com xudaqing@huawei.com +./sdk/discovery/ liufeihu@huawei.com xudaqing@huawei.com +./tests/adapter/fuzztest/softbusadapterrange_fuzzer/ liufeihu@huawei.com xudaqing@huawei.com +./tests/adapter/unittest/softbus_adapter_range_test.cpp liufeihu@huawei.com xudaqing@huawei.com +./tests/core/discovery/ liufeihu@huawei.com xudaqing@huawei.com +./tests/sdk/discovery/ liufeihu@huawei.com xudaqing@huawei.com + +[DiscInterface] +./interfaces/kits/discovery/ liufeihu@huawei.com xudaqing@huawei.com + +[Lnn] +./adapter/common/bus_center/ zhangshaojie3@huawei.com fengyonghui@huawei.com +./adapter/common/net/hdi/ zhangshaojie3@huawei.com fengyonghui@huawei.com +./adapter/common/net/wifi/ zhangshaojie3@huawei.com fengyonghui@huawei.com +./adapter/common/perf/ zhangshaojie3@huawei.com fengyonghui@huawei.com +./core/adapter/authentication/ zhangshaojie3@huawei.com fengyonghui@huawei.com +./core/adapter/bus_center/ zhangshaojie3@huawei.com fengyonghui@huawei.com +./core/authentication/ zhangshaojie3@huawei.com fengyonghui@huawei.com +./core/bus_center/ zhangshaojie3@huawei.com fengyonghui@huawei.com +./sdk/bus_center/ zhangshaojie3@huawei.com fengyonghui@huawei.com +./tests/adapter/unittest/softbus_adapter_wlan_extend_test.cpp zhangshaojie3@huawei.com fengyonghui@huawei.com +./tests/core/adapter/unittest/bus_center_adapter_test.cpp zhangshaojie3@huawei.com fengyonghui@huawei.com +./tests/core/adapter/unittest/lnn_settingdata_event_monitor_test.cpp zhangshaojie3@huawei.com fengyonghui@huawei.com +./tests/core/authentication/ zhangshaojie3@huawei.com fengyonghui@huawei.com +./tests/core/bus_center/ zhangshaojie3@huawei.com fengyonghui@huawei.com +./tests/sdk/bus_center/ zhangshaojie3@huawei.com fengyonghui@huawei.com + +[LnnInterface] +./interfaces/kits/bus_center/ zhangshaojie3@huawei.com fengyonghui@huawei.com + +[Trans] +./core/adapter/transmission/ zhangchunxin@huawei.com zhangfengxi@huawei.com +./core/transmission/ zhangchunxin@huawei.com zhangfengxi@huawei.com +./sdk/transmission/ zhangchunxin@huawei.com zhangfengxi@huawei.com +./tests/core/transmission/ zhangchunxin@huawei.com zhangfengxi@huawei.com +./tests/sdk/transmission/ zhangchunxin@huawei.com zhangfengxi@huawei.com + +[TransInterface] +./interfaces/inner_kits/transport/ zhangchunxin@huawei.com wuchengwen4@huawei.com +./interfaces/kits/transport/ zhangchunxin@huawei.com wuchengwen4@huawei.com + +[Comm] +./adapter/common/dfx/ zhangchunxin@huawei.com zhusiyuan2@huawei.com +./adapter/common/include/ zhangchunxin@huawei.com zhusiyuan2@huawei.com +./adapter/common/json/ zhangchunxin@huawei.com zhusiyuan2@huawei.com +./adapter/common/kernel/ zhangchunxin@huawei.com zhusiyuan2@huawei.com +./adapter/common/log/ zhangchunxin@huawei.com zhusiyuan2@huawei.com +./tests/adapter/fuzztest/softbusadapterhisysevent_fuzzer/ zhangchunxin@huawei.com zhusiyuan2@huawei.com +./tests/adapter/unittest/ zhangchunxin@huawei.com zhusiyuan2@huawei.com +./tests/core/common/ zhangchunxin@huawei.com zhusiyuan2@huawei.com +./tests/sdk/common/ zhangchunxin@huawei.com zhusiyuan2@huawei.com +./tests/utils/ zhangchunxin@huawei.com zhusiyuan2@huawei.com + +[CommInterface] +./interfaces/kits/common/ zhangchunxin@huawei.com zhangshaojie3@huawei.com + +[Framework] +./core/frame/ zhangshaojie3@huawei.com jiazhenyu1@huawei.com +./sdk/frame/ zhangshaojie3@huawei.com jiazhenyu1@huawei.com +./sdk/BUILD.gn zhangshaojie3@huawei.com jiazhenyu1@huawei.com +./sdk/libsoftbus_client_map zhangshaojie3@huawei.com jiazhenyu1@huawei.com +./tests/core/frame/ zhangshaojie3@huawei.com jiazhenyu1@huawei.com +./tests/sdk/frame/ zhangshaojie3@huawei.com jiazhenyu1@huawei.com + +[Permission] +./core/common/security/permission/ zhangchunxin@huawei.com liubao6@huawei.com +./tests/core/common/security/permission/ zhangchunxin@huawei.com liubao6@huawei.com + +[Crypto] +./adapter/common/mbedtls/ zhangshaojie3@huawei.com liubao6@huawei.com +./adapter/common/openssl/ zhangshaojie3@huawei.com liubao6@huawei.com +./components/mbedtls/ zhangshaojie3@huawei.com liubao6@huawei.com +./core/adapter/huks/ zhangshaojie3@huawei.com liubao6@huawei.com +./tests/adapter/fuzztest/softbusdecryptdata_fuzzer/ zhangshaojie3@huawei.com liubao6@huawei.com +./tests/adapter/unittest/dsoftbus_aes_crypto_test.cpp zhangshaojie3@huawei.com liubao6@huawei.com +./tests/adapter/unittest/dsoftbus_crypto_test.cpp zhangshaojie3@huawei.com liubao6@huawei.com +./tests/core/adapter/unittest/dsoftbus_rsa_crypto_test.cpp zhangshaojie3@huawei.com liubao6@huawei.com + +[Config] +./adapter/default_config/ zhangchunxin@huawei.com zhangshaojie3@huawei.com +./config.py zhangchunxin@huawei.com zhangshaojie3@huawei.com +./Kconfig zhangchunxin@huawei.com zhangshaojie3@huawei.com + +[2nd-Party] +./components/nstackx/ zhangchunxin@huawei.com xuxiaoqing16@huawei.com + +[Misc] +./figures/ zhangchunxin@huawei.com zhangshaojie3@huawei.com +./.clang-format zhangchunxin@huawei.com zhangshaojie3@huawei.com +./.gitignore zhangchunxin@huawei.com zhangshaojie3@huawei.com +./CODEOWNERS zhangchunxin@huawei.com zhangshaojie3@huawei.com +./hisysevent.yaml zhangchunxin@huawei.com zhangshaojie3@huawei.com +./OAT.xml zhangchunxin@huawei.com zhangshaojie3@huawei.com +./README.md zhangchunxin@huawei.com zhangshaojie3@huawei.com +./README_zh.md zhangchunxin@huawei.com zhangshaojie3@huawei.com + +[InterfaceCode] # any change to core/common/include/softbus_server_ipc_interface_code.h needs to be reviewed by @leonchan5 -core/common/include/softbus_server_ipc_interface_code.h @leonchan5 \ No newline at end of file +./core/common/include/softbus_server_ipc_interface_code.h @leonchan5 zhangchunxin@huawei.com zhangshaojie3@huawei.com diff --git a/adapter/BUILD.gn b/adapter/BUILD.gn index 955e4c334..246c66b39 100644 --- a/adapter/BUILD.gn +++ b/adapter/BUILD.gn @@ -75,7 +75,6 @@ if (defined(ohos_lite)) { "$softbus_adapter_common/kernel/liteos_m/softbus_adapter_timer.c", "$softbus_adapter_common/kernel/posix/softbus_adapter_socket.c", "$softbus_adapter_common/kernel/posix/softbus_adapter_thread.c", - "$softbus_adapter_common/log/softbus_adapter_log.c", "$softbus_adapter_common/range/softbus_adapter_range.c", "$softbus_adapter_config/spec_config/softbus_config_adapter.c", ] @@ -92,7 +91,6 @@ if (defined(ohos_lite)) { "$softbus_adapter_common/kernel/posix/softbus_adapter_file.c", "$softbus_adapter_common/kernel/posix/softbus_adapter_socket.c", "$softbus_adapter_common/kernel/posix/softbus_adapter_thread.c", - "$softbus_adapter_common/log/softbus_adapter_log.c", "$softbus_adapter_common/perf/softbus_adapter_perf.c", "$softbus_adapter_common/range/softbus_adapter_range.c", "$softbus_adapter_config/spec_config/softbus_config_adapter.c", @@ -140,7 +138,6 @@ if (defined(ohos_lite)) { "$softbus_adapter_common/kernel/posix/softbus_adapter_socket.c", "$softbus_adapter_common/kernel/posix/softbus_adapter_thread.c", "$softbus_adapter_common/kernel/posix/softbus_adapter_timer.c", - "$softbus_adapter_common/log/softbus_adapter_log.c", "$softbus_adapter_common/perf/softbus_adapter_perf.c", "$softbus_adapter_common/range/softbus_adapter_range.c", "$softbus_adapter_config/spec_config/softbus_config_adapter.c", @@ -207,7 +204,6 @@ if (defined(ohos_lite)) { "$softbus_adapter_common/kernel/posix/softbus_adapter_socket.c", "$softbus_adapter_common/kernel/posix/softbus_adapter_thread.c", "$softbus_adapter_common/kernel/posix/softbus_adapter_timer.c", - "$softbus_adapter_common/log/softbus_adapter_log.c", "$softbus_adapter_common/perf/softbus_adapter_perf.c", ] public_deps = [ diff --git a/adapter/common/bus_center/platform/lnn_product_monitor.c b/adapter/common/bus_center/platform/lnn_product_monitor.c index 4b59f6482..23d945336 100644 --- a/adapter/common/bus_center/platform/lnn_product_monitor.c +++ b/adapter/common/bus_center/platform/lnn_product_monitor.c @@ -17,7 +17,6 @@ #include "bus_center_event.h" #include "lnn_log.h" -#include "softbus_adapter_log.h" #include "softbus_errcode.h" #include "hdf_io_service_if.h" diff --git a/adapter/common/dfx/softbus_adapter_hiview.cpp b/adapter/common/dfx/softbus_adapter_hiview.cpp index b9a9841fc..374a83e65 100644 --- a/adapter/common/dfx/softbus_adapter_hiview.cpp +++ b/adapter/common/dfx/softbus_adapter_hiview.cpp @@ -17,9 +17,9 @@ #include #include "hiview.h" +#include "comm_log.h" #include "parameter.h" #include "securec.h" -#include "softbus_adapter_log.h" #include "softbus_adapter_mem.h" #define PROP_USER_TYPE "ro.logsystem.usertype" diff --git a/adapter/common/include/lnn_ip_utils_adapter.h b/adapter/common/include/lnn_ip_utils_adapter.h index b213c0931..4af4aab3d 100644 --- a/adapter/common/include/lnn_ip_utils_adapter.h +++ b/adapter/common/include/lnn_ip_utils_adapter.h @@ -25,7 +25,6 @@ #include #include -#include "softbus_adapter_log.h" #include "softbus_def.h" #include "softbus_errcode.h" diff --git a/adapter/common/include/softbus_adapter_log.h b/adapter/common/include/softbus_adapter_log.h deleted file mode 100644 index 7cd0adcd7..000000000 --- a/adapter/common/include/softbus_adapter_log.h +++ /dev/null @@ -1,113 +0,0 @@ -/* - * 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 SOFTBUS_ADAPTER_LOG_H -#define SOFTBUS_ADAPTER_LOG_H - -#include -#include - -#ifndef SOFTBUS_DEBUG -#if defined(__LITEOS_M__) -#define SOFTBUS_PRINTF -#include "log.h" -#else -#include "hilog/log.h" -#endif -#endif - -#ifdef __cplusplus -#if __cplusplus -extern "C" { -#endif -#endif - -#ifndef SOFTBUS_DEBUG -#if defined(__LITEOS_M__) - -#define LOG_DBG(fmt, ...) HILOG_DEBUG(HILOG_MODULE_SOFTBUS, fmt"\n", ##__VA_ARGS__); -#define LOG_INFO(fmt, ...) HILOG_INFO(HILOG_MODULE_SOFTBUS, fmt"\n", ##__VA_ARGS__); -#define LOG_WARN(fmt, ...) HILOG_WARN(HILOG_MODULE_SOFTBUS, fmt"\n", ##__VA_ARGS__); -#define LOG_ERR(fmt, ...) HILOG_ERROR(HILOG_MODULE_SOFTBUS, fmt"\n", ##__VA_ARGS__); -#else - -#undef LOG_DOMAIN -#undef LOG_TAG -#define LOG_DOMAIN 0xD0015C0 -#define LOG_TAG "dsoftbus" - -#define LOG_DBG(fmt, ...) HILOG_DEBUG(LOG_CORE, fmt"\n", ##__VA_ARGS__); -#define LOG_INFO(fmt, ...) HILOG_INFO(LOG_CORE, fmt"\n", ##__VA_ARGS__); -#define LOG_WARN(fmt, ...) HILOG_WARN(LOG_CORE, fmt"\n", ##__VA_ARGS__); -#define LOG_ERR(fmt, ...) HILOG_ERROR(LOG_CORE, fmt"\n", ##__VA_ARGS__); -#endif -#else -enum { - SOFTBUS_LOG_LEVEL_DEBUG = 0, - SOFTBUS_LOG_LEVEL_INFO, - SOFTBUS_LOG_LEVEL_WARNING, - SOFTBUS_LOG_LEVEL_ERROR -}; - -#define SOFTBUS_LOG_LEVEL SOFTBUS_LOG_LEVEL_INFO - -#define LOG_DBG(fmt, ...) do { \ - if (SOFTBUS_LOG_LEVEL_DEBUG >= SOFTBUS_LOG_LEVEL) { \ - printf("DEBUG:%s:%d " fmt "\n", __FUNCTION__, __LINE__, ##__VA_ARGS__); \ - } \ -} while (0) - -#define LOG_INFO(fmt, ...) do { \ - if (SOFTBUS_LOG_LEVEL_INFO >= SOFTBUS_LOG_LEVEL) { \ - printf("INFO:%s:%d " fmt "\n", __FUNCTION__, __LINE__, ##__VA_ARGS__); \ - } \ -} while (0) - -#define LOG_WARN(fmt, ...) do { \ - if (SOFTBUS_LOG_LEVEL_WARNING >= SOFTBUS_LOG_LEVEL) { \ - printf("WARN:%s:%d " fmt "\n", __FUNCTION__, __LINE__, ##__VA_ARGS__); \ - } \ -} while (0) - -#define LOG_ERR(fmt, ...) do { \ - if (SOFTBUS_LOG_LEVEL_ERROR >= SOFTBUS_LOG_LEVEL) { \ - printf("ERROR:%s:%d " fmt "\n", __FUNCTION__, __LINE__, ##__VA_ARGS__); \ - } \ -} while (0) -#endif - -#if defined(__LITEOS_M__) -#define SOFTBUS_HILOG_ID HILOG_MODULE_SOFTBUS -#else -#define SOFTBUS_HILOG_ID LOG_CORE -#endif - -typedef enum { - SOFTBUS_LOG_DBG, - SOFTBUS_LOG_INFO, - SOFTBUS_LOG_WARN, - SOFTBUS_LOG_ERROR, - SOFTBUS_LOG_LEVEL_MAX, -} SoftBusLogLevel; - -void SoftBusOutPrint(const char *buf, SoftBusLogLevel level); - -#ifdef __cplusplus -#if __cplusplus -} -#endif /* __cplusplus */ -#endif /* __cplusplus */ - -#endif diff --git a/adapter/common/json/nlohmann/softbus_adapter_json.cpp b/adapter/common/json/nlohmann/softbus_adapter_json.cpp index c9db2a1c3..dfda49424 100644 --- a/adapter/common/json/nlohmann/softbus_adapter_json.cpp +++ b/adapter/common/json/nlohmann/softbus_adapter_json.cpp @@ -21,6 +21,7 @@ #include "softbus_adapter_mem.h" #define JSON_LOGE(fmt, ...) COMM_LOGE(COMM_ADAPTER, "[%s] " fmt, __FUNCTION__, ##__VA_ARGS__) +#define JSON_LOGD(fmt, ...) COMM_LOGD(COMM_ADAPTER, "[%s] " fmt, __FUNCTION__, ##__VA_ARGS__) JsonObj *JSON_CreateObject(void) { @@ -256,7 +257,7 @@ bool JSON_GetStringFromOject(const JsonObj *obj, const char *key, char *value, u } nlohmann::json item = (*json)[key]; if (!item.is_string()) { - JSON_LOGE("cannot find or invalid [%s]", key); + JSON_LOGD("cannot find or invalid [%s]", key); return false; } std::string valueString = item.get(); @@ -324,4 +325,4 @@ bool JSON_GetStringArrayFromOject(const JsonObj *obj, const char * const key, ch } *len = item.size(); return true; -} \ No newline at end of file +} diff --git a/adapter/common/kernel/posix/softbus_adapter_thread.c b/adapter/common/kernel/posix/softbus_adapter_thread.c index 75da99a04..108edf0a7 100644 --- a/adapter/common/kernel/posix/softbus_adapter_thread.c +++ b/adapter/common/kernel/posix/softbus_adapter_thread.c @@ -97,7 +97,7 @@ int32_t SoftBusMutexInit(SoftBusMutex *mutex, SoftBusMutexAttr *mutexAttr) int32_t SoftBusMutexLock(SoftBusMutex *mutex) { if ((mutex == NULL) || ((void *)(*mutex) == NULL)) { - COMM_LOGE(COMM_ADAPTER, "mutex is null"); + COMM_LOGD(COMM_ADAPTER, "mutex is null"); return SOFTBUS_INVALID_PARAM; } @@ -130,7 +130,7 @@ int32_t SoftBusMutexUnlock(SoftBusMutex *mutex) int32_t SoftBusMutexDestroy(SoftBusMutex *mutex) { if ((mutex == NULL) || ((void *)(*mutex) == NULL)) { - COMM_LOGE(COMM_ADAPTER, "mutex is null"); + COMM_LOGD(COMM_ADAPTER, "mutex is null"); return SOFTBUS_INVALID_PARAM; } diff --git a/adapter/common/log/softbus_adapter_log.c b/adapter/common/log/softbus_adapter_log.c deleted file mode 100644 index 17a69fd89..000000000 --- a/adapter/common/log/softbus_adapter_log.c +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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 "softbus_adapter_log.h" - -void SoftBusOutPrint(const char *buf, SoftBusLogLevel level) -{ -#ifdef SOFTBUS_PRINTF - (void)level; - printf("%s\n", buf); - return; -#else - switch (level) { - case SOFTBUS_LOG_DBG: - HILOG_DEBUG(SOFTBUS_HILOG_ID, "%{public}s", buf); - break; - case SOFTBUS_LOG_INFO: - HILOG_INFO(SOFTBUS_HILOG_ID, "%{public}s", buf); - break; - case SOFTBUS_LOG_WARN: - HILOG_WARN(SOFTBUS_HILOG_ID, "%{public}s", buf); - break; - case SOFTBUS_LOG_ERROR: - HILOG_ERROR(SOFTBUS_HILOG_ID, "%{public}s", buf); - break; - default: - break; - } -#endif -} diff --git a/adapter/common/net/bluetooth/broadcast/adapter/ble/include/softbus_ble_gatt.h b/adapter/common/net/bluetooth/broadcast/adapter/ble/include/softbus_ble_gatt.h index 2c22a7461..675f07b3d 100644 --- a/adapter/common/net/bluetooth/broadcast/adapter/ble/include/softbus_ble_gatt.h +++ b/adapter/common/net/bluetooth/broadcast/adapter/ble/include/softbus_ble_gatt.h @@ -25,13 +25,12 @@ #define SOFTBUS_BLE_GATT_H #include "softbus_broadcast_adapter_interface.h" -#include "softbus_broadcast_adapter_type.h" #ifdef __cplusplus extern "C"{ #endif -void softbus_ble_adapter_init(void); +void SoftbusBleAdapterInit(void); #ifdef __cplusplus } diff --git a/adapter/common/net/bluetooth/broadcast/adapter/ble/include/softbus_ble_utils.h b/adapter/common/net/bluetooth/broadcast/adapter/ble/include/softbus_ble_utils.h new file mode 100644 index 000000000..d565df582 --- /dev/null +++ b/adapter/common/net/bluetooth/broadcast/adapter/ble/include/softbus_ble_utils.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2023 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. + */ + +/** + * @file softbus_ble_utils.h + * @brief ble utils + * + * @since 4.1 + * @version 1.0 + */ + +#ifndef SOFTBUS_BLE_UTILS_H +#define SOFTBUS_BLE_UTILS_H + +#include "softbus_broadcast_adapter_interface.h" +#include "c_header/ohos_bt_gatt.h" +#include "c_header/ohos_bt_def.h" + +#ifdef __cplusplus +extern "C"{ +#endif + +int32_t BtStatusToSoftBus(BtStatus btStatus); + +void SoftbusAdvParamToBt(const SoftbusBroadcastParam *src, BleAdvParams *dst); + +void BtScanResultToSoftbus(const BtScanResultData *src, SoftBusBcScanResult *dst); + +void SoftbusFilterToBt(BleScanNativeFilter *nativeFilter, const SoftBusBcScanFilter *filter, uint8_t filterSize); + +void FreeBtFilter(BleScanNativeFilter *nativeFilter, int32_t filterSize); + +void DumpBleScanFilter(BleScanNativeFilter *nativeFilter, int32_t filterSize); + +int GetBtScanMode(uint16_t scanInterval, uint16_t scanWindow); + +uint8_t *AssembleAdvData(const SoftbusBroadcastData *data, uint16_t *dataLen); + +uint8_t *AssembleRspData(const SoftbusBroadcastPayload *data, uint16_t *dataLen); + +int32_t ParseScanResult(const uint8_t *advData, uint8_t advLen, SoftBusBcScanResult *dst); + +void DumpSoftbusAdapterData(const char *description, uint8_t *data, uint16_t len); + +#ifdef __cplusplus +} +#endif + +#endif /* SOFTBUS_BLE_UTILS_H */ \ No newline at end of file diff --git a/adapter/common/net/bluetooth/broadcast/adapter/ble/src/softbus_ble_gatt.c b/adapter/common/net/bluetooth/broadcast/adapter/ble/src/softbus_ble_gatt.c index 3bd1d133a..951cf9647 100644 --- a/adapter/common/net/bluetooth/broadcast/adapter/ble/src/softbus_ble_gatt.c +++ b/adapter/common/net/bluetooth/broadcast/adapter/ble/src/softbus_ble_gatt.c @@ -14,7 +14,804 @@ */ #include "softbus_ble_gatt.h" +#include "softbus_adapter_thread.h" +#include "softbus_adapter_mem.h" +#include "softbus_broadcast_type.h" +#include "softbus_error_code.h" +#include "softbus_ble_utils.h" +#include "disc_log.h" +#include +#include -void softbus_ble_adapter_init(void) +#define GATT_ADV_MAX_NUM 16 +#define GATT_SCAN_MAX_NUM 2 +#define LP_BT_UUID "43d4a49f-604d-45b5-9302-4ddbbfd538fd" +#define LP_DELIVERY_MODE_REPLY 0xF0 +#define LP_ADV_DURATION_MS 0 +#define SCAN_CHANNEL_0 0 +#define SCAN_CHANNEL_1 1 + +static atomic_bool g_init = false; +static atomic_bool g_bcCbReg = false; +static SoftBusMutex g_advLock = {0}; +static SoftBusMutex g_scannerLock = {0}; + +typedef struct { + int32_t advId; + bool isUsed; + bool isAdvertising; + SoftbusBroadcastCallback *advCallback; +} AdvChannel; + +typedef struct { + int32_t scannerId; + bool isUsed; + bool isScanning; + SoftbusScanCallback *scanCallback; +} ScanChannel; + +static AdvChannel g_advChannel[GATT_ADV_MAX_NUM]; +static ScanChannel g_scanChannel[GATT_SCAN_MAX_NUM]; + +static int32_t Init(void) { + if (g_init) { + DISC_LOGI(DISC_BLE_ADAPTER, "already inited"); + return SOFTBUS_OK; + } + g_init = true; + if (SoftBusMutexInit(&g_advLock, NULL) != SOFTBUS_OK) { + g_init = false; + DISC_LOGE(DISC_BLE_ADAPTER, "g_advLock init failed"); + return SOFTBUS_ERR; + } + if (SoftBusMutexInit(&g_scannerLock, NULL) != SOFTBUS_OK) { + SoftBusMutexDestroy(&g_advLock); + g_init = false; + DISC_LOGE(DISC_BLE_ADAPTER, "g_scannerLock init failed"); + return SOFTBUS_ERR; + } + DISC_LOGI(DISC_BLE_ADAPTER, "init success"); + return SOFTBUS_OK; } + +static int32_t DeInit(void) +{ + if (!g_init) { + DISC_LOGI(DISC_BLE_ADAPTER, "already deinited"); + return SOFTBUS_OK; + } + g_init = false; + SoftBusMutexDestroy(&g_advLock); + SoftBusMutexDestroy(&g_scannerLock); + DISC_LOGI(DISC_BLE_ADAPTER, "deinit success"); + return SOFTBUS_OK; +} + +static void WrapperAdvEnableCallback(int advId, int status) +{ + int32_t ret = BtStatusToSoftBus((BtStatus)status); + for (uint8_t channelId = 0; channelId < GATT_ADV_MAX_NUM; channelId++) { + if (SoftBusMutexLock(&g_advLock) != SOFTBUS_OK) { + DISC_LOGW(DISC_BLE_ADAPTER, "lock adv failed, advId: %u, bt-advId: %d", channelId, advId); + continue; + } + AdvChannel *advChannel = &g_advChannel[channelId]; + if (advChannel->advId != advId || !advChannel->isUsed) { + SoftBusMutexUnlock(&g_advLock); + continue; + } + advChannel->isAdvertising = (ret == SOFTBUS_BC_STATUS_SUCCESS); + if (!advChannel->isAdvertising) { + advChannel->advId = -1; + } + DISC_LOGI(DISC_BLE_ADAPTER, "advId: %u, bt-advId: %d, status: %d", channelId, advId, ret); + SoftBusMutexUnlock(&g_advLock); + if (advChannel->advCallback != NULL && advChannel->advCallback->OnStartBroadcastingCallback != NULL) { + advChannel->advCallback->OnStartBroadcastingCallback(channelId, ret); + } + break; + } +} + +static void WrapperAdvDisableCallback(int advId, int status) +{ + int32_t ret = BtStatusToSoftBus((BtStatus)status); + for (uint8_t channelId = 0; channelId < GATT_ADV_MAX_NUM; channelId++) { + if (SoftBusMutexLock(&g_advLock) != SOFTBUS_OK) { + DISC_LOGW(DISC_BLE_ADAPTER, "lock adv failed, advId: %u, bt-advId: %d", channelId, advId); + continue; + } + AdvChannel *advChannel = &g_advChannel[channelId]; + if (advChannel->advId != advId || !advChannel->isUsed) { + SoftBusMutexUnlock(&g_advLock); + continue; + } + advChannel->isAdvertising = false; + advChannel->advId = -1; + DISC_LOGI(DISC_BLE_ADAPTER, "advId: %u, bt-advId: %d, status: %d", channelId, advId, ret); + SoftBusMutexUnlock(&g_advLock); + if (advChannel->advCallback != NULL && advChannel->advCallback->OnStopBroadcastingCallback != NULL) { + advChannel->advCallback->OnStopBroadcastingCallback(channelId, ret); + } + break; + } +} + +static void WrapperAdvSetDataCallback(int advId, int status) +{ + int32_t ret = BtStatusToSoftBus((BtStatus)status); + for (uint32_t channelId = 0; channelId < GATT_ADV_MAX_NUM; channelId++) { + if (SoftBusMutexLock(&g_advLock) != SOFTBUS_OK) { + DISC_LOGW(DISC_BLE_ADAPTER, "lock adv failed, advId: %u, bt-advId: %d", channelId, advId); + continue; + } + AdvChannel *advChannel = &g_advChannel[channelId]; + if (advChannel->advId != advId || !advChannel->isUsed) { + SoftBusMutexUnlock(&g_advLock); + continue; + } + DISC_LOGI(DISC_BLE_ADAPTER, "advId: %u, bt-advId: %d, status: %d", channelId, advId, ret); + SoftBusMutexUnlock(&g_advLock); + if (advChannel->advCallback != NULL && advChannel->advCallback->OnSetBroadcastingCallback != NULL) { + advChannel->advCallback->OnSetBroadcastingCallback(channelId, ret); + } + break; + } +} + +static void WrapperAdvUpdateDataCallback(int advId, int status) +{ + int32_t ret = BtStatusToSoftBus((BtStatus)status); + for (uint32_t channelId = 0; channelId < GATT_ADV_MAX_NUM; channelId++) { + if (SoftBusMutexLock(&g_advLock) != SOFTBUS_OK) { + DISC_LOGW(DISC_BLE_ADAPTER, "lock adv failed, advId: %u, bt-advId: %d", channelId, advId); + continue; + } + AdvChannel *advChannel = &g_advChannel[channelId]; + if (advChannel->advId != advId || !advChannel->isUsed) { + SoftBusMutexUnlock(&g_advLock); + continue; + } + DISC_LOGI(DISC_BLE_ADAPTER, "advId: %u, bt-advId: %d, status: %d", channelId, advId, ret); + SoftBusMutexUnlock(&g_advLock); + if (advChannel->advCallback != NULL && advChannel->advCallback->OnUpdateBroadcastingCallback != NULL) { + advChannel->advCallback->OnUpdateBroadcastingCallback(channelId, ret); + } + break; + } +} + +static BtGattCallbacks g_softbusGattCb = { + .advEnableCb = WrapperAdvEnableCallback, + .advDisableCb = WrapperAdvDisableCallback, + .advDataCb = WrapperAdvSetDataCallback, + .advUpdateCb = WrapperAdvUpdateDataCallback, +}; + +static int32_t RegisterAdvCallback(int32_t *advId, const SoftbusBroadcastCallback *cb) +{ + if (advId == NULL || cb == NULL) { + DISC_LOGE(DISC_BLE_ADAPTER, "adv param is null"); + return SOFTBUS_INVALID_PARAM; + } + if (SoftBusMutexLock(&g_advLock) != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE_ADAPTER, "lock failed"); + return SOFTBUS_LOCK_ERR; + } + for (uint8_t channelId = 0; channelId < GATT_ADV_MAX_NUM; channelId++) { + if (g_advChannel[channelId].isUsed) { + continue; + } + if (!g_bcCbReg) { + if (BleGattRegisterCallbacks(&g_softbusGattCb) != OHOS_BT_STATUS_SUCCESS) { + DISC_LOGE(DISC_BLE_ADAPTER, "register failed, advId: %u", channelId); + SoftBusMutexUnlock(&g_advLock); + return SOFTBUS_ERR; + } + g_bcCbReg = true; + } + g_advChannel[channelId].advId = -1; + g_advChannel[channelId].isUsed = true; + g_advChannel[channelId].isAdvertising = false; + g_advChannel[channelId].advCallback = (SoftbusBroadcastCallback *)cb; + *advId = channelId; + DISC_LOGI(DISC_BLE_ADAPTER, "register success, advId: %u", channelId); + SoftBusMutexUnlock(&g_advLock); + return SOFTBUS_OK; + } + DISC_LOGE(DISC_BLE_ADAPTER, "no available adv channel"); + SoftBusMutexUnlock(&g_advLock); + return SOFTBUS_ERR; +} + +static int32_t UnRegisterAdvCallback(int32_t advId) +{ + if (advId < 0 || advId >= GATT_ADV_MAX_NUM) { + DISC_LOGE(DISC_BLE_ADAPTER, "invalid advId: %d", advId); + return SOFTBUS_INVALID_PARAM; + } + if (SoftBusMutexLock(&g_advLock) != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE_ADAPTER, "lock failed, advId: %d", advId); + return SOFTBUS_LOCK_ERR; + } + if (!g_advChannel[advId].isUsed) { + DISC_LOGI(DISC_BLE_ADAPTER, "already unregistered, advId: %d, bt-advId: %d", advId, g_advChannel[advId].advId); + SoftBusMutexUnlock(&g_advLock); + return SOFTBUS_OK; + } + DISC_LOGI(DISC_BLE_ADAPTER, "advId: %d, bt-advId: %d", advId, g_advChannel[advId].advId); + g_advChannel[advId].advId = -1; + g_advChannel[advId].isUsed = false; + g_advChannel[advId].isAdvertising = false; + g_advChannel[advId].advCallback = NULL; + SoftBusMutexUnlock(&g_advLock); + return SOFTBUS_OK; +} + +static void WrapperScanResultCallback(uint8_t channelId, BtScanResultData *data) +{ + if (data == NULL) { + DISC_LOGE(DISC_BLE_ADAPTER, "scan result data is null, scannerId: %u", channelId); + return; + } + if (SoftBusMutexLock(&g_scannerLock) != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE_ADAPTER, "lock failed, scannerId: %u", channelId); + return; + } + ScanChannel *scanChannel = &g_scanChannel[channelId]; + if (!scanChannel->isUsed || !scanChannel->isScanning) { + DISC_LOGE(DISC_BLE_ADAPTER, "scanner is not in used, scannerId: %u, bt-scannerId: %d", + channelId, scanChannel->scannerId); + SoftBusMutexUnlock(&g_scannerLock); + return; + } + SoftBusBcScanResult scanResult = {}; + BtScanResultToSoftbus(data, &scanResult); + + if (ParseScanResult(data->advData, data->advLen, &scanResult) != SOFTBUS_OK) { + SoftBusFree(scanResult.data.bcData.payload); + SoftBusFree(scanResult.data.rspData.payload); + SoftBusMutexUnlock(&g_scannerLock); + return; + } + SoftBusMutexUnlock(&g_scannerLock); + if (scanChannel->scanCallback != NULL && scanChannel->scanCallback->OnReportScanDataCallback != NULL) { + scanChannel->scanCallback->OnReportScanDataCallback(channelId, &scanResult); + } + SoftBusFree(scanResult.data.bcData.payload); + SoftBusFree(scanResult.data.rspData.payload); +} + +static void WrapperScanStateChangeCallback(uint8_t channelId, int32_t resultCode, bool isStartScan) +{ + if (SoftBusMutexLock(&g_scannerLock) != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE_ADAPTER, "lock failed, scannerId: %u", channelId); + return; + } + ScanChannel *scanChannel = &g_scanChannel[channelId]; + if (!scanChannel->isUsed) { + DISC_LOGE(DISC_BLE_ADAPTER, "scanner is not in used, scannerId: %u, bt-scannerId: %d", + channelId, scanChannel->scannerId); + SoftBusMutexUnlock(&g_scannerLock); + return; + } + DISC_LOGI(DISC_BLE_ADAPTER, "scannerId: %d, bt-scannerId: %d, resultCode: %d, isStartScan: %d", + channelId, scanChannel->scannerId, resultCode, isStartScan); + SoftBusMutexUnlock(&g_scannerLock); + if (scanChannel->scanCallback != NULL && scanChannel->scanCallback->OnScanStateChanged != NULL) { + scanChannel->scanCallback->OnScanStateChanged(resultCode, isStartScan); + } +} + +static void WrapperLpDeviceInfoCallback(uint8_t channelId, BtUuid *uuid, int32_t type, uint8_t *data, uint32_t dataSize) +{ + if (SoftBusMutexLock(&g_scannerLock) != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE_ADAPTER, "lock failed, scannerId: %u", channelId); + return; + } + ScanChannel *scanChannel = &g_scanChannel[channelId]; + if (!scanChannel->isUsed) { + DISC_LOGE(DISC_BLE_ADAPTER, "scanner is not in used, scannerId: %u, bt-scannerId: %d", + channelId, scanChannel->scannerId); + SoftBusMutexUnlock(&g_scannerLock); + return; + } + SoftBusMutexUnlock(&g_scannerLock); + if (scanChannel->scanCallback != NULL && scanChannel->scanCallback->OnLpDeviceInfoCallback != NULL) { + SoftbusBroadcastUuid bcUuid; + bcUuid.uuid = (uint8_t *)uuid->uuid; + bcUuid.uuidLen = (uint8_t)uuid->uuidLen; + scanChannel->scanCallback->OnLpDeviceInfoCallback(&bcUuid, type, data, dataSize); + } +} + +static void WrapperScanResultCallback0(BtScanResultData *data) +{ + WrapperScanResultCallback(SCAN_CHANNEL_0, data); +} + +static void WrapperScanResultCallback1(BtScanResultData *data) +{ + WrapperScanResultCallback(SCAN_CHANNEL_1, data); +} + +static void WrapperScanStateChangeCallback0(int32_t resultCode, bool isStartScan) +{ + WrapperScanStateChangeCallback(SCAN_CHANNEL_0, resultCode, isStartScan); +} + +static void WrapperScanStateChangeCallback1(int32_t resultCode, bool isStartScan) +{ + WrapperScanStateChangeCallback(SCAN_CHANNEL_1, resultCode, isStartScan); +} + +static void WrapperLpDeviceInfoCallback0(BtUuid *uuid, int32_t type, uint8_t *data, uint32_t dataSize) +{ + WrapperLpDeviceInfoCallback(SCAN_CHANNEL_0, uuid, type, data, dataSize); +} + +static void WrapperLpDeviceInfoCallback1(BtUuid *uuid, int32_t type, uint8_t *data, uint32_t dataSize) +{ + WrapperLpDeviceInfoCallback(SCAN_CHANNEL_1, uuid, type, data, dataSize); +} + +static BleScanCallbacks g_softbusBleScanCb[GATT_SCAN_MAX_NUM] = { + { + .scanResultCb = WrapperScanResultCallback0, + .scanStateChangeCb = WrapperScanStateChangeCallback0, + .lpDeviceInfoCb = WrapperLpDeviceInfoCallback0, + }, + { + .scanResultCb = WrapperScanResultCallback1, + .scanStateChangeCb = WrapperScanStateChangeCallback1, + .lpDeviceInfoCb = WrapperLpDeviceInfoCallback1, + } +}; + +static BleScanCallbacks *GetAdapterScanCallback(uint8_t channelId) +{ + return &g_softbusBleScanCb[channelId]; +} + +static int32_t RegisterScanCallback(int32_t *scannerId, const SoftbusScanCallback *cb) +{ + if (scannerId == NULL || cb == NULL) { + DISC_LOGE(DISC_BLE_ADAPTER, "scan param is null"); + return SOFTBUS_ERR; + } + if (SoftBusMutexLock(&g_scannerLock) != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE_ADAPTER, "lock failed"); + return SOFTBUS_LOCK_ERR; + } + for (uint8_t channelId = 0; channelId < GATT_SCAN_MAX_NUM; channelId++) { + if (g_scanChannel[channelId].isUsed) { + continue; + } + if (BleRegisterScanCallbacks(GetAdapterScanCallback(channelId), + &g_scanChannel[channelId].scannerId) != OHOS_BT_STATUS_SUCCESS) { + DISC_LOGE(DISC_BLE_ADAPTER, "register callback failed, scannerId: %u", channelId); + SoftBusMutexUnlock(&g_scannerLock); + return SOFTBUS_ERR; + } + g_scanChannel[channelId].isUsed = true; + g_scanChannel[channelId].isScanning = false; + g_scanChannel[channelId].scanCallback = (SoftbusScanCallback *)cb; + *scannerId = channelId; + DISC_LOGI(DISC_BLE_ADAPTER, "scannerId: %u, bt-scannerId: %d", channelId, g_scanChannel[channelId].scannerId); + SoftBusMutexUnlock(&g_scannerLock); + return SOFTBUS_OK; + } + DISC_LOGE(DISC_BLE_ADAPTER, "no available scan channel"); + SoftBusMutexUnlock(&g_scannerLock); + return SOFTBUS_ERR; +} + +static int32_t UnRegisterScanCallback(int32_t scannerId) +{ + if (scannerId < 0 || scannerId >= GATT_SCAN_MAX_NUM) { + DISC_LOGE(DISC_BLE_ADAPTER, "scannerId is invalid: %d", scannerId); + return SOFTBUS_INVALID_PARAM; + } + if (SoftBusMutexLock(&g_scannerLock) != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE_ADAPTER, "lock failed, scannerId: %u", scannerId); + return SOFTBUS_LOCK_ERR; + } + if (!g_scanChannel[scannerId].isUsed) { + DISC_LOGI(DISC_BLE_ADAPTER, "already unregistered, scannerId: %d, bt-scannerId: %d", + scannerId, g_scanChannel[scannerId].scannerId); + SoftBusMutexUnlock(&g_scannerLock); + return SOFTBUS_OK; + } + int32_t ret = BleDeregisterScanCallbacks(g_scanChannel[scannerId].scannerId); + DISC_LOGI(DISC_BLE_ADAPTER, "scannerId: %d, bt-scannerId: %d, result: %d", + scannerId, g_scanChannel[scannerId].scannerId, ret); + g_scanChannel[scannerId].scannerId = -1; + g_scanChannel[scannerId].isUsed = false; + g_scanChannel[scannerId].isScanning = false; + g_scanChannel[scannerId].scanCallback = NULL; + SoftBusMutexUnlock(&g_scannerLock); + return SOFTBUS_OK; +} + +static bool CheckAdvChannelInUsed(int32_t advId) +{ + if (advId < 0 || advId >= GATT_ADV_MAX_NUM) { + DISC_LOGE(DISC_BLE_ADAPTER, "invalid advId: %d", advId); + return false; + } + if (!g_advChannel[advId].isUsed) { + DISC_LOGE(DISC_BLE_ADAPTER, "advId: %d, bt-advId: %d", advId, g_advChannel[advId].advId); + return false; + } + return true; +} + +static int32_t StartBleAdv(int32_t advId, const SoftbusBroadcastParam *param, const SoftbusBroadcastData *data) +{ + BleAdvParams advParam = {}; + SoftbusAdvParamToBt(param, &advParam); + StartAdvRawData advRawData = {}; + advRawData.advData = (unsigned char *)AssembleAdvData(data, (uint16_t *)&advRawData.advDataLen); + if (advRawData.advData == NULL) { + DISC_LOGE(DISC_BLE_ADAPTER, "assemble adv data failed, advId: %d, bt-advId: %d", + advId, g_advChannel[advId].advId); + return SOFTBUS_ERR; + } + advRawData.rspDataLen = 0; + advRawData.rspData = NULL; + if (data->rspData.payloadLen > 0 && data->rspData.payload != NULL) { + advRawData.rspData = (unsigned char *)AssembleRspData(&data->rspData, (uint16_t *)&advRawData.rspDataLen); + if (advRawData.rspData == NULL) { + SoftBusFree(advRawData.advData); + DISC_LOGE(DISC_BLE_ADAPTER, "assemble rsp data failed, advId: %d, bt-advId: %d", + advId, g_advChannel[advId].advId); + return SOFTBUS_ERR; + } + } + DumpSoftbusAdapterData("mgr pkg:", advRawData.advData, advRawData.advDataLen); + int32_t ret = BleStartAdvEx(&g_advChannel[advId].advId, advRawData, advParam); + SoftBusFree(advRawData.advData); + SoftBusFree(advRawData.rspData); + return (ret == OHOS_BT_STATUS_SUCCESS) ? SOFTBUS_OK : SOFTBUS_ERR; +} + +static int32_t StartAdv(int32_t advId, const SoftbusBroadcastParam *param, const SoftbusBroadcastData *data) +{ + if (param == NULL || data == NULL || data->bcData.payloadLen == 0 || data->bcData.payload == NULL) { + DISC_LOGE(DISC_BLE_ADAPTER, "invalid adv param, advId: %d", advId); + return SOFTBUS_INVALID_PARAM; + } + if (SoftBusMutexLock(&g_advLock) != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE_ADAPTER, "lock failed, advId: %d", advId); + return SOFTBUS_LOCK_ERR; + } + if (!CheckAdvChannelInUsed(advId)) { + DISC_LOGE(DISC_BLE_ADAPTER, "adv is not in used, advId: %d", advId); + SoftBusMutexUnlock(&g_advLock); + return SOFTBUS_ERR; + } + if (g_advChannel[advId].isAdvertising) { + DISC_LOGE(DISC_BLE_ADAPTER, "already started, advId: %d, bt-advId: %d", advId, g_advChannel[advId].advId); + SoftBusMutexUnlock(&g_advLock); + return SOFTBUS_ERR; + } + int32_t ret = StartBleAdv(advId, param, data); + g_advChannel[advId].isAdvertising = (ret == SOFTBUS_OK); + DISC_LOGI(DISC_BLE_ADAPTER, "advId: %d, bt-advId: %d, ret: %d", advId, g_advChannel[advId].advId, ret); + SoftBusMutexUnlock(&g_advLock); + if (ret != SOFTBUS_OK) { + return SOFTBUS_ERR; + } + return SOFTBUS_OK; +} + +static int32_t StopAdv(int32_t advId) +{ + if (SoftBusMutexLock(&g_advLock) != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE_ADAPTER, "lock adv failed, advId: %d", advId); + return SOFTBUS_LOCK_ERR; + } + if (!CheckAdvChannelInUsed(advId)) { + DISC_LOGE(DISC_BLE_ADAPTER, "adv is not in used, advId: %d", advId); + SoftBusMutexUnlock(&g_advLock); + return SOFTBUS_ERR; + } + if (!g_advChannel[advId].isAdvertising) { + DISC_LOGI(DISC_BLE_ADAPTER, "already stopped, advId: %d, bt-advId: %d", advId, g_advChannel[advId].advId); + SoftBusMutexUnlock(&g_advLock); + return SOFTBUS_OK; + } + int32_t ret = BleStopAdv(g_advChannel[advId].advId); + DISC_LOGI(DISC_BLE_ADAPTER, "advId: %d, bt-advId: %d, ret: %d", advId, g_advChannel[advId].advId, ret); + g_advChannel[advId].isAdvertising = false; + SoftBusMutexUnlock(&g_advLock); + if (ret != OHOS_BT_STATUS_SUCCESS) { + return SOFTBUS_ERR; + } + return SOFTBUS_OK; +} + +static int32_t SetAdvData(int32_t advId, const SoftbusBroadcastData *data) +{ + if (data == NULL) { + DISC_LOGE(DISC_BLE_ADAPTER, "data is null, advId: %d", advId); + return SOFTBUS_INVALID_PARAM; + } + if (SoftBusMutexLock(&g_advLock) != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE_ADAPTER, "lock adv failed, advId: %d", advId); + return SOFTBUS_LOCK_ERR; + } + if (!CheckAdvChannelInUsed(advId)) { + DISC_LOGE(DISC_BLE_ADAPTER, "adv is not in used, advId: %d", advId); + SoftBusMutexUnlock(&g_advLock); + return SOFTBUS_ERR; + } + if (!g_advChannel[advId].isAdvertising) { + DISC_LOGE(DISC_BLE_ADAPTER, "adv is not advertising, advId: %d, bt-advId: %d", + advId, g_advChannel[advId].advId); + SoftBusMutexUnlock(&g_advLock); + return SOFTBUS_ERR; + } + StartAdvRawData advRawData = {}; + advRawData.advData = (unsigned char *)AssembleAdvData(data, (uint16_t *)&advRawData.advDataLen); + if (advRawData.advData == NULL) { + DISC_LOGE(DISC_BLE_ADAPTER, "assemble adv data failed, advId: %d, bt-advId: %d", + advId, g_advChannel[advId].advId); + SoftBusMutexUnlock(&g_advLock); + return SOFTBUS_ERR; + } + advRawData.rspDataLen = 0; + advRawData.rspData = NULL; + if (data->rspData.payloadLen > 0 && data->rspData.payload != NULL) { + advRawData.rspData = (unsigned char *)AssembleRspData(&data->rspData, (uint16_t *)&advRawData.rspDataLen); + if (advRawData.rspData == NULL) { + SoftBusFree(advRawData.advData); + DISC_LOGE(DISC_BLE_ADAPTER, "assemble rsp data failed, advId: %d, bt-advId: %d", + advId, g_advChannel[advId].advId); + SoftBusMutexUnlock(&g_advLock); + return SOFTBUS_ERR; + } + } + int32_t ret = BtStatusToSoftBus(BleSetAdvData(g_advChannel[advId].advId, advRawData)); + DISC_LOGI(DISC_BLE_ADAPTER, "advId: %d, bt-advId: %d, ret: %d", advId, g_advChannel[advId].advId, ret); + SoftBusFree(advRawData.advData); + SoftBusFree(advRawData.rspData); + SoftBusMutexUnlock(&g_advLock); + return ret; +} + +static int32_t UpdateAdvData(int32_t advId, const SoftbusBroadcastParam *param, const SoftbusBroadcastData *data) +{ + if (StopAdv(advId) != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE_ADAPTER, "update adv data failed, advId: %d", advId); + return SOFTBUS_ERR; + } + DISC_LOGI(DISC_BLE_ADAPTER, "update adv data, advId: %d", advId); + return StartAdv(advId, param, data); +} + +static bool CheckScanChannelInUsed(int32_t scannerId) +{ + if (scannerId < 0 || scannerId >= GATT_SCAN_MAX_NUM) { + DISC_LOGE(DISC_BLE_ADAPTER, "invalid scannerId: %d", scannerId); + return false; + } + if (!g_scanChannel[scannerId].isUsed) { + DISC_LOGE(DISC_BLE_ADAPTER, "scannerId: %d, bt-scannerId: %d", scannerId, g_scanChannel[scannerId].scannerId); + return false; + } + return true; +} + +static int32_t StartScan(int32_t scannerId, const SoftBusBcScanParams *param, const SoftBusBcScanFilter *scanFilter, + int32_t filterSize) +{ + if (param == NULL || scanFilter == NULL || filterSize <= 0) { + DISC_LOGE(DISC_BLE_ADAPTER, "invalid param, scannerId: %d", scannerId); + return SOFTBUS_INVALID_PARAM; + } + if (SoftBusMutexLock(&g_scannerLock) != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE_ADAPTER, "lock failed, scannerId: %d", scannerId); + return SOFTBUS_LOCK_ERR; + } + if (!CheckScanChannelInUsed(scannerId)) { + DISC_LOGE(DISC_BLE_ADAPTER, "scanner is not in used, scannerId: %d", scannerId); + SoftBusMutexUnlock(&g_scannerLock); + return SOFTBUS_ERR; + } + if (g_scanChannel[scannerId].isScanning) { + DISC_LOGE(DISC_BLE_ADAPTER, "already scanning, scannerId: %d, bt-scannerId: %d", + scannerId, g_scanChannel[scannerId].scannerId); + SoftBusMutexUnlock(&g_scannerLock); + return SOFTBUS_ERR; + } + BleScanNativeFilter *nativeFilter = + (BleScanNativeFilter *)SoftBusCalloc(sizeof(BleScanNativeFilter) * filterSize); + if (nativeFilter == NULL) { + DISC_LOGE(DISC_BLE_ADAPTER, "malloc native filter failed, scannerId: %d, bt-scannerId: %d", + scannerId, g_scanChannel[scannerId].scannerId); + SoftBusMutexUnlock(&g_scannerLock); + return SOFTBUS_MALLOC_ERR; + } + SoftbusFilterToBt(nativeFilter, scanFilter, filterSize); + DumpBleScanFilter(nativeFilter, filterSize); + BleScanConfigs scanConfig = {}; + scanConfig.scanMode = GetBtScanMode(param->scanInterval, param->scanWindow); + scanConfig.phy = (int)param->scanPhy; + int32_t ret = BleStartScanEx(g_scanChannel[scannerId].scannerId, &scanConfig, nativeFilter, (uint32_t)filterSize); + g_scanChannel[scannerId].isScanning = (ret == OHOS_BT_STATUS_SUCCESS); + DISC_LOGI(DISC_BLE_ADAPTER, "scannerId: %d, bt-scannerId: %d, ret: %d", + scannerId, g_scanChannel[scannerId].scannerId, ret); + FreeBtFilter(nativeFilter, filterSize); + SoftBusMutexUnlock(&g_scannerLock); + if (ret != OHOS_BT_STATUS_SUCCESS) { + return SOFTBUS_ERR; + } + return SOFTBUS_OK; +} + +static int32_t StopScan(int32_t scannerId) +{ + if (SoftBusMutexLock(&g_scannerLock) != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE_ADAPTER, "lock failed, scannerId: %d", scannerId); + return SOFTBUS_LOCK_ERR; + } + if (!CheckScanChannelInUsed(scannerId)) { + DISC_LOGE(DISC_BLE_ADAPTER, "scanner is not in used: %d", scannerId); + SoftBusMutexUnlock(&g_scannerLock); + return SOFTBUS_ERR; + } + if (!g_scanChannel[scannerId].isScanning) { + DISC_LOGI(DISC_BLE_ADAPTER, "already stopped, scannerId: %d, bt-scannerId: %d", + scannerId, g_scanChannel[scannerId].scannerId); + SoftBusMutexUnlock(&g_scannerLock); + return SOFTBUS_OK; + } + int32_t ret = BleStopScan(g_scanChannel[scannerId].scannerId); + DISC_LOGI(DISC_BLE_ADAPTER, "stop scan, scannerId: %d, bt-scannerId: %d, ret: %d", + scannerId, g_scanChannel[scannerId].scannerId, ret); + g_scanChannel[scannerId].isScanning = false; + SoftBusMutexUnlock(&g_scannerLock); + if (ret != OHOS_BT_STATUS_SUCCESS) { + return SOFTBUS_ERR; + } + return SOFTBUS_OK; +} + +static bool IsLpAvailable(void) +{ + DISC_LOGI(DISC_BLE_ADAPTER, "is lp available"); + return IsLpDeviceAvailable(); +} + +static bool SetLpParam(const SoftBusLpBroadcastParam *bcParam, const SoftBusLpScanParam *scanParam) +{ + BleScanConfigs scanConfig = {}; + scanConfig.scanMode = GetBtScanMode(scanParam->scanParam.scanInterval, scanParam->scanParam.scanWindow); + BtLpDeviceParam lpParam = {}; + lpParam.scanConfig = &scanConfig; + lpParam.rawData.advData = (unsigned char *)AssembleAdvData(&bcParam->advData, + (uint16_t *)&lpParam.rawData.advDataLen); + if (lpParam.rawData.advData == NULL) { + DISC_LOGE(DISC_BLE_ADAPTER, "assemble adv data failed, advHandle: %d", bcParam->advHandle); + return SOFTBUS_ERR; + } + if (bcParam->advData.rspData.payloadLen > 0 && bcParam->advData.rspData.payload != NULL) { + lpParam.rawData.rspData = (unsigned char *)AssembleRspData(&bcParam->advData.rspData, + (uint16_t *)&lpParam.rawData.rspDataLen); + if (lpParam.rawData.rspData == NULL) { + SoftBusFree(lpParam.rawData.advData); + DISC_LOGE(DISC_BLE_ADAPTER, "assemble rsp data failed, advHandle: %d", bcParam->advHandle); + return SOFTBUS_ERR; + } + } + lpParam.filter = (BleScanNativeFilter *)SoftBusCalloc(sizeof(BleScanNativeFilter) * scanParam->filterSize); + if (lpParam.filter == NULL) { + SoftBusFree(lpParam.rawData.advData); + SoftBusFree(lpParam.rawData.rspData); + DISC_LOGE(DISC_BLE_ADAPTER, "malloc native filter failed, advHandle: %d", bcParam->advHandle); + return SOFTBUS_MALLOC_ERR; + } + SoftbusFilterToBt(lpParam.filter, scanParam->filter, scanParam->filterSize); + lpParam.filterSize = (unsigned int)scanParam->filterSize; + SoftbusAdvParamToBt(&bcParam->advParam, &lpParam.advParam); + BtUuid btUuid = {}; + btUuid.uuid = LP_BT_UUID; + btUuid.uuidLen = (unsigned char)strlen(LP_BT_UUID); + lpParam.uuid = btUuid; + lpParam.activeDeviceInfo = NULL; + lpParam.activeDeviceSize = 0; + lpParam.deliveryMode = LP_DELIVERY_MODE_REPLY; + lpParam.advHandle = bcParam->advHandle; + lpParam.duration = LP_ADV_DURATION_MS; + int32_t ret = SetLpDeviceParam(&lpParam); + FreeBtFilter(lpParam.filter, scanParam->filterSize); + SoftBusFree(lpParam.rawData.advData); + SoftBusFree(lpParam.rawData.rspData); + DISC_LOGI(DISC_BLE_ADAPTER, "advHandle: %d, ret: %d", bcParam->advHandle, ret); + return (ret == OHOS_BT_STATUS_SUCCESS) ? true : false; +} + +static int32_t GetBroadcastHandle(int32_t advId, int32_t *bcHandle) +{ + if (SoftBusMutexLock(&g_advLock) != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE_ADAPTER, "lock adv failed, advId: %d", advId); + return SOFTBUS_LOCK_ERR; + } + if (!CheckAdvChannelInUsed(advId)) { + DISC_LOGE(DISC_BLE_ADAPTER, "adv is not in used: %d", advId); + SoftBusMutexUnlock(&g_advLock); + return SOFTBUS_ERR; + } + int32_t ret = GetAdvHandle(g_advChannel[advId].advId, bcHandle); + DISC_LOGI(DISC_BLE_ADAPTER, "advId: %d, bt-advId: %d, ret: %d", advId, g_advChannel[advId].advId, ret); + SoftBusMutexUnlock(&g_advLock); + return ret; +} + +static int32_t EnableSyncDataToLp(void) +{ + DISC_LOGI(DISC_BLE_ADAPTER, "enable sync data to lp"); + return EnableSyncDataToLpDevice(); +} + +static int32_t DisableSyncDataToLp(void) +{ + DISC_LOGI(DISC_BLE_ADAPTER, "disable sync data to lp"); + return DisableSyncDataToLpDevice(); +} + +static int32_t SetScanReportChannelToLp(int32_t scannerId, bool enable) +{ + if (SoftBusMutexLock(&g_scannerLock) != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE_ADAPTER, "lock failed, scannerId: %d", scannerId); + return SOFTBUS_LOCK_ERR; + } + if (!CheckScanChannelInUsed(scannerId)) { + DISC_LOGE(DISC_BLE_ADAPTER, "scanner is not in used: %d", scannerId); + SoftBusMutexUnlock(&g_scannerLock); + return SOFTBUS_ERR; + } + int32_t ret = SetScanReportChannelToLpDevice(g_scanChannel[scannerId].scannerId, enable); + DISC_LOGI(DISC_BLE_ADAPTER, "scannerId: %d, bt-scannerId: %d, ret: %d", + scannerId, g_scanChannel[scannerId].scannerId, ret); + SoftBusMutexUnlock(&g_scannerLock); + return ret; +} + +static int32_t SetLpAdvParam(int32_t duration, int32_t maxExtAdvEvents, int32_t window, + int32_t interval, int32_t bcHandle) +{ + DISC_LOGI(DISC_BLE_ADAPTER, "advHandle: %d", bcHandle); + return SetLpDeviceAdvParam(duration, maxExtAdvEvents, window, interval, bcHandle); +} + +void SoftbusBleAdapterInit(void) +{ + DISC_LOGI(DISC_BLE_ADAPTER, "SoftbusBleAdapterInit"); + static SoftbusBroadcastMediumInterface interface = { + .Init = Init, + .DeInit = DeInit, + .RegisterBroadcaster = RegisterAdvCallback, + .UnRegisterBroadcaster = UnRegisterAdvCallback, + .RegisterScanListener = RegisterScanCallback, + .UnRegisterScanListener = UnRegisterScanCallback, + .StartBroadcasting = StartAdv, + .StopBroadcasting = StopAdv, + .SetBroadcastingData = SetAdvData, + .UpdateBroadcasting = UpdateAdvData, + .StartScan = StartScan, + .StopScan = StopScan, + .IsLpDeviceAvailable = IsLpAvailable, + .SetAdvFilterParam = SetLpParam, + .GetBroadcastHandle = GetBroadcastHandle, + .EnableSyncDataToLpDevice = EnableSyncDataToLp, + .DisableSyncDataToLpDevice = DisableSyncDataToLp, + .SetScanReportChannelToLpDevice = SetScanReportChannelToLp, + .SetLpDeviceParam = SetLpAdvParam, + }; + if (RegisterBroadcastMediumFunction(BROADCAST_MEDIUM_TYPE_BLE, &interface) != 0) { + DISC_LOGE(DISC_BLE_ADAPTER, "Register gatt interface failed."); + } +} \ No newline at end of file diff --git a/adapter/common/net/bluetooth/broadcast/adapter/ble/src/softbus_ble_utils.c b/adapter/common/net/bluetooth/broadcast/adapter/ble/src/softbus_ble_utils.c new file mode 100644 index 000000000..565c1896f --- /dev/null +++ b/adapter/common/net/bluetooth/broadcast/adapter/ble/src/softbus_ble_utils.c @@ -0,0 +1,475 @@ +/* + * Copyright (c) 2023 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 "softbus_ble_utils.h" +#include "softbus_adapter_mem.h" +#include "softbus_broadcast_type.h" +#include "softbus_error_code.h" +#include "softbus_utils.h" +#include "softbus_broadcast_utils.h" +#include "disc_log.h" +#include + +#define UUID_LEN 2 +#define UUID_MASK_LEN 2 +#define ID_LEN 2 + +int32_t BtStatusToSoftBus(BtStatus btStatus) +{ + switch (btStatus) { + case OHOS_BT_STATUS_SUCCESS: + return SOFTBUS_BC_STATUS_SUCCESS; + case OHOS_BT_STATUS_FAIL: + return SOFTBUS_BC_STATUS_FAIL; + case OHOS_BT_STATUS_NOT_READY: + return SOFTBUS_BC_STATUS_NOT_READY; + case OHOS_BT_STATUS_NOMEM: + return SOFTBUS_BC_STATUS_NOMEM; + case OHOS_BT_STATUS_BUSY: + return SOFTBUS_BC_STATUS_BUSY; + case OHOS_BT_STATUS_DONE: + return SOFTBUS_BC_STATUS_DONE; + case OHOS_BT_STATUS_UNSUPPORTED: + return SOFTBUS_BC_STATUS_UNSUPPORTED; + case OHOS_BT_STATUS_PARM_INVALID: + return SOFTBUS_BC_STATUS_PARM_INVALID; + case OHOS_BT_STATUS_UNHANDLED: + return SOFTBUS_BC_STATUS_UNHANDLED; + case OHOS_BT_STATUS_AUTH_FAILURE: + return SOFTBUS_BC_STATUS_AUTH_FAILURE; + case OHOS_BT_STATUS_RMT_DEV_DOWN: + return SOFTBUS_BC_STATUS_RMT_DEV_DOWN; + case OHOS_BT_STATUS_AUTH_REJECTED: + return SOFTBUS_BC_STATUS_AUTH_REJECTED; + default: + return SOFTBUS_BC_STATUS_FAIL; + } +} + +static uint16_t SoftbusAdvDataTypeToBt(uint16_t advType) +{ + switch (advType) { + case BC_DATA_TYPE_SERVICE: + return SERVICE_BC_TYPE; + case BC_DATA_TYPE_MANUFACTURER: + return MANUFACTURE_BC_TYPE; + default: + return 0x00; + } +} + +static uint16_t BtAdvTypeToSoftbus(uint16_t advType) +{ + switch (advType) { + case SERVICE_BC_TYPE: + return BC_DATA_TYPE_SERVICE; + case MANUFACTURE_BC_TYPE: + return BC_DATA_TYPE_MANUFACTURER; + default: + return 0x00; + } +} + +static BleAdvFilter SoftbusAdvFilterToBt(uint8_t advFilter) +{ + switch (advFilter) { + case SOFTBUS_BC_ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY: + return OHOS_BLE_ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY; + case SOFTBUS_BC_ADV_FILTER_ALLOW_SCAN_WLST_CON_ANY: + return OHOS_BLE_ADV_FILTER_ALLOW_SCAN_WLST_CON_ANY; + case SOFTBUS_BC_ADV_FILTER_ALLOW_SCAN_ANY_CON_WLST: + return OHOS_BLE_ADV_FILTER_ALLOW_SCAN_ANY_CON_WLST; + case SOFTBUS_BC_ADV_FILTER_ALLOW_SCAN_WLST_CON_WLST: + return OHOS_BLE_ADV_FILTER_ALLOW_SCAN_WLST_CON_WLST; + default: + return OHOS_BLE_ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY; + } +} + +static BleAdvType SoftbusAdvTypeToBt(uint8_t advType) +{ + switch (advType) { + case SOFTBUS_BC_ADV_IND: + return OHOS_BLE_ADV_IND; + case SOFTBUS_BC_ADV_DIRECT_IND_HIGH: + return OHOS_BLE_ADV_DIRECT_IND_HIGH; + case SOFTBUS_BC_ADV_SCAN_IND: + return OHOS_BLE_ADV_SCAN_IND; + case SOFTBUS_BC_ADV_NONCONN_IND: + return OHOS_BLE_ADV_NONCONN_IND; + case SOFTBUS_BC_ADV_DIRECT_IND_LOW: + return OHOS_BLE_ADV_DIRECT_IND_LOW; + default: + return OHOS_BLE_ADV_IND; + } +} + +void SoftbusAdvParamToBt(const SoftbusBroadcastParam *src, BleAdvParams *dst) +{ + if (memcpy_s(dst->peerAddr.addr, SOFTBUS_ADDR_MAC_LEN, src->peerAddr.addr, SOFTBUS_ADDR_MAC_LEN) != EOK) { + DISC_LOGW(DISC_BLE_ADAPTER, "copy peer addr failed"); + } + dst->minInterval = src->minInterval; + dst->maxInterval = src->maxInterval; + dst->advType = SoftbusAdvTypeToBt(src->advType); + dst->ownAddrType = (unsigned char)src->ownAddrType; + dst->peerAddrType = (unsigned char)src->peerAddrType; + dst->channelMap = src->channelMap; + dst->advFilterPolicy = SoftbusAdvFilterToBt(src->advFilterPolicy); + dst->txPower = src->txPower; + dst->duration = src->duration; +} + +static uint8_t BtScanEventTypeToSoftbus(unsigned char eventType) +{ + switch (eventType) { + case OHOS_BLE_EVT_NON_CONNECTABLE_NON_SCANNABLE: + return SOFTBUS_BC_EVT_NON_CONNECTABLE_NON_SCANNABLE; + case OHOS_BLE_EVT_NON_CONNECTABLE_NON_SCANNABLE_DIRECTED: + return SOFTBUS_BC_EVT_NON_CONNECTABLE_NON_SCANNABLE_DIRECTED; + case OHOS_BLE_EVT_CONNECTABLE: + return SOFTBUS_BC_EVT_CONNECTABLE; + case OHOS_BLE_EVT_CONNECTABLE_DIRECTED: + return SOFTBUS_BC_EVT_CONNECTABLE_DIRECTED; + case OHOS_BLE_EVT_SCANNABLE: + return SOFTBUS_BC_EVT_SCANNABLE; + case OHOS_BLE_EVT_SCANNABLE_DIRECTED: + return SOFTBUS_BC_EVT_SCANNABLE_DIRECTED; + case OHOS_BLE_EVT_LEGACY_NON_CONNECTABLE: + return SOFTBUS_BC_EVT_LEGACY_NON_CONNECTABLE; + case OHOS_BLE_EVT_LEGACY_SCANNABLE: + return SOFTBUS_BC_EVT_LEGACY_SCANNABLE; + case OHOS_BLE_EVT_LEGACY_CONNECTABLE: + return SOFTBUS_BC_EVT_LEGACY_CONNECTABLE; + case OHOS_BLE_EVT_LEGACY_CONNECTABLE_DIRECTED: + return SOFTBUS_BC_EVT_LEGACY_CONNECTABLE_DIRECTED; + case OHOS_BLE_EVT_LEGACY_SCAN_RSP_TO_ADV_SCAN: + return SOFTBUS_BC_EVT_LEGACY_SCAN_RSP_TO_ADV_SCAN; + case OHOS_BLE_EVT_LEGACY_SCAN_RSP_TO_ADV: + return SOFTBUS_BC_EVT_LEGACY_SCAN_RSP_TO_ADV; + default: + return SOFTBUS_BC_EVT_NON_CONNECTABLE_NON_SCANNABLE; + } +} + +static uint8_t BtScanDataStatusToSoftbus(unsigned char dataStatus) +{ + switch (dataStatus) { + case OHOS_BLE_DATA_COMPLETE: + return SOFTBUS_BC_DATA_COMPLETE; + case OHOS_BLE_DATA_INCOMPLETE_MORE_TO_COME: + return SOFTBUS_BC_DATA_INCOMPLETE_MORE_TO_COME; + case OHOS_BLE_DATA_INCOMPLETE_TRUNCATED: + return SOFTBUS_BC_DATA_INCOMPLETE_TRUNCATED; + default: + return SOFTBUS_BC_DATA_INCOMPLETE_TRUNCATED; + } +} + +static uint8_t BtScanAddrTypeToSoftbus(unsigned char addrType) +{ + switch (addrType) { + case OHOS_BLE_PUBLIC_DEVICE_ADDRESS: + return SOFTBUS_BC_PUBLIC_DEVICE_ADDRESS; + case OHOS_BLE_RANDOM_DEVICE_ADDRESS: + return SOFTBUS_BC_RANDOM_DEVICE_ADDRESS; + case OHOS_BLE_PUBLIC_IDENTITY_ADDRESS: + return SOFTBUS_BC_PUBLIC_IDENTITY_ADDRESS; + case OHOS_BLE_RANDOM_STATIC_IDENTITY_ADDRESS: + return SOFTBUS_BC_RANDOM_STATIC_IDENTITY_ADDRESS; + case OHOS_BLE_UNRESOLVABLE_RANDOM_DEVICE_ADDRESS: + return SOFTBUS_BC_UNRESOLVABLE_RANDOM_DEVICE_ADDRESS; + case OHOS_BLE_NO_ADDRESS: + return SOFTBUS_BC_NO_ADDRESS; + default: + return SOFTBUS_BC_NO_ADDRESS; + } +} + +static uint8_t BtScanPhyTypeToSoftbus(unsigned char phyType) +{ + switch (phyType) { + case OHOS_BLE_SCAN_PHY_NO_PACKET: + return SOFTBUS_BC_SCAN_PHY_NO_PACKET; + case OHOS_BLE_SCAN_PHY_1M: + return SOFTBUS_BC_SCAN_PHY_1M; + case OHOS_BLE_SCAN_PHY_2M: + return SOFTBUS_BC_SCAN_PHY_2M; + case OHOS_BLE_SCAN_PHY_CODED: + return SOFTBUS_BC_SCAN_PHY_CODED; + default: + return SOFTBUS_BC_SCAN_PHY_NO_PACKET; + } +} + +void BtScanResultToSoftbus(const BtScanResultData *src, SoftBusBcScanResult *dst) +{ + dst->eventType = BtScanEventTypeToSoftbus(src->eventType); + dst->dataStatus = BtScanDataStatusToSoftbus(src->dataStatus); + dst->addrType = BtScanAddrTypeToSoftbus(src->addrType); + if (memcpy_s(dst->addr.addr, SOFTBUS_ADDR_MAC_LEN, src->addr.addr, SOFTBUS_ADDR_MAC_LEN) != EOK) { + DISC_LOGW(DISC_BLE_ADAPTER, "copy addr failed"); + } + dst->primaryPhy = BtScanPhyTypeToSoftbus(src->primaryPhy); + dst->secondaryPhy = BtScanPhyTypeToSoftbus(src->secondaryPhy); + dst->advSid = (uint8_t)src->advSid; + dst->txPower = (int8_t)src->txPower; + dst->rssi = (int8_t)src->rssi; +} + +void SoftbusFilterToBt(BleScanNativeFilter *nativeFilter, const SoftBusBcScanFilter *filter, uint8_t filterSize) +{ + while (filterSize-- > 0) { + (nativeFilter + filterSize)->address = (char *)(filter + filterSize)->address; + (nativeFilter + filterSize)->deviceName = (char *)(filter + filterSize)->deviceName; + (nativeFilter + filterSize)->manufactureData = (unsigned char *)(filter + filterSize)->manufactureData; + (nativeFilter + filterSize)->manufactureDataLength = + (unsigned int)(filter + filterSize)->manufactureDataLength; + (nativeFilter + filterSize)->manufactureDataMask = (unsigned char *)(filter + filterSize)->manufactureDataMask; + (nativeFilter + filterSize)->manufactureId = (unsigned short)(filter + filterSize)->manufactureId; + + if ((filter + filterSize)->serviceData == NULL || (filter + filterSize)->serviceDataMask == NULL) { + continue; + } + + // serviceData = uuid + serviceData, serviceDataMask = 0xFFFF + serviceDataMask + uint16_t serviceUuid = (filter + filterSize)->serviceUuid; + uint16_t serviceDataLen = (filter + filterSize)->serviceDataLength + 2; + uint8_t *serviceData = (uint8_t *)SoftBusCalloc(serviceDataLen); + if (serviceData == NULL) { + DISC_LOGW(DISC_BLE_ADAPTER, "malloc service data failed"); + continue; + } + serviceData[0] = serviceUuid & BC_BYTE_MASK; + serviceData[1] = (serviceUuid >> BC_SHIFT_BIT) & BC_BYTE_MASK; + if (memcpy_s(serviceData + UUID_LEN, serviceDataLen - UUID_LEN, (filter + filterSize)->serviceData, + serviceDataLen - UUID_LEN) != EOK) { + DISC_LOGW(DISC_BLE_ADAPTER, "copy service data failed"); + } + uint8_t *serviceDataMask = (uint8_t *)SoftBusCalloc(serviceDataLen); + if (serviceDataMask == NULL) { + SoftBusFree(serviceData); + DISC_LOGW(DISC_BLE_ADAPTER, "malloc service data mask failed"); + continue; + } + serviceDataMask[0] = BC_BYTE_MASK; + serviceDataMask[1] = BC_BYTE_MASK; + if (memcpy_s(serviceDataMask + UUID_MASK_LEN, serviceDataLen - UUID_MASK_LEN, + (filter + filterSize)->serviceDataMask, serviceDataLen - UUID_MASK_LEN) != EOK) { + DISC_LOGW(DISC_BLE_ADAPTER, "copy service data mask failed"); + } + (nativeFilter + filterSize)->serviceData = (unsigned char *)serviceData; + (nativeFilter + filterSize)->serviceDataLength = (unsigned int)serviceDataLen; + (nativeFilter + filterSize)->serviceDataMask = (unsigned char *)serviceDataMask; + } +} + +void FreeBtFilter(BleScanNativeFilter *nativeFilter, int32_t filterSize) +{ + while (filterSize-- > 0) { + SoftBusFree((nativeFilter + filterSize)->serviceData); + SoftBusFree((nativeFilter + filterSize)->serviceDataMask); + } + SoftBusFree(nativeFilter); +} + +void DumpBleScanFilter(BleScanNativeFilter *nativeFilter, int32_t filterSize) +{ + while (filterSize-- > 0) { + uint32_t len = (nativeFilter + filterSize)->serviceDataLength; + if (len == 0) { + continue; + } + uint32_t hexLen = HEXIFY_LEN(len); + char *serviceData = (char *)SoftBusCalloc(sizeof(char) * hexLen); + if (serviceData == NULL) { + continue; + } + char *serviceDataMask = (char *)SoftBusCalloc(sizeof(char) * hexLen); + if (serviceDataMask == NULL) { + SoftBusFree(serviceData); + continue; + } + (void)ConvertBytesToHexString(serviceData, hexLen, (nativeFilter + filterSize)->serviceData, len); + (void)ConvertBytesToHexString(serviceDataMask, hexLen, (nativeFilter + filterSize)->serviceDataMask, len); + DISC_LOGI(DISC_BLE_ADAPTER, "BLE Scan Filter size:%d [serviceData:%s, serviceDataMask:%s]", + filterSize, serviceData, serviceDataMask); + SoftBusFree(serviceData); + SoftBusFree(serviceDataMask); + } +} + +int GetBtScanMode(uint16_t scanInterval, uint16_t scanWindow) +{ + if (scanInterval == SOFTBUS_BC_SCAN_INTERVAL_P2 && scanWindow == SOFTBUS_BC_SCAN_WINDOW_P2) { + return OHOS_BLE_SCAN_MODE_OP_P2_60_3000; + } + if (scanInterval == SOFTBUS_BC_SCAN_INTERVAL_P10 && scanWindow == SOFTBUS_BC_SCAN_WINDOW_P10) { + return OHOS_BLE_SCAN_MODE_OP_P10_60_600; + } + if (scanInterval == SOFTBUS_BC_SCAN_INTERVAL_P25 && scanWindow == SOFTBUS_BC_SCAN_WINDOW_P25) { + return OHOS_BLE_SCAN_MODE_OP_P25_60_240; + } + if (scanInterval == SOFTBUS_BC_SCAN_INTERVAL_P100 && scanWindow == SOFTBUS_BC_SCAN_WINDOW_P100) { + return OHOS_BLE_SCAN_MODE_OP_P100_1000_1000; + } + return OHOS_BLE_SCAN_MODE_LOW_POWER; +} + +uint8_t *AssembleAdvData(const SoftbusBroadcastData *data, uint16_t *dataLen) +{ + uint16_t payloadLen = (data->bcData.payloadLen > BC_DATA_MAX_LEN) ? BC_DATA_MAX_LEN : data->bcData.payloadLen; + uint16_t len = data->isSupportFlag ? payloadLen + BC_HEAD_LEN : payloadLen + BC_HEAD_LEN - BC_FLAG_LEN; + uint8_t *advData = (uint8_t *)SoftBusCalloc(len); + if (advData == NULL) { + DISC_LOGE(DISC_BLE_ADAPTER, "malloc adv data failed"); + return NULL; + } + int8_t offset = -BC_FLAG_LEN; + if (data->isSupportFlag) { + advData[IDX_BC_FLAG_BYTE_LEN] = BC_FLAG_BYTE_LEN; + advData[IDX_BC_FLAG_AD_TYPE] = BC_FLAG_AD_TYPE; + advData[IDX_BC_FLAG_AD_DATA] = data->flag; + offset += BC_FLAG_LEN; + } + advData[IDX_PACKET_LEN + offset] = payloadLen + BC_HEAD_LEN - BC_FLAG_LEN - 1; + advData[IDX_BC_TYPE + offset] = SoftbusAdvDataTypeToBt(data->bcData.type); + uint16_t payloadId = data->bcData.id; + advData[IDX_BC_UUID + offset] = (uint8_t)(payloadId & BC_BYTE_MASK); + advData[IDX_BC_UUID + offset + 1] = (uint8_t)((payloadId >> BC_SHIFT_BIT) & BC_BYTE_MASK); + + if (memcpy_s(&advData[BC_HEAD_LEN + offset], payloadLen, data->bcData.payload, payloadLen) != EOK) { + DISC_LOGE(DISC_BLE_ADAPTER, "copy adv payload failed"); + SoftBusFree(advData); + return NULL; + } + *dataLen = len; + return advData; +} + +uint8_t *AssembleRspData(const SoftbusBroadcastPayload *data, uint16_t *dataLen) +{ + uint16_t payloadLen = (data->payloadLen > RSP_DATA_MAX_LEN) ? RSP_DATA_MAX_LEN : data->payloadLen; + uint16_t len = payloadLen + RSP_HEAD_LEN; + uint8_t *rspData = (uint8_t *)SoftBusCalloc(len); + if (rspData == NULL) { + DISC_LOGE(DISC_BLE_ADAPTER, "malloc rsp data failed"); + return NULL; + } + rspData[IDX_RSP_PACKET_LEN] = payloadLen + RSP_HEAD_LEN - 1; + rspData[IDX_RSP_TYPE] = SoftbusAdvDataTypeToBt(data->type); + uint16_t payloadId = data->id; + rspData[IDX_RSP_UUID] = (uint8_t)(payloadId & BC_BYTE_MASK); + rspData[IDX_RSP_UUID + 1] = (uint8_t)((payloadId >> BC_SHIFT_BIT) & BC_BYTE_MASK); + + if (memcpy_s(&rspData[RSP_HEAD_LEN], payloadLen, data->payload, payloadLen) != EOK) { + DISC_LOGE(DISC_BLE_ADAPTER, "copy rsp payload failed"); + SoftBusFree(rspData); + return NULL; + } + *dataLen = len; + return rspData; +} + +static int32_t ParseFlag(const uint8_t *advData, uint8_t advLen, SoftBusBcScanResult *dst, uint8_t index) +{ + if (index + 1 >= advLen) { + DISC_LOGE(DISC_BLE_ADAPTER, "parse flag failed"); + return SOFTBUS_ERR; + } + dst->data.flag = advData[index + 1]; + dst->data.isSupportFlag = true; + return SOFTBUS_OK; +} + +static int32_t ParseLocalName(const uint8_t *advData, uint8_t advLen, SoftBusBcScanResult *dst, uint8_t index, + uint8_t len) +{ + if (index + 1 >= advLen) { + DISC_LOGE(DISC_BLE_ADAPTER, "parse local name failed"); + return SOFTBUS_ERR; + } + if (memcpy_s(dst->localName, sizeof(dst->localName), &advData[index + 1], len - 1) != EOK) { + DISC_LOGE(DISC_BLE_ADAPTER, "copy local name failed"); + return SOFTBUS_ERR; + } + return SOFTBUS_OK; +} + +int32_t ParseScanResult(const uint8_t *advData, uint8_t advLen, SoftBusBcScanResult *dst) +{ + uint8_t index = 0; + bool isRsp = false; + while (index < advLen) { + uint8_t len = advData[index]; + if (len == 0) { + index++; + continue; + } + if (index + len >= advLen || index + 1 >= advLen) { + break; + } + uint8_t type = advData[++index]; + if (type == BC_FLAG_AD_TYPE) { + DISC_CHECK_AND_RETURN_RET_LOGE(ParseFlag(advData, advLen, dst, index) == SOFTBUS_OK, SOFTBUS_ERR, + DISC_BLE_ADAPTER, "parse flag failed"); + } else if (type == SHORTENED_LOCAL_NAME_BC_TYPE || type == LOCAL_NAME_BC_TYPE) { + DISC_CHECK_AND_RETURN_RET_LOGE(ParseLocalName(advData, advLen, dst, index, len) == SOFTBUS_OK, SOFTBUS_ERR, + DISC_BLE_ADAPTER, "parse local name failed"); + } else { + if (type != SERVICE_BC_TYPE && type != MANUFACTURE_BC_TYPE) { + index += len; + DISC_LOGW(DISC_BLE_ADAPTER, "unsupported type: %hhu", type); + continue; + } + SoftbusBroadcastPayload *data = isRsp ? &dst->data.rspData : &dst->data.bcData; + data->payloadLen = len - ID_LEN - 1; + if (data->payloadLen < 0 || index + ID_LEN >= advLen) { + DISC_LOGE(DISC_BLE_ADAPTER, "parse payload failed"); + return SOFTBUS_ERR; + } + isRsp = !isRsp; + data->type = BtAdvTypeToSoftbus(type); + data->id = ((uint16_t)advData[index + ID_LEN] << BC_SHIFT_BIT) | (uint16_t)advData[index + ID_LEN - 1]; + if (data->payloadLen == 0) { + index += len; + DISC_LOGW(DISC_BLE_ADAPTER, "parse no payload, isRsp: %d", isRsp); + continue; + } + data->payload = (uint8_t *)SoftBusCalloc(data->payloadLen); + DISC_CHECK_AND_RETURN_RET_LOGE(data->payload != NULL, SOFTBUS_ERR, DISC_BLE_ADAPTER, + "malloc payload failed"); + (void)memcpy_s(data->payload, data->payloadLen, &advData[index + ID_LEN + 1], data->payloadLen); + } + index += len; + } + return SOFTBUS_OK; +} + +void DumpSoftbusAdapterData(const char *description, uint8_t *data, uint16_t len) +{ + DISC_CHECK_AND_RETURN_LOGE(description != NULL, DISC_BLE_ADAPTER, "data is null!"); + DISC_CHECK_AND_RETURN_LOGE(len != 0, DISC_BLE_ADAPTER, "len is 0!"); + DISC_CHECK_AND_RETURN_LOGE(data != NULL, DISC_BLE_ADAPTER, "data is null!"); + + int32_t hexLen = HEXIFY_LEN(len); + char *softbusData = (char *)SoftBusCalloc(sizeof(char) * hexLen); + DISC_CHECK_AND_RETURN_LOGE(softbusData != NULL, DISC_BLE_ADAPTER, "malloc failed!"); + + (void)ConvertBytesToHexString(softbusData, hexLen, data, len); + DISC_LOGI(DISC_BLE_ADAPTER, "%s softbusData:%s", description, softbusData); + + SoftBusFree(softbusData); +} \ No newline at end of file diff --git a/adapter/common/net/bluetooth/broadcast/adapter/include/softbus_broadcast_adapter_interface.h b/adapter/common/net/bluetooth/broadcast/adapter/include/softbus_broadcast_adapter_interface.h index 0c142dd0c..ca2985fdc 100644 --- a/adapter/common/net/bluetooth/broadcast/adapter/include/softbus_broadcast_adapter_interface.h +++ b/adapter/common/net/bluetooth/broadcast/adapter/include/softbus_broadcast_adapter_interface.h @@ -77,7 +77,7 @@ typedef struct { int32_t (*SetBroadcastingData)(int32_t advId, const SoftbusBroadcastData *data); int32_t (*UpdateBroadcasting)(int32_t advId, const SoftbusBroadcastParam *param, const SoftbusBroadcastData *data); int32_t (*StartScan)(int32_t scannerId, const SoftBusBcScanParams *param, const SoftBusBcScanFilter *scanFilter, - uint8_t filterSize); + int32_t filterSize); int32_t (*StopScan)(int32_t scannerId); bool (*IsLpDeviceAvailable)(void); bool (*SetAdvFilterParam)(const SoftBusLpBroadcastParam *bcParam, const SoftBusLpScanParam *scanParam); diff --git a/adapter/common/net/bluetooth/broadcast/interface/softbus_broadcast_manager.h b/adapter/common/net/bluetooth/broadcast/interface/softbus_broadcast_manager.h index 6a6ef1097..6c7a98590 100644 --- a/adapter/common/net/bluetooth/broadcast/interface/softbus_broadcast_manager.h +++ b/adapter/common/net/bluetooth/broadcast/interface/softbus_broadcast_manager.h @@ -246,7 +246,7 @@ int32_t SetScanFilter(int32_t listenerId, const BcScanFilter *scanFilter, uint8_ * @since 4.1 * @version 1.0 */ -int32_t GetScanFilter(int32_t listenerId, const BcScanFilter *scanFilter, uint8_t *filterNum); +int32_t GetScanFilter(int32_t listenerId, BcScanFilter **scanFilter, uint8_t *filterNum); /** * @brief Check whether available resources are available by using the bcid diff --git a/adapter/common/net/bluetooth/broadcast/interface/softbus_broadcast_type.h b/adapter/common/net/bluetooth/broadcast/interface/softbus_broadcast_type.h index e5c56f460..c3e9eaca9 100644 --- a/adapter/common/net/bluetooth/broadcast/interface/softbus_broadcast_type.h +++ b/adapter/common/net/bluetooth/broadcast/interface/softbus_broadcast_type.h @@ -87,6 +87,7 @@ typedef enum { SRV_TYPE_SHARE, // The service type is share discovery. SRV_TYPE_APPROACH, // The service type is approach discovery. SRV_TYPE_SH, // The service type is sensorhub. + SRV_TYPE_FAST_OFFLINE, // The service type is fast offline. SRV_TYPE_BUTT, } BaseServiceType; @@ -396,8 +397,7 @@ typedef struct { */ typedef struct { BcScanParams scanParam; - BcScanFilter *filter; - uint8_t filterSize; + int32_t listenerId; } LpScanParam; #ifdef __cplusplus diff --git a/adapter/common/net/bluetooth/broadcast/interface/softbus_broadcast_utils.h b/adapter/common/net/bluetooth/broadcast/interface/softbus_broadcast_utils.h index 7499f42f5..5c19836ad 100644 --- a/adapter/common/net/bluetooth/broadcast/interface/softbus_broadcast_utils.h +++ b/adapter/common/net/bluetooth/broadcast/interface/softbus_broadcast_utils.h @@ -33,8 +33,8 @@ extern "C"{ #define MEDIUM_NUM_MAX 2 // max broadcasting and scan limit -#define BC_NUM_MAX 9 -#define SCAN_NUM_MAX 9 +#define BC_NUM_MAX 16 +#define SCAN_NUM_MAX 16 #define BC_DATA_MAX_LEN 24 #define RSP_DATA_MAX_LEN 27 diff --git a/adapter/common/net/bluetooth/broadcast/manager/src/softbus_broadcast_mgr.c b/adapter/common/net/bluetooth/broadcast/manager/src/softbus_broadcast_mgr.c index b5f23358c..3a7dd9c56 100644 --- a/adapter/common/net/bluetooth/broadcast/manager/src/softbus_broadcast_mgr.c +++ b/adapter/common/net/bluetooth/broadcast/manager/src/softbus_broadcast_mgr.c @@ -13,10 +13,1696 @@ * limitations under the License. */ +#include "securec.h" + +#include "disc_log.h" +#include "softbus_adapter_bt_common.h" +#include "softbus_adapter_mem.h" +#include "softbus_adapter_thread.h" +#include "softbus_ble_gatt.h" +#include "softbus_broadcast_adapter_interface.h" #include "softbus_broadcast_manager.h" -#include "softbus_broadcast_type.h" +#include "softbus_broadcast_utils.h" +#include "softbus_errcode.h" +#include "softbus_utils.h" + +#define BC_WAIT_TIME_SEC 2 + +static volatile bool g_mgrInit = false; +static volatile bool g_mgrLockInit = false; +static SoftBusMutex g_bcLock = {0}; +static SoftBusMutex g_scanLock = {0}; + +static int32_t g_adapterScannerId = -1; +static int32_t g_adapterLpScannerId = -1; +static int32_t g_btStateListenerId = -1; +static volatile bool g_isScanCbReg = false; +static volatile bool g_isLpScanCbReg = false; + +typedef struct { + BaseServiceType srvType; + int32_t adapterBcId; + bool isUsed; + bool isAdvertising; + SoftBusCond cond; + BroadcastCallback *bcCallback; +} BroadcastManager; + +typedef enum { + SCAN_FREQ_LOW_POWER, + SCAN_FREQ_P2_60_3000, + SCAN_FREQ_P10_60_600, + SCAN_FREQ_P25_60_240, + SCAN_FREQ_P100_1000_1000, + SCAN_FREQ_BUTT, +} ScanFreq; + +typedef struct { + BaseServiceType srvType; + int32_t adapterScanId; + bool isUsed; + bool isNeedReset; + bool isScanning; + BcScanParams param; + ScanFreq freq; + BcScanFilter *filter; + uint8_t filterSize; + ScanCallback *scanCallback; +} ScanManager; + +static BroadcastManager g_bcManager[BC_NUM_MAX]; +static ScanManager g_scanManager[SCAN_NUM_MAX]; + +// Global variable for specifying an interface type {@link SoftbusMediumType}. +static uint32_t g_interfaceId = BROADCAST_MEDIUM_TYPE_BLE; +static SoftbusBroadcastMediumInterface *g_interface[MEDIUM_NUM_MAX]; + +int32_t RegisterBroadcastMediumFunction(SoftbusMediumType type, const SoftbusBroadcastMediumInterface *interface) +{ + DISC_LOGI(DISC_BLE, "enter, register type = %d.", type); + DISC_CHECK_AND_RETURN_RET_LOGE(type >= 0 && type < BROADCAST_MEDIUM_TYPE_BUTT, SOFTBUS_INVALID_PARAM, DISC_BLE, + "type is invalid!"); + DISC_CHECK_AND_RETURN_RET_LOGE(interface != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, "interface is null!"); + + g_interface[type] = (SoftbusBroadcastMediumInterface *)interface; + return SOFTBUS_OK; +} + +static void BcBtStateChanged(int32_t listenerId, int32_t state) +{ + (void)listenerId; + if (state != SOFTBUS_BC_BT_STATE_TURN_OFF) { + return; + } + DISC_LOGI(DISC_BLE, "receive bt turn off event, start reset broadcast mgr state..."); + + for (uint32_t managerId = 0; managerId < BC_NUM_MAX; managerId++) { + DISC_CHECK_AND_RETURN_LOGE(SoftBusMutexLock(&g_bcLock) == SOFTBUS_OK, DISC_BLE, "bcLock mutex err!"); + + BroadcastManager *bcManager = &g_bcManager[managerId]; + if (!bcManager->isUsed || bcManager->adapterBcId == -1 || !bcManager->isAdvertising || + bcManager->bcCallback == NULL || bcManager->bcCallback->OnStopBroadcastingCallback == NULL) { + SoftBusMutexUnlock(&g_bcLock); + continue; + } + (void)g_interface[g_interfaceId]->StopBroadcasting(bcManager->adapterBcId); + bcManager->isAdvertising = false; + SoftBusCondBroadcast(&bcManager->cond); + + SoftBusMutexUnlock(&g_bcLock); + bcManager->bcCallback->OnStopBroadcastingCallback((int32_t)managerId, (int32_t)SOFTBUS_BC_STATUS_SUCCESS); + } + + for (uint32_t managerId = 0; managerId < SCAN_NUM_MAX; managerId++) { + DISC_CHECK_AND_RETURN_LOGE(SoftBusMutexLock(&g_scanLock) == SOFTBUS_OK, DISC_BLE, "scanLock mutex err!"); + + ScanManager *scanManager = &g_scanManager[managerId]; + if (!scanManager->isUsed || scanManager->adapterScanId == -1 || !scanManager->isScanning || + scanManager->scanCallback == NULL || scanManager->scanCallback->OnStopScanCallback == NULL) { + SoftBusMutexUnlock(&g_scanLock); + continue; + } + (void)g_interface[g_interfaceId]->StopScan(scanManager->adapterScanId); + scanManager->isScanning = false; + + SoftBusMutexUnlock(&g_scanLock); + scanManager->scanCallback->OnStopScanCallback((int32_t)managerId, (int32_t)SOFTBUS_BC_STATUS_SUCCESS); + } +} + +static SoftBusBtStateListener g_softbusBcBtStateLister = { + .OnBtStateChanged = BcBtStateChanged, + .OnBtAclStateChanged = NULL, +}; + +static int32_t BcManagerLockInit(void) +{ + DISC_LOGI(DISC_BLE, "enter."); + if (g_mgrLockInit) { + return SOFTBUS_OK; + } + if (SoftBusMutexInit(&g_bcLock, NULL) != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE, "g_bcLock init failed"); + return SOFTBUS_NO_INIT; + } + if (SoftBusMutexInit(&g_scanLock, NULL) != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE, "g_scanLock init failed"); + (void)SoftBusMutexDestroy(&g_bcLock); + return SOFTBUS_NO_INIT; + } + g_mgrLockInit = true; + return SOFTBUS_OK; +} int32_t InitBroadcastMgr(void) { + DISC_LOGI(DISC_BLE, "enter."); + if (g_mgrInit) { + DISC_LOGD(DISC_BLE, "mgr already init."); + return SOFTBUS_OK; + } + int32_t ret = BcManagerLockInit(); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, DISC_BLE, "lock init fail!"); + + SoftbusBleAdapterInit(); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId] != NULL, SOFTBUS_ERR, DISC_BLE, "interface is null!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId]->Init != NULL, + SOFTBUS_ERR, DISC_BLE, "function is null!"); + + ret = g_interface[g_interfaceId]->Init(); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, DISC_BLE, "call from adapter fail!"); + + ret = SoftBusAddBtStateListener(&g_softbusBcBtStateLister); + DISC_CHECK_AND_RETURN_RET_LOGE(ret != SOFTBUS_ERR, ret, DISC_BLE, "add bt state listener fail!"); + g_btStateListenerId = ret; + g_mgrInit = true; return SOFTBUS_OK; -} \ No newline at end of file +} + +static bool CheckLockIsInit(SoftBusMutex *lock) +{ + if (SoftBusMutexLock(lock) != SOFTBUS_OK) { + return false; + } + SoftBusMutexUnlock(lock); + return true; +} + +int32_t DeInitBroadcastMgr(void) +{ + DISC_LOGI(DISC_BLE, "enter."); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId] != NULL, SOFTBUS_ERR, DISC_BLE, "interface is null!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId]->DeInit != NULL, + SOFTBUS_ERR, DISC_BLE, "function is null!"); + + if (CheckLockIsInit(&g_bcLock)) { + (void)SoftBusMutexDestroy(&g_bcLock); + } + if (CheckLockIsInit(&g_scanLock)) { + (void)SoftBusMutexDestroy(&g_scanLock); + } + g_mgrLockInit = false; + g_mgrInit = false; + int32_t ret; + if (g_btStateListenerId != -1) { + ret = SoftBusRemoveBtStateListener(g_btStateListenerId); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, DISC_BLE, "RemoveBtStateListener fail!"); + g_btStateListenerId = -1; + } + + ret = g_interface[g_interfaceId]->DeInit(); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, DISC_BLE, "call from adapter fail!"); + return SOFTBUS_OK; +} + +static void BcStartBroadcastingCallback(int32_t adapterBcId, int32_t status) +{ + DISC_LOGD(DISC_BLE, "enter."); + for (uint32_t managerId = 0; managerId < BC_NUM_MAX; managerId++) { + int32_t ret = SoftBusMutexLock(&g_bcLock); + DISC_CHECK_AND_RETURN_LOGE(ret == SOFTBUS_OK, DISC_BLE, "mutex err!"); + + BroadcastManager *bcManager = &g_bcManager[managerId]; + if (bcManager->adapterBcId != adapterBcId || !bcManager->isUsed || bcManager->bcCallback == NULL || + bcManager->bcCallback->OnStartBroadcastingCallback == NULL) { + SoftBusMutexUnlock(&g_bcLock); + continue; + } + DISC_LOGD(DISC_BLE, "srvType = %d, managerId = %u, adapterBcId = %d, status = %d", bcManager->srvType, + managerId, adapterBcId, status); + if (status == SOFTBUS_BC_STATUS_SUCCESS) { + bcManager->isAdvertising = true; + SoftBusCondSignal(&bcManager->cond); + } + SoftBusMutexUnlock(&g_bcLock); + bcManager->bcCallback->OnStartBroadcastingCallback((int32_t)managerId, status); + break; // The broadcast channel cannot be multiplexed. + } +} + +static void BcStopBroadcastingCallback(int32_t adapterBcId, int32_t status) +{ + DISC_LOGD(DISC_BLE, "enter."); + for (uint32_t managerId = 0; managerId < BC_NUM_MAX; managerId++) { + int32_t ret = SoftBusMutexLock(&g_bcLock); + DISC_CHECK_AND_RETURN_LOGE(ret == SOFTBUS_OK, DISC_BLE, "mutex err!"); + + BroadcastManager *bcManager = &g_bcManager[managerId]; + if (bcManager->adapterBcId != adapterBcId || !bcManager->isUsed || bcManager->bcCallback == NULL || + bcManager->bcCallback->OnStopBroadcastingCallback == NULL) { + SoftBusMutexUnlock(&g_bcLock); + continue; + } + DISC_LOGD(DISC_BLE, "srvType = %d, managerId = %u, adapterBcId = %d, status = %d", bcManager->srvType, + managerId, adapterBcId, status); + if (status == SOFTBUS_BC_STATUS_SUCCESS) { + bcManager->isAdvertising = false; + SoftBusCondSignal(&bcManager->cond); + } + SoftBusMutexUnlock(&g_bcLock); + bcManager->bcCallback->OnStopBroadcastingCallback((int32_t)managerId, status); + break; // The broadcast channel cannot be multiplexed. + } +} + +static void BcUpdateBroadcastingCallback(int32_t adapterBcId, int32_t status) +{ + DISC_LOGD(DISC_BLE, "enter."); + for (uint32_t managerId = 0; managerId < BC_NUM_MAX; managerId++) { + int32_t ret = SoftBusMutexLock(&g_bcLock); + DISC_CHECK_AND_RETURN_LOGE(ret == SOFTBUS_OK, DISC_BLE, "mutex err!"); + + BroadcastManager *bcManager = &g_bcManager[managerId]; + if (bcManager->adapterBcId != adapterBcId || !bcManager->isUsed || bcManager->bcCallback == NULL || + bcManager->bcCallback->OnUpdateBroadcastingCallback == NULL) { + SoftBusMutexUnlock(&g_bcLock); + continue; + } + DISC_LOGD(DISC_BLE, "srvType = %d, managerId = %u, adapterBcId = %d, status = %d", bcManager->srvType, + managerId, adapterBcId, status); + SoftBusMutexUnlock(&g_bcLock); + bcManager->bcCallback->OnUpdateBroadcastingCallback((int32_t)managerId, status); + break; // The broadcast channel cannot be multiplexed. + } +} + +static void BcSetBroadcastingCallback(int32_t adapterBcId, int32_t status) +{ + DISC_LOGD(DISC_BLE, "enter."); + for (uint32_t managerId = 0; managerId < BC_NUM_MAX; managerId++) { + int32_t ret = SoftBusMutexLock(&g_bcLock); + DISC_CHECK_AND_RETURN_LOGE(ret == SOFTBUS_OK, DISC_BLE, "mutex err!"); + + BroadcastManager *bcManager = &g_bcManager[managerId]; + if (bcManager->adapterBcId != adapterBcId || !bcManager->isUsed || bcManager->bcCallback == NULL || + bcManager->bcCallback->OnSetBroadcastingCallback == NULL) { + SoftBusMutexUnlock(&g_bcLock); + continue; + } + DISC_LOGD(DISC_BLE, "srvType = %d, managerId = %u, adapterBcId = %d, status = %d", bcManager->srvType, + managerId, adapterBcId, status); + SoftBusMutexUnlock(&g_bcLock); + bcManager->bcCallback->OnSetBroadcastingCallback((int32_t)managerId, status); + break; // The broadcast channel cannot be multiplexed. + } +} + +static SoftbusBroadcastCallback g_softbusBcBleCb = { + .OnStartBroadcastingCallback = BcStartBroadcastingCallback, + .OnStopBroadcastingCallback = BcStopBroadcastingCallback, + .OnUpdateBroadcastingCallback = BcUpdateBroadcastingCallback, + .OnSetBroadcastingCallback = BcSetBroadcastingCallback, +}; + +static void BcOnStartScanCallback(int32_t adapterScanId, int32_t status) +{ + DISC_LOGD(DISC_BLE, "enter."); + for (uint32_t managerId = 0; managerId < SCAN_NUM_MAX; managerId++) { + ScanManager *scanManager = &g_scanManager[managerId]; + if (scanManager->adapterScanId != adapterScanId || !scanManager->isUsed || scanManager->scanCallback == NULL || + scanManager->scanCallback->OnStartScanCallback == NULL) { + continue; + } + DISC_LOGD(DISC_BLE, "srvType = %d, managerId = %u, adapterScanId = %d, status = %d", scanManager->srvType, + managerId, adapterScanId, status); + if (status == SOFTBUS_BC_STATUS_SUCCESS) { + scanManager->isScanning = true; + } + + scanManager->scanCallback->OnStartScanCallback((int32_t)managerId, status); + } +} + +static void BcStopScanCallback(int32_t adapterScanId, int32_t status) +{ + DISC_LOGD(DISC_BLE, "enter."); + for (uint32_t managerId = 0; managerId < SCAN_NUM_MAX; managerId++) { + ScanManager *scanManager = &g_scanManager[managerId]; + if (scanManager->adapterScanId != adapterScanId || !scanManager->isUsed || scanManager->scanCallback == NULL || + scanManager->scanCallback->OnStopScanCallback == NULL) { + continue; + } + DISC_LOGD(DISC_BLE, "srvType = %d, managerId = %u, adapterScanId = %d, status = %d", scanManager->srvType, + managerId, adapterScanId, status); + if (status == SOFTBUS_BC_STATUS_SUCCESS) { + scanManager->isScanning = false; + } + + scanManager->scanCallback->OnStopScanCallback((int32_t)managerId, status); + } +} + +static int32_t BuildBcInfoCommon(const SoftBusBcScanResult *reportData, BroadcastReportInfo *bcInfo) +{ + bcInfo->eventType = reportData->eventType; + bcInfo->dataStatus = reportData->dataStatus; + bcInfo->primaryPhy = reportData->primaryPhy; + bcInfo->secondaryPhy = reportData->secondaryPhy; + bcInfo->advSid = reportData->advSid; + bcInfo->txPower = reportData->txPower; + bcInfo->rssi = reportData->rssi; + bcInfo->addrType = reportData->addrType; + + int32_t ret = memcpy_s(bcInfo->addr.addr, BC_ADDR_MAC_LEN, reportData->addr.addr, SOFTBUS_ADDR_MAC_LEN); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, SOFTBUS_MEM_ERR, DISC_BLE, "memcpy addr fail!"); + + ret = memcpy_s(bcInfo->localName, BC_LOCAL_NAME_LEN_MAX, reportData->localName, SOFTBUS_LOCAL_NAME_LEN_MAX); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, SOFTBUS_MEM_ERR, DISC_BLE, "memcpy localName fail!"); + + return SOFTBUS_OK; +} + +static bool CheckManufactureIsMatch(const BcScanFilter *filter, const BroadcastPayload *bcData) +{ + uint8_t dataLen = bcData->payloadLen; + uint32_t filterLen = filter->manufactureDataLength; + if ((uint32_t)dataLen < filterLen) { + DISC_LOGD(DISC_BLE, "payload is too short!"); + return false; + } + if (filter->manufactureId != bcData->id) { + DISC_LOGD(DISC_BLE, "manufactureId not match!"); + return false; + } + for (uint32_t i = 0; i < filterLen; i++) { + if ((filter->manufactureData[i] & filter->manufactureDataMask[i]) != + (bcData->payload[i] & filter->manufactureDataMask[i])) { + return false; + } + } + return true; +} + +static bool CheckServiceIsMatch(const BcScanFilter *filter, const BroadcastPayload *bcData) +{ + uint8_t dataLen = bcData->payloadLen; + uint32_t filterLen = filter->serviceDataLength; + if ((uint32_t)dataLen < filterLen) { + DISC_LOGW(DISC_BLE, "payload is too short!"); + return false; + } + if (filter->serviceUuid != bcData->id) { + DISC_LOGW(DISC_BLE, "serviceUuid not match!"); + return false; + } + for (uint32_t i = 0; i < filterLen; i++) { + if ((filter->serviceData[i] & filter->serviceDataMask[i]) != + (bcData->payload[i] & filter->serviceDataMask[i])) { + return false; + } + } + return true; +} + +static bool CheckScanResultDataIsMatch(const uint32_t managerId, BroadcastPayload *bcData) +{ + if (bcData->type != BC_DATA_TYPE_SERVICE && bcData->type != BC_DATA_TYPE_MANUFACTURER) { + DISC_LOGE(DISC_BLE, "not support type %d", bcData->type); + return false; + } + + uint8_t filterSize = g_scanManager[managerId].filterSize; + for (uint8_t i = 0; i < filterSize; i++) { + BcScanFilter filter = g_scanManager[managerId].filter[i]; + if (bcData->type == BC_DATA_TYPE_SERVICE && CheckServiceIsMatch(&filter, bcData)) { + return true; + } + if (bcData->type == BC_DATA_TYPE_MANUFACTURER && CheckManufactureIsMatch(&filter, bcData)) { + return true; + } + } + return false; +} + +static void DumpSoftbusData(const char *description, uint16_t len, const uint8_t *data) +{ + DISC_CHECK_AND_RETURN_LOGE(description != NULL, DISC_BLE, "data is null!"); + DISC_CHECK_AND_RETURN_LOGE(len != 0, DISC_BLE, "len is 0!"); + DISC_CHECK_AND_RETURN_LOGE(data != NULL, DISC_BLE, "data is null!"); + + int32_t hexLen = HEXIFY_LEN(len); + char *softbusData = (char *)SoftBusCalloc(sizeof(char) * hexLen); + DISC_CHECK_AND_RETURN_LOGE(softbusData != NULL, DISC_BLE, "malloc failed!"); + + (void)ConvertBytesToHexString(softbusData, hexLen, data, len); + DISC_LOGI(DISC_BLE, "%s softbusData:%s", description, softbusData); + + SoftBusFree(softbusData); +} + +static void ReleaseBroadcastReportInfo(BroadcastReportInfo *bcInfo) +{ + SoftBusFree(bcInfo->packet.bcData.payload); + SoftBusFree(bcInfo->packet.rspData.payload); +} + +static int32_t BuildBcPayload(int32_t maxPayloadLen, const SoftbusBroadcastPayload *srcData, BroadcastPayload *dstData) +{ + DISC_CHECK_AND_RETURN_RET_LOGE(srcData->payload != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, + "broadcast payload is null!"); + + dstData->type = (BroadcastDataType)srcData->type; + dstData->id = srcData->id; + dstData->payloadLen = srcData->payloadLen; + + if (srcData->payloadLen > maxPayloadLen) { + DISC_LOGW(DISC_BLE, "payloadLen = %d is too long!", srcData->payloadLen); + } + int32_t bcDataLen = (srcData->payloadLen > maxPayloadLen) ? maxPayloadLen : srcData->payloadLen; + dstData->payload = (uint8_t *)SoftBusCalloc(bcDataLen); + DISC_CHECK_AND_RETURN_RET_LOGE(dstData->payload != NULL, SOFTBUS_MALLOC_ERR, DISC_BLE, "malloc failed!"); + + if (memcpy_s(dstData->payload, bcDataLen, srcData->payload, bcDataLen) != EOK) { + DISC_LOGE(DISC_BLE, "memcpy payload fail"); + SoftBusFree(dstData->payload); + return SOFTBUS_MEM_ERR; + } + + return SOFTBUS_OK; +} + +static int32_t BuildBroadcastPacket(const SoftbusBroadcastData *softbusBcData, BroadcastPacket *packet) +{ + packet->isSupportFlag = softbusBcData->isSupportFlag; + packet->flag = softbusBcData->flag; + + // 2.1. Build broadcast payload. + int32_t maxPayloadLen = (softbusBcData->isSupportFlag) ? BC_DATA_MAX_LEN : (BC_DATA_MAX_LEN + BC_FLAG_LEN); + + int32_t ret = BuildBcPayload(maxPayloadLen, &(softbusBcData->bcData), &(packet->bcData)); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, DISC_BLE, "build broadcast payload failed!"); + + DumpSoftbusData("scan result bcData:", softbusBcData->bcData.payloadLen, softbusBcData->bcData.payload); + + // 2.2. Build broadcast response payload. + if (softbusBcData->rspData.payload == NULL) { + packet->rspData.payload = NULL; + DISC_LOGW(DISC_BLE, "no rspData!"); + } else { + maxPayloadLen = RSP_DATA_MAX_LEN; + ret = BuildBcPayload(maxPayloadLen, &(softbusBcData->rspData), &(packet->rspData)); + if (ret != SOFTBUS_OK) { + SoftBusFree(packet->bcData.payload); + DISC_LOGE(DISC_BLE, "build broadcast rsp payload failed!"); + return SOFTBUS_ERR; + } + DumpSoftbusData("scan result rspData:", softbusBcData->rspData.payloadLen, softbusBcData->rspData.payload); + } + return SOFTBUS_OK; +} + +static int32_t BuildBroadcastReportInfo(const SoftBusBcScanResult *reportData, BroadcastReportInfo *bcInfo) +{ + // 1. Build BroadcastReportInfo from SoftBusBcScanResult except BroadcastPacket. + int32_t ret = BuildBcInfoCommon(reportData, bcInfo); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, DISC_BLE, "build broadcast common info failed!"); + + // 2. Build BroadcastPacket. + ret = BuildBroadcastPacket(&(reportData->data), &(bcInfo->packet)); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, DISC_BLE, "build broadcast packet failed!"); + + return SOFTBUS_OK; +} + +static bool CheckScanResultDataIsMatchApproach(const uint32_t managerId, BroadcastPayload *bcData) +{ + if (bcData->payload == NULL) { + return false; + } + DISC_CHECK_AND_RETURN_RET_LOGE(bcData->type == BC_DATA_TYPE_SERVICE, false, DISC_BLE, + "type %d dismatch", bcData->type); + + uint8_t filterSize = g_scanManager[managerId].filterSize; + for (uint8_t i = 0; i < filterSize; i++) { + BcScanFilter filter = g_scanManager[managerId].filter[i]; + if (CheckServiceIsMatch(&filter, bcData)) { + return true; + } + } + return false; +} + +static void BcReportScanDataCallback(int32_t adapterScanId, const SoftBusBcScanResult *reportData) +{ + DISC_LOGD(DISC_BLE, "enter."); + DISC_CHECK_AND_RETURN_LOGE(reportData != NULL, DISC_BLE, "reportData is null!"); + + BroadcastReportInfo bcInfo; + int32_t ret = BuildBroadcastReportInfo(reportData, &bcInfo); + DISC_CHECK_AND_RETURN_LOGE(ret == SOFTBUS_OK, DISC_BLE, "BuildBroadcastReportInfo fail!"); + + for (uint32_t managerId = 0; managerId < SCAN_NUM_MAX; managerId++) { + if (SoftBusMutexLock(&g_scanLock) != 0) { + ReleaseBroadcastReportInfo(&bcInfo); + return; + } + ScanManager *scanManager = &g_scanManager[managerId]; + if (!scanManager->isUsed || !scanManager->isScanning || scanManager->filter == NULL || + scanManager->scanCallback == NULL || scanManager->scanCallback->OnReportScanDataCallback == NULL || + scanManager->adapterScanId != adapterScanId || + !(CheckScanResultDataIsMatch(managerId, &(bcInfo.packet.bcData)) || + (scanManager->srvType == SRV_TYPE_APPROACH && + CheckScanResultDataIsMatchApproach(managerId, &(bcInfo.packet.rspData))))) { + SoftBusMutexUnlock(&g_scanLock); + continue; + } + + DISC_LOGD(DISC_BLE, "service srvType = %d, managerId = %u, adapterScanId = %d", + scanManager->srvType, managerId, adapterScanId); + SoftBusMutexUnlock(&g_scanLock); + scanManager->scanCallback->OnReportScanDataCallback((int32_t)managerId, &bcInfo); + } + ReleaseBroadcastReportInfo(&bcInfo); +} + +static void BcScanStateChanged(int32_t resultCode, bool isStartScan) +{ + DISC_LOGD(DISC_BLE, "enter."); + for (uint32_t managerId = 0; managerId < SCAN_NUM_MAX; managerId++) { + int32_t ret = SoftBusMutexLock(&g_scanLock); + DISC_CHECK_AND_RETURN_LOGE(ret == SOFTBUS_OK, DISC_BLE, "mutex err!"); + + ScanManager *scanManager = &g_scanManager[managerId]; + if (!scanManager->isUsed || !scanManager->isScanning || scanManager->scanCallback == NULL || + scanManager->scanCallback->OnScanStateChanged == NULL) { + SoftBusMutexUnlock(&g_scanLock); + continue; + } + DISC_LOGD(DISC_BLE, "srvType = %d, managerId = %u, adapterScanId = %d, isStartScan = %d", scanManager->srvType, + managerId, scanManager->adapterScanId, isStartScan); + SoftBusMutexUnlock(&g_scanLock); + scanManager->scanCallback->OnScanStateChanged(resultCode, isStartScan); + } +} + +static int32_t ConvertBroadcastUuid(const SoftbusBroadcastUuid *uuid, BroadcastUuid *bcUuid) +{ + bcUuid->uuidLen = uuid->uuidLen; + bcUuid->uuid = (int8_t *)SoftBusCalloc(uuid->uuidLen); + DISC_CHECK_AND_RETURN_RET_LOGE(bcUuid->uuid != NULL, SOFTBUS_MALLOC_ERR, DISC_BLE, "malloc failed!"); + if (memcpy_s(bcUuid->uuid, bcUuid->uuidLen, uuid->uuid, uuid->uuidLen) != EOK) { + DISC_LOGE(DISC_BLE, "memcpy_s err!"); + SoftBusFree(bcUuid->uuid); + return SOFTBUS_MEM_ERR; + } + return SOFTBUS_OK; +} + +static void BcLpDeviceInfoCallback(const SoftbusBroadcastUuid *uuid, int32_t type, uint8_t *data, uint32_t dataSize) +{ + DISC_LOGD(DISC_BLE, "enter."); + BroadcastUuid bcUuid = {0}; + int32_t ret = ConvertBroadcastUuid(uuid, &bcUuid); + DISC_CHECK_AND_RETURN_LOGE(ret == SOFTBUS_OK, DISC_BLE, "ConvertBroadcastUuid failed!"); + + for (uint32_t managerId = 0; managerId < SCAN_NUM_MAX; managerId++) { + ScanManager *scanManager = &g_scanManager[managerId]; + if (!scanManager->isUsed || scanManager->scanCallback == NULL || + scanManager->scanCallback->OnLpDeviceInfoCallback == NULL) { + continue; + } + + scanManager->scanCallback->OnLpDeviceInfoCallback(&bcUuid, type, data, dataSize); + break; + } + SoftBusFree(bcUuid.uuid); +} + +static SoftbusScanCallback g_softbusBcBleScanCb = { + .OnStartScanCallback = BcOnStartScanCallback, + .OnStopScanCallback = BcStopScanCallback, + .OnReportScanDataCallback = BcReportScanDataCallback, + .OnScanStateChanged = BcScanStateChanged, + .OnLpDeviceInfoCallback = BcLpDeviceInfoCallback, +}; + +int32_t RegisterBroadcaster(BaseServiceType srvType, int32_t *bcId, const BroadcastCallback *cb) +{ + DISC_LOGI(DISC_BLE, "enter."); + int32_t ret = SOFTBUS_OK; + int32_t adapterBcId = -1; + DISC_CHECK_AND_RETURN_RET_LOGE(bcId != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, "invalid param bcId!"); + DISC_CHECK_AND_RETURN_RET_LOGE(cb != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, "invalid param cb!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId] != NULL, SOFTBUS_ERR, DISC_BLE, "interface is null!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId]->RegisterBroadcaster != NULL, + SOFTBUS_ERR, DISC_BLE, "function is null!"); + + ret = SoftBusMutexLock(&g_bcLock); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, SOFTBUS_LOCK_ERR, DISC_BLE, "mutex err!"); + + ret = g_interface[g_interfaceId]->RegisterBroadcaster(&adapterBcId, &g_softbusBcBleCb); + if (ret != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE, "call from adapter fail!"); + SoftBusMutexUnlock(&g_bcLock); + return ret; + } + + int32_t managerId; + for (managerId = 0; managerId < BC_NUM_MAX; managerId++) { + if (!g_bcManager[managerId].isUsed) { + break; + } + } + if (managerId == BC_NUM_MAX) { + DISC_LOGE(DISC_BLE, "no available adv manager"); + SoftBusMutexUnlock(&g_bcLock); + return SOFTBUS_ERR; + } + DISC_LOGD(DISC_BLE, "BaseServiceType = %d, bcId = %d, adapterBcId = %d", srvType, managerId, adapterBcId); + + *bcId = managerId; + ret = SoftBusCondInit(&g_bcManager[managerId].cond); + if (ret != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE, "SoftBusCondInit failed!"); + SoftBusMutexUnlock(&g_bcLock); + return ret; + } + g_bcManager[managerId].srvType = srvType; + g_bcManager[managerId].adapterBcId = adapterBcId; + g_bcManager[managerId].isUsed = true; + g_bcManager[managerId].isAdvertising = false; + g_bcManager[managerId].bcCallback = (BroadcastCallback *)cb; + SoftBusMutexUnlock(&g_bcLock); + return SOFTBUS_OK; +} + +static bool CheckBcIdIsValid(int32_t bcId) +{ + if (bcId < 0 || bcId >= BC_NUM_MAX || !g_bcManager[bcId].isUsed) { + DISC_LOGE(DISC_BLE, "invalid param bcId = %d", bcId); + return false; + } + return true; +} + +int32_t UnRegisterBroadcaster(int32_t bcId) +{ + DISC_LOGI(DISC_BLE, "enter."); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId] != NULL, SOFTBUS_ERR, DISC_BLE, "interface is null!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId]->UnRegisterBroadcaster != NULL, + SOFTBUS_ERR, DISC_BLE, "function is null!"); + + int32_t ret = SoftBusMutexLock(&g_bcLock); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, SOFTBUS_LOCK_ERR, DISC_BLE, "mutex err!"); + + if (!CheckBcIdIsValid(bcId)) { + DISC_LOGE(DISC_BLE, "bcId is invalid"); + SoftBusMutexUnlock(&g_bcLock); + return SOFTBUS_INVALID_PARAM; + } + + ret = g_interface[g_interfaceId]->UnRegisterBroadcaster(g_bcManager[bcId].adapterBcId); + if (ret != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE, "call from adapter fail!"); + SoftBusMutexUnlock(&g_bcLock); + return ret; + } + + if (g_bcManager[bcId].isAdvertising) { + ret = g_interface[g_interfaceId]->StopBroadcasting(g_bcManager[bcId].adapterBcId); + if (ret != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE, "stop broadcasting fail!"); + SoftBusMutexUnlock(&g_bcLock); + return ret; + } + } + g_bcManager[bcId].srvType = -1; + g_bcManager[bcId].adapterBcId = -1; + g_bcManager[bcId].isUsed = false; + g_bcManager[bcId].isAdvertising = false; + SoftBusCondDestroy(&g_bcManager[bcId].cond); + g_bcManager[bcId].bcCallback = NULL; + + SoftBusMutexUnlock(&g_bcLock); + return SOFTBUS_OK; +} + +static int32_t RegisterScanListenerSub(BaseServiceType srvType, int32_t *adapterScanId, const ScanCallback *cb) +{ + int32_t ret; + + if (srvType == SRV_TYPE_SH) { + if (g_isLpScanCbReg) { + *adapterScanId = g_adapterLpScannerId; + DISC_LOGD(DISC_BLE, "service %d is already registered", srvType); + return SOFTBUS_OK; + } + ret = g_interface[g_interfaceId]->RegisterScanListener(adapterScanId, &g_softbusBcBleScanCb); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, DISC_BLE, "call from adapter fail!"); + + g_isLpScanCbReg = true; + g_adapterLpScannerId = *adapterScanId; + return SOFTBUS_OK; + } + + if (g_isScanCbReg) { + *adapterScanId = g_adapterScannerId; + return SOFTBUS_OK; + } + DISC_LOGD(DISC_BLE, "register scan listener"); + ret = g_interface[g_interfaceId]->RegisterScanListener(adapterScanId, &g_softbusBcBleScanCb); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, DISC_BLE, "call from adapter fail!"); + + g_isScanCbReg = true; + g_adapterScannerId = *adapterScanId; + return SOFTBUS_OK; +} + +static bool CheckSrvRegistered(BaseServiceType srvType) +{ + for (int32_t managerId = 0; managerId < SCAN_NUM_MAX; managerId++) { + if (!g_scanManager[managerId].isUsed) { + continue; + } + if (g_scanManager[managerId].srvType == srvType) { + DISC_LOGE(DISC_BLE, "service = %d is registered", srvType); + return true; + } + } + return false; +} + +int32_t RegisterScanListener(BaseServiceType srvType, int32_t *listenerId, const ScanCallback *cb) +{ + DISC_LOGI(DISC_BLE, "enter."); + int32_t ret = SOFTBUS_OK; + int32_t adapterScanId = -1; + + DISC_CHECK_AND_RETURN_RET_LOGE(listenerId != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, "invalid param listenerId!"); + DISC_CHECK_AND_RETURN_RET_LOGE(cb != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, "invalid param cb!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId] != NULL, SOFTBUS_ERR, DISC_BLE, "interface is null!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId]->RegisterScanListener != NULL, + SOFTBUS_ERR, DISC_BLE, "function is null!"); + DISC_CHECK_AND_RETURN_RET_LOGE(!CheckSrvRegistered(srvType), SOFTBUS_ERR, DISC_BLE, "already registered!"); + + ret = SoftBusMutexLock(&g_scanLock); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, SOFTBUS_LOCK_ERR, DISC_BLE, "mutex err!"); + + ret = RegisterScanListenerSub(srvType, &adapterScanId, cb); + if (ret != SOFTBUS_OK) { + SoftBusMutexUnlock(&g_scanLock); + DISC_LOGE(DISC_BLE, "register listerner failed!"); + return ret; + } + + int32_t managerId; + for (managerId = 0; managerId < SCAN_NUM_MAX; managerId++) { + if (!g_scanManager[managerId].isUsed) { + break; + } + } + if (managerId == SCAN_NUM_MAX) { + DISC_LOGE(DISC_BLE, "no available scanner"); + SoftBusMutexUnlock(&g_scanLock); + return SOFTBUS_ERR; + } + DISC_LOGD(DISC_BLE, "BaseServiceType = %d, listenerId = %d, adapterScanId = %d", + srvType, managerId, adapterScanId); + *listenerId = managerId; + g_scanManager[managerId].srvType = srvType; + g_scanManager[managerId].adapterScanId = adapterScanId; + g_scanManager[managerId].isUsed = true; + g_scanManager[managerId].isNeedReset = true; + g_scanManager[managerId].isScanning = false; + g_scanManager[managerId].freq = SCAN_FREQ_LOW_POWER; + g_scanManager[managerId].scanCallback = (ScanCallback *)cb; + + SoftBusMutexUnlock(&g_scanLock); + return SOFTBUS_OK; +} + +static bool CheckScanIdIsValid(int32_t listenerId) +{ + if (listenerId < 0 || listenerId >= SCAN_NUM_MAX || !g_scanManager[listenerId].isUsed) { + DISC_LOGE(DISC_BLE, "invalid param listenerId = %d", listenerId); + return false; + } + return true; +} + +static void ReleaseBcScanFilter(int listenerId) +{ + DISC_LOGD(DISC_BLE, "enter."); + BcScanFilter *filter = g_scanManager[listenerId].filter; + uint8_t filterSize = g_scanManager[listenerId].filterSize; + while (filterSize-- > 0) { + SoftBusFree((filter + filterSize)->address); + SoftBusFree((filter + filterSize)->deviceName); + SoftBusFree((filter + filterSize)->serviceData); + SoftBusFree((filter + filterSize)->serviceDataMask); + SoftBusFree((filter + filterSize)->manufactureData); + SoftBusFree((filter + filterSize)->manufactureDataMask); + } + SoftBusFree(filter); + g_scanManager[listenerId].filterSize = 0; + g_scanManager[listenerId].filter = NULL; +} + +static bool CheckNeedUnRegisterScanListener(int32_t listenerId) +{ + int32_t adapterScanId = g_scanManager[listenerId].adapterScanId; + for (int32_t managerId = 0; managerId < SCAN_NUM_MAX; managerId++) { + if (managerId != listenerId && g_scanManager[managerId].adapterScanId == adapterScanId && + g_scanManager[managerId].isScanning) { + return false; + } + } + return true; +} + +static bool CheckNeedUpdateScan(int32_t listenerId, int32_t *liveListenerId) +{ + int32_t adapterScanId = g_scanManager[listenerId].adapterScanId; + for (int32_t managerId = 0; managerId < SCAN_NUM_MAX; managerId++) { + if (managerId != listenerId && g_scanManager[managerId].adapterScanId == adapterScanId && + g_scanManager[managerId].isScanning) { + *liveListenerId = managerId; + return true; + } + } + return false; +} + +static void CovertSoftBusBcScanFilters(const BcScanFilter *filter, uint8_t size, SoftBusBcScanFilter *adapterFilter) +{ + while (size-- > 0) { + (adapterFilter + size)->address = (filter + size)->address; + (adapterFilter + size)->deviceName = (filter + size)->deviceName; + (adapterFilter + size)->serviceUuid = (filter + size)->serviceUuid; + (adapterFilter + size)->serviceDataLength = (filter + size)->serviceDataLength; + (adapterFilter + size)->serviceData = (filter + size)->serviceData; + (adapterFilter + size)->serviceDataMask = (filter + size)->serviceDataMask; + (adapterFilter + size)->manufactureId = (filter + size)->manufactureId; + (adapterFilter + size)->manufactureDataLength = (filter + size)->manufactureDataLength; + (adapterFilter + size)->manufactureData = (filter + size)->manufactureData; + (adapterFilter + size)->manufactureDataMask = (filter + size)->manufactureDataMask; + } +} + +static void BuildSoftBusBcScanFilters(int32_t listenerId, SoftBusBcScanFilter **adapterFilter, int32_t *filterSize) +{ + DISC_LOGD(DISC_BLE, "enter."); + uint8_t size = g_scanManager[listenerId].filterSize; + BcScanFilter *filter = g_scanManager[listenerId].filter; + + *adapterFilter = (SoftBusBcScanFilter *)SoftBusCalloc(sizeof(SoftBusBcScanFilter) * size); + if (*adapterFilter == NULL) { + return; + } + *filterSize = size; + + CovertSoftBusBcScanFilters(filter, size, *adapterFilter); + g_scanManager[listenerId].isNeedReset = false; +} + +static void CombineSoftbusBcScanFilters(int32_t listenerId, SoftBusBcScanFilter **adapterFilter, int32_t *filterSize) +{ + DISC_LOGD(DISC_BLE, "enter."); + uint8_t size = 0; + for (int32_t managerId = 0; managerId < SCAN_NUM_MAX; managerId++) { + ScanManager *scanManager = &g_scanManager[managerId]; + if (!scanManager->isUsed || (!scanManager->isScanning && managerId != listenerId) || + scanManager->adapterScanId != g_scanManager[listenerId].adapterScanId) { + continue; + } + + size += scanManager->filterSize; + } + *adapterFilter = (SoftBusBcScanFilter *)SoftBusCalloc(sizeof(SoftBusBcScanFilter) * size); + if (*adapterFilter == NULL) { + return; + } + *filterSize = size; + + for (int32_t managerId = 0; managerId < SCAN_NUM_MAX; managerId++) { + ScanManager *scanManager = &g_scanManager[managerId]; + if (!scanManager->isUsed || (!scanManager->isScanning && managerId != listenerId) || + scanManager->adapterScanId != g_scanManager[listenerId].adapterScanId) { + continue; + } + + uint8_t currentSize = g_scanManager[managerId].filterSize; + BcScanFilter *filter = g_scanManager[managerId].filter; + size = size - currentSize; + CovertSoftBusBcScanFilters(filter, currentSize, *adapterFilter + size); + g_scanManager[managerId].isNeedReset = false; + } +} + +static void GetBcScanFilters(int32_t listenerId, SoftBusBcScanFilter **adapterFilter, int32_t *filterSize) +{ + int32_t adapterScanId = g_scanManager[listenerId].adapterScanId; + if (adapterScanId == g_adapterLpScannerId) { + BuildSoftBusBcScanFilters(listenerId, adapterFilter, filterSize); + return; + } + CombineSoftbusBcScanFilters(listenerId, adapterFilter, filterSize); +} + +static void DumpBcScanFilter(const SoftBusBcScanFilter *nativeFilter, uint8_t filterSize) +{ + DISC_CHECK_AND_RETURN_LOGE(nativeFilter != NULL, DISC_BLE, "invalid param nativeFilter!"); + DISC_CHECK_AND_RETURN_LOGE(filterSize != 0, DISC_BLE, "filterSize is 0!"); + + while (filterSize-- > 0) { + int32_t len = (nativeFilter + filterSize)->serviceDataLength; + if (len > 0) { + DumpSoftbusData("service data:", len, (nativeFilter + filterSize)->serviceData); + DumpSoftbusData("service dataMask:", len, (nativeFilter + filterSize)->serviceDataMask); + } else { + len = (nativeFilter + filterSize)->manufactureDataLength; + if (len <= 0) { + continue; + } + DumpSoftbusData("manufacture data:", len, (nativeFilter + filterSize)->manufactureData); + DumpSoftbusData("manufacture dataMask:", len, (nativeFilter + filterSize)->manufactureDataMask); + } + } +} + +static void BuildSoftBusBcScanParams(const BcScanParams *param, SoftBusBcScanParams *adapterParam) +{ + DISC_LOGD(DISC_BLE, "enter."); + (void)memset_s(adapterParam, sizeof(SoftBusBcScanParams), 0x0, sizeof(SoftBusBcScanParams)); + + // convert params + adapterParam->scanInterval = param->scanInterval; + adapterParam->scanWindow = param->scanWindow; + adapterParam->scanType = param->scanType; + adapterParam->scanPhy = param->scanPhy; + adapterParam->scanFilterPolicy = param->scanFilterPolicy; +} + +static void GetScanIntervalAndWindow(int32_t freq, SoftBusBcScanParams *adapterParam) +{ + if (freq == SCAN_FREQ_P2_60_3000) { + adapterParam->scanInterval = SOFTBUS_BC_SCAN_INTERVAL_P2; + adapterParam->scanWindow = SOFTBUS_BC_SCAN_WINDOW_P2; + } + if (freq == SCAN_FREQ_P10_60_600) { + adapterParam->scanInterval = SOFTBUS_BC_SCAN_INTERVAL_P10; + adapterParam->scanWindow = SOFTBUS_BC_SCAN_WINDOW_P10; + } + if (freq == SCAN_FREQ_P25_60_240) { + adapterParam->scanInterval = SOFTBUS_BC_SCAN_INTERVAL_P25; + adapterParam->scanWindow = SOFTBUS_BC_SCAN_WINDOW_P25; + } + if (freq == SCAN_FREQ_P100_1000_1000) { + adapterParam->scanInterval = SOFTBUS_BC_SCAN_INTERVAL_P100; + adapterParam->scanWindow = SOFTBUS_BC_SCAN_WINDOW_P100; + } +} + +static void CheckScanFreq(int32_t listenerId, SoftBusBcScanParams *adapterParam) +{ + static int32_t scanFreq = SCAN_FREQ_LOW_POWER; + static int32_t scanLpFreq = SCAN_FREQ_LOW_POWER; + + int32_t adapterScanId = g_scanManager[listenerId].adapterScanId; + int32_t maxFreq = g_scanManager[listenerId].freq; + + if (adapterScanId == g_adapterLpScannerId) { + if (maxFreq != scanLpFreq) { + DISC_LOGD(DISC_BLE, "lp freq need to update."); + scanLpFreq = maxFreq; + g_scanManager[listenerId].isNeedReset = true; + } + return; + } + + for (uint32_t managerId = 0; managerId < SCAN_NUM_MAX; managerId++) { + ScanManager *scanManager = &g_scanManager[managerId]; + if (!scanManager->isUsed || !scanManager->isScanning || scanManager->adapterScanId != adapterScanId) { + continue; + } + maxFreq = (maxFreq > (int32_t)(scanManager->freq)) ? maxFreq : (int32_t)(scanManager->freq); + } + if (scanFreq != maxFreq) { + g_scanManager[listenerId].isNeedReset = true; + scanFreq = maxFreq; + DISC_LOGD(DISC_BLE, "need to update."); + } + GetScanIntervalAndWindow(scanFreq, adapterParam); +} + +static int32_t CheckAndStopScan(int32_t listenerId) +{ + int32_t liveListenerId = -1; + int32_t ret; + bool needUpdate = CheckNeedUpdateScan(listenerId, &liveListenerId); + if (!needUpdate) { + ret = g_interface[g_interfaceId]->StopScan(g_scanManager[listenerId].adapterScanId); + if (ret != SOFTBUS_OK) { + g_scanManager[listenerId].scanCallback->OnStopScanCallback(listenerId, (int32_t)SOFTBUS_BC_STATUS_FAIL); + DISC_LOGE(DISC_BLE, "call from adapter fail!"); + return ret; + } + } else { + int32_t filterSize = 0; + SoftBusBcScanFilter *adapterFilter = NULL; + g_scanManager[listenerId].isScanning = false; + GetBcScanFilters(liveListenerId, &adapterFilter, &filterSize); + DumpBcScanFilter(adapterFilter, filterSize); + SoftBusBcScanParams adapterParam; + BuildSoftBusBcScanParams(&(g_scanManager[listenerId].param), &adapterParam); + CheckScanFreq(liveListenerId, &adapterParam); + ret = g_interface[g_interfaceId]->StopScan(g_scanManager[listenerId].adapterScanId); + if (ret != SOFTBUS_OK) { + g_scanManager[listenerId].scanCallback->OnStopScanCallback(listenerId, (int32_t)SOFTBUS_BC_STATUS_FAIL); + DISC_LOGE(DISC_BLE, "call from adapter fail!"); + SoftBusFree(adapterFilter); + return ret; + } + ret = g_interface[g_interfaceId]->StartScan(g_scanManager[listenerId].adapterScanId, &adapterParam, + adapterFilter, filterSize); + SoftBusFree(adapterFilter); + if (ret != SOFTBUS_OK) { + g_scanManager[listenerId].scanCallback->OnStartScanCallback(listenerId, (int32_t)SOFTBUS_BC_STATUS_FAIL); + DISC_LOGE(DISC_BLE, "call from adapter fail!"); + return ret; + } + } + return SOFTBUS_OK; +} + +int32_t UnRegisterScanListener(int32_t listenerId) +{ + DISC_LOGI(DISC_BLE, "enter."); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId] != NULL, SOFTBUS_ERR, DISC_BLE, "interface is null!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId]->UnRegisterScanListener != NULL, + SOFTBUS_ERR, DISC_BLE, "function is null!"); + int32_t ret = SoftBusMutexLock(&g_scanLock); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, SOFTBUS_LOCK_ERR, DISC_BLE, "mutex err!"); + if (!CheckScanIdIsValid(listenerId)) { + SoftBusMutexUnlock(&g_scanLock); + return SOFTBUS_INVALID_PARAM; + } + int32_t adapterScanId = g_scanManager[listenerId].adapterScanId; + if (g_scanManager[listenerId].isScanning) { + ret = CheckAndStopScan(listenerId); + if (ret != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE, "stop scan fail!"); + SoftBusMutexUnlock(&g_scanLock); + return ret; + } + } + + if (CheckNeedUnRegisterScanListener(listenerId)) { + if (adapterScanId == g_adapterLpScannerId) { + g_isLpScanCbReg = false; + g_adapterLpScannerId = -1; + } + if (adapterScanId == g_adapterScannerId) { + g_isScanCbReg = false; + g_adapterScannerId = -1; + } + ret = g_interface[g_interfaceId]->UnRegisterScanListener(adapterScanId); + if (ret != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE, "call from adapter fail!"); + SoftBusMutexUnlock(&g_scanLock); + return ret; + } + } + + ReleaseBcScanFilter(listenerId); + g_scanManager[listenerId].srvType = -1; + g_scanManager[listenerId].adapterScanId = -1; + g_scanManager[listenerId].isUsed = false; + g_scanManager[listenerId].isNeedReset = true; + g_scanManager[listenerId].freq = SCAN_FREQ_LOW_POWER; + g_scanManager[listenerId].scanCallback = NULL; + g_scanManager[listenerId].isScanning = false; + + SoftBusMutexUnlock(&g_scanLock); + return SOFTBUS_OK; +} + +static void ConvertBcParams(const BroadcastParam *srcParam, SoftbusBroadcastParam *dstParam) +{ + DISC_LOGD(DISC_BLE, "enter."); + dstParam->minInterval = srcParam->minInterval; + dstParam->maxInterval = srcParam->maxInterval; + dstParam->advType = srcParam->advType; + dstParam->advFilterPolicy = srcParam->advFilterPolicy; + dstParam->ownAddrType = srcParam->ownAddrType; + dstParam->peerAddrType = srcParam->peerAddrType; + if (memcpy_s(dstParam->peerAddr.addr, BC_ADDR_MAC_LEN, srcParam->peerAddr.addr, BC_ADDR_MAC_LEN) != EOK) { + DISC_LOGE(DISC_BLE, "memcpy peerAddr fail"); + return; + } + dstParam->channelMap = srcParam->channelMap; + dstParam->duration = srcParam->duration; + dstParam->txPower = srcParam->txPower; + dstParam->isSupportRpa = srcParam->isSupportRpa; + if (memcpy_s(dstParam->ownIrk, SOFTBUS_IRK_LEN, srcParam->ownIrk, BC_IRK_LEN) != EOK) { + DISC_LOGE(DISC_BLE, "memcpy ownIrk fail"); + return; + } + if (memcpy_s(dstParam->ownUdidHash, SOFTBUS_UDID_HASH_LEN, srcParam->ownUdidHash, BC_UDID_HASH_LEN) != EOK) { + DISC_LOGE(DISC_BLE, "memcpy ownUdidHash fail"); + return; + } +} + +static void DumpBroadcastPacket(const BroadcastPayload *bcData, const BroadcastPayload *rspData) +{ + DumpSoftbusData("BroadcastPayload bcData:", bcData->payloadLen, bcData->payload); + DumpSoftbusData("BroadcastPayload rspData:", rspData->payloadLen, rspData->payload); +} + +static int32_t SoftBusCondWaitTwoSec(int32_t bcId, SoftBusMutex *mutex) +{ + SoftBusSysTime absTime = {0}; + if (SoftBusGetTime(&absTime) != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE, "softbus get time failed"); + return SOFTBUS_ERR; + } + + absTime.sec += BC_WAIT_TIME_SEC; + if (SoftBusCondWait(&g_bcManager[bcId].cond, mutex, &absTime) != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE, "wait timeout"); + return SOFTBUS_TIMOUT; + } + return SOFTBUS_OK; +} + +static int32_t BuildSoftbusBcPayload(int32_t maxPayloadLen, const BroadcastPayload *srcData, + SoftbusBroadcastPayload *dstData) +{ + dstData->type = (SoftbusBcDataType)srcData->type; + dstData->id = srcData->id; + dstData->payloadLen = srcData->payloadLen; + if (srcData->payloadLen > maxPayloadLen) { + DISC_LOGW(DISC_BLE, "payloadLen = %d is too long!", srcData->payloadLen); + } + int32_t bcDataLen = (srcData->payloadLen > maxPayloadLen) ? maxPayloadLen : srcData->payloadLen; + + dstData->payload = (uint8_t *)SoftBusCalloc(bcDataLen); + DISC_CHECK_AND_RETURN_RET_LOGE(dstData->payload != NULL, SOFTBUS_MALLOC_ERR, DISC_BLE, "malloc failed!"); + + if (memcpy_s(dstData->payload, bcDataLen, srcData->payload, bcDataLen) != EOK) { + DISC_LOGE(DISC_BLE, "memcpy_s err!"); + SoftBusFree(dstData->payload); + return SOFTBUS_MEM_ERR; + } + return SOFTBUS_OK; +} + +static void ReleaseSoftbusBroadcastData(SoftbusBroadcastData *softbusBcData) +{ + DISC_LOGD(DISC_BLE, "enter."); + SoftBusFree(softbusBcData->bcData.payload); + SoftBusFree(softbusBcData->rspData.payload); +} + +static int32_t BuildSoftbusBroadcastData(const BroadcastPacket *packet, SoftbusBroadcastData *softbusBcData) +{ + softbusBcData->isSupportFlag = packet->isSupportFlag; + softbusBcData->flag = packet->flag; + + // 1. Build broadcast paylod. + int32_t maxPayloadLen = (packet->isSupportFlag) ? BC_DATA_MAX_LEN : (BC_DATA_MAX_LEN + BC_FLAG_LEN); + int32_t ret = BuildSoftbusBcPayload(maxPayloadLen, &(packet->bcData), &(softbusBcData->bcData)); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, DISC_BLE, "BuildSoftbusBcPayload fail!"); + + // 2. Build response broadcast paylod. + if (packet->rspData.payload != NULL) { + maxPayloadLen = RSP_DATA_MAX_LEN; + ret = BuildSoftbusBcPayload(maxPayloadLen, &(packet->rspData), &(softbusBcData->rspData)); + if (ret != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE, "convert rspData failed!"); + SoftBusFree(softbusBcData->bcData.payload); + return ret; + } + } else { + softbusBcData->rspData.payload = NULL; + softbusBcData->rspData.payloadLen = 0; + } + return SOFTBUS_OK; +} + +int32_t StartBroadcasting(int32_t bcId, const BroadcastParam *param, const BroadcastPacket *packet) +{ + DISC_LOGI(DISC_BLE, "enter."); + DISC_CHECK_AND_RETURN_RET_LOGE(param != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, "invalid param!"); + DISC_CHECK_AND_RETURN_RET_LOGE(packet != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, "invalid param packet!"); + DISC_CHECK_AND_RETURN_RET_LOGE(packet->bcData.payload != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, + "invalid param payload!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId] != NULL, SOFTBUS_ERR, DISC_BLE, "interface is null!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId]->StartBroadcasting != NULL, + SOFTBUS_ERR, DISC_BLE, "function is null!"); + + int32_t ret = SoftBusMutexLock(&g_bcLock); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, SOFTBUS_LOCK_ERR, DISC_BLE, "mutex err!"); + if (!CheckBcIdIsValid(bcId)) { + SoftBusMutexUnlock(&g_bcLock); + return SOFTBUS_ERR; + } + + if (g_bcManager[bcId].isAdvertising) { + DISC_LOGW(DISC_BLE, "wait condition managerId: %d", bcId); + if (SoftBusCondWaitTwoSec(bcId, &g_bcLock) != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE, "SoftBusCondWaitTwoSec failed"); + SoftBusMutexUnlock(&g_bcLock); + return SOFTBUS_ERR; + } + } + + DumpBroadcastPacket(&(packet->bcData), &(packet->rspData)); + SoftbusBroadcastData softbusBcData = {0}; + ret = BuildSoftbusBroadcastData(packet, &softbusBcData); + if (ret != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE, "Build SoftbusBroadcastData failed!"); + SoftBusMutexUnlock(&g_bcLock); + return ret; + } + SoftbusBroadcastParam adapterParam; + ConvertBcParams(param, &adapterParam); + DISC_LOGD(DISC_BLE, "start service srvType = %d, bcId = %d, adapterId = %d", + g_bcManager[bcId].srvType, bcId, g_bcManager[bcId].adapterBcId); + ret = g_interface[g_interfaceId]->StartBroadcasting(g_bcManager[bcId].adapterBcId, &adapterParam, &softbusBcData); + if (ret != SOFTBUS_OK) { + g_bcManager[bcId].bcCallback->OnStartBroadcastingCallback(bcId, (int32_t)SOFTBUS_BC_STATUS_FAIL); + DISC_LOGE(DISC_BLE, "call from adapter fail!"); + ReleaseSoftbusBroadcastData(&softbusBcData); + SoftBusMutexUnlock(&g_bcLock); + return ret; + } + SoftBusMutexUnlock(&g_bcLock); + return SOFTBUS_OK; +} + +int32_t UpdateBroadcasting(int32_t bcId, const BroadcastParam *param, const BroadcastPacket *packet) +{ + DISC_LOGI(DISC_BLE, "enter."); + DISC_CHECK_AND_RETURN_RET_LOGE(param != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, "invald param!"); + DISC_CHECK_AND_RETURN_RET_LOGE(packet != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, "invald param packet!"); + + int ret = StopBroadcasting(bcId); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, DISC_BLE, "StopBroadcasting fail"); + + return StartBroadcasting(bcId, param, packet); +} + +int32_t SetBroadcastingData(int32_t bcId, const BroadcastPacket *packet) +{ + DISC_CHECK_AND_RETURN_RET_LOGE(packet != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, "invalid param packet!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId] != NULL, SOFTBUS_ERR, DISC_BLE, "interface is null!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId]->SetBroadcastingData != NULL, + SOFTBUS_ERR, DISC_BLE, "function is null!"); + + int32_t ret = SoftBusMutexLock(&g_bcLock); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, SOFTBUS_LOCK_ERR, DISC_BLE, "mutex err!"); + + if (!CheckBcIdIsValid(bcId)) { + SoftBusMutexUnlock(&g_bcLock); + return SOFTBUS_ERR; + } + + if (!g_bcManager[bcId].isAdvertising) { + DISC_LOGW(DISC_BLE, "bcId = %d is not advertising", bcId); + SoftBusMutexUnlock(&g_bcLock); + return SOFTBUS_ERR; + } + + SoftbusBroadcastData softbusBcData = {0}; + ret = BuildSoftbusBroadcastData(packet, &softbusBcData); + if (ret != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE, "Build SoftbusBroadcastData failed!"); + SoftBusMutexUnlock(&g_bcLock); + return ret; + } + + ret = g_interface[g_interfaceId]->SetBroadcastingData(g_bcManager[bcId].adapterBcId, &softbusBcData); + if (ret != SOFTBUS_OK) { + g_bcManager[bcId].bcCallback->OnSetBroadcastingCallback(bcId, (int32_t)SOFTBUS_BC_STATUS_FAIL); + DISC_LOGE(DISC_BLE, "call from adapter fail!"); + ReleaseSoftbusBroadcastData(&softbusBcData); + SoftBusMutexUnlock(&g_bcLock); + return ret; + } + + ReleaseSoftbusBroadcastData(&softbusBcData); + SoftBusMutexUnlock(&g_bcLock); + return SOFTBUS_OK; +} + +int32_t StopBroadcasting(int32_t bcId) +{ + DISC_LOGI(DISC_BLE, "enter."); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId] != NULL, SOFTBUS_ERR, DISC_BLE, "interface is null!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId]->StopBroadcasting != NULL, + SOFTBUS_ERR, DISC_BLE, "function is null!"); + + int32_t ret = SoftBusMutexLock(&g_bcLock); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, SOFTBUS_LOCK_ERR, DISC_BLE, "mutex err!"); + + if (!CheckBcIdIsValid(bcId)) { + SoftBusMutexUnlock(&g_bcLock); + return SOFTBUS_ERR; + } + + if (!g_bcManager[bcId].isAdvertising) { + DISC_LOGW(DISC_BLE, "bcId = %d is not advertising", bcId); + SoftBusMutexUnlock(&g_bcLock); + return SOFTBUS_OK; + } + + DISC_LOGD(DISC_BLE, "stop service srvType = %d, bcId = %d, adapterId = %d", + g_bcManager[bcId].srvType, bcId, g_bcManager[bcId].adapterBcId); + ret = g_interface[g_interfaceId]->StopBroadcasting(g_bcManager[bcId].adapterBcId); + if (ret != SOFTBUS_OK) { + g_bcManager[bcId].bcCallback->OnStopBroadcastingCallback(bcId, (int32_t)SOFTBUS_BC_STATUS_FAIL); + DISC_LOGE(DISC_BLE, "call from adapter fail!"); + SoftBusMutexUnlock(&g_bcLock); + return ret; + } + + g_bcManager[bcId].bcCallback->OnStopBroadcastingCallback(bcId, (int32_t)SOFTBUS_BC_STATUS_SUCCESS); + + SoftBusMutexUnlock(&g_bcLock); + return SOFTBUS_OK; +} + +static int32_t GetScanFreq(uint16_t scanInterval, uint16_t scanWindow) +{ + if (scanInterval == SOFTBUS_BC_SCAN_INTERVAL_P2 && scanWindow == SOFTBUS_BC_SCAN_WINDOW_P2) { + return SCAN_FREQ_P2_60_3000; + } + if (scanInterval == SOFTBUS_BC_SCAN_INTERVAL_P10 && scanWindow == SOFTBUS_BC_SCAN_WINDOW_P10) { + return SCAN_FREQ_P10_60_600; + } + if (scanInterval == SOFTBUS_BC_SCAN_INTERVAL_P25 && scanWindow == SOFTBUS_BC_SCAN_WINDOW_P25) { + return SCAN_FREQ_P25_60_240; + } + if (scanInterval == SOFTBUS_BC_SCAN_INTERVAL_P100 && scanWindow == SOFTBUS_BC_SCAN_WINDOW_P100) { + return SCAN_FREQ_P100_1000_1000; + } + return SCAN_FREQ_LOW_POWER; +} + +static bool NeedUpdateScan(int32_t listenerId) +{ + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId] != NULL, SOFTBUS_ERR, DISC_BLE, "interface is null!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId]->StopScan != NULL, + SOFTBUS_ERR, DISC_BLE, "function is null!"); + bool isNeedReset = false; + bool isScanning = false; + int32_t adapterScanId = g_scanManager[listenerId].adapterScanId; + + for (int32_t managerId = 0; managerId < SCAN_NUM_MAX; managerId++) { + if (g_scanManager[managerId].adapterScanId != adapterScanId) { + continue; + } + if (g_scanManager[managerId].isNeedReset) { + isNeedReset = true; + } + if (g_scanManager[managerId].isScanning) { + isScanning = true; + } + } + if (!isScanning) { + return true; + } + if (!isNeedReset) { + return false; + } + int32_t ret = g_interface[g_interfaceId]->StopScan(adapterScanId); + if (ret != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE, "call from adapter fail!"); + return false; + } + return true; +} + +int32_t StartScan(int32_t listenerId, const BcScanParams *param) +{ + DISC_LOGI(DISC_BLE, "enter."); + DISC_CHECK_AND_RETURN_RET_LOGE(param != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, "invalid param!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId] != NULL, SOFTBUS_ERR, DISC_BLE, "interface is null!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId]->StartScan != NULL, + SOFTBUS_ERR, DISC_BLE, "function is null!"); + + int32_t ret = SoftBusMutexLock(&g_scanLock); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, SOFTBUS_LOCK_ERR, DISC_BLE, "mutex err!"); + + if (!CheckScanIdIsValid(listenerId)) { + DISC_LOGE(DISC_BLE, "invalid param listenerId: %d", listenerId); + SoftBusMutexUnlock(&g_scanLock); + return SOFTBUS_ERR; + } + + g_scanManager[listenerId].param = *param; + SoftBusBcScanParams adapterParam; + BuildSoftBusBcScanParams(param, &adapterParam); + + g_scanManager[listenerId].freq = GetScanFreq(param->scanInterval, param->scanWindow); + CheckScanFreq(listenerId, &adapterParam); + + int32_t filterSize = 0; + SoftBusBcScanFilter *adapterFilter = NULL; + + if (NeedUpdateScan(listenerId)) { + GetBcScanFilters(listenerId, &adapterFilter, &filterSize); + DumpBcScanFilter(adapterFilter, filterSize); + + ret = g_interface[g_interfaceId]->StartScan(g_scanManager[listenerId].adapterScanId, &adapterParam, + adapterFilter, filterSize); + SoftBusFree(adapterFilter); + if (ret != SOFTBUS_OK) { + g_scanManager[listenerId].scanCallback->OnStartScanCallback(listenerId, (int32_t)SOFTBUS_BC_STATUS_FAIL); + DISC_LOGE(DISC_BLE, "call from adapter fail!"); + SoftBusMutexUnlock(&g_scanLock); + return ret; + } + } + + g_scanManager[listenerId].isScanning = true; + g_scanManager[listenerId].scanCallback->OnStartScanCallback(listenerId, (int32_t)SOFTBUS_BC_STATUS_SUCCESS); + + SoftBusMutexUnlock(&g_scanLock); + return SOFTBUS_OK; +} + +int32_t StopScan(int32_t listenerId) +{ + DISC_LOGI(DISC_BLE, "enter."); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId] != NULL, SOFTBUS_ERR, DISC_BLE, "interface is null!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId]->StopScan != NULL, + SOFTBUS_ERR, DISC_BLE, "function is null!"); + + int32_t ret = SoftBusMutexLock(&g_scanLock); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, SOFTBUS_LOCK_ERR, DISC_BLE, "mutex err!"); + + if (!CheckScanIdIsValid(listenerId)) { + DISC_LOGE(DISC_BLE, "invalid param listenerId: %d", listenerId); + SoftBusMutexUnlock(&g_scanLock); + return SOFTBUS_ERR; + } + if (!g_scanManager[listenerId].isScanning) { + DISC_LOGI(DISC_BLE, "listenerId %d is not scanning", listenerId); + SoftBusMutexUnlock(&g_scanLock); + return SOFTBUS_OK; + } + + ret = CheckAndStopScan(listenerId); + if (ret != SOFTBUS_OK) { + SoftBusMutexUnlock(&g_scanLock); + return ret; + } + + g_scanManager[listenerId].isScanning = false; + g_scanManager[listenerId].scanCallback->OnStopScanCallback(listenerId, (int32_t)SOFTBUS_BC_STATUS_SUCCESS); + + SoftBusMutexUnlock(&g_scanLock); + return SOFTBUS_OK; +} + +int32_t SetScanFilter(int32_t listenerId, const BcScanFilter *scanFilter, uint8_t filterNum) +{ + DISC_LOGI(DISC_BLE, "enter."); + DISC_CHECK_AND_RETURN_RET_LOGE(scanFilter != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, "param is null!"); + DISC_CHECK_AND_RETURN_RET_LOGE(filterNum != 0, SOFTBUS_INVALID_PARAM, DISC_BLE, "filterNum is 0!"); + int32_t ret = SoftBusMutexLock(&g_scanLock); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, SOFTBUS_LOCK_ERR, DISC_BLE, "mutex err!"); + + if (!CheckScanIdIsValid(listenerId)) { + DISC_LOGE(DISC_BLE, "invalid param listenerId: %d", listenerId); + SoftBusMutexUnlock(&g_scanLock); + return SOFTBUS_ERR; + } + + ReleaseBcScanFilter(listenerId); + g_scanManager[listenerId].filter = (BcScanFilter *)scanFilter; + g_scanManager[listenerId].filterSize = filterNum; + g_scanManager[listenerId].isNeedReset = true; + SoftBusMutexUnlock(&g_scanLock); + return SOFTBUS_OK; +} + +int32_t GetScanFilter(int32_t listenerId, BcScanFilter **scanFilter, uint8_t *filterNum) +{ + DISC_LOGI(DISC_BLE, "enter."); + DISC_CHECK_AND_RETURN_RET_LOGE(scanFilter != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, "invalid param scanFilter!"); + DISC_CHECK_AND_RETURN_RET_LOGE(filterNum != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, "invalid param filterNum!"); + + int32_t ret = SoftBusMutexLock(&g_scanLock); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, SOFTBUS_LOCK_ERR, DISC_BLE, "mutex err!"); + + if (!CheckScanIdIsValid(listenerId)) { + DISC_LOGE(DISC_BLE, "invalid param listenerId: %d", listenerId); + SoftBusMutexUnlock(&g_scanLock); + return SOFTBUS_ERR; + } + + *scanFilter = g_scanManager[listenerId].filter; + *filterNum = g_scanManager[listenerId].filterSize; + SoftBusMutexUnlock(&g_scanLock); + return SOFTBUS_OK; +} + +int32_t QueryBroadcastStatus(int32_t bcId, int32_t *status) +{ + DISC_LOGI(DISC_BLE, "enter."); + (void)bcId; + (void)status; + return SOFTBUS_OK; +} + +bool BroadcastIsLpDeviceAvailable(void) +{ + DISC_LOGI(DISC_BLE, "enter."); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId] != NULL, false, DISC_BLE, "interface is null!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId]->IsLpDeviceAvailable != NULL, + false, DISC_BLE, "function is null!"); + + return g_interface[g_interfaceId]->IsLpDeviceAvailable(); +} + +bool BroadcastSetAdvDeviceParam(const LpBroadcastParam *bcParam, const LpScanParam *scanParam) +{ + DISC_LOGI(DISC_BLE, "enter."); + DISC_CHECK_AND_RETURN_RET_LOGE(bcParam != NULL, false, DISC_BLE, "invalid param bcParam!"); + DISC_CHECK_AND_RETURN_RET_LOGE(scanParam != NULL, false, DISC_BLE, "invalid param scanParam!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId] != NULL, false, DISC_BLE, "interface is null!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId]->SetAdvFilterParam != NULL, + false, DISC_BLE, "function is null!"); + + SoftBusLpBroadcastParam bcDstParam = {0}; + SoftBusLpScanParam scanDstParam = {0}; + + bcDstParam.advHandle = bcParam->bcHandle; + ConvertBcParams(&bcParam->bcParam, &bcDstParam.advParam); + + int32_t ret = BuildSoftbusBroadcastData(&bcParam->packet, &bcDstParam.advData); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, false, DISC_BLE, "Build SoftbusBroadcastData failed!"); + + BuildSoftBusBcScanParams(&scanParam->scanParam, &scanDstParam.scanParam); + BcScanFilter *scanFilter = NULL; + uint8_t filterNum = 0; + ret = GetScanFilter(scanParam->listenerId, &scanFilter, &filterNum); + if (ret != SOFTBUS_OK || scanFilter == NULL || filterNum == 0) { + DISC_LOGE(DISC_BLE, "get listenerId [%d] filters failed!", scanParam->listenerId); + ReleaseSoftbusBroadcastData(&bcDstParam.advData); + return false; + } + scanDstParam.filter = (SoftBusBcScanFilter *)SoftBusCalloc(sizeof(SoftBusBcScanFilter) * (filterNum)); + if (scanDstParam.filter == NULL) { + ReleaseSoftbusBroadcastData(&bcDstParam.advData); + return false; + } + scanDstParam.filterSize = filterNum; + CovertSoftBusBcScanFilters(scanFilter, filterNum, scanDstParam.filter); + + ret = g_interface[g_interfaceId]->SetAdvFilterParam(&bcDstParam, &scanDstParam); + if (!ret) { + DISC_LOGE(DISC_BLE, "call from adapter fail!"); + SoftBusFree(scanDstParam.filter); + ReleaseSoftbusBroadcastData(&bcDstParam.advData); + return false; + } + ReleaseSoftbusBroadcastData(&bcDstParam.advData); + SoftBusFree(scanDstParam.filter); + return true; +} + +int32_t BroadcastGetBroadcastHandle(int32_t bcId, int32_t *bcHandle) +{ + DISC_LOGI(DISC_BLE, "enter."); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId] != NULL, SOFTBUS_ERR, DISC_BLE, "interface is null!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId]->GetBroadcastHandle != NULL, + SOFTBUS_ERR, DISC_BLE, "function is null!"); + + int32_t ret = g_interface[g_interfaceId]->GetBroadcastHandle(g_bcManager[bcId].adapterBcId, bcHandle); + if (ret != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE, "call from adapter fail!"); + return ret; + } + return SOFTBUS_OK; +} + +int32_t BroadcastEnableSyncDataToLpDevice(void) +{ + DISC_LOGI(DISC_BLE, "enter."); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId] != NULL, SOFTBUS_ERR, DISC_BLE, "interface is null!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId]->EnableSyncDataToLpDevice != NULL, + SOFTBUS_ERR, DISC_BLE, "function is null!"); + + int32_t ret = g_interface[g_interfaceId]->EnableSyncDataToLpDevice(); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, DISC_BLE, "call from adapter fail!"); + + return SOFTBUS_OK; +} + +int32_t BroadcastDisableSyncDataToLpDevice(void) +{ + DISC_LOGI(DISC_BLE, "enter."); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId] != NULL, SOFTBUS_ERR, DISC_BLE, "interface is null!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId]->DisableSyncDataToLpDevice != NULL, + SOFTBUS_ERR, DISC_BLE, "function is null!"); + + int32_t ret = g_interface[g_interfaceId]->DisableSyncDataToLpDevice(); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, DISC_BLE, "call from adapter fail!"); + + return SOFTBUS_OK; +} + +int32_t BroadcastSetScanReportChannelToLpDevice(int32_t listenerId, bool enable) +{ + DISC_LOGI(DISC_BLE, "enter."); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId] != NULL, SOFTBUS_ERR, DISC_BLE, "interface is null!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId]->SetScanReportChannelToLpDevice != NULL, + SOFTBUS_ERR, DISC_BLE, "function is null!"); + + int32_t ret = SoftBusMutexLock(&g_scanLock); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, SOFTBUS_LOCK_ERR, DISC_BLE, "mutex err!"); + + if (!CheckScanIdIsValid(listenerId)) { + DISC_LOGE(DISC_BLE, "invalid param listenerId: %d", listenerId); + SoftBusMutexUnlock(&g_scanLock); + return SOFTBUS_ERR; + } + + ret = g_interface[g_interfaceId]->SetScanReportChannelToLpDevice(g_scanManager[listenerId].adapterScanId, enable); + if (ret != SOFTBUS_OK) { + DISC_LOGE(DISC_BLE, "call from adapter fail!"); + SoftBusMutexUnlock(&g_scanLock); + return ret; + } + SoftBusMutexUnlock(&g_scanLock); + return SOFTBUS_OK; +} + +int32_t BroadcastSetLpAdvParam(int32_t duration, int32_t maxExtAdvEvents, int32_t window, + int32_t interval, int32_t bcHandle) +{ + DISC_LOGI(DISC_BLE, "enter."); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId] != NULL, SOFTBUS_ERR, DISC_BLE, "interface is null!"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_interface[g_interfaceId]->SetLpDeviceParam != NULL, + SOFTBUS_ERR, DISC_BLE, "function is null!"); + + int32_t ret = g_interface[g_interfaceId]->SetLpDeviceParam(duration, maxExtAdvEvents, window, interval, bcHandle); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, DISC_BLE, "call from adapter fail!"); + + return SOFTBUS_OK; +} diff --git a/adapter/common/net/bluetooth/common/softbus_adapter_bt_common.c b/adapter/common/net/bluetooth/common/softbus_adapter_bt_common.c index 82566b8cf..1fa56a346 100644 --- a/adapter/common/net/bluetooth/common/softbus_adapter_bt_common.c +++ b/adapter/common/net/bluetooth/common/softbus_adapter_bt_common.c @@ -102,7 +102,7 @@ static void WrapperAclStateChangedCallback(const BdAddr *bdAddr, GapAclState sta return; } - COMM_LOGI(COMM_ADAPTER, "WrapperAclStateChangedCallback, addr:%02X:%02X:***%02X, state=%d, reason=%u", + COMM_LOGD(COMM_ADAPTER, "WrapperAclStateChangedCallback, addr:%02X:%02X:***%02X, state=%d, reason=%u", bdAddr->addr[MAC_FIRST_INDEX], bdAddr->addr[MAC_ONE_INDEX], bdAddr->addr[MAC_FIVE_INDEX], state, reason); int listenerId; int aclState = ConvertAclState(state); @@ -248,7 +248,6 @@ int SoftBusSetBtName(const char *name) return SOFTBUS_ERR; } - void SoftBusBtInit(void) { if (SoftBusGetBtState() == BLE_ENABLE) { diff --git a/adapter/common/net/bluetooth/net_bluetooth.gni b/adapter/common/net/bluetooth/net_bluetooth.gni index 249e3d0b6..961f7194c 100644 --- a/adapter/common/net/bluetooth/net_bluetooth.gni +++ b/adapter/common/net/bluetooth/net_bluetooth.gni @@ -18,6 +18,9 @@ adapter_ble_inc = [ "$dsoftbus_root_path/core/common/include", "$dsoftbus_root_path/adapter/common/net/bluetooth/include", "$dsoftbus_root_path/adapter/common/net/bluetooth/common", + "$dsoftbus_root_path/adapter/common/net/bluetooth/broadcast/interface", + "$dsoftbus_root_path/adapter/common/net/bluetooth/broadcast/adapter/include", + "$dsoftbus_root_path/adapter/common/net/bluetooth/broadcast/adapter/ble/include", ] adapter_ble_src = [ "$dsoftbus_root_path/adapter/common/net/bluetooth/ble/softbus_adapter_ble_gatt.c", @@ -25,7 +28,20 @@ adapter_ble_src = [ "$dsoftbus_root_path/adapter/common/net/bluetooth/ble/softbus_adapter_ble_gatt_server.c", "$dsoftbus_root_path/adapter/common/net/bluetooth/common/adapter_bt_utils.c", "$dsoftbus_root_path/adapter/common/net/bluetooth/common/softbus_adapter_bt_common.c", + "$dsoftbus_root_path/adapter/common/net/bluetooth/broadcast/adapter/ble/src/softbus_ble_utils.c", + "$dsoftbus_root_path/adapter/common/net/bluetooth/broadcast/manager/src/softbus_broadcast_mgr.c", ] + +if (dsoftbus_feature_ex_kits) { + import( + "$dsoftbus_root_path/dsoftbus_enhance/adapter/common/net/bluetooth/broadcast/adapter/ble/adapter_ble_enhance.gni") + + adapter_ble_inc += adapter_ble_enhance_inc + adapter_ble_src += adapter_ble_enhance_src +} else { + adapter_ble_src += [ "$dsoftbus_root_path/adapter/common/net/bluetooth/broadcast/adapter/ble/src/softbus_ble_gatt.c" ] +} + adapter_net_br_src = [ "$dsoftbus_root_path/adapter/common/net/bluetooth/common/softbus_adapter_bt_common.c" ] adapter_ble_external_deps = [ "bluetooth:btframework" ] if (defined(ohos_lite)) { diff --git a/adapter/common/perf/softbus_adapter_perf.c b/adapter/common/perf/softbus_adapter_perf.c index 5abad9e6a..8d65a1771 100644 --- a/adapter/common/perf/softbus_adapter_perf.c +++ b/adapter/common/perf/softbus_adapter_perf.c @@ -15,7 +15,6 @@ #include "softbus_adapter_perf.h" - bool SoftBusIsRamTest(void) { return false; diff --git a/bundle.json b/bundle.json index 83a33f46b..faca402bf 100644 --- a/bundle.json +++ b/bundle.json @@ -110,6 +110,7 @@ "test": [ "//foundation/communication/dsoftbus/tests/adapter:fuzztest", "//foundation/communication/dsoftbus/tests/adapter:unittest", + "//foundation/communication/dsoftbus/tests/core/adapter:fuzztest", "//foundation/communication/dsoftbus/tests/core/adapter:unittest", "//foundation/communication/dsoftbus/tests/core/authentication:fuzztest", "//foundation/communication/dsoftbus/tests/core/authentication:unittest", diff --git a/components/nstackx/nstackx_ctrl/core/coap_discover/coap_client.c b/components/nstackx/nstackx_ctrl/core/coap_discover/coap_client.c index 2c000ff89..ccf3afafb 100644 --- a/components/nstackx/nstackx_ctrl/core/coap_discover/coap_client.c +++ b/components/nstackx/nstackx_ctrl/core/coap_discover/coap_client.c @@ -28,7 +28,6 @@ #include #include #endif -#include #include #include "nstackx_device.h" #include "nstackx_error.h" diff --git a/components/nstackx/nstackx_ctrl/core/coap_discover/coap_discover.c b/components/nstackx/nstackx_ctrl/core/coap_discover/coap_discover.c index 3d19caab9..08f0c16c3 100644 --- a/components/nstackx/nstackx_ctrl/core/coap_discover/coap_discover.c +++ b/components/nstackx/nstackx_ctrl/core/coap_discover/coap_discover.c @@ -189,7 +189,7 @@ static int32_t CoapSendRequestEx(CoapCtxType *ctx, uint8_t coapType, const char DFINDER_LOGD("MYCOAP", "send coap pdu mid: %d", coap_pdu_get_mid(pdu)); DFINDER_MGT_REQ_LOG(&coapRequest); tid = coap_send(session, pdu); - if (tid == COAP_INVALID_TID) { + if (tid == COAP_INVALID_MID) { DFINDER_LOGE(TAG, "coap send failed"); goto SESSION_RELEASE; } @@ -983,7 +983,7 @@ int32_t CoapInitResources(coap_context_t *ctx) DFINDER_LOGE(TAG, "coap resource init discover failed"); return NSTACKX_ENOMEM; } - coap_register_handler(r, COAP_REQUEST_POST, HndPostServiceDiscover); + coap_register_request_handler(r, COAP_REQUEST_POST, HndPostServiceDiscover); coap_resource_set_get_observable(r, NSTACKX_TRUE); coap_add_resource(ctx, r); @@ -994,7 +994,7 @@ int32_t CoapInitResources(coap_context_t *ctx) (void)coap_delete_resource(ctx, r); return NSTACKX_ENOMEM; } - coap_register_handler(msg, COAP_REQUEST_POST, HndPostServiceMsg); + coap_register_request_handler(msg, COAP_REQUEST_POST, HndPostServiceMsg); coap_add_resource(ctx, msg); return NSTACKX_EOK; } diff --git a/components/nstackx/nstackx_ctrl/core/json_payload.c b/components/nstackx/nstackx_ctrl/core/json_payload.c index b5723a1ca..1887833a8 100644 --- a/components/nstackx/nstackx_ctrl/core/json_payload.c +++ b/components/nstackx/nstackx_ctrl/core/json_payload.c @@ -361,7 +361,7 @@ static void ParseBusinessType(const cJSON *data, DeviceInfo *dev) item = cJSON_GetObjectItemCaseSensitive(data, JSON_BUSINESS_TYPE); if (item == NULL) { dev->businessType = NSTACKX_BUSINESS_TYPE_NULL; - DFINDER_LOGW(TAG, "Cannot get businessType json"); + DFINDER_LOGD(TAG, "Cannot get businessType json"); return; } if (!cJSON_IsNumber(item) || (item->valuedouble < 0)) { @@ -377,7 +377,7 @@ static void ParseBusinessDataJsonData(const cJSON *data, DeviceInfo *dev, uint8_ cJSON *item = NULL; item = cJSON_GetObjectItemCaseSensitive(data, JSON_BUSINESS_DATA); if (item == NULL) { - DFINDER_LOGE(TAG, "Cannot get businessData json"); + DFINDER_LOGD(TAG, "Cannot get businessData json"); return; } if (!cJSON_IsString(item)) { diff --git a/components/nstackx/nstackx_ctrl/core/nstackx_device.c b/components/nstackx/nstackx_ctrl/core/nstackx_device.c index 3af3407c4..78b9a3118 100644 --- a/components/nstackx/nstackx_ctrl/core/nstackx_device.c +++ b/components/nstackx/nstackx_ctrl/core/nstackx_device.c @@ -124,8 +124,7 @@ static int32_t UpdateDeviceDbInDeviceList(const CoapCtxType *coapCtx, const Devi } // for non-automatic reply businessType, report each unicast received, even if the content is same if (!receiveBcast && (CheckBusinessTypeReplyUnicast(deviceInfo->businessType) != NSTACKX_EOK)) { - DeviceInfoNotify(deviceInfo); - return NSTACKX_EOK; + return updated ? DeviceInfoNotify(deviceInfo) : NSTACKX_EOK; } if (updated || forceUpdate) { DFINDER_LOGD(TAG, "updated is: %hhu, forceUpdate is: %hhu", updated, forceUpdate); diff --git a/core/adapter/br/mock/wrapper_br_interface.c b/core/adapter/br/mock/wrapper_br_interface.c index 51c0c9a0e..4bf157237 100644 --- a/core/adapter/br/mock/wrapper_br_interface.c +++ b/core/adapter/br/mock/wrapper_br_interface.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 @@ -15,15 +15,12 @@ #include "wrapper_br_interface.h" -#include "message_handler.h" #include "c_header/ohos_bt_def.h" #include "c_header/ohos_bt_gap.h" #include "c_header/ohos_bt_spp.h" #include "c_header/ohos_bt_socket.h" -#include "securec.h" #include "conn_log.h" -#include "softbus_adapter_mem.h" -#include "softbus_def.h" +#include "securec.h" #include "softbus_errcode.h" #include "string.h" @@ -106,6 +103,7 @@ static int32_t Accept(int32_t serverFd) CONN_LOGI(CONN_BR, "[Accept remote device to connect, and serverFd = %d]", serverFd); int32_t ret = SppServerAccept(serverFd); if (ret == BT_SPP_INVALID_ID) { + CONN_LOGE(CONN_BR, "Accept spp server failed"); return SOFTBUS_ERR; } return ret; diff --git a/core/adapter/bus_center/src/bus_center_adapter.c b/core/adapter/bus_center/src/bus_center_adapter.c index 7b34da250..a43da2154 100644 --- a/core/adapter/bus_center/src/bus_center_adapter.c +++ b/core/adapter/bus_center/src/bus_center_adapter.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 @@ -14,7 +14,6 @@ */ #include -#include #include #include @@ -25,9 +24,7 @@ #include "lnn_log.h" #include "lnn_settingdata_event_monitor.h" #include "softbus_adapter_bt_common.h" -#include "softbus_adapter_log.h" #include "softbus_common.h" -#include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_feature_config.h" #include "softbus_utils.h" @@ -109,7 +106,7 @@ int32_t GetCommonDevInfo(const CommonDeviceKey key, char *value, uint32_t len) switch (key) { case COMM_DEVICE_KEY_DEVNAME: LNN_LOGI(LNN_STATE, "set default devicename in netledger init"); - if (strncpy_s(value, len, DEFAULT_DEVICE_NAME, strlen(DEFAULT_DEVICE_NAME)) != EOK) { + if (strcpy_s(value, len, DEFAULT_DEVICE_NAME) != EOK) { return SOFTBUS_ERR; } break; diff --git a/core/adapter/bus_center/src/bus_center_adapter_weak.c b/core/adapter/bus_center/src/bus_center_adapter_weak.c index 820354b5d..295db488e 100644 --- a/core/adapter/bus_center/src/bus_center_adapter_weak.c +++ b/core/adapter/bus_center/src/bus_center_adapter_weak.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 @@ -14,7 +14,6 @@ */ #include -#include #include #include diff --git a/core/adapter/bus_center/src/lnn_ohos_account.cpp b/core/adapter/bus_center/src/lnn_ohos_account.cpp index 63d8aaab3..fc2594088 100644 --- a/core/adapter/bus_center/src/lnn_ohos_account.cpp +++ b/core/adapter/bus_center/src/lnn_ohos_account.cpp @@ -23,7 +23,6 @@ #include "softbus_adapter_crypto.h" #include "softbus_adapter_mem.h" #include "softbus_common.h" -#include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_utils.h" diff --git a/core/adapter/bus_center/src/lnn_ohos_account_adapter.cpp b/core/adapter/bus_center/src/lnn_ohos_account_adapter.cpp index bf841ac9f..17035f8e0 100644 --- a/core/adapter/bus_center/src/lnn_ohos_account_adapter.cpp +++ b/core/adapter/bus_center/src/lnn_ohos_account_adapter.cpp @@ -22,7 +22,7 @@ #include "securec.h" #include "softbus_errcode.h" -#define ACCOUNT_STRTOLL_BASE 10 +static const int32_t ACCOUNT_STRTOLL_BASE = 10; #define DEFAULT_ACCOUNT_NAME "ohosAnonymousName" int32_t GetOsAccountId(char *id, uint32_t idLen, uint32_t *len) diff --git a/core/adapter/bus_center/src/lnn_ohos_account_adapter_virtual.cpp b/core/adapter/bus_center/src/lnn_ohos_account_adapter_virtual.cpp index f33d3f44f..bc6d6c470 100644 --- a/core/adapter/bus_center/src/lnn_ohos_account_adapter_virtual.cpp +++ b/core/adapter/bus_center/src/lnn_ohos_account_adapter_virtual.cpp @@ -19,12 +19,15 @@ int32_t GetOsAccountId(char *id, uint32_t idLen, uint32_t *len) { + (void)id; + (void)idLen; + (void)len; return SOFTBUS_OK; } int64_t GetCurrentAccount(void) { - return 0; + return SOFTBUS_OK; } int32_t GetActiveOsAccountIds(void) diff --git a/core/adapter/bus_center/src/lnn_settingdata_event_monitor.cpp b/core/adapter/bus_center/src/lnn_settingdata_event_monitor.cpp index 196470e4c..c3fd34194 100644 --- a/core/adapter/bus_center/src/lnn_settingdata_event_monitor.cpp +++ b/core/adapter/bus_center/src/lnn_settingdata_event_monitor.cpp @@ -38,10 +38,10 @@ namespace OHOS { namespace BusCenter { static const std::string SETTINGS_DATA_BASE_URI = "datashare:///com.ohos.settingsdata/entry/settingsdata/SETTINGSDATA?Proxy=true"; -static const std::string SETTINGS_DATA_EXT_URI = "datashare:///com.ohos.settingsdata.DataAbility"; -static const std::string SETTINGS_DATA_FIELD_KEYWORD = "KEYWORD"; -static const std::string SETTINGS_DATA_FIELD_VALUE = "VALUE"; -static const std::string PREDICATES_STRING = "settings.general.device_name"; +static constexpr const char *SETTINGS_DATA_EXT_URI = "datashare:///com.ohos.settingsdata.DataAbility"; +static constexpr const char *SETTINGS_DATA_FIELD_KEYWORD = "KEYWORD"; +static constexpr const char *SETTINGS_DATA_FIELD_VALUE = "VALUE"; +static constexpr const char *PREDICATES_STRING = "settings.general.device_name"; std::shared_ptr g_dataShareHelper; static const uint32_t SOFTBUS_SA_ID = 4700; diff --git a/core/adapter/bus_center/src/lnn_settingdata_event_monitor_virtual.cpp b/core/adapter/bus_center/src/lnn_settingdata_event_monitor_virtual.cpp index 30f21e87d..d4a85bd6e 100644 --- a/core/adapter/bus_center/src/lnn_settingdata_event_monitor_virtual.cpp +++ b/core/adapter/bus_center/src/lnn_settingdata_event_monitor_virtual.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 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 @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "lnn_ohos_account.h" #include "lnn_settingdata_event_monitor.h" #include "softbus_errcode.h" diff --git a/core/authentication/include/auth_session_fsm.h b/core/authentication/include/auth_session_fsm.h index d8fd29ef0..523e34182 100644 --- a/core/authentication/include/auth_session_fsm.h +++ b/core/authentication/include/auth_session_fsm.h @@ -91,7 +91,6 @@ int32_t AuthSessionProcessDevInfoDataByConnId(uint64_t connId, bool isServer, co int32_t AuthSessionProcessCloseAckByConnId(uint64_t connId, bool isServer, const uint8_t *data, uint32_t len); int32_t AuthSessionHandleDeviceNotTrusted(const char *udid); int32_t AuthSessionHandleDeviceDisconnected(uint64_t connId); -AuthFsm *GetAuthFsmByAuthSeq(int64_t authSeq); AuthFsm *GetAuthFsmByConnId(uint64_t connId, bool isServer); void AuthSessionFsmExit(void); diff --git a/core/authentication/interface/auth_interface.h b/core/authentication/interface/auth_interface.h index be5382b33..8d8e00bb0 100644 --- a/core/authentication/interface/auth_interface.h +++ b/core/authentication/interface/auth_interface.h @@ -50,6 +50,7 @@ typedef enum { AUTH_LINK_TYPE_BR, AUTH_LINK_TYPE_BLE, AUTH_LINK_TYPE_P2P, + AUTH_LINK_TYPE_ENHANCED_P2P, AUTH_LINK_TYPE_MAX, } AuthLinkType; @@ -69,6 +70,8 @@ typedef struct { char ip[IP_LEN]; int32_t port; int64_t authId; /* for open p2p auth conn */ + ListenerModule moduleId; /* for open enhance p2p auth conn */ + char udid[UDID_BUF_LEN]; } ipInfo; } info; char peerUid[MAX_ACCOUNT_HASH_LEN]; @@ -128,6 +131,9 @@ bool IsAuthHasTrustedRelation(void); int32_t AuthStartListening(AuthLinkType type, const char *ip, int32_t port); void AuthStopListening(AuthLinkType type); +int32_t AuthStartListeningForWifiDirect(AuthLinkType type, const char *ip, int32_t port, ListenerModule *moduleId); +void AuthStopListeningForWifiDirect(AuthLinkType type, ListenerModule moduleId); + typedef struct { int32_t module; int32_t flag; @@ -177,11 +183,11 @@ int32_t AuthGetGroupType(const char *udid, const char *uuid); int32_t AuthInit(void); void AuthDeinit(void); int32_t AuthRestoreAuthManager(const char *udidHash, - const AuthConnInfo *connInfo, int32_t requestId, NodeInfo *nodeInfo, int64_t *authId); + const AuthConnInfo *connInfo, uint32_t requestId, NodeInfo *nodeInfo, int64_t *authId); #ifdef __cplusplus #if __cplusplus } #endif #endif -#endif /* AUTH_INTERFACE_H */ +#endif /* AUTH_INTERFACE_H */ \ No newline at end of file diff --git a/core/authentication/src/auth_common.c b/core/authentication/src/auth_common.c index e7ba916f4..42e49a394 100644 --- a/core/authentication/src/auth_common.c +++ b/core/authentication/src/auth_common.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 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 @@ -131,9 +131,11 @@ static int32_t CustomFunc(const SoftBusMessage *msg, void *param) CHECK_NULL_PTR_RETURN_VALUE(param, SOFTBUS_ERR); EventRemoveInfo *info = (EventRemoveInfo *)param; if (msg->what != (int32_t)info->event) { + AUTH_LOGE(AUTH_CONN, "msg->what and event inequality"); return SOFTBUS_ERR; } if (info->cmpFunc == NULL) { + AUTH_LOGE(AUTH_CONN, "cmpFunc is null"); return SOFTBUS_ERR; } return info->cmpFunc(msg->obj, info->param); @@ -185,13 +187,16 @@ bool GetConfigSupportAsServer(void) uint8_t *DupMemBuffer(const uint8_t *buf, uint32_t size) { if (buf == NULL || size == 0) { + AUTH_LOGE(AUTH_CONN, "param err"); return NULL; } uint8_t *dup = (uint8_t *)SoftBusMalloc(size); if (dup == NULL) { + AUTH_LOGE(AUTH_CONN, "malloc err"); return NULL; } if (memcpy_s(dup, size, buf, size) != EOK) { + AUTH_LOGE(AUTH_CONN, "memcpy err"); SoftBusFree(dup); return NULL; } @@ -278,6 +283,12 @@ bool CompareConnInfo(const AuthConnInfo *info1, const AuthConnInfo *info2, bool return true; } break; + case AUTH_LINK_TYPE_ENHANCED_P2P: + if (info2->type == AUTH_LINK_TYPE_ENHANCED_P2P && info1->info.ipInfo.port == info2->info.ipInfo.port && + strcmp(info1->info.ipInfo.ip, info2->info.ipInfo.ip) == 0) { + return true; + } + break; default: AUTH_LOGE(AUTH_CONN, "unexpected connType=%d", info1->type); return false; @@ -321,6 +332,18 @@ int32_t ConvertToConnectOption(const AuthConnInfo *connInfo, ConnectOption *opti option->socketOption.protocol = LNN_PROTOCOL_IP; option->socketOption.keepAlive = 1; break; + case AUTH_LINK_TYPE_ENHANCED_P2P: + option->type = CONNECT_TCP; + if (strcpy_s(option->socketOption.addr, sizeof(option->socketOption.addr), connInfo->info.ipInfo.ip) != + EOK) { + AUTH_LOGE(AUTH_CONN, "copy ip fail"); + return SOFTBUS_MEM_ERR; + } + option->socketOption.port = connInfo->info.ipInfo.port; + option->socketOption.moduleId = connInfo->info.ipInfo.moduleId; + option->socketOption.protocol = LNN_PROTOCOL_IP; + option->socketOption.keepAlive = 1; + break; default: AUTH_LOGE(AUTH_CONN, "unexpected connType=%d", connInfo->type); return SOFTBUS_ERR; @@ -328,6 +351,14 @@ int32_t ConvertToConnectOption(const AuthConnInfo *connInfo, ConnectOption *opti return SOFTBUS_OK; } +static bool IsEnhanceP2pModuleId(ListenerModule moduleId) +{ + if (moduleId >= AUTH_ENHANCED_P2P_START && moduleId <= AUTH_ENHANCED_P2P_END) { + return true; + } + return false; +} + int32_t ConvertToAuthConnInfo(const ConnectionInfo *info, AuthConnInfo *connInfo) { CHECK_NULL_PTR_RETURN_VALUE(info, SOFTBUS_INVALID_PARAM); @@ -338,7 +369,11 @@ int32_t ConvertToAuthConnInfo(const ConnectionInfo *info, AuthConnInfo *connInfo AUTH_LOGW(AUTH_CONN, "only support LNN_PROTOCOL_IP"); return SOFTBUS_ERR; } - connInfo->type = AUTH_LINK_TYPE_P2P; + if (IsEnhanceP2pModuleId(info->socketInfo.moduleId)) { + connInfo->type = AUTH_LINK_TYPE_ENHANCED_P2P; + } else { + connInfo->type = AUTH_LINK_TYPE_P2P; + } connInfo->info.ipInfo.port = info->socketInfo.port; if (strcpy_s(connInfo->info.ipInfo.ip, IP_LEN, info->socketInfo.addr) != EOK) { AUTH_LOGE(AUTH_CONN, "copy ip fail"); @@ -406,5 +441,6 @@ int32_t GetPeerUdidByNetworkId(const char *networkId, char *udid) } return SOFTBUS_OK; } + AUTH_LOGE(AUTH_CONN, "info or deviceUdid is null"); return SOFTBUS_ERR; -} +} \ No newline at end of file diff --git a/core/authentication/src/auth_connection.c b/core/authentication/src/auth_connection.c index 8540f4a90..2f7d561d3 100644 --- a/core/authentication/src/auth_connection.c +++ b/core/authentication/src/auth_connection.c @@ -23,12 +23,11 @@ #include "lnn_async_callback_utils.h" #include "lnn_event.h" #include "softbus_adapter_bt_common.h" +#include "softbus_adapter_errcode.h" #include "softbus_adapter_mem.h" #include "softbus_adapter_socket.h" -#include "softbus_base_listener.h" #include "softbus_conn_interface.h" #include "softbus_def.h" -#include "softbus_adapter_errcode.h" #define AUTH_CONN_DATA_HEAD_SIZE 24 #define AUTH_CONN_CONNECT_TIMEOUT_MS 10000 @@ -52,6 +51,8 @@ typedef struct { static ListNode g_connRequestList = { &g_connRequestList, &g_connRequestList }; static AuthConnListener g_listener = { 0 }; +static bool g_enahnceP2pModuleIdStatics[AUTH_ENHANCED_P2P_NUM]; + void __attribute__((weak)) RouteBuildClientAuthManager(int32_t cfd) { (void)cfd; @@ -61,6 +62,32 @@ void __attribute__((weak)) RouteClearAuthChannelId(int32_t cfd) (void)cfd; } +static bool IsEnhanceP2pModuleId(ListenerModule moduleId) +{ + if (moduleId >= AUTH_ENHANCED_P2P_START && moduleId <= AUTH_ENHANCED_P2P_END) { + return true; + } + return false; +} + +static ListenerModule AllocateWfiDirectListenerModuleId(void) +{ + for (int32_t i = 0; i < AUTH_ENHANCED_P2P_NUM; i++) { + if (!g_enahnceP2pModuleIdStatics[i]) { + g_enahnceP2pModuleIdStatics[i] = true; + return (ListenerModule)(AUTH_ENHANCED_P2P_START + i); + } + } + return (ListenerModule)SOFTBUS_ERR; +} + +static void FreeWifiDirectListenerModuleId(ListenerModule moduleId) +{ + if (IsEnhanceP2pModuleId(moduleId)) { + g_enahnceP2pModuleIdStatics[moduleId - AUTH_ENHANCED_P2P_START] = false; + } +} + uint64_t GenConnId(int32_t connType, int32_t id) { uint64_t connId = (uint64_t)connType; @@ -86,6 +113,8 @@ const char *GetConnTypeStr(uint64_t connId) return "ble"; case AUTH_LINK_TYPE_P2P: return "p2p"; + case AUTH_LINK_TYPE_ENHANCED_P2P: + return "enhanced_p2p"; default: break; } @@ -101,9 +130,10 @@ int32_t GetFd(uint64_t connId) { return (int32_t)(connId & MASK_UINT64_L32); } - + void UpdateFd(uint64_t *connId, int32_t id) { + CHECK_NULL_PTR_RETURN_VOID(connId); *connId &= MASK_UINT64_H32; *connId |= (((uint64_t)id) & MASK_UINT64_L32); } @@ -348,7 +378,7 @@ static void OnWiFiDataReceived(ListenerModule module, int32_t fd, const AuthData CHECK_NULL_PTR_RETURN_VOID(head); CHECK_NULL_PTR_RETURN_VOID(data); - if (module != AUTH && module != AUTH_P2P) { + if (module != AUTH && module != AUTH_P2P && !IsEnhanceP2pModuleId(module)) { return; } bool fromServer = false; @@ -615,6 +645,7 @@ int32_t ConnectAuthDevice(uint32_t requestId, const AuthConnInfo *connInfo, Conn } __attribute__((fallthrough)); case AUTH_LINK_TYPE_P2P: + case AUTH_LINK_TYPE_ENHANCED_P2P: ret = ConnectCommDevice(connInfo, requestId, sideType); break; default: @@ -662,6 +693,7 @@ void DisconnectAuthDevice(uint64_t *connId) ConnDisconnectDevice(GetConnId(*connId)); __attribute__((fallthrough)); case AUTH_LINK_TYPE_P2P: + case AUTH_LINK_TYPE_ENHANCED_P2P: break; default: AUTH_LOGI(AUTH_CONN, "unknown connType"); @@ -681,6 +713,7 @@ int32_t PostAuthData(uint64_t connId, bool toServer, const AuthDataHead *head, c case AUTH_LINK_TYPE_BLE: case AUTH_LINK_TYPE_BR: case AUTH_LINK_TYPE_P2P: + case AUTH_LINK_TYPE_ENHANCED_P2P: return PostCommData(GetConnId(connId), toServer, head, data); default: AUTH_LOGI(AUTH_CONN, "unknown connType"); @@ -744,22 +777,6 @@ int32_t AuthStartListening(AuthLinkType type, const char *ip, int32_t port) } return StartSocketListening(AUTH, &info); } - case AUTH_LINK_TYPE_P2P: { - LocalListenerInfo local = { - .type = CONNECT_TCP, - .socketOption = { - .addr = "", - .port = port, - .moduleId = AUTH_P2P, - .protocol = LNN_PROTOCOL_IP, - }, - }; - if (strcpy_s(local.socketOption.addr, sizeof(local.socketOption.addr), ip) != EOK) { - AUTH_LOGE(AUTH_CONN, "strcpy_s ip fail"); - return SOFTBUS_MEM_ERR; - } - return ConnStartLocalListening(&local); - } default: AUTH_LOGE(AUTH_CONN, "unsupport linkType=%d", type); break; @@ -774,21 +791,56 @@ void AuthStopListening(AuthLinkType type) case AUTH_LINK_TYPE_WIFI: StopSocketListening(); break; - case AUTH_LINK_TYPE_P2P: { - LocalListenerInfo local = { - .type = CONNECT_TCP, - .socketOption = { - .moduleId = AUTH_P2P, - .protocol = LNN_PROTOCOL_IP, - }, - }; - if (ConnStopLocalListening(&local) != SOFTBUS_OK) { - AUTH_LOGE(AUTH_CONN, "ConnStopLocalListening fail"); - } - break; - } default: AUTH_LOGE(AUTH_CONN, "unsupport linkType=%d", type); break; } } + +int32_t AuthStartListeningForWifiDirect(AuthLinkType type, const char *ip, int32_t port, ListenerModule *moduleId) +{ + AUTH_CHECK_AND_RETURN_RET_LOGE(ip != NULL, SOFTBUS_INVALID_PARAM, AUTH_CONN, "ip is null"); + AUTH_CHECK_AND_RETURN_RET_LOGE(moduleId != NULL, SOFTBUS_INVALID_PARAM, AUTH_CONN, "moduleId is null"); + + LocalListenerInfo local; + local.type = CONNECT_TCP; + local.socketOption.port = port; + local.socketOption.protocol = LNN_PROTOCOL_IP; + int32_t ret = strcpy_s(local.socketOption.addr, sizeof(local.socketOption.addr), ip); + AUTH_CHECK_AND_RETURN_RET_LOGE(ret == EOK, SOFTBUS_STRCPY_ERR, AUTH_CONN, "copy ip failed"); + + if (type == AUTH_LINK_TYPE_P2P) { + local.socketOption.moduleId = AUTH_P2P; + } else if (type == AUTH_LINK_TYPE_ENHANCED_P2P) { + local.socketOption.moduleId = AllocateWfiDirectListenerModuleId(); + AUTH_CHECK_AND_RETURN_RET_LOGE(local.socketOption.moduleId > 0, SOFTBUS_ERR, AUTH_CONN, + "alloc listener module id failed"); + } else { + AUTH_LOGE(AUTH_CONN, "type=%d invalid", type); + return SOFTBUS_INVALID_PARAM; + } + + int32_t realPort = ConnStartLocalListening(&local); + AUTH_CHECK_AND_RETURN_RET_LOGE(realPort > 0, SOFTBUS_ERR, AUTH_CONN, "start local listening failed"); + AUTH_LOGI(AUTH_CONN, "moduleId=%u port=%d", local.socketOption.moduleId, realPort); + *moduleId = local.socketOption.moduleId; + return realPort; +} + +void AuthStopListeningForWifiDirect(AuthLinkType type, ListenerModule moduleId) +{ + AUTH_CHECK_AND_RETURN_LOGE(type == AUTH_LINK_TYPE_P2P || type == AUTH_LINK_TYPE_ENHANCED_P2P, AUTH_CONN, + "type=%d invalid", type); + LocalListenerInfo local = { + .type = CONNECT_TCP, + .socketOption = { + .moduleId = moduleId, + .protocol = LNN_PROTOCOL_IP, + }, + }; + + FreeWifiDirectListenerModuleId(moduleId); + if (ConnStopLocalListening(&local) != SOFTBUS_OK) { + AUTH_LOGE(AUTH_CONN, "ConnStopLocalListening fail"); + } +} \ No newline at end of file diff --git a/core/authentication/src/auth_device_common_key.c b/core/authentication/src/auth_device_common_key.c index 15fb135d0..1f50558cc 100755 --- a/core/authentication/src/auth_device_common_key.c +++ b/core/authentication/src/auth_device_common_key.c @@ -25,10 +25,9 @@ #include "lnn_secure_storage.h" #include "softbus_adapter_crypto.h" #include "softbus_adapter_thread.h" -#include "softbus_json_utils.h" #include "softbus_adapter_mem.h" #include "softbus_errcode.h" -#include "softbus_log_old.h" +#include "softbus_json_utils.h" #include "softbus_utils.h" #define UDID_SHORT_HASH 8 @@ -402,6 +401,10 @@ void AuthRemoveDeviceKey(const char *udidHash, int32_t keyType) void AuthRemoveDeviceKeyByUdid(const char *udidOrHash) { + if (udidOrHash == NULL) { + AUTH_LOGE(AUTH_KEY, "param err"); + return; + } char *anonyUdid = NULL; Anonymize(udidOrHash, &anonyUdid); AUTH_LOGE(AUTH_KEY, "remove device key, udid=%s", anonyUdid); @@ -418,7 +421,7 @@ void AuthRemoveDeviceKeyByUdid(const char *udidOrHash) } while (LnnMapHasNext(it)) { it = LnnMapNext(it); - if (it ==NULL || it->node->value == NULL) { + if (it == NULL || it->node == NULL) { break; } AuthDeviceCommonKey *deviceKey = (AuthDeviceCommonKey *)it->node->value; @@ -464,6 +467,7 @@ int32_t AuthFindDeviceKey(const char *udidHash, int32_t keyType, AuthDeviceKeyIn return SOFTBUS_ERR; } if (KeyLock() != SOFTBUS_OK) { + AUTH_LOGE(AUTH_KEY, "keyLock fail"); return SOFTBUS_ERR; } AuthDeviceCommonKey *data = (AuthDeviceCommonKey *)LnnMapGet(&g_deviceKeyMap, (const char *)keyStr); @@ -500,7 +504,7 @@ static bool AuthParseDeviceKey(const char *deviceKey) } int32_t arraySize = cJSON_GetArraySize(json); if (arraySize <= 0) { - AUTH_LOGE(AUTH_KEY, "no valid deviceKey"); + AUTH_LOGE(AUTH_KEY, "invalid deviceKey log"); cJSON_Delete(json); return false; } @@ -521,7 +525,7 @@ static bool AuthParseDeviceKey(const char *deviceKey) void AuthUpdateKeyIndex(const char *udidHash, int32_t keyType, int64_t index, bool isServer) { if (udidHash == NULL) { - AUTH_LOGW(AUTH_KEY, "update fail"); + AUTH_LOGE(AUTH_KEY, "udidiHash log update fail"); return; } char keyStr[MAP_KEY_LEN] = {0}; @@ -534,6 +538,10 @@ void AuthUpdateKeyIndex(const char *udidHash, int32_t keyType, int64_t index, bo return; } AuthDeviceCommonKey *data = (AuthDeviceCommonKey *)LnnMapGet(&g_deviceKeyMap, (const char *)keyStr); + if (data == NULL) { + AUTH_LOGE(AUTH_KEY, "data is nullptr"); + return; + } data->keyInfo.keyIndex = index; data->keyInfo.isServerSide = isServer; KeyUnlock(); @@ -566,7 +574,7 @@ void AuthLoadDeviceKey(void) AUTH_LOGD(AUTH_KEY, "load deviceKey finish"); } -void AUthClearDeviceKey(void) +void AuthClearDeviceKey(void) { /*need aging mechanism*/ LnnMapDelete(&g_deviceKeyMap); diff --git a/core/authentication/src/auth_hichain.c b/core/authentication/src/auth_hichain.c index b52964cfc..b3431d537 100644 --- a/core/authentication/src/auth_hichain.c +++ b/core/authentication/src/auth_hichain.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 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 @@ -22,9 +22,8 @@ #include "auth_hichain_adapter.h" #include "auth_log.h" #include "auth_session_fsm.h" -#include "device_auth.h" #include "bus_center_manager.h" -#include "device_auth_defines.h" +#include "device_auth.h" #include "softbus_adapter_mem.h" #include "softbus_def.h" #include "softbus_json_utils.h" @@ -184,6 +183,7 @@ static void OnGroupCreated(const char *groupInfo) return; } GroupInfo info; + (void)memset_s(&info, sizeof(GroupInfo), 0, sizeof(GroupInfo)); if (ParseGroupInfo(groupInfo, &info) != SOFTBUS_OK) { return; } @@ -212,6 +212,7 @@ static void OnGroupDeleted(const char *groupInfo) return; } GroupInfo info; + (void)memset_s(&info, sizeof(GroupInfo), 0, sizeof(GroupInfo)); if (ParseGroupInfo(groupInfo, &info) != SOFTBUS_OK) { return; } @@ -259,7 +260,7 @@ int32_t RegTrustDataChangeListener(const TrustDataChangeListener *listener) void UnregTrustDataChangeListener(void) { int32_t ret = UnregChangeListener(AUTH_APPID); - if (ret != 0) { + if (ret != SOFTBUS_OK) { AUTH_LOGE(AUTH_HICHAIN, "hichain unRegDataChangeListener err=%d", ret); } (void)memset_s(&g_dataChangeListener, sizeof(TrustDataChangeListener), 0, sizeof(TrustDataChangeListener)); @@ -289,6 +290,7 @@ int32_t HichainStartAuth(int64_t authSeq, const char *udid, const char *uid) int32_t HichainProcessData(int64_t authSeq, const uint8_t *data, uint32_t len) { if (data == NULL) { + AUTH_LOGE(AUTH_HICHAIN, "data is null"); return SOFTBUS_INVALID_PARAM; } int32_t ret = ProcessAuthData(authSeq, data, len, &g_hichainCallback); diff --git a/core/authentication/src/auth_hichain_adapter.c b/core/authentication/src/auth_hichain_adapter.c index c328e658f..37aa376b6 100644 --- a/core/authentication/src/auth_hichain_adapter.c +++ b/core/authentication/src/auth_hichain_adapter.c @@ -15,9 +15,7 @@ #include "auth_hichain_adapter.h" -#include #include -#include #include "auth_common.h" #include "auth_hichain.h" @@ -81,6 +79,8 @@ int32_t RegChangeListener(const char *appId, DataChangeListener *listener) int32_t UnregChangeListener(const char *appId) { + AUTH_CHECK_AND_RETURN_RET_LOGE(appId != NULL, SOFTBUS_INVALID_PARAM, AUTH_HICHAIN, + "appId is null"); const DeviceGroupManager *gmInstance = GetGmInstance(); AUTH_CHECK_AND_RETURN_RET_LOGE(gmInstance != NULL, SOFTBUS_ERR, AUTH_HICHAIN, "hichain GetGmInstance failed"); @@ -286,6 +286,7 @@ uint32_t HichainGetJoinedGroups(int32_t groupType) void CancelRequest(int64_t authReqId, const char *appId) { + AUTH_CHECK_AND_RETURN_LOGE(appId != NULL, AUTH_HICHAIN, "appId is null"); if (g_hichain == NULL) { g_hichain = InitHichain(); } diff --git a/core/authentication/src/auth_interface.c b/core/authentication/src/auth_interface.c index 4cc8eec9a..7f3c3048c 100644 --- a/core/authentication/src/auth_interface.c +++ b/core/authentication/src/auth_interface.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 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 @@ -124,6 +124,10 @@ static void NotifyTransDisconnected(int64_t authId) int32_t AuthOpenConn(const AuthConnInfo *info, uint32_t requestId, const AuthConnCallback *callback, bool isMeta) { + if (info == NULL || callback == NULL) { + AUTH_LOGE(AUTH_CONN, "info or callback is null"); + return SOFTBUS_INVALID_PARAM; + } if (isMeta) { return AuthMetaOpenConn(info, requestId, callback); } @@ -185,10 +189,10 @@ int64_t AuthGetIdByUuid(const char *uuid, AuthLinkType type, bool isServer, bool } int32_t AuthRestoreAuthManager(const char *udidHash, - const AuthConnInfo *connInfo, int32_t requestId, NodeInfo *nodeInfo, int64_t *authId) + const AuthConnInfo *connInfo, uint32_t requestId, NodeInfo *nodeInfo, int64_t *authId) { if (udidHash == NULL || connInfo == NULL || nodeInfo == NULL || authId == NULL) { - AUTH_LOGW(AUTH_CONN, "restore manager fail because para error"); + AUTH_LOGE(AUTH_CONN, "restore manager fail because para error"); return SOFTBUS_ERR; } // get device key @@ -367,7 +371,7 @@ TrustedReturnType AuthHasTrustedRelation(void) return TRUSTED_RELATION_IGNORE; } SoftBusFree(udidArray); - AUTH_LOGD(AUTH_CONN, "auth get trusted relation num=%d", num); + AUTH_LOGD(AUTH_CONN, "auth get trusted relation num=%u", num); return (num != 0) ? TRUSTED_RELATION_YES : TRUSTED_RELATION_NO; } diff --git a/core/authentication/src/auth_manager.c b/core/authentication/src/auth_manager.c index 53752fbc9..fa323d24c 100644 --- a/core/authentication/src/auth_manager.c +++ b/core/authentication/src/auth_manager.c @@ -28,14 +28,14 @@ #include "auth_session_message.h" #include "bus_center_manager.h" #include "lnn_async_callback_utils.h" -#include "lnn_heartbeat_ctrl.h" #include "lnn_app_bind_interface.h" #include "lnn_decision_db.h" +#include "lnn_feature_capability.h" +#include "lnn_heartbeat_ctrl.h" +#include "lnn_net_builder.h" #include "softbus_adapter_hitrace.h" #include "softbus_adapter_mem.h" #include "softbus_def.h" -#include "lnn_feature_capability.h" -#include "lnn_net_builder.h" #define MAX_AUTH_VALID_PERIOD (30 * 60 * 1000L) /* 30 mins */ #define SCHEDULE_UPDATE_SESSION_KEY_PERIOD ((5 * 60 + 30) * 60 * 1000L) /* 5 hour 30 mins */ @@ -56,7 +56,7 @@ static bool g_regDataChangeListener = false; /* Auth Manager */ AuthManager *NewAuthManager(int64_t authSeq, const AuthSessionInfo *info) { - AuthManager *auth = (AuthManager *)SoftBusMalloc(sizeof(AuthManager)); + AuthManager *auth = (AuthManager *)SoftBusCalloc(sizeof(AuthManager)); if (auth == NULL) { AUTH_LOGW(AUTH_FSM, "malloc AuthManager fail"); return NULL; @@ -79,8 +79,7 @@ AuthManager *NewAuthManager(int64_t authSeq, const AuthSessionInfo *info) } else { ListTailInsert(&g_authClientList, &auth->node); } - AUTH_LOGI(AUTH_FSM, "create auth manager, side=%s, authId=%" PRId64, - GetAuthSideStr(auth->isServer), auth->authId); + AUTH_LOGI(AUTH_FSM, "create auth manager, side=%s, authId=%" PRId64, GetAuthSideStr(auth->isServer), auth->authId); return auth; } @@ -103,7 +102,7 @@ static AuthManager *DupAuthManager(const AuthManager *auth) void DelAuthManager(AuthManager *auth, bool removeAuthFromList) { - CHECK_NULL_PTR_RETURN_VOID(auth); + AUTH_CHECK_AND_RETURN_LOGE(auth != NULL, AUTH_FSM, "auth is null"); if (removeAuthFromList) { char *anonyUdid = NULL; Anonymize(auth->udid, &anonyUdid); @@ -203,6 +202,8 @@ static AuthManager *FindAuthManagerByAuthId(int64_t authId) return item; } } + + AUTH_LOGE(AUTH_FSM, "auth manager[%" PRId64 "] not found", authId); return NULL; } @@ -272,14 +273,16 @@ static int32_t UpdateAuthManagerByAuthId( static ConnectionAddrType ConvertAuthLinkTypeToConnect(AuthLinkType type) { - if (type == AUTH_LINK_TYPE_WIFI) { - return CONNECTION_ADDR_WLAN; - } else if (type == AUTH_LINK_TYPE_BLE) { - return CONNECTION_ADDR_BLE; - } else if (type == AUTH_LINK_TYPE_BR) { - return CONNECTION_ADDR_BR; + switch (type) { + case AUTH_LINK_TYPE_WIFI: + return CONNECTION_ADDR_WLAN; + case AUTH_LINK_TYPE_BLE: + return CONNECTION_ADDR_BLE; + case AUTH_LINK_TYPE_BR: + return CONNECTION_ADDR_BR; + default: + return CONNECTION_ADDR_MAX; } - return CONNECTION_ADDR_MAX; } void RemoveAuthSessionKeyByIndex(int64_t authId, int32_t index) @@ -289,8 +292,8 @@ void RemoveAuthSessionKeyByIndex(int64_t authId, int32_t index) } AuthManager *auth = FindAuthManagerByAuthId(authId); if (auth == NULL) { - AUTH_LOGE(AUTH_CONN, "auth manager already removed, authId=%" PRId64, authId); ReleaseAuthLock(); + AUTH_LOGI(AUTH_CONN, "auth manager already removed, authId=%" PRId64, authId); return; } RemoveSessionkeyByIndex(&auth->sessionKeyList, index); @@ -472,8 +475,7 @@ static int64_t GetAuthIdByConnInfo(const AuthConnInfo *connInfo, bool isServer) } AuthManager *auth = FindAuthManagerByConnInfo(connInfo, isServer); if (auth == NULL) { - AUTH_LOGE(AUTH_CONN, "auth manager not found, connType=%d, side=%s", connInfo->type, - GetAuthSideStr(isServer)); + AUTH_LOGE(AUTH_CONN, "auth manager not found, connType=%d, side=%s", connInfo->type, GetAuthSideStr(isServer)); ReleaseAuthLock(); return AUTH_INVALID_ID; } @@ -501,7 +503,8 @@ static int64_t GetActiveAuthIdByConnInfo(const AuthConnInfo *connInfo) /* Get lastest authId */ int64_t authId = AUTH_INVALID_ID; uint64_t maxVerifyTime = 0; - for (uint32_t i = 0; i < sizeof(auth) / sizeof(auth[0]); i++) { + uint32_t authMgrNum = sizeof(auth) / sizeof(auth[0]); + for (uint32_t i = 0; i < authMgrNum; i++) { if (auth[i] == NULL) { continue; } @@ -518,10 +521,10 @@ static int64_t GetActiveAuthIdByConnInfo(const AuthConnInfo *connInfo) int32_t AuthManagerSetSessionKey(int64_t authSeq, const AuthSessionInfo *info, const SessionKey *sessionKey, bool isConnect) { - CHECK_NULL_PTR_RETURN_VALUE(info, SOFTBUS_INVALID_PARAM); - CHECK_NULL_PTR_RETURN_VALUE(sessionKey, SOFTBUS_INVALID_PARAM); - AUTH_LOGI(AUTH_FSM, "SetSessionKey: authSeq=%" PRId64 ", side=%s, requestId=%u", - authSeq, GetAuthSideStr(info->isServer), info->requestId); + AUTH_CHECK_AND_RETURN_RET_LOGE(info != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "info is NULL"); + AUTH_CHECK_AND_RETURN_RET_LOGE(sessionKey != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "sessionKey is NULL"); + AUTH_LOGI(AUTH_FSM, "SetSessionKey: authSeq=%" PRId64 ", side=%s, requestId=%u", authSeq, + GetAuthSideStr(info->isServer), info->requestId); if (!RequireAuthLock()) { return SOFTBUS_LOCK_ERR; } @@ -575,13 +578,12 @@ int32_t AuthManagerSetSessionKey(int64_t authSeq, const AuthSessionInfo *info, return SOFTBUS_OK; } - int32_t AuthManagerGetSessionKey(int64_t authSeq, const AuthSessionInfo *info, SessionKey *sessionKey) { - CHECK_NULL_PTR_RETURN_VALUE(info, SOFTBUS_INVALID_PARAM); - CHECK_NULL_PTR_RETURN_VALUE(sessionKey, SOFTBUS_INVALID_PARAM); - AUTH_LOGI(AUTH_FSM, "GetSessionKey: authSeq=%" PRId64 ", side=%s, requestId=%u", - authSeq, GetAuthSideStr(info->isServer), info->requestId); + AUTH_CHECK_AND_RETURN_RET_LOGE(info != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "info is NULL"); + AUTH_CHECK_AND_RETURN_RET_LOGE(sessionKey != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "sessionKey is NULL"); + AUTH_LOGI(AUTH_FSM, "GetSessionKey: authSeq=%" PRId64 ", side=%s, requestId=%u", authSeq, + GetAuthSideStr(info->isServer), info->requestId); if (!RequireAuthLock()) { return SOFTBUS_LOCK_ERR; } @@ -605,9 +607,10 @@ static void NotifyDeviceVerifyPassed(int64_t authId, const NodeInfo *nodeInfo) { AuthManager *auth = GetAuthManagerByAuthId(authId); if (auth == NULL) { + AUTH_LOGE(AUTH_FSM, "get auth manager failed"); return; } - if (auth->connInfo.type == AUTH_LINK_TYPE_P2P) { + if (auth->connInfo.type == AUTH_LINK_TYPE_P2P || auth->connInfo.type == AUTH_LINK_TYPE_ENHANCED_P2P) { /* P2P auth no need notify to LNN. */ DelAuthManager(auth, false); return; @@ -724,8 +727,7 @@ static int32_t StartVerifyDevice(uint32_t requestId, const AuthConnInfo *connInf return SOFTBUS_AUTH_INNER_ERR; } if (waitNum > 1) { - AUTH_LOGI(AUTH_CONN, "wait last verify request complete, waitNum=%u, requestId=%u", - waitNum, requestId); + AUTH_LOGI(AUTH_CONN, "wait last verify request complete, waitNum=%u, requestId=%u", waitNum, requestId); SoftbusHitraceStop(); return SOFTBUS_OK; } @@ -782,7 +784,8 @@ static void ReportAuthRequestPassed(uint32_t requestId, int64_t authId, const No do { if (CheckAuthConnCallback(&request.connCb)) { NotifyDeviceVerifyPassed(authId, nodeInfo); - if (request.connInfo.type == AUTH_LINK_TYPE_WIFI || request.connInfo.type == AUTH_LINK_TYPE_P2P) { + if (request.connInfo.type == AUTH_LINK_TYPE_WIFI || request.connInfo.type == AUTH_LINK_TYPE_P2P || + request.connInfo.type == AUTH_LINK_TYPE_ENHANCED_P2P) { PerformAuthConnCallback(request.requestId, SOFTBUS_OK, authId); DelAuthRequest(request.requestId); continue; @@ -829,6 +832,7 @@ static int32_t ComplementConnectionInfoIfNeed(AuthManager *auth, const char *udi return SOFTBUS_OK; } if (udid == NULL || strlen(udid) == 0) { + AUTH_LOGE(AUTH_FSM, "invalid udid"); return SOFTBUS_INVALID_PARAM; } int32_t ret = SoftBusGenerateStrHash((unsigned char *)udid, strlen(udid), @@ -839,9 +843,9 @@ static int32_t ComplementConnectionInfoIfNeed(AuthManager *auth, const char *udi void AuthManagerSetAuthPassed(int64_t authSeq, const AuthSessionInfo *info) { int64_t authId; - CHECK_NULL_PTR_RETURN_VOID(info); - AUTH_LOGI(AUTH_FSM, "SetAuthPassed: authSeq=%" PRId64 ", side=%s, requestId=%u", - authSeq, GetAuthSideStr(info->isServer), info->requestId); + AUTH_CHECK_AND_RETURN_LOGE(info != NULL, AUTH_FSM, "info is null"); + AUTH_LOGI(AUTH_FSM, "SetAuthPassed: authSeq=%" PRId64 ", side=%s, requestId=%u", authSeq, + GetAuthSideStr(info->isServer), info->requestId); if (!RequireAuthLock()) { return; @@ -849,16 +853,16 @@ void AuthManagerSetAuthPassed(int64_t authSeq, const AuthSessionInfo *info) AuthManager *auth = FindAuthManagerByConnInfo(&info->connInfo, info->isServer); if (auth == NULL) { PrintAuthConnInfo(&info->connInfo); - AUTH_LOGE(AUTH_FSM, "auth manager not found, connType=%d, side=%s", - info->connInfo.type, GetAuthSideStr(info->isServer)); ReleaseAuthLock(); + AUTH_LOGE(AUTH_FSM, "auth manager not found, connType=%d, side=%s", info->connInfo.type, + GetAuthSideStr(info->isServer)); return; } int32_t ret = ComplementConnectionInfoIfNeed(auth, info->nodeInfo.deviceInfo.deviceUdid); if (ret != SOFTBUS_OK) { - AUTH_LOGE(AUTH_FSM, "complement auth connection info failed, authSeq=%" PRId64 ", error=%d", authSeq, ret); ReleaseAuthLock(); + AUTH_LOGE(AUTH_FSM, "complement auth connection info failed, authSeq=%" PRId64 ", error=%d", authSeq, ret); return; } @@ -881,8 +885,9 @@ void AuthManagerSetAuthPassed(int64_t authSeq, const AuthSessionInfo *info) void AuthManagerSetAuthFailed(int64_t authSeq, const AuthSessionInfo *info, int32_t reason) { - AUTH_LOGE(AUTH_FSM, "SetAuthFailed: authSeq=%" PRId64 ", requestId=%u, reason=%d", - authSeq, info->requestId, reason); + AUTH_CHECK_AND_RETURN_LOGE(info != NULL, AUTH_FSM, "auth session info is null"); + AUTH_LOGE( + AUTH_FSM, "SetAuthFailed: authSeq=%" PRId64 ", requestId=%u, reason=%d", authSeq, info->requestId, reason); AuthManager *auth = GetAuthManagerByConnInfo(&info->connInfo, info->isServer); if (auth != NULL && auth->hasAuthPassed) { AUTH_LOGE(AUTH_FSM, "update session key fail, authId=%" PRId64, auth->authId); @@ -903,7 +908,7 @@ void AuthManagerSetAuthFailed(int64_t authSeq, const AuthSessionInfo *info, int3 static void HandleBleDisconnectDelay(const void *para) { - CHECK_NULL_PTR_RETURN_VOID(para); + AUTH_CHECK_AND_RETURN_LOGE(para != NULL, AUTH_FSM, "para is null"); uint64_t connId = *((uint64_t *)para); DisconnectAuthDevice(&connId); } @@ -915,6 +920,7 @@ static void BleDisconnectDelay(uint64_t connId, uint64_t delayMs) void AuthManagerSetAuthFinished(int64_t authSeq, const AuthSessionInfo *info) { + AUTH_CHECK_AND_RETURN_LOGE(info != NULL, AUTH_FSM, "auth session info is null"); AUTH_LOGI(AUTH_FSM, "SetAuthFinished: authSeq=%" PRId64 ", requestId=%u", authSeq, info->requestId); if (info->isServer) { AUTH_LOGI(AUTH_FSM, "SERVER: wait client close connection"); @@ -969,7 +975,7 @@ static void HandleBleConnectResult(uint32_t requestId, int64_t authId, uint64_t AUTH_LOGI(AUTH_CONN, "get request info failed, requestId=%u", requestId); return; } - AuthManager inAuth = {.connId = connId }; + AuthManager inAuth = { .connId = connId }; if (UpdateAuthManagerByAuthId(authId, SetAuthConnId, &inAuth) != SOFTBUS_OK) { AUTH_LOGE(AUTH_CONN, "set auth connId fail, requestId=%u", requestId); return; @@ -1076,8 +1082,8 @@ static void FlushDeviceProcess(const AuthConnInfo *connInfo, bool isServer) AuthManager *auth = FindAuthManagerByConnInfo(connInfo, isServer); if (auth == NULL) { PrintAuthConnInfo(connInfo); - AUTH_LOGI(AUTH_FSM, "auth manager not found"); ReleaseAuthLock(); + AUTH_LOGE(AUTH_FSM, "auth manager not found"); return; } if (PostVerifyDeviceMessage(auth, FLAG_REPLY) == SOFTBUS_OK) { @@ -1130,7 +1136,6 @@ static void HandleCloseAckData( } } - static void HandleConnectionData( uint64_t connId, const AuthConnInfo *connInfo, bool fromServer, const AuthDataHead *head, const uint8_t *data) { @@ -1196,7 +1201,7 @@ static void OnDataReceived( static void HandleDisconnectedEvent(const void *para) { - CHECK_NULL_PTR_RETURN_VOID(para); + AUTH_CHECK_AND_RETURN_LOGE(para != NULL, AUTH_FSM, "para is null"); uint64_t connId = *((uint64_t *)para); uint32_t num = 0; uint64_t dupConnId = connId; @@ -1210,7 +1215,8 @@ static void HandleDisconnectedEvent(const void *para) if (g_transCallback.OnDisconnected != NULL) { g_transCallback.OnDisconnected(authIds[i]); } - if (GetConnType(connId) == AUTH_LINK_TYPE_WIFI || GetConnType(connId) == AUTH_LINK_TYPE_P2P) { + if (GetConnType(connId) == AUTH_LINK_TYPE_WIFI || GetConnType(connId) == AUTH_LINK_TYPE_P2P || + GetConnType(connId) == AUTH_LINK_TYPE_ENHANCED_P2P) { NotifyDeviceDisconnect(authIds[i]); DisconnectAuthDevice(&dupConnId); AuthManager inAuth = { .connId = dupConnId }; @@ -1267,13 +1273,13 @@ void AuthHandleLeaveLNN(int64_t authId) } AuthManager *auth = FindAuthManagerByAuthId(authId); if (auth == NULL) { - AUTH_LOGI(AUTH_FSM, "auth manager not found, authId=%" PRId64, authId); ReleaseAuthLock(); + AUTH_LOGE(AUTH_FSM, "auth manager not found, authId=%" PRId64, authId); return; } if (!auth->hasAuthPassed) { - AUTH_LOGI(AUTH_FSM, "auth pass = false, don't need to leave"); ReleaseAuthLock(); + AUTH_LOGI(AUTH_FSM, "auth pass = false, don't need to leave"); return; } if (auth->connInfo.type == AUTH_LINK_TYPE_WIFI) { @@ -1324,7 +1330,7 @@ static int32_t TryGetBrConnInfo(const char *uuid, AuthConnInfo *connInfo) return SOFTBUS_AUTH_GET_BR_CONN_INFO_FAIL; } if (((local & (1 << BIT_BR)) == 0) || ((remote & (1 << BIT_BR)) == 0)) { - AUTH_LOGI(AUTH_CONN, "can't support BR"); + AUTH_LOGW(AUTH_CONN, "can't support BR"); return SOFTBUS_AUTH_GET_BR_CONN_INFO_FAIL; } if (LnnGetRemoteStrInfo(networkId, STRING_KEY_BT_MAC, connInfo->info.brInfo.brMac, BT_MAC_LEN) != SOFTBUS_OK || @@ -1342,8 +1348,10 @@ int32_t AuthDeviceGetPreferConnInfo(const char *uuid, AuthConnInfo *connInfo) AUTH_LOGE(AUTH_CONN, "invalid uuid or connInfo"); return SOFTBUS_INVALID_PARAM; } - AuthLinkType linkList[] = { AUTH_LINK_TYPE_WIFI, AUTH_LINK_TYPE_BR, AUTH_LINK_TYPE_BLE }; - for (uint32_t i = 0; i < sizeof(linkList) / sizeof(linkList[0]); i++) { + AuthLinkType linkList[] = { AUTH_LINK_TYPE_ENHANCED_P2P, AUTH_LINK_TYPE_WIFI, AUTH_LINK_TYPE_BR, + AUTH_LINK_TYPE_BLE }; + uint32_t linkTypeNum = sizeof(linkList) / sizeof(linkList[0]); + for (uint32_t i = 0; i < linkTypeNum; i++) { if (GetAuthConnInfoByUuid(uuid, linkList[i], connInfo) != SOFTBUS_OK) { continue; } @@ -1373,7 +1381,6 @@ bool AuthDeviceCheckConnInfo(const char *uuid, AuthLinkType type, bool checkConn return checkConnection ? CheckActiveAuthConnection(&connInfo) : true; } - int32_t AuthDeviceOpenConn(const AuthConnInfo *info, uint32_t requestId, const AuthConnCallback *callback) { if (info == NULL || !CheckAuthConnCallback(callback)) { @@ -1398,6 +1405,14 @@ int32_t AuthDeviceOpenConn(const AuthConnInfo *info, uint32_t requestId, const A return StartReconnectDevice(authId, info, requestId, callback); } return StartVerifyDevice(requestId, info, NULL, callback, true); + case AUTH_LINK_TYPE_ENHANCED_P2P: + authId = GetActiveAuthIdByConnInfo(info); + if (authId != AUTH_INVALID_ID) { + AUTH_LOGI(AUTH_CONN, "reuse enhanced p2p authId=%" PRId64, authId); + callback->onConnOpened(requestId, authId); + break; + } + return StartVerifyDevice(requestId, info, NULL, callback, true); default: AUTH_LOGE(AUTH_CONN, "unknown connType: %d", info->type); return SOFTBUS_INVALID_PARAM; @@ -1415,6 +1430,7 @@ void AuthDeviceCloseConn(int64_t authId) switch (auth->connInfo.type) { case AUTH_LINK_TYPE_WIFI: case AUTH_LINK_TYPE_P2P: + case AUTH_LINK_TYPE_ENHANCED_P2P: /* Do nothing. */ break; case AUTH_LINK_TYPE_BR: @@ -1443,6 +1459,7 @@ int32_t AuthDevicePostTransData(int64_t authId, const AuthTransData *dataInfo) head.module = dataInfo->module; head.seq = dataInfo->seq; head.flag = dataInfo->flag; + head.len = 0; uint8_t *encData = NULL; if (EncryptInner(&auth->sessionKeyList, dataInfo->data, dataInfo->len, &encData, &head.len) != SOFTBUS_OK) { AUTH_LOGE(AUTH_KEY, "encrypt trans data fail"); @@ -1463,6 +1480,7 @@ int32_t AuthDevicePostTransData(int64_t authId, const AuthTransData *dataInfo) int32_t RegGroupChangeListener(const GroupChangeListener *listener) { if (listener == NULL) { + AUTH_LOGE(AUTH_CONN, "listener is null"); return SOFTBUS_INVALID_PARAM; } g_groupChangeListener.onGroupCreated = listener->onGroupCreated; @@ -1600,7 +1618,6 @@ uint32_t AuthGetDecryptSize(uint32_t inLen) return inLen - OVERHEAD_LEN; } - int32_t AuthDeviceEncrypt(int64_t authId, const uint8_t *inData, uint32_t inLen, uint8_t *outData, uint32_t *outLen) { if (inData == NULL || inLen == 0 || outData == NULL || outLen == NULL || *outLen < AuthGetEncryptSize(inLen)) { @@ -1620,7 +1637,6 @@ int32_t AuthDeviceEncrypt(int64_t authId, const uint8_t *inData, uint32_t inLen, return SOFTBUS_OK; } - int32_t AuthDeviceDecrypt(int64_t authId, const uint8_t *inData, uint32_t inLen, uint8_t *outData, uint32_t *outLen) { if (inData == NULL || inLen == 0 || outData == NULL || outLen == NULL || *outLen < AuthGetDecryptSize(inLen)) { @@ -1790,4 +1806,4 @@ void AuthDeviceDeinit(void) AuthSessionFsmExit(); AuthCommonDeinit(); AUTH_LOGI(AUTH_INIT, "auth deinit succ"); -} +} \ No newline at end of file diff --git a/core/authentication/src/auth_request.c b/core/authentication/src/auth_request.c index 01ad3ca75..6f234464e 100644 --- a/core/authentication/src/auth_request.c +++ b/core/authentication/src/auth_request.c @@ -15,8 +15,6 @@ #include "auth_request.h" -#include - #include "auth_common.h" #include "auth_log.h" #include "softbus_adapter_mem.h" @@ -35,7 +33,7 @@ static AuthRequest *FindAuthRequestByRequestId(uint64_t requestId) return NULL; } -static uint32_t GetAuthRequestWaitNum(AuthRequest *request) +static uint32_t GetAuthRequestWaitNum(const AuthRequest *request) { uint32_t num = 0; AuthRequest *item = NULL; @@ -67,7 +65,7 @@ static uint32_t GetAuthRequestWaitNum(AuthRequest *request) uint32_t AddAuthRequest(const AuthRequest *request) { - CHECK_NULL_PTR_RETURN_VALUE(request, 0); + AUTH_CHECK_AND_RETURN_RET_LOGE(request != NULL, 0, AUTH_CONN, "request is NULL"); AuthRequest *newRequest = SoftBusCalloc(sizeof(AuthRequest)); if (newRequest == NULL) { AUTH_LOGE(AUTH_CONN, "malloc AuthRequest fail"); @@ -86,7 +84,7 @@ uint32_t AddAuthRequest(const AuthRequest *request) int32_t GetAuthRequest(uint32_t requestId, AuthRequest *request) { - CHECK_NULL_PTR_RETURN_VALUE(request, SOFTBUS_INVALID_PARAM); + AUTH_CHECK_AND_RETURN_RET_LOGE(request != NULL, SOFTBUS_INVALID_PARAM, AUTH_CONN, "request is NULL"); if (!RequireAuthLock()) { return SOFTBUS_LOCK_ERR; } @@ -102,9 +100,10 @@ int32_t GetAuthRequest(uint32_t requestId, AuthRequest *request) int32_t GetAuthRequestNoLock(uint32_t requestId, AuthRequest *request) { - CHECK_NULL_PTR_RETURN_VALUE(request, SOFTBUS_INVALID_PARAM); + AUTH_CHECK_AND_RETURN_RET_LOGE(request != NULL, SOFTBUS_INVALID_PARAM, AUTH_CONN, "request is NULL"); AuthRequest *item = FindAuthRequestByRequestId(requestId); if (item == NULL) { + AUTH_LOGE(AUTH_CONN, "find auth request failed"); return SOFTBUS_NOT_FIND; } *request = *item; @@ -113,8 +112,8 @@ int32_t GetAuthRequestNoLock(uint32_t requestId, AuthRequest *request) int32_t FindAuthRequestByConnInfo(const AuthConnInfo *connInfo, AuthRequest *request) { - CHECK_NULL_PTR_RETURN_VALUE(connInfo, SOFTBUS_INVALID_PARAM); - CHECK_NULL_PTR_RETURN_VALUE(request, SOFTBUS_INVALID_PARAM); + AUTH_CHECK_AND_RETURN_RET_LOGE(connInfo != NULL, SOFTBUS_INVALID_PARAM, AUTH_CONN, "connInfo is NULL"); + AUTH_CHECK_AND_RETURN_RET_LOGE(request != NULL, SOFTBUS_INVALID_PARAM, AUTH_CONN, "request is NULL"); if (!RequireAuthLock()) { return SOFTBUS_LOCK_ERR; } @@ -134,7 +133,7 @@ int32_t FindAuthRequestByConnInfo(const AuthConnInfo *connInfo, AuthRequest *req int32_t FindAndDelAuthRequestByConnInfo(uint32_t requestId, const AuthConnInfo *connInfo) { - CHECK_NULL_PTR_RETURN_VALUE(connInfo, SOFTBUS_INVALID_PARAM); + AUTH_CHECK_AND_RETURN_RET_LOGE(connInfo != NULL, SOFTBUS_INVALID_PARAM, AUTH_CONN, "connInfo is NULL"); if (!RequireAuthLock()) { return SOFTBUS_LOCK_ERR; } @@ -195,9 +194,11 @@ void ClearAuthRequest(void) bool CheckVerifyCallback(const AuthVerifyCallback *verifyCb) { if (verifyCb == NULL) { + AUTH_LOGE(AUTH_CONN, "verifyCb is null"); return false; } if (verifyCb->onVerifyPassed == NULL || verifyCb->onVerifyFailed == NULL) { + AUTH_LOGE(AUTH_CONN, "onVerifyPassed or onVerifyFailed is null"); return false; } return true; @@ -206,9 +207,11 @@ bool CheckVerifyCallback(const AuthVerifyCallback *verifyCb) bool CheckAuthConnCallback(const AuthConnCallback *connCb) { if (connCb == NULL) { + AUTH_LOGE(AUTH_CONN, "connCb is null"); return false; } if (connCb->onConnOpened == NULL || connCb->onConnOpenFailed == NULL) { + AUTH_LOGE(AUTH_CONN, "onConnOpened or onConnOpenFailed is null"); return false; } return true; @@ -218,9 +221,11 @@ void PerformVerifyCallback(uint32_t requestId, int32_t result, int64_t authId, c { AuthRequest request; if (GetAuthRequest(requestId, &request) != SOFTBUS_OK) { + AUTH_LOGE(AUTH_CONN, "get auth request failed"); return; } if (!CheckVerifyCallback(&request.verifyCb)) { + AUTH_LOGE(AUTH_CONN, "check verifyCb failed"); return; } if (result == SOFTBUS_OK) { @@ -234,9 +239,11 @@ void PerformAuthConnCallback(uint32_t requestId, int32_t result, int64_t authId) { AuthRequest request; if (GetAuthRequest(requestId, &request) != SOFTBUS_OK) { + AUTH_LOGE(AUTH_CONN, "get auth request failed"); return; } if (!CheckAuthConnCallback(&request.connCb)) { + AUTH_LOGE(AUTH_CONN, "check connCb failed"); return; } if (result == SOFTBUS_OK) { diff --git a/core/authentication/src/auth_session_fsm.c b/core/authentication/src/auth_session_fsm.c index 31752a793..2aa6d9bd9 100644 --- a/core/authentication/src/auth_session_fsm.c +++ b/core/authentication/src/auth_session_fsm.c @@ -30,7 +30,6 @@ #include "softbus_adapter_hitrace.h" #include "softbus_adapter_mem.h" #include "softbus_def.h" -#include "softbus_log_old.h" #define AUTH_TIMEOUT_MS (10 * 1000) #define TO_AUTH_FSM(ptr) CONTAINER_OF(ptr, AuthFsm, fsm) @@ -157,6 +156,49 @@ static bool IsNeedExchangeNetworkId(uint32_t feature, AuthCapability capaBit) return ((feature & (1 << (uint32_t)capaBit)) != 0); } +static void AddUdidInfo(uint32_t requestId, bool isServer, AuthConnInfo *connInfo) +{ + if (isServer || connInfo->type != AUTH_LINK_TYPE_ENHANCED_P2P) { + AUTH_LOGD(AUTH_FSM, "is not server or enhancedP2p"); + return; + } + AuthRequest request; + (void)memset_s(&request, sizeof(request), 0, sizeof(request)); + if (GetAuthRequestNoLock(requestId, &request) != SOFTBUS_OK) { + AUTH_LOGE(AUTH_FSM, "get auth request fail"); + return; + } + if (strcpy_s(connInfo->info.ipInfo.udid, UDID_BUF_LEN, + request.connInfo.info.ipInfo.udid) != EOK) { + AUTH_LOGE(AUTH_FSM, "strcpy udid fail"); + return; + } +} + +static int32_t ProcAuthFsm(uint32_t requestId, bool isServer, AuthFsm *authFsm) +{ + AuthRequest request; + NodeInfo nodeInfo; + (void)memset_s(&request, sizeof(request), 0, sizeof(request)); + (void)memset_s(&nodeInfo, sizeof(nodeInfo), 0, sizeof(nodeInfo)); + AddUdidInfo(requestId, isServer, &authFsm->info.connInfo); + if (authFsm->info.connInfo.type == AUTH_LINK_TYPE_BLE) { + if (GetAuthRequestNoLock(requestId, &request) != SOFTBUS_OK) { + AUTH_LOGE(AUTH_FSM, "get auth request fail"); + return SOFTBUS_ERR; + } + char udidHash[SHORT_UDID_HASH_HEX_LEN + 1] = {0}; + int32_t ret = ConvertBytesToHexString(udidHash, SHORT_UDID_HASH_HEX_LEN + 1, + (const unsigned char *)request.connInfo.info.bleInfo.deviceIdHash, SHORT_UDID_HASH_LEN); + if (ret == SOFTBUS_OK && LnnRetrieveDeviceInfo((const char *)udidHash, &nodeInfo) == SOFTBUS_OK && + IsNeedExchangeNetworkId(nodeInfo.authCapacity, BIT_SUPPORT_EXCHANGE_NETWORKID)) { + AUTH_LOGI(AUTH_FSM, "LnnRetrieveDeviceInfo success"); + authFsm->info.idType = EXCHANGE_NETWORKID; + } + } + return SOFTBUS_OK; +} + static AuthFsm *CreateAuthFsm(int64_t authSeq, uint32_t requestId, uint64_t connId, const AuthConnInfo *connInfo, bool isServer) { @@ -172,30 +214,11 @@ static AuthFsm *CreateAuthFsm(int64_t authSeq, uint32_t requestId, uint64_t conn authFsm->info.connId = connId; authFsm->info.connInfo = *connInfo; authFsm->info.version = SOFTBUS_NEW_V2; - NodeInfo nodeInfo; - AuthRequest request; - if (memset_s(&nodeInfo, sizeof(NodeInfo), 0, sizeof(NodeInfo)) != EOK || - memset_s(&request, sizeof(NodeInfo), 0, sizeof(NodeInfo)) != EOK) { - AUTH_LOGE(AUTH_FSM, "memset fail."); - SoftBusFree(authFsm); - return NULL; - } authFsm->info.idType = EXCHANHE_UDID; if (!isServer) { - if (authFsm->info.connInfo.type == AUTH_LINK_TYPE_BLE) { - if (GetAuthRequestNoLock(requestId, &request) != SOFTBUS_OK) { - AUTH_LOGE(AUTH_FSM, "get auth request fail"); - SoftBusFree(authFsm); - return NULL; - } - char udidHash[SHORT_UDID_HASH_HEX_LEN + 1] = {0}; - int32_t ret = ConvertBytesToHexString(udidHash, SHORT_UDID_HASH_HEX_LEN + 1, - (const unsigned char *)request.connInfo.info.bleInfo.deviceIdHash, SHORT_UDID_HASH_LEN); - if (ret == SOFTBUS_OK && LnnRetrieveDeviceInfo((const char *)udidHash, &nodeInfo) == SOFTBUS_OK && - IsNeedExchangeNetworkId(nodeInfo.authCapacity, BIT_SUPPORT_EXCHANGE_NETWORKID)) { - AUTH_LOGI(AUTH_FSM, "LnnRetrieveDeviceInfo success"); - authFsm->info.idType = EXCHANGE_NETWORKID; - } + if (ProcAuthFsm(requestId, isServer, authFsm) != SOFTBUS_OK) { + SoftBusFree(authFsm); + return NULL; } } if (sprintf_s(authFsm->fsmName, sizeof(authFsm->fsmName), "AuthFsm-%u", authFsm->id) == -1) { @@ -447,7 +470,12 @@ static int32_t RecoveryDeviceKey(AuthFsm *authFsm) AUTH_LOGE(AUTH_FSM, "convert bytes to string fail"); return SOFTBUS_ERR; } - if (AuthFindDeviceKey(udidShortHash, authFsm->info.connInfo.type, &key) != SOFTBUS_OK) { + AuthLinkType linkType = authFsm->info.connInfo.type; + if (authFsm->info.connInfo.type == AUTH_LINK_TYPE_ENHANCED_P2P) { + // enhanced p2p reuse ble authKey + linkType = AUTH_LINK_TYPE_BLE; + } + if (AuthFindDeviceKey(udidShortHash, linkType, &key) != SOFTBUS_OK) { AUTH_LOGE(AUTH_FSM, "find key fail, fastAuth error"); return SOFTBUS_ERR; } @@ -480,6 +508,7 @@ static void AuditReportSetPeerDevInfo(LnnAuditExtra *lnnAuditExtra, AuthSessionI break; case AUTH_LINK_TYPE_WIFI: case AUTH_LINK_TYPE_P2P: + case AUTH_LINK_TYPE_ENHANCED_P2P: if (strcpy_s((char *)lnnAuditExtra->peerIp, IP_STR_MAX_LEN, info->connInfo.info.ipInfo.ip) != EOK) { AUTH_LOGE(AUTH_FSM, "IP COPY ERROR"); } @@ -545,7 +574,7 @@ static int32_t ClientSetExchangeIdType(AuthFsm *authFsm) { AuthSessionInfo *info = &authFsm->info; if (info->idType == EXCHANGE_FAIL) { - AUTH_LOGI(AUTH_FSM, "fsm switch to reauth due to not find networkId"); + AUTH_LOGE(AUTH_FSM, "fsm switch to reauth due to not find networkId"); info->idType = EXCHANHE_UDID; LnnFsmTransactState(&authFsm->fsm, g_states + STATE_SYNC_DEVICE_ID); return SOFTBUS_ERR; @@ -553,7 +582,7 @@ static int32_t ClientSetExchangeIdType(AuthFsm *authFsm) return SOFTBUS_OK; } -static void HandleMsgRecvDeviceId(AuthFsm *authFsm, MessagePara *para) +static void HandleMsgRecvDeviceId(AuthFsm *authFsm, const MessagePara *para) { int32_t ret; AuthSessionInfo *info = &authFsm->info; @@ -567,6 +596,11 @@ static void HandleMsgRecvDeviceId(AuthFsm *authFsm, MessagePara *para) break; } if (info->isServer) { + if (info->connInfo.type == AUTH_LINK_TYPE_BLE && strlen(info->udid) != 0 && + authFsm->info.connInfo.info.bleInfo.deviceIdHash[0] == '\0') { + (void)SoftBusGenerateStrHash((unsigned char *)info->udid, strlen(info->nodeInfo.deviceInfo.deviceUdid), + (unsigned char *)authFsm->info.connInfo.info.bleInfo.deviceIdHash); + } if (PostDeviceIdMessage(authFsm->authSeq, info) != SOFTBUS_OK) { ret = SOFTBUS_AUTH_SYNC_DEVID_FAIL; break; @@ -633,7 +667,7 @@ static bool SyncDevIdStateProcess(FsmStateMachine *fsm, int32_t msgType, void *p return true; } -static void HandleMsgRecvAuthData(AuthFsm *authFsm, MessagePara *para) +static void HandleMsgRecvAuthData(AuthFsm *authFsm, const MessagePara *para) { LnnEventExtra lnnEventExtra = {0}; LNN_EVENT(EVENT_SCENE_JOIN_LNN, EVENT_STAGE_EXCHANGE_CIPHER, lnnEventExtra); @@ -655,7 +689,7 @@ static void HandleMsgRecvAuthData(AuthFsm *authFsm, MessagePara *para) } } -static int32_t TrySyncDeviceInfo(int64_t authSeq, AuthSessionInfo *info) +static int32_t TrySyncDeviceInfo(int64_t authSeq, const AuthSessionInfo *info) { switch (info->connInfo.type) { case AUTH_LINK_TYPE_WIFI: @@ -667,6 +701,7 @@ static int32_t TrySyncDeviceInfo(int64_t authSeq, AuthSessionInfo *info) case AUTH_LINK_TYPE_BR: case AUTH_LINK_TYPE_BLE: case AUTH_LINK_TYPE_P2P: + case AUTH_LINK_TYPE_ENHANCED_P2P: return PostDeviceInfoMessage(authSeq, info); default: break; @@ -674,7 +709,7 @@ static int32_t TrySyncDeviceInfo(int64_t authSeq, AuthSessionInfo *info) return SOFTBUS_ERR; } -static void HandleMsgSaveSessionKey(AuthFsm *authFsm, MessagePara *para) +static void HandleMsgSaveSessionKey(AuthFsm *authFsm, const MessagePara *para) { LnnEventExtra lnnEventExtra = { .result = EVENT_STAGE_RESULT_OK }; LNN_EVENT(EVENT_SCENE_JOIN_LNN, EVENT_STAGE_EXCHANGE_CIPHER, lnnEventExtra); @@ -706,14 +741,14 @@ static void HandleMsgSaveSessionKey(AuthFsm *authFsm, MessagePara *para) LnnFsmTransactState(&authFsm->fsm, g_states + STATE_SYNC_DEVICE_INFO); } -static void HandleMsgAuthError(AuthFsm *authFsm, MessagePara *para) +static void HandleMsgAuthError(AuthFsm *authFsm, const MessagePara *para) { int32_t result = *((int32_t *)(para->data)); AUTH_LOGE(AUTH_FSM, "auth fsm[%" PRId64"] handle hichain error, reason=%d", authFsm->authSeq, result); CompleteAuthSession(authFsm, SOFTBUS_AUTH_HICHAIN_AUTH_ERROR); } -static void HandleMsgRecvDevInfoEarly(AuthFsm *authFsm, MessagePara *para) +static void HandleMsgRecvDevInfoEarly(AuthFsm *authFsm, const MessagePara *para) { AUTH_LOGI(AUTH_FSM, "auth fsm[%" PRId64 "] recv device info early, save it", authFsm->authSeq); AuthSessionInfo *info = &authFsm->info; @@ -789,7 +824,7 @@ static bool DeviceAuthStateProcess(FsmStateMachine *fsm, int32_t msgType, void * return true; } -static void HandleMsgRecvDeviceInfo(AuthFsm *authFsm, MessagePara *para) +static void HandleMsgRecvDeviceInfo(AuthFsm *authFsm, const MessagePara *para) { LnnEventExtra lnnEventExtra = { .result = EVENT_STAGE_RESULT_OK }; AuthSessionInfo *info = &authFsm->info; @@ -895,7 +930,7 @@ static bool SyncDevInfoStateProcess(FsmStateMachine *fsm, int32_t msgType, void return true; } -AuthFsm *GetAuthFsmByAuthSeq(int64_t authSeq) +static AuthFsm *GetAuthFsmByAuthSeq(int64_t authSeq) { AuthFsm *item = NULL; LIST_FOR_EACH_ENTRY(item, &g_authFsmList, AuthFsm, node) { @@ -1008,7 +1043,7 @@ static void SetAuthStartTime(AuthFsm *authFsm) int32_t AuthSessionStartAuth(int64_t authSeq, uint32_t requestId, uint64_t connId, const AuthConnInfo *connInfo, bool isServer, bool isFastAuth) { - CHECK_NULL_PTR_RETURN_VALUE(connInfo, SOFTBUS_INVALID_PARAM); + AUTH_CHECK_AND_RETURN_RET_LOGE(connInfo != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "connInfo is NULL"); if (!RequireAuthLock()) { return SOFTBUS_LOCK_ERR; } @@ -1033,6 +1068,7 @@ int32_t AuthSessionStartAuth(int64_t authSeq, uint32_t requestId, int32_t AuthSessionProcessDevIdData(int64_t authSeq, const uint8_t *data, uint32_t len) { if (data == NULL) { + AUTH_LOGE(AUTH_FSM, "data is null"); return SOFTBUS_INVALID_PARAM; } return PostMessageToAuthFsm(FSM_MSG_RECV_DEVICE_ID, authSeq, data, len); @@ -1053,6 +1089,7 @@ int32_t AuthSessionPostAuthData(int64_t authSeq, const uint8_t *data, uint32_t l int32_t AuthSessionProcessAuthData(int64_t authSeq, const uint8_t *data, uint32_t len) { if (data == NULL) { + AUTH_LOGE(AUTH_FSM, "data is null"); return SOFTBUS_INVALID_PARAM; } return PostMessageToAuthFsm(FSM_MSG_RECV_AUTH_DATA, authSeq, data, len); @@ -1061,6 +1098,7 @@ int32_t AuthSessionProcessAuthData(int64_t authSeq, const uint8_t *data, uint32_ int32_t AuthSessionGetUdid(int64_t authSeq, char *udid, uint32_t size) { if (udid == NULL) { + AUTH_LOGE(AUTH_FSM, "udid is null"); return SOFTBUS_INVALID_PARAM; } AuthSessionInfo info = {0}; @@ -1077,6 +1115,7 @@ int32_t AuthSessionGetUdid(int64_t authSeq, char *udid, uint32_t size) int32_t AuthSessionSaveSessionKey(int64_t authSeq, const uint8_t *key, uint32_t len) { if (key == NULL) { + AUTH_LOGE(AUTH_FSM, "key is null"); return SOFTBUS_INVALID_PARAM; } return PostMessageToAuthFsm(FSM_MSG_SAVE_SESSION_KEY, authSeq, key, len); @@ -1095,6 +1134,7 @@ int32_t AuthSessionHandleAuthError(int64_t authSeq, int32_t reason) int32_t AuthSessionProcessDevInfoData(int64_t authSeq, const uint8_t *data, uint32_t len) { if (data == NULL) { + AUTH_LOGE(AUTH_FSM, "data is null"); return SOFTBUS_INVALID_PARAM; } return PostMessageToAuthFsm(FSM_MSG_RECV_DEVICE_INFO, authSeq, data, len); @@ -1103,6 +1143,7 @@ int32_t AuthSessionProcessDevInfoData(int64_t authSeq, const uint8_t *data, uint int32_t AuthSessionProcessCloseAck(int64_t authSeq, const uint8_t *data, uint32_t len) { if (data == NULL) { + AUTH_LOGE(AUTH_FSM, "data is null"); return SOFTBUS_INVALID_PARAM; } return PostMessageToAuthFsm(FSM_MSG_RECV_CLOSE_ACK, authSeq, data, len); @@ -1112,6 +1153,7 @@ int32_t AuthSessionProcessDevInfoDataByConnId(uint64_t connId, bool isServer, co uint32_t len) { if (data == NULL) { + AUTH_LOGE(AUTH_FSM, "data is null"); return SOFTBUS_INVALID_PARAM; } return PostMessageToAuthFsmByConnId(FSM_MSG_RECV_DEVICE_INFO, connId, isServer, data, len); @@ -1121,6 +1163,7 @@ int32_t AuthSessionProcessCloseAckByConnId(uint64_t connId, bool isServer, const uint32_t len) { if (data == NULL) { + AUTH_LOGE(AUTH_FSM, "data is null"); return SOFTBUS_INVALID_PARAM; } return PostMessageToAuthFsmByConnId(FSM_MSG_RECV_CLOSE_ACK, connId, isServer, data, len); @@ -1129,6 +1172,7 @@ int32_t AuthSessionProcessCloseAckByConnId(uint64_t connId, bool isServer, const int32_t AuthSessionHandleDeviceNotTrusted(const char *udid) { if (udid == NULL || udid[0] == '\0') { + AUTH_LOGE(AUTH_FSM, "invalid udid"); return SOFTBUS_INVALID_PARAM; } if (!RequireAuthLock()) { diff --git a/core/authentication/src/auth_session_key.c b/core/authentication/src/auth_session_key.c index 30b6483d5..2e7e1ffa6 100644 --- a/core/authentication/src/auth_session_key.c +++ b/core/authentication/src/auth_session_key.c @@ -55,19 +55,20 @@ static void RemoveOldKey(SessionKeyList *list) void InitSessionKeyList(SessionKeyList *list) { - CHECK_NULL_PTR_RETURN_VOID(list); + AUTH_CHECK_AND_RETURN_LOGE(list != NULL, AUTH_FSM, "list is NULL"); ListInit(list); } int32_t DupSessionKeyList(const SessionKeyList *srcList, SessionKeyList *dstList) { - CHECK_NULL_PTR_RETURN_VALUE(srcList, SOFTBUS_INVALID_PARAM); - CHECK_NULL_PTR_RETURN_VALUE(dstList, SOFTBUS_INVALID_PARAM); + AUTH_CHECK_AND_RETURN_RET_LOGE(srcList != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "srcList is NULL"); + AUTH_CHECK_AND_RETURN_RET_LOGE(dstList != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "dstList is NULL"); SessionKeyItem *item = NULL; SessionKeyItem *newItem = NULL; LIST_FOR_EACH_ENTRY(item, srcList, SessionKeyItem, node) { newItem = (SessionKeyItem *)DupMemBuffer((uint8_t *)item, sizeof(SessionKeyItem)); if (newItem == NULL) { + AUTH_LOGE(AUTH_FSM, "malloc newItem fail"); DestroySessionKeyList(dstList); return SOFTBUS_MALLOC_ERR; } @@ -78,7 +79,7 @@ int32_t DupSessionKeyList(const SessionKeyList *srcList, SessionKeyList *dstList void DestroySessionKeyList(SessionKeyList *list) { - CHECK_NULL_PTR_RETURN_VOID(list); + AUTH_CHECK_AND_RETURN_LOGE(list != NULL, AUTH_FSM, "list is NULL"); SessionKeyItem *item = NULL; SessionKeyItem *next = NULL; LIST_FOR_EACH_ENTRY_SAFE(item, next, list, SessionKeyItem, node) { @@ -90,14 +91,14 @@ void DestroySessionKeyList(SessionKeyList *list) bool HasSessionKey(const SessionKeyList *list) { - CHECK_NULL_PTR_RETURN_VALUE(list, false); + AUTH_CHECK_AND_RETURN_RET_LOGE(list != NULL, false, AUTH_FSM, "list is NULL"); return !IsListEmpty(list); } int32_t AddSessionKey(SessionKeyList *list, int32_t index, const SessionKey *key) { - CHECK_NULL_PTR_RETURN_VALUE(key, SOFTBUS_INVALID_PARAM); - CHECK_NULL_PTR_RETURN_VALUE(list, SOFTBUS_INVALID_PARAM); + AUTH_CHECK_AND_RETURN_RET_LOGE(key != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "key is NULL"); + AUTH_CHECK_AND_RETURN_RET_LOGE(list != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "list is NULL"); AUTH_LOGD(AUTH_FSM, "keyLen=%d", key->len); SessionKeyItem *item = (SessionKeyItem *)SoftBusMalloc(sizeof(SessionKeyItem)); if (item == NULL) { @@ -118,9 +119,9 @@ int32_t AddSessionKey(SessionKeyList *list, int32_t index, const SessionKey *key int32_t GetLatestSessionKey(const SessionKeyList *list, int32_t *index, SessionKey *key) { - CHECK_NULL_PTR_RETURN_VALUE(list, SOFTBUS_INVALID_PARAM); - CHECK_NULL_PTR_RETURN_VALUE(index, SOFTBUS_INVALID_PARAM); - CHECK_NULL_PTR_RETURN_VALUE(key, SOFTBUS_INVALID_PARAM); + AUTH_CHECK_AND_RETURN_RET_LOGE(list != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "list is NULL"); + AUTH_CHECK_AND_RETURN_RET_LOGE(index != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "index is NULL"); + AUTH_CHECK_AND_RETURN_RET_LOGE(key != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "key is NULL"); if (IsListEmpty((const ListNode *)list)) { AUTH_LOGE(AUTH_FSM, "session key list is empty"); return SOFTBUS_ERR; @@ -142,8 +143,8 @@ int32_t GetLatestSessionKey(const SessionKeyList *list, int32_t *index, SessionK int32_t GetSessionKeyByIndex(const SessionKeyList *list, int32_t index, SessionKey *key) { - CHECK_NULL_PTR_RETURN_VALUE(list, SOFTBUS_INVALID_PARAM); - CHECK_NULL_PTR_RETURN_VALUE(key, SOFTBUS_INVALID_PARAM); + AUTH_CHECK_AND_RETURN_RET_LOGE(list != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "list is NULL"); + AUTH_CHECK_AND_RETURN_RET_LOGE(key != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "key is NULL"); SessionKeyItem *item = NULL; LIST_FOR_EACH_ENTRY(item, (const ListNode *)list, SessionKeyItem, node) { if (item->index != index) { @@ -163,7 +164,7 @@ int32_t GetSessionKeyByIndex(const SessionKeyList *list, int32_t index, SessionK void RemoveSessionkeyByIndex(SessionKeyList *list, int32_t index) { - CHECK_NULL_PTR_RETURN_VOID(list); + AUTH_CHECK_AND_RETURN_LOGE(list != NULL, AUTH_FSM, "list is NULL"); bool isFind = false; SessionKeyItem *item = NULL; LIST_FOR_EACH_ENTRY(item, (const ListNode *)list, SessionKeyItem, node) { @@ -192,7 +193,6 @@ int32_t EncryptData(const SessionKeyList *list, const uint8_t *inData, uint32_t SessionKey sessionKey; if (GetLatestSessionKey(list, &index, &sessionKey) != SOFTBUS_OK) { AUTH_LOGE(AUTH_FSM, "get key fail"); - AUTH_LOGD(AUTH_FSM, "keyLen=%d", sessionKey.len); return SOFTBUS_ENCRYPT_ERR; } /* pack key index */ @@ -295,7 +295,7 @@ int32_t DecryptInner(const SessionKeyList *list, const uint8_t *inData, uint32_t /* For Debug */ void DumpSessionkeyList(const SessionKeyList *list) { - CHECK_NULL_PTR_RETURN_VOID(list); + AUTH_CHECK_AND_RETURN_LOGE(list != NULL, AUTH_FSM, "list is NULL"); uint32_t keyNum = 0; SessionKeyItem *item = NULL; LIST_FOR_EACH_ENTRY(item, (const ListNode *)list, SessionKeyItem, node) { @@ -308,7 +308,7 @@ void DumpSessionkeyList(const SessionKeyList *list) static void HandleUpdateSessionKeyEvent(const void *obj) { - CHECK_NULL_PTR_RETURN_VOID(obj); + AUTH_CHECK_AND_RETURN_LOGE(obj != NULL, AUTH_FSM, "obj is NULL"); int64_t authId = *(int64_t *)(obj); AUTH_LOGI(AUTH_FSM, "update session key begin, authId=%" PRId64, authId); AuthManager *auth = GetAuthManagerByAuthId(authId); @@ -324,8 +324,8 @@ static void HandleUpdateSessionKeyEvent(const void *obj) static int32_t RemoveUpdateSessionKeyFunc(const void *obj, void *para) { - CHECK_NULL_PTR_RETURN_VALUE(obj, SOFTBUS_ERR); - CHECK_NULL_PTR_RETURN_VALUE(para, SOFTBUS_ERR); + AUTH_CHECK_AND_RETURN_RET_LOGE(obj != NULL, SOFTBUS_ERR, AUTH_FSM, "obj is NULL"); + AUTH_CHECK_AND_RETURN_RET_LOGE(para != NULL, SOFTBUS_ERR, AUTH_FSM, "para is NULL"); int64_t authId = *(int64_t *)(obj); if (authId == *(int64_t *)(para)) { AUTH_LOGI(AUTH_FSM, "remove update session key event, authId=%" PRId64, authId); diff --git a/core/authentication/src/auth_session_message.c b/core/authentication/src/auth_session_message.c index a94f1f440..b44da82a3 100644 --- a/core/authentication/src/auth_session_message.c +++ b/core/authentication/src/auth_session_message.c @@ -209,8 +209,7 @@ static void OptInt(const JsonObj *json, const char * const key, int *target, int *target = defaultValue; } -static void OptInt64(const JsonObj *json, const char * const key, - int64_t *target, int64_t defaultValue) +static void OptInt64(const JsonObj *json, const char * const key, int64_t *target, int64_t defaultValue) { if (JSON_GetInt64FromOject(json, key, target)) { return; @@ -258,21 +257,30 @@ static int32_t PackFastAuthValue(JsonObj *obj, AuthDeviceKeyInfo *deviceCommKey) return SOFTBUS_OK; } +static bool GenerateUdidShortHash(const char *udid, char *udidHashBuf, uint32_t bufLen) +{ + uint8_t hash[SHA_256_HASH_LEN] = {0}; + int ret = SoftBusGenerateStrHash((uint8_t *)udid, strlen(udid), hash); + if (ret != SOFTBUS_OK) { + AUTH_LOGE(AUTH_FSM, "generate udidHash fail"); + return false; + } + if (ConvertBytesToUpperCaseHexString(udidHashBuf, bufLen, hash, UDID_SHORT_HASH_LEN_TEMP) != SOFTBUS_OK) { + AUTH_LOGE(AUTH_FSM, "convert bytes to string fail"); + return false; + } + return true; +} + static bool GetUdidOrShortHash(const AuthSessionInfo *info, char *udidBuf, uint32_t bufLen) { + if (!info->isServer && info->connInfo.type == AUTH_LINK_TYPE_ENHANCED_P2P) { + AUTH_LOGD(AUTH_FSM, "client(enhance p2p), use conninfo udid"); + return GenerateUdidShortHash(info->connInfo.info.ipInfo.udid, udidBuf, bufLen); + } if (strlen(info->udid) != 0) { AUTH_LOGI(AUTH_FSM, "use info->udid build fastAuthInfo"); - uint8_t hash[SHA_256_HASH_LEN] = {0}; - int ret = SoftBusGenerateStrHash((uint8_t *)info->udid, strlen(info->udid), hash); - if (ret != SOFTBUS_OK) { - AUTH_LOGE(AUTH_FSM, "generate udidHash fail"); - return false; - } - if (ConvertBytesToUpperCaseHexString(udidBuf, bufLen, hash, UDID_SHORT_HASH_LEN_TEMP) != SOFTBUS_OK) { - AUTH_LOGE(AUTH_FSM, "convert bytes to string fail"); - return false; - } - return true; + return GenerateUdidShortHash(info->udid, udidBuf, bufLen); } if (info->connInfo.type == AUTH_LINK_TYPE_BLE) { AUTH_LOGI(AUTH_FSM, "use bleInfo deviceIdHash build fastAuthInfo"); @@ -281,13 +289,59 @@ static bool GetUdidOrShortHash(const AuthSessionInfo *info, char *udidBuf, uint3 AUTH_LOGE(AUTH_FSM, "GetAuthRequest fail"); return false; } - return (memcpy_s(udidBuf, bufLen, request.connInfo.info.bleInfo.deviceIdHash, - UDID_SHORT_HASH_HEX_STR) == EOK); + return (memcpy_s(udidBuf, bufLen, request.connInfo.info.bleInfo.deviceIdHash, UDID_SHORT_HASH_HEX_STR) == EOK); } AUTH_LOGD(AUTH_FSM, "udid len=%d, connInfo type=%d", strlen(info->udid), info->connInfo.type); return false; } +static int32_t GetEnhancedP2pAuthKey(const char *udidHash, AuthSessionInfo *info, AuthDeviceKeyInfo *deviceKey) +{ + /* first, reuse ble authKey */ + if (AuthFindDeviceKey(udidHash, AUTH_LINK_TYPE_BLE, deviceKey) == SOFTBUS_OK) { + AUTH_LOGD(AUTH_FSM, "get ble authKey succ"); + return SOFTBUS_OK; + } + /* second, reuse wifi authKey */ + int64_t authId = AuthGetLatestIdByUuid(info->uuid, AUTH_LINK_TYPE_WIFI, false); + if (authId == AUTH_INVALID_ID) { + AUTH_LOGE(AUTH_FSM, "get wifi authKey fail"); + return SOFTBUS_ERR; + } + AuthManager *auth = GetAuthManagerByAuthId(authId); + int32_t index; + SessionKey sessionKey; + (void)memset_s(&sessionKey, sizeof(SessionKey), 0, sizeof(SessionKey)); + if (GetLatestSessionKey(&auth->sessionKeyList, &index, &sessionKey) != SOFTBUS_OK) { + AUTH_LOGE(AUTH_FSM, "get key fail"); + DelAuthManager(auth, false); + return SOFTBUS_ERR; + } + DelAuthManager(auth, false); + if (memcpy_s(deviceKey->deviceKey, SESSION_KEY_LENGTH, + sessionKey.value, sizeof(sessionKey.value)) != EOK) { + AUTH_LOGE(AUTH_FSM, "memcpy fail"); + return SOFTBUS_MEM_ERR; + } + deviceKey->keyLen = sessionKey.len; + /* wifi authKey not enable, associated with recoveryDeviceKey */ + return SOFTBUS_ERR; +} + +static int32_t GetFastAuthKey(const char *udidHash, AuthSessionInfo *info, AuthDeviceKeyInfo *deviceKey) +{ + if (info->connInfo.type == AUTH_LINK_TYPE_ENHANCED_P2P) { + AUTH_LOGI(AUTH_FSM, "get enhanced p2p fastAuth key"); + return GetEnhancedP2pAuthKey(udidHash, info, deviceKey); + } + if (AuthFindDeviceKey(udidHash, info->connInfo.type, deviceKey) != SOFTBUS_OK) { + AUTH_LOGW(AUTH_FSM, "can't find common key, unsupport fastAuth"); + info->isSupportFastAuth = false; + return SOFTBUS_ERR; + } + return SOFTBUS_OK; +} + static void PackFastAuth(JsonObj *obj, AuthSessionInfo *info, const NodeInfo *localNodeInfo) { AUTH_LOGD(AUTH_FSM, "pack fastAuth, isServer=%d", info->isServer); @@ -312,26 +366,26 @@ static void PackFastAuth(JsonObj *obj, AuthSessionInfo *info, const NodeInfo *lo return; } AUTH_LOGD(AUTH_FSM, "udidHashHexStr=%s", udidHashHexStr); - if (!IsPotentialTrustedDevice(ID_TYPE_DEVID, (const char *)udidHashHexStr, false, true)) { + if (info->connInfo.type != AUTH_LINK_TYPE_ENHANCED_P2P && + !IsPotentialTrustedDevice(ID_TYPE_DEVID, (const char *)udidHashHexStr, false, false)) { AUTH_LOGI(AUTH_FSM, "not potential trusted realtion, bypass fastAuthProc"); info->isSupportFastAuth = false; return; } AuthDeviceKeyInfo deviceCommKey = {0}; - if (AuthFindDeviceKey(udidHashHexStr, info->connInfo.type, &deviceCommKey) != SOFTBUS_OK) { - AUTH_LOGW(AUTH_FSM, "can't find common key, unsupport fastAuth"); + if (GetFastAuthKey(udidHashHexStr, info, &deviceCommKey) != SOFTBUS_OK) { info->isSupportFastAuth = false; return; } if (PackFastAuthValue(obj, &deviceCommKey) != SOFTBUS_OK) { + (void)memset_s(&deviceCommKey, sizeof(AuthDeviceKeyInfo), 0, sizeof(AuthDeviceKeyInfo)); info->isSupportFastAuth = false; return; } (void)memset_s(&deviceCommKey, sizeof(AuthDeviceKeyInfo), 0, sizeof(AuthDeviceKeyInfo)); } -static void ParseFastAuthValue(AuthSessionInfo *info, const char *encryptedFastAuth, - AuthDeviceKeyInfo *deviceKey) +static void ParseFastAuthValue(AuthSessionInfo *info, const char *encryptedFastAuth, AuthDeviceKeyInfo *deviceKey) { uint8_t fastAuthBytes[ENCRYPTED_FAST_AUTH_MAX_LEN] = {0}; if (ConvertHexStringToBytes(fastAuthBytes, ENCRYPTED_FAST_AUTH_MAX_LEN, @@ -387,14 +441,14 @@ static void UnpackFastAuth(JsonObj *obj, AuthSessionInfo *info) AUTH_LOGE(AUTH_FSM, "udid hash bytes to hexString fail"); return; } - if (!IsPotentialTrustedDevice(ID_TYPE_DEVID, (const char *)udidShortHash, false, true)) { + if (info->connInfo.type != AUTH_LINK_TYPE_ENHANCED_P2P && + !IsPotentialTrustedDevice(ID_TYPE_DEVID, (const char *)udidShortHash, false, false)) { AUTH_LOGI(AUTH_FSM, "not potential trusted realtion, fastAuth not support"); return; } AuthDeviceKeyInfo deviceKey = {0}; - /* find comm key use udid or udidShortHash */ - if (AuthFindDeviceKey(udidShortHash, info->connInfo.type, &deviceKey) != SOFTBUS_OK) { - AUTH_LOGW(AUTH_FSM, "can't find common key, fastAuth not support"); + if (GetFastAuthKey(udidShortHash, info, &deviceKey) != SOFTBUS_OK) { + AUTH_LOGW(AUTH_FSM, "can't find device key, fastAuth not support"); return; } ParseFastAuthValue(info, encryptedFastAuth, &deviceKey); @@ -415,6 +469,7 @@ static void PackCompressInfo(JsonObj *obj, const NodeInfo *info) static void PackWifiSinglePassInfo(JsonObj *obj, const AuthSessionInfo *info) { if (info->connInfo.type != AUTH_LINK_TYPE_WIFI) { + AUTH_LOGE(AUTH_FSM, "link type is not wifi"); return; } uint8_t hash[SHA_256_HASH_LEN] = {0}; @@ -487,8 +542,7 @@ static char *PackDeviceIdJson(const AuthSessionInfo *info) AUTH_LOGI(AUTH_FSM, "exchangeIdType=%d, udid=%s", info->idType, anonyUdid); AnonymizeFree(anonyUdid); } - if (!JSON_AddStringToObject(obj, DATA_TAG, uuid) || - !JSON_AddInt32ToObject(obj, DATA_BUF_SIZE_TAG, PACKET_SIZE) || + if (!JSON_AddStringToObject(obj, DATA_TAG, uuid) || !JSON_AddInt32ToObject(obj, DATA_BUF_SIZE_TAG, PACKET_SIZE) || !JSON_AddInt32ToObject(obj, SOFTBUS_VERSION_TAG, info->version) || !JSON_AddInt32ToObject(obj, EXCHANGE_ID_TYPE, info->idType)) { AUTH_LOGE(AUTH_FSM, "add msg body fail"); @@ -519,7 +573,7 @@ static bool UnpackWifiSinglePassInfo(JsonObj *obj, AuthSessionInfo *info) SoftBusSockAddrIn addr = {0}; SocketAddr socketAddr; int32_t rc = SoftBusSocketGetPeerName(socketFd, (SoftBusSockAddr *)&addr); - if (rc != 0) { + if (rc != SOFTBUS_OK) { AUTH_LOGE(AUTH_FSM, "fd=%d, GetPerrName rc=%d", socketFd, rc); return true; } @@ -531,11 +585,11 @@ static bool UnpackWifiSinglePassInfo(JsonObj *obj, AuthSessionInfo *info) uint8_t hash[SHA_256_HASH_LEN] = {0}; rc = SoftBusGenerateStrHash((const unsigned char *)socketAddr.addr, strlen(socketAddr.addr), hash); if (rc != SOFTBUS_OK) { + AUTH_LOGE(AUTH_FSM, "generate hash failed rc=%d", rc); return true; } - char socketIpHash[SHA_256_HEX_HASH_LEN] = {0}; - if (ConvertBytesToUpperCaseHexString(socketIpHash, SHA_256_HEX_HASH_LEN, - hash, SHA_256_HASH_LEN) != SOFTBUS_OK) { + char socketIpHash[SHA_256_HEX_HASH_LEN] = { 0 }; + if (ConvertBytesToUpperCaseHexString(socketIpHash, SHA_256_HEX_HASH_LEN, hash, SHA_256_HASH_LEN) != SOFTBUS_OK) { return true; } if (strcmp(devIpHash, socketIpHash) == 0) { @@ -548,7 +602,7 @@ static bool UnpackWifiSinglePassInfo(JsonObj *obj, AuthSessionInfo *info) static int32_t UnPackBtDeviceIdV1(AuthSessionInfo *info, const uint8_t *data, uint32_t len) { if (!info->isServer) { - AUTH_LOGE(AUTH_FSM, "invalid bt deviceId msg"); + AUTH_LOGE(AUTH_FSM, "is not server"); return SOFTBUS_INVALID_PARAM; } if (memcpy_s(info->udid, UDID_BUF_LEN, data, len) != EOK) { // data:StandardCharsets.UTF_8 @@ -696,9 +750,8 @@ static int32_t UnpackDeviceIdJson(const char *msg, uint32_t len, AuthSessionInfo return SOFTBUS_ERR; } if (info->connInfo.type != AUTH_LINK_TYPE_WIFI) { - char compressParse[PARSE_UNCOMPRESS_STRING_BUFF_LEN] = {0}; - OptString(obj, SUPPORT_INFO_COMPRESS, compressParse, - PARSE_UNCOMPRESS_STRING_BUFF_LEN, FALSE_STRING_TAG); + char compressParse[PARSE_UNCOMPRESS_STRING_BUFF_LEN] = { 0 }; + OptString(obj, SUPPORT_INFO_COMPRESS, compressParse, PARSE_UNCOMPRESS_STRING_BUFF_LEN, FALSE_STRING_TAG); SetCompressFlag(compressParse, &info->isSupportCompress); } UnpackFastAuth(obj, info); @@ -1051,7 +1104,7 @@ static void UnpackCommon(const JsonObj *json, NodeInfo *info, SoftBusVersion ver OptInt64(json, ACCOUNT_ID, &info->accountId, 0); OptInt(json, NODE_WEIGHT, &info->masterWeight, DEFAULT_NODE_WEIGHT); - //IS_SUPPORT_TCP_HEARTBEAT + // IS_SUPPORT_TCP_HEARTBEAT OptInt64(json, NEW_CONN_CAP, (int64_t *)&info->netCapacity, -1); if (info->netCapacity == (uint32_t)-1) { (void)JSON_GetInt64FromOject(json, CONN_CAP, (int64_t *)&info->netCapacity); @@ -1105,7 +1158,7 @@ static void AddDiscoveryType(JsonObj *json, const char *remoteUuid) } char networkId[NETWORK_ID_BUF_LEN] = {0}; if (LnnGetNetworkIdByUuid(remoteUuid, networkId, sizeof(networkId)) != SOFTBUS_OK) { - AUTH_LOGI(AUTH_FSM, "networkId not found by uuid, maybe first online"); + AUTH_LOGE(AUTH_FSM, "networkId not found by uuid, maybe first online"); return; } uint32_t discoveryType = 0; @@ -1182,8 +1235,7 @@ static int32_t UnpackBt(const JsonObj *json, NodeInfo *info, SoftBusVersion vers static int32_t PackWiFi(JsonObj *json, const NodeInfo *info, SoftBusVersion version, bool isMetaAuth) { AUTH_LOGD(AUTH_FSM, "devIp %d", strlen(info->connectInfo.deviceIp)); - if (!JSON_AddInt32ToObject(json, CODE, CODE_VERIFY_IP) || - !JSON_AddInt32ToObject(json, BUS_MAX_VERSION, BUS_V2) || + if (!JSON_AddInt32ToObject(json, CODE, CODE_VERIFY_IP) || !JSON_AddInt32ToObject(json, BUS_MAX_VERSION, BUS_V2) || !JSON_AddInt32ToObject(json, BUS_MIN_VERSION, BUS_V1) || !JSON_AddInt32ToObject(json, AUTH_PORT, LnnGetAuthPort(info)) || !JSON_AddInt32ToObject(json, SESSION_PORT, LnnGetSessionPort(info)) || @@ -1285,7 +1337,7 @@ static int32_t PackDeviceInfoBtV1(JsonObj *json, const NodeInfo *info, bool isMe static int32_t UnpackDeviceInfoBtV1(const JsonObj *json, NodeInfo *info) { - char deviceType[DEVICE_TYPE_BUF_LEN] = {0}; + char deviceType[DEVICE_TYPE_BUF_LEN] = { 0 }; if (!JSON_GetStringFromOject(json, DEVICE_NAME, info->deviceInfo.deviceName, DEVICE_NAME_BUF_LEN) || !JSON_GetStringFromOject(json, DEVICE_TYPE, deviceType, DEVICE_TYPE_BUF_LEN) || !JSON_GetStringFromOject(json, DEVICE_UDID, info->deviceInfo.deviceUdid, UDID_BUF_LEN) || @@ -1314,6 +1366,7 @@ static int32_t UnpackDeviceInfoBtV1(const JsonObj *json, NodeInfo *info) } if (strcpy_s(info->networkId, NETWORK_ID_BUF_LEN, info->uuid) != EOK) { AUTH_LOGE(AUTH_FSM, "strcpy networkId fail"); + return SOFTBUS_ERR; } return SOFTBUS_OK; } @@ -1365,8 +1418,7 @@ static void UpdatePeerDeviceName(NodeInfo *peerNodeInfo) if (strlen(peerNodeInfo->deviceInfo.unifiedName) != 0 && strcmp(peerNodeInfo->deviceInfo.unifiedName, peerNodeInfo->deviceInfo.unifiedDefaultName) != 0) { ret = strcpy_s(deviceName, DEVICE_NAME_BUF_LEN, peerNodeInfo->deviceInfo.unifiedName); - } else if (strlen(peerNodeInfo->deviceInfo.nickName) == 0 || - localInfo->accountId == peerNodeInfo->accountId) { + } else if (strlen(peerNodeInfo->deviceInfo.nickName) == 0 || localInfo->accountId == peerNodeInfo->accountId) { ret = strcpy_s(deviceName, DEVICE_NAME_BUF_LEN, peerNodeInfo->deviceInfo.unifiedDefaultName); } else { LnnGetDeviceDisplayName(peerNodeInfo->deviceInfo.nickName, @@ -1385,8 +1437,8 @@ static void UpdatePeerDeviceName(NodeInfo *peerNodeInfo) int32_t UnpackDeviceInfoMessage(const DevInfoData *devInfo, NodeInfo *nodeInfo, bool isMetaAuth) { - CHECK_NULL_PTR_RETURN_VALUE(devInfo, SOFTBUS_INVALID_PARAM); - CHECK_NULL_PTR_RETURN_VALUE(nodeInfo, SOFTBUS_INVALID_PARAM); + AUTH_CHECK_AND_RETURN_RET_LOGE(devInfo != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "devInfo is NULL"); + AUTH_CHECK_AND_RETURN_RET_LOGE(nodeInfo != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "nodeInfo is NULL"); AUTH_LOGI(AUTH_FSM, "connType=%d", devInfo->linkType); JsonObj *json = JSON_Parse(devInfo->msg, devInfo->len); if (json == NULL) { @@ -1489,7 +1541,7 @@ static int32_t PostDeviceIdNew(int64_t authSeq, const AuthSessionInfo *info) int32_t PostDeviceIdMessage(int64_t authSeq, const AuthSessionInfo *info) { - CHECK_NULL_PTR_RETURN_VALUE(info, SOFTBUS_INVALID_PARAM); + AUTH_CHECK_AND_RETURN_RET_LOGE(info != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "info is NULL"); if (info->version == SOFTBUS_OLD_V1) { return PostDeviceIdV1(authSeq, info); } else { @@ -1499,11 +1551,9 @@ int32_t PostDeviceIdMessage(int64_t authSeq, const AuthSessionInfo *info) int32_t ProcessDeviceIdMessage(AuthSessionInfo *info, const uint8_t *data, uint32_t len) { - CHECK_NULL_PTR_RETURN_VALUE(info, SOFTBUS_INVALID_PARAM); - CHECK_NULL_PTR_RETURN_VALUE(data, SOFTBUS_INVALID_PARAM); - if ((info->connInfo.type != AUTH_LINK_TYPE_WIFI) && - (len == DEVICE_ID_STR_LEN) && - (info->isServer)) { + AUTH_CHECK_AND_RETURN_RET_LOGE(info != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "info is NULL"); + AUTH_CHECK_AND_RETURN_RET_LOGE(data != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "data is NULL"); + if ((info->connInfo.type != AUTH_LINK_TYPE_WIFI) && (len == DEVICE_ID_STR_LEN) && (info->isServer)) { info->version = SOFTBUS_OLD_V1; return UnPackBtDeviceIdV1(info, data, len); } @@ -1520,13 +1570,15 @@ static void GetSessionKeyList(int64_t authSeq, const AuthSessionInfo *info, Sess } if (AddSessionKey(list, TO_INT32(authSeq), &sessionKey) != SOFTBUS_OK) { AUTH_LOGE(AUTH_FSM, "add session key fail"); + (void)memset_s(&sessionKey, sizeof(SessionKey), 0, sizeof(SessionKey)); return; } + (void)memset_s(&sessionKey, sizeof(SessionKey), 0, sizeof(SessionKey)); } int32_t PostDeviceInfoMessage(int64_t authSeq, const AuthSessionInfo *info) { - CHECK_NULL_PTR_RETURN_VALUE(info, SOFTBUS_INVALID_PARAM); + AUTH_CHECK_AND_RETURN_RET_LOGE(info != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "info is NULL"); char *msg = PackDeviceInfoMessage(info->connInfo.type, info->version, false, info->uuid); if (msg == NULL) { AUTH_LOGE(AUTH_FSM, "pack device info fail"); @@ -1543,7 +1595,7 @@ int32_t PostDeviceInfoMessage(int64_t authSeq, const AuthSessionInfo *info) compressFlag = FLAG_COMPRESS_DEVICE_INFO; AUTH_LOGI(AUTH_FSM, "deviceInfo compress finish"); } - AUTH_LOGI(AUTH_FSM, "after compress, datalen=%d", compressLen); + AUTH_LOGI(AUTH_FSM, "after compress, datalen=%u", compressLen); } uint8_t *inputData = NULL; uint32_t inputLen; @@ -1593,8 +1645,8 @@ int32_t PostDeviceInfoMessage(int64_t authSeq, const AuthSessionInfo *info) int32_t ProcessDeviceInfoMessage(int64_t authSeq, AuthSessionInfo *info, const uint8_t *data, uint32_t len) { - CHECK_NULL_PTR_RETURN_VALUE(info, SOFTBUS_INVALID_PARAM); - CHECK_NULL_PTR_RETURN_VALUE(data, SOFTBUS_INVALID_PARAM); + AUTH_CHECK_AND_RETURN_RET_LOGE(info != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "info is NULL"); + AUTH_CHECK_AND_RETURN_RET_LOGE(data != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "data is NULL"); uint8_t *msg = NULL; uint32_t msgSize = 0; SessionKeyList sessionKeyList; @@ -1606,7 +1658,7 @@ int32_t ProcessDeviceInfoMessage(int64_t authSeq, AuthSessionInfo *info, const u uint8_t *decompressData = NULL; uint32_t decompressLen = 0; if ((info->connInfo.type != AUTH_LINK_TYPE_WIFI) && info->isSupportCompress) { - AUTH_LOGI(AUTH_FSM, "before decompress, msgSize=%d", msgSize); + AUTH_LOGI(AUTH_FSM, "before decompress, msgSize=%u", msgSize); if (DataDecompress((uint8_t *)msg, msgSize, &decompressData, &decompressLen) != SOFTBUS_OK) { AUTH_LOGE(AUTH_FSM, "data decompress fail"); SoftBusFree(msg); @@ -1637,7 +1689,7 @@ int32_t ProcessDeviceInfoMessage(int64_t authSeq, AuthSessionInfo *info, const u int32_t PostCloseAckMessage(int64_t authSeq, const AuthSessionInfo *info) { - CHECK_NULL_PTR_RETURN_VALUE(info, SOFTBUS_INVALID_PARAM); + AUTH_CHECK_AND_RETURN_RET_LOGE(info != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "info is NULL"); const char *msg = ""; AuthDataHead head = { .dataType = DATA_TYPE_CLOSE_ACK, @@ -1655,8 +1707,8 @@ int32_t PostCloseAckMessage(int64_t authSeq, const AuthSessionInfo *info) int32_t PostHichainAuthMessage(int64_t authSeq, const AuthSessionInfo *info, const uint8_t *data, uint32_t len) { - CHECK_NULL_PTR_RETURN_VALUE(info, SOFTBUS_INVALID_PARAM); - CHECK_NULL_PTR_RETURN_VALUE(data, SOFTBUS_INVALID_PARAM); + AUTH_CHECK_AND_RETURN_RET_LOGE(info != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "info is NULL"); + AUTH_CHECK_AND_RETURN_RET_LOGE(data != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "data is NULL"); AuthDataHead head = { .dataType = DATA_TYPE_AUTH, .module = MODULE_AUTH_SDK, @@ -1678,8 +1730,7 @@ static char *PackVerifyDeviceMessage(const char *uuid) AUTH_LOGE(AUTH_FSM, "create json fail"); return NULL; } - if (!JSON_AddInt32ToObject(obj, CODE, CODE_VERIFY_DEVICE) || - !JSON_AddStringToObject(obj, DEVICE_ID, uuid)) { + if (!JSON_AddInt32ToObject(obj, CODE, CODE_VERIFY_DEVICE) || !JSON_AddStringToObject(obj, DEVICE_ID, uuid)) { AUTH_LOGE(AUTH_FSM, "add uuid fail"); JSON_Delete(obj); return NULL; @@ -1730,7 +1781,7 @@ bool IsFlushDevicePacket(const AuthConnInfo *connInfo, const AuthDataHead *head, int32_t PostVerifyDeviceMessage(const AuthManager *auth, int32_t flagRelay) { - CHECK_NULL_PTR_RETURN_VALUE(auth, SOFTBUS_INVALID_PARAM); + AUTH_CHECK_AND_RETURN_RET_LOGE(auth != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "auth is NULL"); char *msg = PackVerifyDeviceMessage(auth->uuid); if (msg == NULL) { AUTH_LOGE(AUTH_FSM, "pack verify device msg fail"); @@ -1760,4 +1811,4 @@ int32_t PostVerifyDeviceMessage(const AuthManager *auth, int32_t flagRelay) } SoftBusFree(data); return SOFTBUS_OK; -} +} \ No newline at end of file diff --git a/core/authentication/src/auth_tcp_connection.c b/core/authentication/src/auth_tcp_connection.c index dd9471efa..d5a14cda6 100644 --- a/core/authentication/src/auth_tcp_connection.c +++ b/core/authentication/src/auth_tcp_connection.c @@ -248,6 +248,14 @@ static int32_t ProcessSocketInEvent(ListenerModule module, int32_t fd) return SOFTBUS_OK; } +static bool IsEnhanceP2pModuleId(ListenerModule moduleId) +{ + if (moduleId >= AUTH_ENHANCED_P2P_START && moduleId <= AUTH_ENHANCED_P2P_END) { + return true; + } + return false; +} + static int32_t OnConnectEvent(ListenerModule module, int32_t cfd, const ConnectOption *clientAddr) { @@ -265,7 +273,7 @@ static int32_t OnConnectEvent(ListenerModule module, ConnShutdownSocket(cfd); return SOFTBUS_ERR; } - if (module != AUTH && module != AUTH_P2P) { + if (module != AUTH && module != AUTH_P2P && !IsEnhanceP2pModuleId(module)) { AUTH_LOGI(AUTH_CONN, "newip auth process"); if (RouteBuildServerAuthManager(cfd, clientAddr) != SOFTBUS_OK) { AUTH_LOGE(AUTH_CONN, "build auth manager fail."); @@ -585,4 +593,4 @@ int32_t AuthPostChannelData(int32_t channelId, const AuthChannelData *data) .len = data->len, }; return SocketPostBytes(channelId, &head, data->data); -} +} \ No newline at end of file diff --git a/core/bus_center/ipc/include/lnn_bus_center_ipc.h b/core/bus_center/ipc/include/lnn_bus_center_ipc.h index 3a3ea5239..a258592e7 100644 --- a/core/bus_center/ipc/include/lnn_bus_center_ipc.h +++ b/core/bus_center/ipc/include/lnn_bus_center_ipc.h @@ -35,7 +35,7 @@ int32_t LnnIpcSetNodeDataChangeFlag(const char *pkgName, const char *networkId, int32_t LnnIpcGetNodeKeyInfoLen(int32_t key); int32_t LnnIpcStartTimeSync( const char *pkgName, int32_t callingPid, const char *targetNetworkId, int32_t accuracy, int32_t period); -int32_t LnnIpcStopTimeSync(const char *pkgName, const char *targetNetworkId); +int32_t LnnIpcStopTimeSync(const char *pkgName, const char *targetNetworkId, int32_t callingPid); int32_t LnnIpcPublishLNN(const char *pkgName, const PublishInfo *info); int32_t LnnIpcStopPublishLNN(const char *pkgName, int32_t publishId); int32_t LnnIpcRefreshLNN(const char *pkgName, int32_t callingPid, const SubscribeInfo *info); diff --git a/core/bus_center/ipc/mini/lnn_bus_center_ipc.c b/core/bus_center/ipc/mini/lnn_bus_center_ipc.c index fc561e0f2..7651f0ead 100644 --- a/core/bus_center/ipc/mini/lnn_bus_center_ipc.c +++ b/core/bus_center/ipc/mini/lnn_bus_center_ipc.c @@ -97,9 +97,9 @@ int32_t LnnIpcStartTimeSync(const char *pkgName, int32_t callingPid, const char return LnnStartTimeSync(pkgName, callingPid, targetNetworkId, (TimeSyncAccuracy)accuracy, (TimeSyncPeriod)period); } -int32_t LnnIpcStopTimeSync(const char *pkgName, const char *targetNetworkId) +int32_t LnnIpcStopTimeSync(const char *pkgName, const char *targetNetworkId, int32_t callingPid) { - return LnnStopTimeSync(pkgName, targetNetworkId); + return LnnStopTimeSync(pkgName, targetNetworkId, callingPid); } int32_t LnnIpcPublishLNN(const char *pkgName, const PublishInfo *info) diff --git a/core/bus_center/ipc/small/src/lnn_bus_center_ipc.c b/core/bus_center/ipc/small/src/lnn_bus_center_ipc.c index 6eb7f704f..94806079c 100644 --- a/core/bus_center/ipc/small/src/lnn_bus_center_ipc.c +++ b/core/bus_center/ipc/small/src/lnn_bus_center_ipc.c @@ -310,9 +310,9 @@ int32_t LnnIpcStartTimeSync(const char *pkgName, int32_t callingPid, const char return LnnStartTimeSync(pkgName, callingPid, targetNetworkId, (TimeSyncAccuracy)accuracy, (TimeSyncPeriod)period); } -int32_t LnnIpcStopTimeSync(const char *pkgName, const char *targetNetworkId) +int32_t LnnIpcStopTimeSync(const char *pkgName, const char *targetNetworkId, int32_t callingPid) { - return LnnStopTimeSync(pkgName, targetNetworkId); + return LnnStopTimeSync(pkgName, targetNetworkId, callingPid); } int32_t LnnIpcPublishLNN(const char *pkgName, const PublishInfo *info) diff --git a/core/bus_center/ipc/standard/src/lnn_bus_center_ipc.cpp b/core/bus_center/ipc/standard/src/lnn_bus_center_ipc.cpp index 5ccc4146a..cfd62d589 100644 --- a/core/bus_center/ipc/standard/src/lnn_bus_center_ipc.cpp +++ b/core/bus_center/ipc/standard/src/lnn_bus_center_ipc.cpp @@ -223,9 +223,9 @@ int32_t LnnIpcStartTimeSync(const char *pkgName, int32_t callingPid, const char return LnnStartTimeSync(pkgName, callingPid, targetNetworkId, (TimeSyncAccuracy)accuracy, (TimeSyncPeriod)period); } -int32_t LnnIpcStopTimeSync(const char *pkgName, const char *targetNetworkId) +int32_t LnnIpcStopTimeSync(const char *pkgName, const char *targetNetworkId, int32_t callingPid) { - return LnnStopTimeSync(pkgName, targetNetworkId); + return LnnStopTimeSync(pkgName, targetNetworkId, callingPid); } int32_t LnnIpcPublishLNN(const char *pkgName, const PublishInfo *info) diff --git a/core/bus_center/lnn/lane_hub/lane_manager/include/lnn_lane_interface.h b/core/bus_center/lnn/lane_hub/lane_manager/include/lnn_lane_interface.h index c4161d7a9..447de0c11 100644 --- a/core/bus_center/lnn/lane_hub/lane_manager/include/lnn_lane_interface.h +++ b/core/bus_center/lnn/lane_hub/lane_manager/include/lnn_lane_interface.h @@ -151,6 +151,7 @@ typedef struct { bool p2pOnly; ProtocolType acceptableProtocols; int32_t pid; + bool isWithQos; //OldInfo char peerBleMac[MAX_MAC_LEN]; //'psm' is valid only when 'expectedlink' contains 'LANE_COC' diff --git a/core/bus_center/lnn/lane_hub/lane_manager/include/lnn_select_rule.h b/core/bus_center/lnn/lane_hub/lane_manager/include/lnn_select_rule.h index 9dc415c70..bf84ec37a 100755 --- a/core/bus_center/lnn/lane_hub/lane_manager/include/lnn_select_rule.h +++ b/core/bus_center/lnn/lane_hub/lane_manager/include/lnn_select_rule.h @@ -28,7 +28,8 @@ extern "C" { typedef enum { HIGH_BAND_WIDTH = 0, - MIDDLE_BAND_WIDTH, + MIDDLE_HIGH_BAND_WIDTH, + MIDDLE_LOW_BAND_WIDTH, LOW_BAND_WIDTH, BW_TYPE_BUTT, } BandWidthType; diff --git a/core/bus_center/lnn/lane_hub/lane_manager/include/lnn_trans_lane.h b/core/bus_center/lnn/lane_hub/lane_manager/include/lnn_trans_lane.h index 6b82fead3..3ada4732c 100644 --- a/core/bus_center/lnn/lane_hub/lane_manager/include/lnn_trans_lane.h +++ b/core/bus_center/lnn/lane_hub/lane_manager/include/lnn_trans_lane.h @@ -17,28 +17,18 @@ #define LNN_TRANS_LANE_H #include "lnn_lane_assign.h" +#include "lnn_lane_link.h" #ifdef __cplusplus extern "C" { #endif -typedef enum { - MSG_TYPE_LANE_TRIGGER_LINK = 0, - MSG_TYPE_LANE_LINK_SUCCESS, - MSG_TYPE_LANE_LINK_FAIL, - MSG_TYPE_LANE_LINK_EXCEPTION, - MSG_TYPE_DELAY_DESTROY_LINK, - MSG_TYPE_LANE_DETECT_TIMEOUT, - MSG_TYPE_RELIABILITY_TIME, -} LaneMsgType; - LaneInterface *TransLaneGetInstance(void); -int32_t GetQosInfoByLaneId(uint32_t laneId, QosInfo *qosOpt); -int32_t LnnLanePostMsgToHandler(int32_t msgType, uint64_t param1, uint64_t param2, - void *obj, uint64_t delayMillis); +int32_t GetTransOptionByLaneId(uint32_t laneId, TransOption *reqInfo); int32_t PostDetectTimeoutMessage(uint32_t detectId, uint64_t delayMillis); int32_t PostReliabilityTimeMessage(void); void RemoveDetectTimeoutMessage(uint32_t detectId); +int32_t PostDelayDestroyMessage(uint32_t laneId, LaneResource *resourseItem, uint64_t delayMillis); #ifdef __cplusplus } diff --git a/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_link.c b/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_link.c index 3dd688d69..cf3586a09 100644 --- a/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_link.c +++ b/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_link.c @@ -179,10 +179,12 @@ int32_t AddLaneResourceItem(const LaneResource *inputResource) return SOFTBUS_MALLOC_ERR; } if (CreateResourceItem(inputResource, resourceItem) != SOFTBUS_OK) { + SoftBusFree(resourceItem); LNN_LOGE(LNN_LANE, "create resourceItem fail"); return SOFTBUS_ERR; } if (LaneLock() != SOFTBUS_OK) { + SoftBusFree(resourceItem); LNN_LOGE(LNN_LANE, "lane lock fail"); return SOFTBUS_LOCK_ERR; } @@ -198,6 +200,25 @@ int32_t AddLaneResourceItem(const LaneResource *inputResource) return SOFTBUS_OK; } +static int32_t StartDelayDestroyLink(uint32_t laneId, LaneResource *item) +{ + LaneResource *resourceItem = (LaneResource *)SoftBusMalloc(sizeof(LaneResource)); + if (resourceItem == NULL) { + LNN_LOGE(LNN_LANE, "resourceItem malloc fail"); + return SOFTBUS_MALLOC_ERR; + } + if (memcpy_s(resourceItem, sizeof(LaneResource), item, sizeof(LaneResource)) != EOK) { + LNN_LOGE(LNN_LANE, "memcpy LaneResource error"); + SoftBusFree(resourceItem); + return SOFTBUS_MEM_ERR; + } + if (PostDelayDestroyMessage(laneId, resourceItem, DELAY_DESTROY_LANE_TIME) != SOFTBUS_OK) { + SoftBusFree(resourceItem); + return SOFTBUS_ERR; + } + return SOFTBUS_OK; +} + int32_t DelLaneResourceItemWithDelay(LaneResource *resourceItem, uint32_t laneId, bool *isDelayDestroy) { if (resourceItem == NULL || isDelayDestroy == NULL) { @@ -210,9 +231,9 @@ int32_t DelLaneResourceItemWithDelay(LaneResource *resourceItem, uint32_t laneId } LaneResource* item = LaneResourceIsExist(resourceItem); if (item != NULL) { + LNN_LOGI(LNN_LANE, "link=%d ref=%d", item->type, item->laneRef); if (item->type == LANE_HML && item->laneRef == 1) { - if (LnnLanePostMsgToHandler(MSG_TYPE_DELAY_DESTROY_LINK, laneId, *isDelayDestroy, item, - DELAY_DESTROY_LANE_TIME) == SOFTBUS_OK) { + if (StartDelayDestroyLink(laneId, item) == SOFTBUS_OK) { *isDelayDestroy = true; LaneUnlock(); return SOFTBUS_OK; @@ -324,10 +345,12 @@ int32_t AddLinkInfoItem(const LaneLinkInfo *inputLinkInfo) return SOFTBUS_MALLOC_ERR; } if (CreateLinkInfoItem(inputLinkInfo, linkInfoItem) != SOFTBUS_OK) { + SoftBusFree(linkInfoItem); LNN_LOGE(LNN_LANE, "create linkInfoItem fail"); return SOFTBUS_ERR; } if (LaneLock() != SOFTBUS_OK) { + SoftBusFree(linkInfoItem); LNN_LOGE(LNN_LANE, "lane lock fail"); return SOFTBUS_LOCK_ERR; } @@ -703,6 +726,22 @@ static int32_t LaneLinkOfBleReuse(uint32_t reqId, const LinkRequest *reqInfo, co return LaneLinkOfBleReuseCommon(reqId, reqInfo, callback, BLE_GATT); } +static int32_t LaneLinkSetBleMac(const LinkRequest *reqInfo, LaneLinkInfo *linkInfo) +{ + NodeInfo node; + (void)memset_s(&node, sizeof(NodeInfo), 0, sizeof(NodeInfo)); + if (LnnGetRemoteNodeInfoById(reqInfo->peerNetworkId, CATEGORY_NETWORK_ID, &node) != SOFTBUS_OK) { + LNN_LOGE(LNN_LANE, "can not find node"); + return SOFTBUS_ERR; + } + if (node.bleMacRefreshSwitch == 0 && strlen(node.connectInfo.bleMacAddr) > 0) { + if (strcpy_s(linkInfo->linkInfo.ble.bleMac, BT_MAC_LEN, node.connectInfo.bleMacAddr) == EOK) { + return SOFTBUS_OK; + } + } + return SOFTBUS_ERR; +} + static int32_t LaneLinkOfBle(uint32_t reqId, const LinkRequest *reqInfo, const LaneLinkCb *callback) { LaneLinkInfo linkInfo; @@ -712,8 +751,10 @@ static int32_t LaneLinkOfBle(uint32_t reqId, const LinkRequest *reqInfo, const L return SOFTBUS_MEM_ERR; } if (strlen(linkInfo.linkInfo.ble.bleMac) == 0) { - LNN_LOGE(LNN_LANE, "get peerBleMac error"); - return SOFTBUS_ERR; + if (LaneLinkSetBleMac(reqInfo, &linkInfo) != SOFTBUS_OK) { + LNN_LOGE(LNN_LANE, "get peerBleMac error"); + return SOFTBUS_ERR; + } } char peerUdid[UDID_BUF_LEN] = {0}; if (LnnGetRemoteStrInfo(reqInfo->peerNetworkId, STRING_KEY_DEV_UDID, peerUdid, UDID_BUF_LEN) != SOFTBUS_OK) { diff --git a/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_link_p2p.c b/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_link_p2p.c index a3a03090b..bb316b503 100644 --- a/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_link_p2p.c +++ b/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_link_p2p.c @@ -62,6 +62,7 @@ typedef struct { bool networkDelegate; bool p2pOnly; uint32_t bandWidth; + bool isWithQos; } P2pRequestInfo; typedef struct { @@ -362,11 +363,12 @@ static int32_t GetP2pLinkReqParamByChannelRequetId( return SOFTBUS_ERR; } wifiDirectInfo->isNetworkDelegate = item->p2pInfo.networkDelegate; - if (item->p2pInfo.p2pOnly) { - wifiDirectInfo->connectType = WIFI_DIRECT_CONNECT_TYPE_AUTH_NEGO_P2P; - } else { + if (item->p2pInfo.isWithQos) { wifiDirectInfo->connectType = ((item->laneRequestInfo.laneType == LANE_HML) ? WIFI_DIRECT_CONNECT_TYPE_AUTH_NEGO_HML : WIFI_DIRECT_CONNECT_TYPE_AUTH_NEGO_P2P); + } else { + wifiDirectInfo->connectType = item->p2pInfo.p2pOnly ? WIFI_DIRECT_CONNECT_TYPE_AUTH_NEGO_P2P : + WIFI_DIRECT_CONNECT_TYPE_AUTH_NEGO_HML; } item->p2pInfo.p2pRequestId = p2pRequestId; item->proxyChannelInfo.channelId = channelId; @@ -407,11 +409,12 @@ static int32_t GetP2pLinkReqParamByAuthId(uint32_t authRequestId, int32_t p2pReq } wifiDirectInfo->bandWidth = item->p2pInfo.bandWidth; wifiDirectInfo->isNetworkDelegate = item->p2pInfo.networkDelegate; - if (item->p2pInfo.p2pOnly) { - wifiDirectInfo->connectType = WIFI_DIRECT_CONNECT_TYPE_AUTH_NEGO_P2P; - } else { + if (item->p2pInfo.isWithQos) { wifiDirectInfo->connectType = ((item->laneRequestInfo.laneType == LANE_HML) ? WIFI_DIRECT_CONNECT_TYPE_AUTH_NEGO_HML : WIFI_DIRECT_CONNECT_TYPE_AUTH_NEGO_P2P); + } else { + wifiDirectInfo->connectType = item->p2pInfo.p2pOnly ? WIFI_DIRECT_CONNECT_TYPE_AUTH_NEGO_P2P : + WIFI_DIRECT_CONNECT_TYPE_AUTH_NEGO_HML; } item->p2pInfo.p2pRequestId = p2pRequestId; LinkUnlock(); @@ -617,6 +620,25 @@ static void OnAuthConnOpenFailed(uint32_t authRequestId, int32_t reason) NotifyLinkFail(ASYNC_RESULT_AUTH, authRequestId, reason); } +static int32_t updataP2pLinkReq(P2pLinkReqList *p2pReqInfo, uint32_t laneLinkReqId) +{ + TransOption reqInfo = {0}; + if (GetTransOptionByLaneId(laneLinkReqId, &reqInfo) != SOFTBUS_OK) { + LNN_LOGE(LNN_LANE, "get TransReqInfo fail, laneId=%d", laneLinkReqId); + return SOFTBUS_ERR; + } + if (reqInfo.isWithQos) { + p2pReqInfo->p2pInfo.bandWidth = reqInfo.qosRequire.minBW; + p2pReqInfo->p2pInfo.isWithQos = true; + } else { + p2pReqInfo->p2pInfo.bandWidth = 0; + p2pReqInfo->p2pInfo.isWithQos = false; + } + LNN_LOGI(LNN_LANE, "wifidirect conn, bandWidth=%d isWithQos=%d laneId=%d", + p2pReqInfo->p2pInfo.bandWidth, p2pReqInfo->p2pInfo.isWithQos, laneLinkReqId); + return SOFTBUS_OK; +} + static int32_t AddConnRequestItem(uint32_t authRequestId, int32_t p2pRequestId, uint32_t laneLinkReqId, const LinkRequest *request, int32_t channelRequestId, const LaneLinkCb *callback) { @@ -634,11 +656,9 @@ static int32_t AddConnRequestItem(uint32_t authRequestId, int32_t p2pRequestId, SoftBusFree(item); return SOFTBUS_MEM_ERR; } - QosInfo qosOpt = {0}; - if (GetQosInfoByLaneId(laneLinkReqId, &qosOpt) != SOFTBUS_OK) { - item->p2pInfo.bandWidth = 0; - } else { - item->p2pInfo.bandWidth = qosOpt.minBW; + if (updataP2pLinkReq(item, laneLinkReqId) != SOFTBUS_OK) { + SoftBusFree(item); + return SOFTBUS_ERR; } item->laneRequestInfo.laneLinkReqId = laneLinkReqId; item->laneRequestInfo.pid = request->pid; diff --git a/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_query.c b/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_query.c index 5ff32106c..27685a76b 100755 --- a/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_query.c +++ b/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_query.c @@ -25,7 +25,6 @@ #include "lnn_lane_link.h" #include "softbus_bus_center.h" #include "softbus_errcode.h" -#include "softbus_log_old.h" #include "softbus_wifi_api_adapter.h" #include "wifi_direct_manager.h" diff --git a/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_reliability.c b/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_reliability.c index c190e5132..19f37938a 100644 --- a/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_reliability.c +++ b/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_reliability.c @@ -208,6 +208,7 @@ static int32_t WlanDetectReliability(uint32_t lnnReqId, const LaneLinkInfo *lane } infoItem->linkInfo.wlanDetect.wlanFd = fd; if (SoftBusMutexLock(&g_laneDetectList.lock) != SOFTBUS_OK) { + ConnShutdownSocket(fd); SoftBusFree(infoItem); return SOFTBUS_LOCK_ERR; } @@ -215,6 +216,7 @@ static int32_t WlanDetectReliability(uint32_t lnnReqId, const LaneLinkInfo *lane ListTailInsert(&g_laneDetectList.list, &infoItem->node); SoftBusMutexUnlock(&g_laneDetectList.lock); if (AddLaneTriggerAndTimeOut(fd, infoItem->laneDetectId) != SOFTBUS_OK) { + ConnShutdownSocket(fd); DelLaneDetectInfo(infoItem->laneDetectId); LNN_LOGI(LNN_LANE, "wlan add trigger and timrout msg fail, lnnReqId=%u", infoItem->laneDetectId); return SOFTBUS_ERR; diff --git a/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_select.c b/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_select.c index 1a8d4b597..673584d04 100644 --- a/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_select.c +++ b/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_select.c @@ -239,24 +239,38 @@ static void SwapListNode(LaneLinkType *left, LaneLinkType *right) *right = tmp; } -static int32_t AdjustLanePriority(LaneLinkType *resList, int32_t *resListScore, uint32_t resNum) +static int32_t AdjustLanePriority(const char *networkId, const LaneSelectParam *request, + LaneLinkType *resList, uint32_t resNum) { + int32_t resListScore[LANE_LINK_TYPE_BUTT]; + (void)memset_s(resListScore, sizeof(resListScore), INVALID_LINK, sizeof(resListScore)); + if (GetListScore(networkId, request->expectedBw, resList, resListScore, resNum) != SOFTBUS_OK) { + LNN_LOGE(LNN_LANE, "get linklist score fail"); + return SOFTBUS_ERR; + } if ((resListScore[LANE_WLAN_2P4G] == INVALID_LINK && resListScore[LANE_WLAN_5G] == INVALID_LINK) || - resListScore[LANE_P2P] == INVALID_LINK) { - LNN_LOGI(LNN_LANE, "resList no change"); + (resListScore[LANE_P2P] == INVALID_LINK && resListScore[LANE_HML] == INVALID_LINK)) { + LNN_LOGI(LNN_LANE, "linklist does not require any changes"); return SOFTBUS_OK; } uint32_t idxWlan = LANE_LINK_TYPE_BUTT; - uint32_t idxP2p = LANE_LINK_TYPE_BUTT; for (uint32_t i = 0; i < resNum; ++i) { - if (resList[i] == LANE_P2P) { - idxP2p = i; - } else if (resList[i] == LANE_WLAN_2P4G || resList[i] == LANE_WLAN_5G) { - idxWlan = (idxWlan == LANE_LINK_TYPE_BUTT) ? i : idxWlan; + if (resList[i] == LANE_WLAN_2P4G || resList[i] == LANE_WLAN_5G) { + idxWlan = i; + break; } } - if (resListScore[resList[idxWlan]] < UNACCEPT_SCORE && idxWlan < idxP2p) { - SwapListNode(&resList[idxWlan], &resList[idxP2p]); + if (resListScore[resList[idxWlan]] >= UNACCEPT_SCORE) { + return SOFTBUS_OK; + } + for (uint32_t j = idxWlan; j < resNum; ++j) { + if (resList[j] == LANE_HML || resList[j] == LANE_P2P) { + SwapListNode(&resList[idxWlan], &resList[j]); + idxWlan = j; + } + } + for (uint32_t k = 0; k < resNum; ++k) { + LNN_LOGD(LNN_LANE, "adjusted linklist , priority link=%d, score=%d", resList[k], resListScore[resList[k]]); } return SOFTBUS_OK; } @@ -282,20 +296,10 @@ int32_t SelectLane(const char *networkId, const LaneSelectParam *request, *listNum = 0; return SOFTBUS_ERR; } - - int32_t resListScore[LANE_LINK_TYPE_BUTT]; - (void)memset_s(resListScore, sizeof(resListScore), INVALID_LINK, sizeof(resListScore)); - if (GetListScore(networkId, request->expectedBw, resList, resListScore, resNum) != SOFTBUS_OK) { - LNN_LOGE(LNN_LANE, "get resListScore fail"); - return SOFTBUS_ERR; - } - if (AdjustLanePriority(resList, resListScore, resNum) != SOFTBUS_OK) { + if (AdjustLanePriority(networkId, request, resList, resNum) != SOFTBUS_OK) { LNN_LOGE(LNN_LANE, "AdjustLanePriority fail"); return SOFTBUS_ERR; } - for (uint32_t i = 0; i < resNum; ++i) { - LNN_LOGD(LNN_LANE, "adjusted list is LaneLinkType=%d, score=%d", resList[i], resListScore[resList[i]]); - } recommendList->linkTypeNum = resNum; for (uint32_t i = 0; i < resNum; i++) { @@ -305,27 +309,6 @@ int32_t SelectLane(const char *networkId, const LaneSelectParam *request, return SOFTBUS_OK; } -static int32_t LanePrioritization(LanePreferredLinkList *recommendList, const uint16_t *laneScore) -{ - (void)recommendList; - (void)laneScore; - return SOFTBUS_OK; -} - -static bool GetLaneScore(const char *networkId, LaneLinkType linkType, uint16_t *score) -{ - if (!IsLinkTypeValid(linkType)) { - return false; - } - LinkAttribute *linkAttr = GetLinkAttrByLinkType(linkType); - if ((linkAttr == NULL) || (!linkAttr->available)) { - return false; - } - uint32_t expectedBw = 0; - score[linkType] = linkAttr->GetLinkScore(networkId, expectedBw); - return true; -} - int32_t SelectExpectLanesByQos(const char *networkId, const LaneSelectParam *request, LanePreferredLinkList *recommendList) { @@ -351,19 +334,16 @@ int32_t SelectExpectLanesByQos(const char *networkId, const LaneSelectParam *req } } recommendList->linkTypeNum = 0; - uint16_t laneScore[LANE_LINK_TYPE_BUTT] = {0}; for (uint32_t i = 0; i < laneLinkList.linkTypeNum; i++) { - if (!GetLaneScore(networkId, laneLinkList.linkType[i], laneScore)) { - LNN_LOGE(LNN_LANE, "link=%d get lane score fail", laneLinkList.linkType[i]); - continue; - } recommendList->linkType[recommendList->linkTypeNum] = laneLinkList.linkType[i]; LNN_LOGI(LNN_LANE, "expect linklist the %u priority link=%d", recommendList->linkTypeNum, laneLinkList.linkType[i]); recommendList->linkTypeNum++; } - if (LanePrioritization(recommendList, laneScore) != SOFTBUS_OK) { + if (AdjustLanePriority(networkId, request, recommendList->linkType, + recommendList->linkTypeNum) != SOFTBUS_OK) { + LNN_LOGE(LNN_LANE, "AdjustLanePriority fail"); return SOFTBUS_ERR; } return SOFTBUS_OK; diff --git a/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_select_rule.c b/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_select_rule.c index 408722516..9b7846e2b 100644 --- a/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_select_rule.c +++ b/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_select_rule.c @@ -41,13 +41,16 @@ #define LNN_LINK_DEFAULT_SCORE 60 /* Indicates that scoring is not supported */ #define LNN_ONLINETIME_OUT 10000 /*BLE connection reuse time*/ -#define LOW_BW (500 * 1024) +#define LOW_BW (384 * 1024) +#define MID_BW (30 * 1024 * 1024) #define HIGH_BW (160 * 1024 * 1024) #define COC_DIRECT_LATENCY 1200 #define BR_LATENCY 2500 #define WLAN_LATENCY 800 #define P2P_LATENCY 1600 +#define BLE_LATENCY 1500 #define HML_LATENCY 1500 +#define BR_REUSE_LATENCY 1000 int32_t GetWlanLinkedFrequency(void) @@ -393,20 +396,24 @@ static int32_t g_laneLatency[LANE_LINK_TYPE_BUTT] = { [LANE_WLAN_2P4G] = WLAN_LATENCY, [LANE_WLAN_5G] = WLAN_LATENCY, [LANE_COC_DIRECT] = COC_DIRECT_LATENCY, + [LANE_BLE] = BLE_LATENCY, }; static uint32_t g_laneBandWidth[BW_TYPE_BUTT][LANE_LINK_TYPE_BUTT + 1] = { [HIGH_BAND_WIDTH] = {LANE_P2P, LANE_LINK_TYPE_BUTT}, - [MIDDLE_BAND_WIDTH] = {LANE_HML, LANE_WLAN_5G, LANE_WLAN_2P4G, LANE_LINK_TYPE_BUTT}, - [LOW_BAND_WIDTH] = {LANE_HML, LANE_WLAN_5G, LANE_WLAN_2P4G, LANE_COC_DIRECT, LANE_LINK_TYPE_BUTT}, + [MIDDLE_HIGH_BAND_WIDTH] = {LANE_HML, LANE_WLAN_5G, LANE_WLAN_2P4G, LANE_LINK_TYPE_BUTT}, + [MIDDLE_LOW_BAND_WIDTH] = {LANE_WLAN_5G, LANE_WLAN_2P4G, LANE_HML, LANE_LINK_TYPE_BUTT}, + [LOW_BAND_WIDTH] = {LANE_WLAN_5G, LANE_WLAN_2P4G, LANE_HML, LANE_COC_DIRECT, LANE_LINK_TYPE_BUTT}, }; static uint32_t g_retryLaneList[BW_TYPE_BUTT][LANE_LINK_TYPE_BUTT + 1] = { [HIGH_BAND_WIDTH] = {LANE_P2P, LANE_WLAN_5G, LANE_WLAN_2P4G, LANE_LINK_TYPE_BUTT}, - [MIDDLE_BAND_WIDTH] = {LANE_HML, LANE_WLAN_5G, LANE_WLAN_2P4G, LANE_P2P, - LANE_BR, LANE_LINK_TYPE_BUTT}, - [LOW_BAND_WIDTH] = {LANE_HML, LANE_WLAN_5G, LANE_WLAN_2P4G, LANE_P2P, LANE_COC_DIRECT, - LANE_BR, LANE_LINK_TYPE_BUTT}, + [MIDDLE_HIGH_BAND_WIDTH] = {LANE_HML, LANE_WLAN_5G, LANE_WLAN_2P4G, LANE_P2P, LANE_BR, + LANE_LINK_TYPE_BUTT}, + [MIDDLE_LOW_BAND_WIDTH] = {LANE_WLAN_5G, LANE_WLAN_2P4G, LANE_HML, LANE_P2P, LANE_BR, + LANE_LINK_TYPE_BUTT}, + [LOW_BAND_WIDTH] = {LANE_WLAN_5G, LANE_WLAN_2P4G, LANE_HML, LANE_P2P, LANE_COC_DIRECT, + LANE_BR, LANE_BLE, LANE_LINK_TYPE_BUTT}, }; static bool IsLinkTypeValid(LaneLinkType type) @@ -449,25 +456,31 @@ static bool IsLaneFillMinLatency(uint32_t minLaneLatency, LaneLinkType linkType) return false; } +static int32_t GetBwType(uint32_t bandWidth) +{ + int32_t bandWidthType; + if (bandWidth >= HIGH_BW) { + bandWidthType = HIGH_BAND_WIDTH; + } else if (bandWidth > MID_BW) { + bandWidthType = MIDDLE_HIGH_BAND_WIDTH; + } else if (bandWidth > LOW_BW) { + bandWidthType = MIDDLE_LOW_BAND_WIDTH; + } else { + bandWidthType = LOW_BAND_WIDTH; + } + return bandWidthType; +} + static void DecideOptimalLinks(const char *networkId, const LaneSelectParam *request, LaneLinkType *linkList, uint32_t *linksNum) { uint32_t minBandWidth = request->qosRequire.minBW; uint32_t minLaneLatency = request->qosRequire.minLaneLatency; - if (minBandWidth == 0) { - minBandWidth = LOW_BW; - } if (minLaneLatency == 0) { - minLaneLatency = BR_LATENCY; - } - int32_t bandWidthType; - if (minBandWidth >= HIGH_BW) { - bandWidthType = HIGH_BAND_WIDTH; - } else if (minBandWidth >= LOW_BW) { - bandWidthType = MIDDLE_BAND_WIDTH; - } else { - bandWidthType = LOW_BAND_WIDTH; + LNN_LOGI(LNN_LANE, "minLaneLatency is zero, cancel decide optimal link"); + return; } + int32_t bandWidthType = GetBwType(minBandWidth); LNN_LOGI(LNN_LANE, "decide optimal link, band width type=%ld, latency=%d", bandWidthType, minLaneLatency); for (uint32_t i = 0; i < (LANE_LINK_TYPE_BUTT + 1); i++) { if (g_laneBandWidth[bandWidthType][i] == LANE_LINK_TYPE_BUTT) { @@ -493,21 +506,31 @@ static bool isLaneExist(LaneLinkType *linkList, LaneLinkType laneType) return false; } +static void GetAllLinksWithBw(const char *networkId, int32_t bandWidthType, const LaneSelectParam *request, + LaneLinkType *linkList, uint32_t *linksNum) +{ + for (uint32_t i = 0; i < (LANE_LINK_TYPE_BUTT + 1); i++) { + if (g_retryLaneList[bandWidthType][i] == LANE_LINK_TYPE_BUTT) { + break; + } + if (IsValidLane(networkId, g_retryLaneList[bandWidthType][i], request->transType) && + !isLaneExist(linkList, g_retryLaneList[bandWidthType][i])) { + linkList[(*linksNum)++] = g_retryLaneList[bandWidthType][i]; + LNN_LOGI(LNN_LANE, "decide retry linkType=%d", g_retryLaneList[bandWidthType][i]); + } + } +} + static void DecideRetryLinks(const char *networkId, const LaneSelectParam *request, LaneLinkType *linkList, uint32_t *linksNum) { uint32_t minBandWidth = request->qosRequire.minBW; uint32_t maxLaneLatency = request->qosRequire.maxLaneLatency; + int32_t bandWidthType = GetBwType(minBandWidth); if (maxLaneLatency == 0) { - maxLaneLatency = (BR_LATENCY + BR_LATENCY + BR_LATENCY + BR_LATENCY); - } - int32_t bandWidthType; - if (minBandWidth >= HIGH_BW) { - bandWidthType = HIGH_BAND_WIDTH; - } else if (minBandWidth >= LOW_BW) { - bandWidthType = MIDDLE_BAND_WIDTH; - } else { - bandWidthType = LOW_BAND_WIDTH; + LNN_LOGI(LNN_LANE, "maxLaneLatency is zero, get all retry link"); + GetAllLinksWithBw(networkId, bandWidthType, request, linkList, linksNum); + return; } int32_t retryTime; if (*linksNum == 0) { @@ -521,14 +544,40 @@ static void DecideRetryLinks(const char *networkId, const LaneSelectParam *reque if (g_retryLaneList[bandWidthType][i] == LANE_LINK_TYPE_BUTT) { break; } - if (IsValidLane(networkId, g_retryLaneList[bandWidthType][i], request->transType) && - !isLaneExist(linkList, g_retryLaneList[bandWidthType][i]) && - retryTime - g_laneLatency[g_retryLaneList[bandWidthType][i]] >= 0) { + if (retryTime - g_laneLatency[g_retryLaneList[bandWidthType][i]] >= 0 && + IsValidLane(networkId, g_retryLaneList[bandWidthType][i], request->transType) && + !isLaneExist(linkList, g_retryLaneList[bandWidthType][i])) { retryTime -= g_laneLatency[g_retryLaneList[bandWidthType][i]]; linkList[(*linksNum)++] = g_retryLaneList[bandWidthType][i]; LNN_LOGI(LNN_LANE, "decide retry linkType=%d", g_retryLaneList[bandWidthType][i]); } } + if (bandWidthType == LOW_BAND_WIDTH && + IsValidLane(networkId, LANE_BR, request->transType) && !isLaneExist(linkList, LANE_BR)) { + linkList[(*linksNum)++] = LANE_BR; + LNN_LOGI(LNN_LANE, "decide retry linkType=%d", LANE_BR); + } +} + +static bool IsSupportBrReuse(const char *peerNetWorkId) +{ + ConnectOption connOpt; + (void)memset_s(&connOpt, sizeof(ConnectOption), 0, sizeof(ConnectOption)); + connOpt.type = CONNECT_BR; + if (LnnGetRemoteStrInfo(peerNetWorkId, STRING_KEY_BT_MAC, connOpt.brOption.brMac, BT_MAC_LEN) != SOFTBUS_OK || + connOpt.brOption.brMac[0] == '\0') { + return false; + } + return CheckActiveConnection(&connOpt); +} + +static void UpdataLaneLatency(const char *peerNetWorkId) +{ + if (IsSupportBrReuse(peerNetWorkId)) { + g_laneLatency[LANE_BR] = BR_REUSE_LATENCY; + } else { + g_laneLatency[LANE_BR] = BR_LATENCY; + } } int32_t DecideAvailableLane(const char *networkId, const LaneSelectParam *request, LanePreferredLinkList *recommendList) @@ -539,6 +588,7 @@ int32_t DecideAvailableLane(const char *networkId, const LaneSelectParam *reques LaneLinkType linkList[LANE_LINK_TYPE_BUTT]; (void)memset_s(linkList, sizeof(linkList), -1, sizeof(linkList)); uint32_t linksNum = 0; + UpdataLaneLatency(networkId); DecideOptimalLinks(networkId, request, linkList, &linksNum); DecideRetryLinks(networkId, request, linkList, &linksNum); for (uint32_t i = 0; i < linksNum; i++) { diff --git a/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_trans_lane.c b/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_trans_lane.c index 00cc8fbe9..12475c3d9 100644 --- a/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_trans_lane.c +++ b/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_trans_lane.c @@ -23,7 +23,6 @@ #include "lnn_lane_common.h" #include "lnn_lane_def.h" #include "lnn_lane_interface.h" -#include "lnn_lane_link.h" #include "lnn_lane_model.h" #include "lnn_lane_select.h" #include "lnn_log.h" @@ -39,6 +38,16 @@ #define DETECT_LANE_TIMELINESS 2000 +typedef enum { + MSG_TYPE_LANE_TRIGGER_LINK = 0, + MSG_TYPE_LANE_LINK_SUCCESS, + MSG_TYPE_LANE_LINK_FAIL, + MSG_TYPE_LANE_LINK_EXCEPTION, + MSG_TYPE_DELAY_DESTROY_LINK, + MSG_TYPE_LANE_DETECT_TIMEOUT, + MSG_TYPE_RELIABILITY_TIME, +} LaneMsgType; + typedef struct { ListNode node; uint32_t laneId; @@ -275,6 +284,7 @@ static int32_t StartTriggerLink(uint32_t laneId, TransOption *transRequest, cons if (newItem == NULL) { return SOFTBUS_ERR; } + newItem->info.isWithQos = true; if (Lock() != SOFTBUS_OK) { SoftBusFree(newItem); return SOFTBUS_ERR; @@ -363,6 +373,7 @@ static int32_t Alloc(uint32_t laneId, const LaneRequestOption *request, const IL SoftBusFree(recommendLinkList); return SOFTBUS_ERR; } + newItem->info.isWithQos = false; if (Lock() != SOFTBUS_OK) { SoftBusFree(newItem); SoftBusFree(recommendLinkList); @@ -404,7 +415,9 @@ static int32_t FreeLaneLink(uint32_t laneId, LaneResource *laneResourceInfo, boo Unlock(); DelLinkInfoItem(laneId); if (isDelayDestroy) { + LNN_LOGI(LNN_LANE, "laneId=%u, delayDestroy finished", laneId); DelLaneResourceItem(laneResourceInfo); + SoftBusFree(laneResourceInfo); } DestroyLink(item->info.networkId, laneId, item->type, item->info.pid); UnbindLaneId(laneId, item); @@ -413,6 +426,11 @@ static int32_t FreeLaneLink(uint32_t laneId, LaneResource *laneResourceInfo, boo return SOFTBUS_OK; } } + DelLinkInfoItem(laneId); + if (isDelayDestroy) { + DelLaneResourceItem(laneResourceInfo); + SoftBusFree(laneResourceInfo); + } Unlock(); FreeLaneId(laneId); return SOFTBUS_OK; @@ -686,6 +704,7 @@ static void HandleDelayDestroyLink(SoftBusMessage *msg) uint32_t laneId = (uint32_t)msg->arg1; bool isDelayDestroy = (bool)msg->arg2; LaneResource *resourceItem = (LaneResource*)msg->obj; + LNN_LOGI(LNN_LANE, "handle delay destory message, laneId=%u", laneId); FreeLaneLink(laneId, resourceItem, isDelayDestroy); } @@ -816,9 +835,9 @@ LaneInterface *TransLaneGetInstance(void) return &g_transLaneObject; } -int32_t GetQosInfoByLaneId(uint32_t laneId, QosInfo *qosOpt) +int32_t GetTransOptionByLaneId(uint32_t laneId, TransOption *reqInfo) { - if (qosOpt == NULL || laneId == INVALID_LANE_ID) { + if (reqInfo == NULL || laneId == INVALID_LANE_ID) { return SOFTBUS_INVALID_PARAM; } if (Lock() != SOFTBUS_OK) { @@ -827,7 +846,11 @@ int32_t GetQosInfoByLaneId(uint32_t laneId, QosInfo *qosOpt) TransReqInfo *item = NULL; LIST_FOR_EACH_ENTRY(item, &g_requestList->list, TransReqInfo, node) { if (item->laneId == laneId) { - *qosOpt = item->info.qosRequire; + if (memcpy_s(reqInfo, sizeof(TransOption), &item->info, sizeof(TransOption)) != EOK) { + LNN_LOGE(LNN_LANE, "memcpy TransReqInfo fail"); + Unlock(); + return SOFTBUS_ERR; + } Unlock(); return SOFTBUS_OK; } @@ -865,4 +888,10 @@ void RemoveDetectTimeoutMessage(uint32_t detectId) int32_t PostReliabilityTimeMessage(void) { return LnnLanePostMsgToHandler(MSG_TYPE_RELIABILITY_TIME, 0, 0, NULL, DETECT_LANE_TIMELINESS); +} + +int32_t PostDelayDestroyMessage(uint32_t laneId, LaneResource *resourseItem, uint64_t delayMillis) +{ + LNN_LOGI(LNN_LANE, "post dely destory message, laneId=%u", laneId); + return LnnLanePostMsgToHandler(MSG_TYPE_DELAY_DESTROY_LINK, laneId, true, resourseItem, delayMillis); } \ No newline at end of file diff --git a/core/bus_center/lnn/lane_hub/time_sync/include/lnn_time_sync_manager.h b/core/bus_center/lnn/lane_hub/time_sync/include/lnn_time_sync_manager.h index 6f3cb202e..80030a533 100644 --- a/core/bus_center/lnn/lane_hub/time_sync/include/lnn_time_sync_manager.h +++ b/core/bus_center/lnn/lane_hub/time_sync/include/lnn_time_sync_manager.h @@ -25,7 +25,7 @@ extern "C" { int32_t LnnStartTimeSync(const char *pkgName, int32_t callingPid, const char *targetNetworkId, TimeSyncAccuracy accuracy, TimeSyncPeriod period); -int32_t LnnStopTimeSync(const char *pkgName, const char *targetNetworkId); +int32_t LnnStopTimeSync(const char *pkgName, const char *targetNetworkId, int32_t callingPid); int32_t LnnInitTimeSync(void); void LnnDeinitTimeSync(void); diff --git a/core/bus_center/lnn/lane_hub/time_sync/src/lnn_time_sync_manager.c b/core/bus_center/lnn/lane_hub/time_sync/src/lnn_time_sync_manager.c index f05133e96..5c02bf02a 100644 --- a/core/bus_center/lnn/lane_hub/time_sync/src/lnn_time_sync_manager.c +++ b/core/bus_center/lnn/lane_hub/time_sync/src/lnn_time_sync_manager.c @@ -69,6 +69,7 @@ typedef struct { } StartTimeSyncReqMsgPara; typedef struct { + int32_t pid; char pkgName[PKG_NAME_SIZE_MAX]; char targetNetworkId[NETWORK_ID_BUF_LEN]; } StopTimeSyncReqMsgPara; @@ -167,13 +168,13 @@ static int32_t TryUpdateStartTimeSyncReq(TimeSyncReqInfo *info, const StartTimeS return SOFTBUS_OK; } -static void RemoveStartTimeSyncReq(const TimeSyncReqInfo *info, const char *pkgName) +static void RemoveStartTimeSyncReq(const TimeSyncReqInfo *info, const char *pkgName, int32_t pid) { StartTimeSyncReq *item = NULL; StartTimeSyncReq *next = NULL; LIST_FOR_EACH_ENTRY_SAFE(item, next, &info->startReqList, StartTimeSyncReq, node) { - if (strcmp(pkgName, item->pkgName) != 0) { + if (strcmp(pkgName, item->pkgName) != 0 || item->pid != pid) { continue; } ListDelete(&item->node); @@ -227,7 +228,7 @@ static int32_t ProcessStartTimeSyncRequest(const StartTimeSyncReqMsgPara *para) if (LnnStartTimeSyncImpl(existInfo->targetNetworkId, existInfo->curAccuracy, existInfo->curPeriod, &g_timeSyncImplCb) != SOFTBUS_OK) { LNN_LOGE(LNN_CLOCK, "start time sync fail"); - RemoveStartTimeSyncReq(existInfo, para->pkgName); + RemoveStartTimeSyncReq(existInfo, para->pkgName, para->pid); break; } } @@ -293,7 +294,7 @@ static int32_t ProcessStopTimeSyncRequest(const StopTimeSyncReqMsgPara *para) SoftBusFree((void *)para); return SOFTBUS_ERR; } - RemoveStartTimeSyncReq(info, para->pkgName); + RemoveStartTimeSyncReq(info, para->pkgName, para->pid); TryUpdateTimeSyncReq(info); SoftBusFree((void *)para); return SOFTBUS_OK; @@ -335,7 +336,7 @@ static void RemoveAllStartTimeSyncReq(TimeSyncReqInfo *info) StartTimeSyncReq *startTimeSyncNextItem = NULL; LIST_FOR_EACH_ENTRY_SAFE(startTimeSyncItem, startTimeSyncNextItem, &info->startReqList, StartTimeSyncReq, node) { - RemoveStartTimeSyncReq(info, startTimeSyncItem->pkgName); + RemoveStartTimeSyncReq(info, startTimeSyncItem->pkgName, startTimeSyncItem->pid); } (void)LnnStopTimeSyncImpl(info->targetNetworkId); ListDelete(&info->node); @@ -530,7 +531,7 @@ int32_t LnnStartTimeSync(const char *pkgName, int32_t callingPid, const char *ta return SOFTBUS_OK; } -int32_t LnnStopTimeSync(const char *pkgName, const char *targetNetworkId) +int32_t LnnStopTimeSync(const char *pkgName, const char *targetNetworkId, int32_t callingPid) { StopTimeSyncReqMsgPara *para = NULL; @@ -547,6 +548,7 @@ int32_t LnnStopTimeSync(const char *pkgName, const char *targetNetworkId) LNN_LOGE(LNN_CLOCK, "malloc stop time sync request msg para fail"); return SOFTBUS_MALLOC_ERR; } + para->pid = callingPid; if (strncpy_s(para->pkgName, PKG_NAME_SIZE_MAX, pkgName, strlen(pkgName)) != EOK || strncpy_s(para->targetNetworkId, NETWORK_ID_BUF_LEN, targetNetworkId, strlen(targetNetworkId)) != EOK) { LNN_LOGE(LNN_CLOCK, "copy time sync request info fail"); diff --git a/core/bus_center/lnn/lane_hub/time_sync/src/lnn_time_sync_manager_virtual.c b/core/bus_center/lnn/lane_hub/time_sync/src/lnn_time_sync_manager_virtual.c index fa49c1c6b..bbe3b1cb6 100644 --- a/core/bus_center/lnn/lane_hub/time_sync/src/lnn_time_sync_manager_virtual.c +++ b/core/bus_center/lnn/lane_hub/time_sync/src/lnn_time_sync_manager_virtual.c @@ -29,10 +29,11 @@ int32_t LnnStartTimeSync(const char *pkgName, int32_t callingPid, const char *ta return SOFTBUS_NOT_IMPLEMENT; } -int32_t LnnStopTimeSync(const char *pkgName, const char *targetNetworkId) +int32_t LnnStopTimeSync(const char *pkgName, const char *targetNetworkId, int32_t callingPid) { (void)pkgName; (void)targetNetworkId; + (void)callingPid; return SOFTBUS_NOT_IMPLEMENT; } diff --git a/core/bus_center/lnn/net_builder/src/lnn_device_info_recovery_virtual.c b/core/bus_center/lnn/net_builder/src/lnn_device_info_recovery_virtual.c index baa0573db..9846bc23f 100644 --- a/core/bus_center/lnn/net_builder/src/lnn_device_info_recovery_virtual.c +++ b/core/bus_center/lnn/net_builder/src/lnn_device_info_recovery_virtual.c @@ -16,7 +16,6 @@ #include "lnn_device_info_recovery.h" #include "softbus_errcode.h" -#include "softbus_log_old.h" int32_t LnnLoadLocalDeviceInfo(void) { diff --git a/core/bus_center/lnn/net_builder/src/lnn_network_info.c b/core/bus_center/lnn/net_builder/src/lnn_network_info.c index 290697192..04756784a 100644 --- a/core/bus_center/lnn/net_builder/src/lnn_network_info.c +++ b/core/bus_center/lnn/net_builder/src/lnn_network_info.c @@ -47,7 +47,7 @@ static bool g_isApCoexistSupported = false; static bool g_isWifiEnable = false; static bool g_isApEnable = false; -static uint32_t ConvertMsgToCapability(uint32_t *capability, const uint8_t *msg, int32_t len) +static uint32_t ConvertMsgToCapability(uint32_t *capability, const uint8_t *msg, uint32_t len) { if (capability == NULL || msg == NULL || len < BITS) { return SOFTBUS_ERR; @@ -112,7 +112,7 @@ static void OnReceiveCapaSyncInfoMsg(LnnSyncInfoType type, const char *networkId return; } uint32_t capability = 0; - if (ConvertMsgToCapability(&capability, (const uint8_t *)msg, len) != SOFTBUS_OK) { + if (ConvertMsgToCapability(&capability, msg, len) != SOFTBUS_OK) { LNN_LOGE(LNN_BUILDER, "convert msg to capability fail"); return; } @@ -202,8 +202,8 @@ static void SendNetCapabilityToRemote(uint32_t netCapability, uint32_t type) static void WifiStateProcess(uint32_t netCapability, bool isSend) { - LNN_LOGI(LNN_BUILDER, "wifi state change netCapability=%d, isSend=%d", netCapability, isSend); - if (LnnSetLocalNumInfo(NUM_KEY_NET_CAP, netCapability) != SOFTBUS_OK) { + LNN_LOGI(LNN_BUILDER, "wifi state change netCapability=%u, isSend=%d", netCapability, isSend); + if (LnnSetLocalNumInfo(NUM_KEY_NET_CAP, (int32_t)netCapability) != SOFTBUS_OK) { return; } if (!isSend) { @@ -335,7 +335,7 @@ static void BtStateChangeEventHandler(const LnnEventBasicInfo *info) LNN_LOGI(LNN_BUILDER, "bt state change netCapability=%d, isSend=%d", netCapability, isSend); - if (LnnSetLocalNumInfo(NUM_KEY_NET_CAP, netCapability) != SOFTBUS_OK) { + if (LnnSetLocalNumInfo(NUM_KEY_NET_CAP, (int32_t)netCapability) != SOFTBUS_OK) { LNN_LOGE(LNN_BUILDER, "set cap to local ledger fail"); return; } diff --git a/core/bus_center/lnn/net_buscenter/src/lnn_bt_network_impl.c b/core/bus_center/lnn/net_buscenter/src/lnn_bt_network_impl.c index 4e8b5f597..130bd08b7 100644 --- a/core/bus_center/lnn/net_buscenter/src/lnn_bt_network_impl.c +++ b/core/bus_center/lnn/net_buscenter/src/lnn_bt_network_impl.c @@ -256,7 +256,7 @@ static VisitNextChoice NotifyBtStatusChanged(const LnnNetIfMgr *netifManager, vo static void BtNetworkInfoUpdate(SoftBusBtState btState) { if (btState == SOFTBUS_BLE_TURN_ON) { - LnnSetLocalNum64Info(NUM_KEY_BLE_START_TIME, SoftBusGetSysTimeMs()); + LnnSetLocalNum64Info(NUM_KEY_BLE_START_TIME, (int64_t)SoftBusGetSysTimeMs()); } if (btState == SOFTBUS_BLE_TURN_OFF) { LnnSetLocalNum64Info(NUM_KEY_BLE_START_TIME, 0); diff --git a/core/bus_center/lnn/net_buscenter/src/lnn_network_manager.c b/core/bus_center/lnn/net_buscenter/src/lnn_network_manager.c index c098ee649..a9253c4e5 100644 --- a/core/bus_center/lnn/net_buscenter/src/lnn_network_manager.c +++ b/core/bus_center/lnn/net_buscenter/src/lnn_network_manager.c @@ -531,6 +531,10 @@ static void NightModeChangeEventHandler(const LnnEventBasicInfo *info) if (g_nightOnCache == NULL) { LNN_LOGD(LNN_BUILDER, "init g_nightOnCache"); g_nightOnCache = (ListNode *)SoftBusMalloc(sizeof(ListNode)); + if (g_nightOnCache == NULL) { + LNN_LOGE(LNN_BUILDER, "malloc g_nightOnCache fail"); + return; + } ListInit(g_nightOnCache); } const LnnMonitorHbStateChangedEvent *event = (const LnnMonitorHbStateChangedEvent *)info; diff --git a/core/bus_center/lnn/net_ledger/common/src/lnn_net_ledger.c b/core/bus_center/lnn/net_ledger/common/src/lnn_net_ledger.c index 243b75eb3..782722983 100644 --- a/core/bus_center/lnn/net_ledger/common/src/lnn_net_ledger.c +++ b/core/bus_center/lnn/net_ledger/common/src/lnn_net_ledger.c @@ -20,6 +20,7 @@ #include "anonymizer.h" #include "auth_device_common_key.h" +#include "bus_center_event.h" #include "bus_center_manager.h" #include "lnn_cipherkey_manager.h" #include "lnn_decision_db.h" @@ -92,6 +93,7 @@ static void LnnRestoreLocalDeviceInfo() if (LnnUpdateLocalNetworkId(info.networkId) != SOFTBUS_OK) { LNN_LOGE(LNN_LEDGER, "set networkId fail"); } + LnnNotifyNetworkIdChangeEvent(info.networkId); } AuthLoadDeviceKey(); if (LnnLoadRemoteDeviceInfo() != SOFTBUS_OK) { @@ -237,7 +239,7 @@ int32_t LnnSetNodeDataChangeFlag(const char *networkId, uint16_t dataChangeFlag) isLocalNetworkId = true; } if (isLocalNetworkId) { - return LnnSetLocalNum16Info(NUM_KEY_DATA_CHANGE_FLAG, dataChangeFlag); + return LnnSetLocalNum16Info(NUM_KEY_DATA_CHANGE_FLAG, (int16_t)dataChangeFlag); } LNN_LOGE(LNN_LEDGER, "remote networkId"); return SOFTBUS_ERR; diff --git a/core/bus_center/lnn/net_ledger/decision_db/src/lnn_decision_db.c b/core/bus_center/lnn/net_ledger/decision_db/src/lnn_decision_db.c index 14036f945..06ed5af35 100644 --- a/core/bus_center/lnn/net_ledger/decision_db/src/lnn_decision_db.c +++ b/core/bus_center/lnn/net_ledger/decision_db/src/lnn_decision_db.c @@ -49,7 +49,7 @@ int32_t EncryptStorageData(uint8_t *dbKey, uint32_t len) LNN_LOGE(LNN_LEDGER, "calloc encrypt dbKey fail"); return SOFTBUS_MEM_ERR; } - LNN_LOGI(LNN_LEDGER, "Encrypt, data len=%d", len); + LNN_LOGI(LNN_LEDGER, "Encrypt, data len=%u", len); plainData.size = len; plainData.data = dbKey; if (LnnEncryptDataByHuks(&g_keyAlias, &plainData, &encryptData) != SOFTBUS_OK) { @@ -79,7 +79,7 @@ int32_t DecryptStorageData(uint8_t *dbKey, uint32_t len) LNN_LOGE(LNN_LEDGER, "calloc decrypt dbKey fail"); return SOFTBUS_MEM_ERR; } - LNN_LOGI(LNN_LEDGER, "Decrypt, data len=%d", len); + LNN_LOGI(LNN_LEDGER, "Decrypt, data len=%u", len); encryptData.size = len; encryptData.data = dbKey; int32_t ret; @@ -363,7 +363,7 @@ static int32_t GetTrustedDevInfoRecord(DbContext *ctx, const char *accountHexHas *num = 0; return SOFTBUS_ERR; } - *num = GetRecordNumByKey(ctx, TABLE_TRUSTED_DEV_INFO, (uint8_t *)accountHexHash); + *((int32_t *)num) = GetRecordNumByKey(ctx, TABLE_TRUSTED_DEV_INFO, (uint8_t *)accountHexHash); if (*num == 0) { LNN_LOGW(LNN_LEDGER, "get none trusted dev info"); *udidArray = NULL; @@ -375,7 +375,7 @@ static int32_t GetTrustedDevInfoRecord(DbContext *ctx, const char *accountHexHas return SOFTBUS_MALLOC_ERR; } if (QueryRecordByKey(ctx, TABLE_TRUSTED_DEV_INFO, (uint8_t *)accountHexHash, - (uint8_t **)udidArray, *num) != SOFTBUS_OK) { + (uint8_t **)udidArray, *((int32_t *)num)) != SOFTBUS_OK) { LNN_LOGE(LNN_LEDGER, "query udidArray failed"); SoftBusFree(*udidArray); *udidArray = NULL; diff --git a/core/bus_center/lnn/net_ledger/distributed_ledger/src/lnn_distributed_net_ledger.c b/core/bus_center/lnn/net_ledger/distributed_ledger/src/lnn_distributed_net_ledger.c index 1f0879296..532b4a20c 100644 --- a/core/bus_center/lnn/net_ledger/distributed_ledger/src/lnn_distributed_net_ledger.c +++ b/core/bus_center/lnn/net_ledger/distributed_ledger/src/lnn_distributed_net_ledger.c @@ -847,7 +847,7 @@ static int32_t DlGetNetCap(const char *networkId, void *buf, uint32_t len) return SOFTBUS_INVALID_PARAM; } RETURN_IF_GET_NODE_VALID(networkId, buf, info); - *((int32_t *)buf) = info->netCapacity; + *((int32_t *)buf) = (int32_t)info->netCapacity; return SOFTBUS_OK; } @@ -869,7 +869,7 @@ static int32_t DlGetNetType(const char *networkId, void *buf, uint32_t len) return SOFTBUS_INVALID_PARAM; } RETURN_IF_GET_NODE_VALID(networkId, buf, info); - *((int32_t *)buf) = info->discoveryType; + *((int32_t *)buf) = (int32_t)info->discoveryType; return SOFTBUS_OK; } @@ -1071,7 +1071,7 @@ static int32_t DlGetNodeDataChangeFlag(const char *networkId, void *buf, uint32_ LNN_LOGE(LNN_LEDGER, "node is offline"); return SOFTBUS_NETWORK_NODE_OFFLINE; } - *((int16_t *)buf) = LnnGetDataChangeFlag(info); + *((int16_t *)buf) = (int16_t)LnnGetDataChangeFlag(info); return SOFTBUS_OK; } diff --git a/core/bus_center/lnn/net_ledger/local_ledger/src/lnn_local_net_ledger.c b/core/bus_center/lnn/net_ledger/local_ledger/src/lnn_local_net_ledger.c index 45c40b629..74b931cd1 100644 --- a/core/bus_center/lnn/net_ledger/local_ledger/src/lnn_local_net_ledger.c +++ b/core/bus_center/lnn/net_ledger/local_ledger/src/lnn_local_net_ledger.c @@ -527,7 +527,7 @@ static int32_t LlGetNetCap(void *buf, uint32_t len) if (buf == NULL || len != LNN_COMMON_LEN) { return SOFTBUS_INVALID_PARAM; } - *((int32_t *)buf) = info->netCapacity; + *((int32_t *)buf) = (int32_t)info->netCapacity; return SOFTBUS_OK; } @@ -547,7 +547,7 @@ static int32_t LlGetNetType(void *buf, uint32_t len) if (buf == NULL || len != LNN_COMMON_LEN) { return SOFTBUS_INVALID_PARAM; } - *((int32_t *)buf) = info->discoveryType; + *((int32_t *)buf) = (int32_t)info->discoveryType; return SOFTBUS_OK; } @@ -674,7 +674,7 @@ static int32_t L1GetNodeDataChangeFlag(void *buf, uint32_t len) if (buf == NULL || len != DATA_CHANGE_FLAG_BUF_LEN) { return SOFTBUS_INVALID_PARAM; } - *((int16_t *)buf) = LnnGetDataChangeFlag(&g_localNetLedger.localInfo); + *((int16_t *)buf) = (int16_t)LnnGetDataChangeFlag(&g_localNetLedger.localInfo); return SOFTBUS_OK; } diff --git a/core/bus_center/service/include/bus_center_event.h b/core/bus_center/service/include/bus_center_event.h index 618c4d873..378e8570d 100644 --- a/core/bus_center/service/include/bus_center_event.h +++ b/core/bus_center/service/include/bus_center_event.h @@ -50,6 +50,7 @@ typedef enum { LNN_EVENT_NETWORK_STATE_CHANGED, LNN_EVENT_SINGLE_NETWORK_OFFLINE, LNN_EVENT_NODE_HB_REPEAT_CYCLE, + LNN_EVENT_NETWORKID_CHANGED, LNN_EVENT_TYPE_MAX, } LnnEventType; @@ -204,6 +205,11 @@ typedef struct { const char *udid; } LnnSingleNetworkOffLineEvent; +typedef struct { + LnnEventBasicInfo basic; + char networkId[NETWORK_ID_BUF_LEN]; +} LnnNetworkIdChangedEvent; + typedef void (*LnnEventHandler)(const LnnEventBasicInfo *info); int32_t LnnInitBusCenterEvent(void); @@ -244,6 +250,8 @@ void LnnNotifyNodeAddressChanged(const char *addr, const char *networkId, bool i void LnnNotifyNetworkStateChanged(SoftBusNetworkState state); void LnnNotifySingleOffLineEvent(const ConnectionAddr *addr, NodeBasicInfo *basicInfo); + +void LnnNotifyNetworkIdChangeEvent(const char *networkId); void LnnNotifyHBRepeat(void); #ifdef __cplusplus diff --git a/core/bus_center/service/src/bus_center_event.c b/core/bus_center/service/src/bus_center_event.c index 58d9ce1f8..0ffbfe50a 100644 --- a/core/bus_center/service/src/bus_center_event.c +++ b/core/bus_center/service/src/bus_center_event.c @@ -119,6 +119,7 @@ static void HandleNetworkUpdateMessage(SoftBusMessage *msg) return; } LnnSetLocalStrInfo(STRING_KEY_NETWORKID, networkId); + LnnNotifyNetworkIdChangeEvent(networkId); LNN_LOGD(LNN_EVENT, "offline exceted 5min, process networkId update event"); } @@ -628,6 +629,21 @@ void LnnNotifySingleOffLineEvent(const ConnectionAddr *addr, NodeBasicInfo *basi NotifyEvent((const LnnEventBasicInfo *)&event); } +void LnnNotifyNetworkIdChangeEvent(const char *networkId) +{ + if (networkId == NULL) { + LNN_LOGW(LNN_EVENT, "networkId is null"); + return; + } + LnnNetworkIdChangedEvent eventInfo; + (void)memset_s(&eventInfo, sizeof(eventInfo), 0, sizeof(eventInfo)); + eventInfo.basic.event = LNN_EVENT_NETWORKID_CHANGED; + if (strcpy_s(eventInfo.networkId, NETWORK_ID_BUF_LEN, networkId) != EOK) { + return; + } + NotifyEvent((LnnEventBasicInfo *)&eventInfo); +} + int32_t LnnInitBusCenterEvent(void) { int32_t i; diff --git a/core/common/BUILD.gn b/core/common/BUILD.gn index 6382fa17c..c82650a47 100644 --- a/core/common/BUILD.gn +++ b/core/common/BUILD.gn @@ -24,7 +24,6 @@ common_utils_src = [ "bitmap/softbus_bitmap.c", "network/softbus_network_utils.c", "json_utils/softbus_json_utils.c", - "log/softbus_log_old.c", "message_handler/message_handler.c", "queue/softbus_queue.c", "security/sequence_verification/softbus_sequence_verification.c", diff --git a/core/common/dfx/anonymize/src/anonymizer.c b/core/common/dfx/anonymize/src/anonymizer.c index ff87cc12a..5c28d55c3 100644 --- a/core/common/dfx/anonymize/src/anonymizer.c +++ b/core/common/dfx/anonymize/src/anonymizer.c @@ -62,7 +62,6 @@ static void AnonymizeUdid(const char *udid, char **anonymizedUdid) } if (memset_s(*anonymizedUdid, ANONYMIZED_UDID_LEN + 1, 0, ANONYMIZED_UDID_LEN + 1) != EOK) { COMM_LOGE(COMM_DFX, "memset_s *anonymizedStr fail"); - free(*anonymizedUdid); return; } // Reserve 5 chars at head, concat with two wildcards, and 5 chars at tail @@ -74,7 +73,6 @@ static void AnonymizeUdid(const char *udid, char **anonymizedUdid) (ANONYMIZED_UDID_LEN - RESERVED_LEN - strlen(WILDCARDS) + 1), (udid + strlen(udid) - RESERVED_LEN), RESERVED_LEN) != EOK) { COMM_LOGE(COMM_DFX, "strncpy_s *anonymizedUdid fail"); - free(*anonymizedUdid); } } @@ -88,12 +86,10 @@ static void AnonymizeMac(const char *mac, char **anonymizedMac) } if (memset_s(*anonymizedMac, anonymizedMacLen + 1, 0, anonymizedMacLen + 1) != EOK) { COMM_LOGE(COMM_DFX, "memset_s *anonymizedStr fail"); - free(*anonymizedMac); return; } if (strcpy_s(*anonymizedMac, anonymizedMacLen + 1, mac) != EOK) { COMM_LOGE(COMM_DFX, "strcpy_s *anonymizedMac fail"); - free(*anonymizedMac); return; } // Anonymize the forth and fifth parts of the mac address @@ -113,12 +109,10 @@ static void AnonymizeIp(const char *ip, char **anonymizedIp) } if (memset_s(*anonymizedIp, anonymizedIpLen + 1, 0, anonymizedIpLen + 1) != EOK) { COMM_LOGE(COMM_DFX, "memset_s *anonymizedIp fail"); - free(*anonymizedIp); return; } if (strcpy_s(*anonymizedIp, anonymizedIpLen + 1, ip) != EOK) { COMM_LOGE(COMM_DFX, "strcpy_s *anonymizedIp fail"); - free(*anonymizedIp); return; } // Anonymize the last part of ip address @@ -160,7 +154,6 @@ static void AnonymizeString(char **anonymizedStr, size_t length, const char *fmt va_end(args); if (ret < 0) { COMM_LOGE(COMM_DFX, "vsprintf_s *anonymizedStr fail"); - free(*anonymizedStr); } } diff --git a/core/common/dfx/event/src/convert/conn_event_converter.h b/core/common/dfx/event/src/convert/conn_event_converter.h index f6a042750..08570b33e 100644 --- a/core/common/dfx/event/src/convert/conn_event_converter.h +++ b/core/common/dfx/event/src/convert/conn_event_converter.h @@ -47,10 +47,10 @@ CONN_ASSIGNER(Int32, CostTime, costTime) CONN_ASSIGNER(Int32, Rssi, rssi) CONN_ASSIGNER(Int32, Load, load) CONN_ASSIGNER(Int32, Frequency, frequency) -CONN_ASSIGNER(String, PeerIp, peerIp) -CONN_ASSIGNER(String, PeerBrMac, peerBrMac) -CONN_ASSIGNER(String, PeerBleMac, peerBleMac) -CONN_ASSIGNER(String, PeerWifiMac, peerWifiMac) +CONN_ASSIGNER(AnonymizeString, PeerIp, peerIp) +CONN_ASSIGNER(AnonymizeString, PeerBrMac, peerBrMac) +CONN_ASSIGNER(AnonymizeString, PeerBleMac, peerBleMac) +CONN_ASSIGNER(AnonymizeString, PeerWifiMac, peerWifiMac) CONN_ASSIGNER(String, PeerPort, peerPort) CONN_ASSIGNER(String, CallerPkg, callerPkg) CONN_ASSIGNER(String, CalleePkg, calleePkg) diff --git a/core/common/dfx/event/src/convert/disc_event_converter.h b/core/common/dfx/event/src/convert/disc_event_converter.h index b6ee455dd..b73966bdb 100644 --- a/core/common/dfx/event/src/convert/disc_event_converter.h +++ b/core/common/dfx/event/src/convert/disc_event_converter.h @@ -43,16 +43,16 @@ DISC_ASSIGNER(String, ScanCycle, scanCycle) DISC_ASSIGNER(Int32, DiscType, discType) DISC_ASSIGNER(Int32, DiscMode, discMode) DISC_ASSIGNER(Int32, CostTime, costTime) -DISC_ASSIGNER(String, LocalNetworkId, localNetworkId) -DISC_ASSIGNER(String, LocalUdid, localUdid) +DISC_ASSIGNER(AnonymizeString, LocalNetworkId, localNetworkId) +DISC_ASSIGNER(AnonymizeString, LocalUdid, localUdid) DISC_ASSIGNER(String, LocalDeviceType, localDeviceType) -DISC_ASSIGNER(String, PeerIp, peerIp) -DISC_ASSIGNER(String, PeerBrMac, peerBrMac) -DISC_ASSIGNER(String, PeerBleMac, peerBleMac) -DISC_ASSIGNER(String, PeerWifiMac, peerWifiMac) +DISC_ASSIGNER(AnonymizeString, PeerIp, peerIp) +DISC_ASSIGNER(AnonymizeString, PeerBrMac, peerBrMac) +DISC_ASSIGNER(AnonymizeString, PeerBleMac, peerBleMac) +DISC_ASSIGNER(AnonymizeString, PeerWifiMac, peerWifiMac) DISC_ASSIGNER(String, PeerPort, peerPort) -DISC_ASSIGNER(String, PeerUdid, peerUdid) -DISC_ASSIGNER(String, PeerNetworkId, peerNetworkId) +DISC_ASSIGNER(AnonymizeString, PeerUdid, peerUdid) +DISC_ASSIGNER(AnonymizeString, PeerNetworkId, peerNetworkId) DISC_ASSIGNER(String, PeerDeviceType, peerDeviceType) DISC_ASSIGNER(String, CallerPkg, callerPkg) diff --git a/core/common/dfx/event/src/convert/lnn_event_converter.h b/core/common/dfx/event/src/convert/lnn_event_converter.h index 9e701554f..0e88f3aba 100644 --- a/core/common/dfx/event/src/convert/lnn_event_converter.h +++ b/core/common/dfx/event/src/convert/lnn_event_converter.h @@ -43,13 +43,13 @@ LNN_ASSIGNER(Int32, LnnType, lnnType) LNN_ASSIGNER(Int32, OnlineNum, onlineNum) LNN_ASSIGNER(Int32, PeerDeviceAbility, peerDeviceAbility) LNN_ASSIGNER(String, PeerDeviceInfo, peerDeviceInfo) -LNN_ASSIGNER(String, PeerIp, peerIp) -LNN_ASSIGNER(String, PeerBrMac, peerBrMac) -LNN_ASSIGNER(String, PeerBleMac, peerBleMac) -LNN_ASSIGNER(String, PeerWifiMac, peerWifiMac) +LNN_ASSIGNER(AnonymizeString, PeerIp, peerIp) +LNN_ASSIGNER(AnonymizeString, PeerBrMac, peerBrMac) +LNN_ASSIGNER(AnonymizeString, PeerBleMac, peerBleMac) +LNN_ASSIGNER(AnonymizeString, PeerWifiMac, peerWifiMac) LNN_ASSIGNER(String, PeerPort, peerPort) -LNN_ASSIGNER(String, PeerUdid, peerUdid) -LNN_ASSIGNER(String, PeerNetworkId, peerNetworkId) +LNN_ASSIGNER(AnonymizeString, PeerUdid, peerUdid) +LNN_ASSIGNER(AnonymizeString, PeerNetworkId, peerNetworkId) LNN_ASSIGNER(String, PeerDeviceType, peerDeviceType) LNN_ASSIGNER(String, CallerPkg, callerPkg) LNN_ASSIGNER(String, CalleePkg, calleePkg) diff --git a/core/common/dfx/event/src/convert/softbus_event_converter.h b/core/common/dfx/event/src/convert/softbus_event_converter.h index ba5b413bf..e22c1c4ee 100644 --- a/core/common/dfx/event/src/convert/softbus_event_converter.h +++ b/core/common/dfx/event/src/convert/softbus_event_converter.h @@ -22,13 +22,15 @@ #include "comm_log.h" #include "form/softbus_event_form.h" #include "hisysevent_c.h" +#include "anonymizer.h" #ifdef __cplusplus extern "C" { #endif -#define INVALID_INT_VALUE 0 -#define PARAM_STRING_VALUE_MAX_LEN 256 +#define INVALID_INT_VALUE 0 +#define PARAM_STRING_VALUE_MAX_LEN 256 +#define PARAM_LONG_STRING_VALUE_MAX_LEN (256 * 1024) typedef struct { char name[MAX_LENGTH_OF_PARAM_NAME]; @@ -73,7 +75,7 @@ static inline bool AssignerInt32(int32_t value, HiSysEventParam **param) /* Used by ASSIGNER macros */ static inline bool AssignerString(const char *value, HiSysEventParam **param) { - if (value == NULL || strlen(value) == 0) { + if (value == NULL || value[0] == '\0' || strnlen(value, PARAM_STRING_VALUE_MAX_LEN) == PARAM_STRING_VALUE_MAX_LEN) { (*param)->v.s = NULL; return false; } @@ -81,6 +83,35 @@ static inline bool AssignerString(const char *value, HiSysEventParam **param) CopyString((*param)->v.s, value, PARAM_STRING_VALUE_MAX_LEN); } +/* Used by ASSIGNER macros */ +static inline bool AssignerLongString(const char *value, HiSysEventParam **param) +{ + if (value == NULL || value[0] == '\0' || strnlen(value, + PARAM_LONG_STRING_VALUE_MAX_LEN) == PARAM_LONG_STRING_VALUE_MAX_LEN) { + (*param)->v.s = NULL; + return false; + } + return InitString(&(*param)->v.s, PARAM_LONG_STRING_VALUE_MAX_LEN) && + CopyString((*param)->v.s, value, PARAM_LONG_STRING_VALUE_MAX_LEN); +} + +/* Used by ASSIGNER macros */ +static inline bool AssignerAnonymizeString(const char *value, HiSysEventParam **param) +{ + if (value == NULL || value[0] == '\0' || strnlen(value, PARAM_STRING_VALUE_MAX_LEN) == PARAM_STRING_VALUE_MAX_LEN) { + (*param)->v.s = NULL; + return false; + } + if (!InitString(&(*param)->v.s, PARAM_STRING_VALUE_MAX_LEN)) { + return false; + } + char *anonyStr = NULL; + Anonymize(value, &anonyStr); + bool status = CopyString((*param)->v.s, anonyStr, PARAM_STRING_VALUE_MAX_LEN); + AnonymizeFree(anonyStr); + return status; +} + /* Used by ASSIGNER macros */ static inline bool AssignerErrcode(int32_t value, HiSysEventParam **param) { diff --git a/core/common/dfx/event/src/convert/stats_event_converter.h b/core/common/dfx/event/src/convert/stats_event_converter.h index 8dc117b11..e1210c0f7 100644 --- a/core/common/dfx/event/src/convert/stats_event_converter.h +++ b/core/common/dfx/event/src/convert/stats_event_converter.h @@ -45,7 +45,7 @@ STATS_ASSIGNER(Int32, DeviceOfflineTimes, deviceOfflineTimes) STATS_ASSIGNER(Int32, LaneScoreOverTimes, laneScoreOverTimes) STATS_ASSIGNER(Int32, ActivationRate, activationRate) STATS_ASSIGNER(Int32, DetectionTimes, detectionTimes) -STATS_ASSIGNER(String, SuccessRateDetail, successRateDetail) +STATS_ASSIGNER(LongString, SuccessRateDetail, successRateDetail) #define STATS_ASSIGNER_SIZE 12 // Size of g_statsAssigners static HiSysEventParamAssigner g_statsAssigners[] = { diff --git a/core/common/dfx/event/src/convert/trans_event_converter.h b/core/common/dfx/event/src/convert/trans_event_converter.h index 83d9e98ab..139af16da 100644 --- a/core/common/dfx/event/src/convert/trans_event_converter.h +++ b/core/common/dfx/event/src/convert/trans_event_converter.h @@ -52,7 +52,7 @@ TRANS_ASSIGNER(Int32, CostTime, costTime) TRANS_ASSIGNER(Int32, ChannelScore, channelScore) TRANS_ASSIGNER(Int32, PeerChannelId, peerChannelId) TRANS_ASSIGNER(Int32, BtFlow, btFlow) -TRANS_ASSIGNER(String, PeerNetworkId, peerNetworkId) +TRANS_ASSIGNER(AnonymizeString, PeerNetworkId, peerNetworkId) TRANS_ASSIGNER(String, CallerPkg, callerPkg) TRANS_ASSIGNER(String, CalleePkg, calleePkg) diff --git a/core/common/dfx/hidumper_adapter/BUILD.gn b/core/common/dfx/hidumper_adapter/BUILD.gn index d1cc417bc..1d3454e4c 100644 --- a/core/common/dfx/hidumper_adapter/BUILD.gn +++ b/core/common/dfx/hidumper_adapter/BUILD.gn @@ -89,7 +89,6 @@ if (defined(ohos_lite)) { include_dirs += trans_common_inc sources = [ "$dsoftbus_root_path/core/bus_center/utils/src/lnn_map.c", - "$dsoftbus_root_path/core/common/log/softbus_log_old.c", "$dsoftbus_root_path/core/common/message_handler/message_handler.c", "$dsoftbus_root_path/core/common/softbus_property/softbus_feature_config.c", "$dsoftbus_root_path/core/common/utils/softbus_utils.c", diff --git a/core/common/dfx/hidumper_adapter/softbus_hidumper.c b/core/common/dfx/hidumper_adapter/softbus_hidumper.c index c7a89a89c..07888f41b 100644 --- a/core/common/dfx/hidumper_adapter/softbus_hidumper.c +++ b/core/common/dfx/hidumper_adapter/softbus_hidumper.c @@ -18,10 +18,10 @@ #include #include +#include "comm_log.h" #include "common_list.h" #include "softbus_errcode.h" #include "softbus_adapter_mem.h" -#include "softbus_log_old.h" #include "softbus_hidumper_buscenter.h" #include "softbus_hidumper_conn.h" #include "softbus_hidumper_disc.h" @@ -33,7 +33,7 @@ static LIST_HEAD(g_hidumperhander_list); void SoftBusDumpShowHelp(int fd) { if (fd < 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "fd is invalid."); + COMM_LOGE(COMM_DFX, "fd is invalid."); return; } @@ -62,7 +62,7 @@ void SoftBusDumpShowHelp(int fd) void SoftBusDumpErrInfo(int fd, const char *argv) { if (fd < 0 || argv == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "param is invalid."); + COMM_LOGE(COMM_DFX, "param is invalid."); return; } SOFTBUS_DPRINTF(fd, "the command %s is invalid, please input again!\n", argv); @@ -71,7 +71,7 @@ void SoftBusDumpErrInfo(int fd, const char *argv) void SoftBusDumpSubModuleHelp(int fd, char *moduleName, ListNode *varList) { if (fd < 0 || moduleName == NULL || varList == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "param is invalid."); + COMM_LOGE(COMM_DFX, "param is invalid."); return; } SOFTBUS_DPRINTF(fd, "Usage: hidumper -s 4700 -a \" %s [Option] \n", moduleName); @@ -90,11 +90,11 @@ static SoftBusDumpVarNode *SoftBusCreateDumpVarNode(const char *varName, SoftBus { SoftBusDumpVarNode *varNode = (SoftBusDumpVarNode *)SoftBusCalloc(sizeof(SoftBusDumpVarNode)); if (varNode == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusCreateDumpVarNode malloc fail."); + COMM_LOGE(COMM_DFX, "SoftBusCreateDumpVarNode malloc fail."); return NULL; } if (strcpy_s(varNode->varName, SOFTBUS_DUMP_VAR_NAME_LEN, varName) != EOK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusCreateDumpVarNode set varName %s fail.", varName); + COMM_LOGE(COMM_DFX, "SoftBusCreateDumpVarNode set varName %s fail.", varName); SoftBusFree(varNode); return NULL; } @@ -107,13 +107,13 @@ static SoftBusDumpVarNode *SoftBusCreateDumpVarNode(const char *varName, SoftBus int32_t SoftBusAddDumpVarToList(const char *dumpVar, SoftBusVarDumpCb cb, ListNode *varList) { if (dumpVar == NULL || strlen(dumpVar) >= SOFTBUS_DUMP_VAR_NAME_LEN || cb == NULL || varList == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusRegDiscDumpCb invalid param"); + COMM_LOGE(COMM_DFX, "SoftBusRegDiscDumpCb invalid param"); return SOFTBUS_ERR; } SoftBusDumpVarNode *varNode = SoftBusCreateDumpVarNode(dumpVar, cb); if (varNode == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusRegDiscDumpCb node create fail"); + COMM_LOGE(COMM_DFX, "SoftBusRegDiscDumpCb node create fail"); return SOFTBUS_ERR; } varNode->dumpCallback = cb; @@ -140,17 +140,17 @@ static HandlerNode *CreateHiDumperHandlerNode(char *moduleName, char *helpInfo, { HandlerNode *handlerNode = (HandlerNode *)SoftBusCalloc(sizeof(HandlerNode)); if (handlerNode == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "CreateHiDumperHandlerNode malloc fail."); + COMM_LOGE(COMM_DFX, "CreateHiDumperHandlerNode malloc fail."); return NULL; } if (strcpy_s(handlerNode->moduleName, SOFTBUS_MODULE_NAME_LEN, moduleName) != EOK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "CreateHiDumperHandlerNode get moduleName fail."); + COMM_LOGE(COMM_DFX, "CreateHiDumperHandlerNode get moduleName fail."); SoftBusFree(handlerNode); return NULL; } if (strcpy_s(handlerNode->helpInfo, SOFTBUS_MODULE_HELP_LEN, helpInfo) != EOK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "CreateHiDumperHandlerNode get helpInfo fail"); + COMM_LOGE(COMM_DFX, "CreateHiDumperHandlerNode get helpInfo fail"); SoftBusFree(handlerNode); return NULL; } @@ -174,13 +174,13 @@ int32_t SoftBusRegHiDumperHandler(char *moduleName, char *helpInfo, DumpHandlerF { if (moduleName == NULL || strlen(moduleName) >= SOFTBUS_MODULE_NAME_LEN || helpInfo == NULL || strlen(helpInfo) >= SOFTBUS_MODULE_HELP_LEN || handler == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusRegHiDumperHandler invalid param"); + COMM_LOGE(COMM_DFX, "SoftBusRegHiDumperHandler invalid param"); return SOFTBUS_ERR; } HandlerNode *handlerNode = CreateHiDumperHandlerNode(moduleName, helpInfo, handler); if (handlerNode == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusRegHiDumperHandler node create fail"); + COMM_LOGE(COMM_DFX, "SoftBusRegHiDumperHandler node create fail"); return SOFTBUS_ERR; } ListTailInsert(&g_hidumperhander_list, &handlerNode->node); @@ -190,7 +190,7 @@ int32_t SoftBusRegHiDumperHandler(char *moduleName, char *helpInfo, DumpHandlerF int32_t SoftBusDumpDispatch(int fd, int32_t argc, const char **argv) { if (fd < 0 || argc < 0 || argv == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusDumpProcess: param invalid "); + COMM_LOGE(COMM_DFX, "SoftBusDumpProcess: param invalid "); return SOFTBUS_ERR; } @@ -226,27 +226,27 @@ int32_t SoftBusDumpDispatch(int fd, int32_t argc, const char **argv) int32_t SoftBusHiDumperModuleInit(void) { if (SoftBusDiscHiDumperInit() != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "init Disc HiDumper fail!"); + COMM_LOGE(COMM_INIT, "init Disc HiDumper fail!"); return SOFTBUS_ERR; } if (SoftBusConnHiDumperInit() != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "init Conn HiDumper fail!"); + COMM_LOGE(COMM_INIT, "init Conn HiDumper fail!"); return SOFTBUS_ERR; } if (SoftBusNStackHiDumperInit() != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "init NStack HiDumper fail!"); + COMM_LOGE(COMM_INIT, "init NStack HiDumper fail!"); return SOFTBUS_ERR; } if (SoftBusHiDumperBusCenterInit() != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "init BusCenter HiDumper fail!"); + COMM_LOGE(COMM_INIT, "init BusCenter HiDumper fail!"); return SOFTBUS_ERR; } if (SoftBusTransDumpHandlerInit() != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "init Trans HiDumper fail!"); + COMM_LOGE(COMM_INIT, "init Trans HiDumper fail!"); return SOFTBUS_ERR; } return SOFTBUS_OK; diff --git a/core/common/dfx/hidumper_adapter/softbus_hidumper_alarm.c b/core/common/dfx/hidumper_adapter/softbus_hidumper_alarm.c index be1740690..14a80cd74 100644 --- a/core/common/dfx/hidumper_adapter/softbus_hidumper_alarm.c +++ b/core/common/dfx/hidumper_adapter/softbus_hidumper_alarm.c @@ -17,12 +17,12 @@ #include #include +#include "comm_log.h" #include "softbus_errcode.h" #include "softbus_adapter_mem.h" #include "softbus_def.h" #include "softbus_hidumper.h" #include "softbus_hidumper_util.h" -#include "softbus_log_old.h" #define SOFTBUS_CONTROL_ALARM_ORDER "control" #define SOFTBUS_MANAGEMENT_ALARM_ORDER "management" @@ -119,7 +119,7 @@ int32_t SoftBusAlarmHiDumperInit(void) int32_t ret = SoftBusRegHiDumperHandler(SOFTBUS_ALARM_MODULE_NAME, SOFTBUS_ALARM_MODULE_HELP, &SoftBusAlarmDumpHander); if (ret != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "SoftBusRegAlarmDumpCb registe fail"); + COMM_LOGE(COMM_DFX, "SoftBusRegAlarmDumpCb registe fail"); } return ret; } diff --git a/core/common/dfx/hidumper_adapter/softbus_hidumper_buscenter.c b/core/common/dfx/hidumper_adapter/softbus_hidumper_buscenter.c index f65846cf0..010c087e2 100644 --- a/core/common/dfx/hidumper_adapter/softbus_hidumper_buscenter.c +++ b/core/common/dfx/hidumper_adapter/softbus_hidumper_buscenter.c @@ -16,7 +16,7 @@ #include #include -#include "softbus_log_old.h" +#include "comm_log.h" #include "softbus_def.h" #include "softbus_error_code.h" #include "softbus_hidumper.h" @@ -30,7 +30,7 @@ static LIST_HEAD(g_busCenter_var_list); int32_t SoftBusRegBusCenterVarDump(char *dumpVar, SoftBusVarDumpCb cb) { if (dumpVar == NULL || strlen(dumpVar) >= SOFTBUS_DUMP_VAR_NAME_LEN || cb == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusRegBusCenterVarDump invalid param"); + COMM_LOGE(COMM_DFX, "SoftBusRegBusCenterVarDump invalid param"); return SOFTBUS_ERR; } return SoftBusAddDumpVarToList(dumpVar, cb, &g_busCenter_var_list); @@ -77,7 +77,7 @@ int32_t SoftBusHiDumperBusCenterInit(void) int32_t ret = SoftBusRegHiDumperHandler( SOFTBUS_BUSCENTER_MODULE_NAME, SOFTBUS_CONN_MODULE_HELP, &SoftBusBusCenterDumpHander); if (ret != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusBusCenterDumpHander regist fail"); + COMM_LOGE(COMM_INIT, "SoftBusBusCenterDumpHander regist fail"); } return ret; } diff --git a/core/common/dfx/hidumper_adapter/softbus_hidumper_conn.c b/core/common/dfx/hidumper_adapter/softbus_hidumper_conn.c index e0631aa7a..dde959fa0 100644 --- a/core/common/dfx/hidumper_adapter/softbus_hidumper_conn.c +++ b/core/common/dfx/hidumper_adapter/softbus_hidumper_conn.c @@ -14,10 +14,10 @@ */ #include #include +#include "comm_log.h" #include "softbus_errcode.h" #include "softbus_adapter_mem.h" #include "softbus_def.h" -#include "softbus_log_old.h" #include "softbus_hidumper.h" #include "softbus_hidumper_conn.h" @@ -29,7 +29,7 @@ static LIST_HEAD(g_conn_var_list); int32_t SoftBusRegConnVarDump(const char *dumpVar, SoftBusVarDumpCb cb) { if (dumpVar == NULL || strlen(dumpVar) >= SOFTBUS_DUMP_VAR_NAME_LEN || cb == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusRegConnVarDump invalid param"); + COMM_LOGE(COMM_DFX, "SoftBusRegConnVarDump invalid param"); return SOFTBUS_ERR; } return SoftBusAddDumpVarToList(dumpVar, cb, &g_conn_var_list); @@ -75,7 +75,7 @@ int32_t SoftBusConnHiDumperInit(void) int32_t ret = SoftBusRegHiDumperHandler(SOFTBUS_CONN_MODULE_NAME, SOFTBUS_CONN_MODULE_HELP, &SoftBusConnDumpHander); if (ret != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusConnDumpHander regist fail"); + COMM_LOGE(COMM_INIT, "SoftBusConnDumpHander regist fail"); } return ret; } diff --git a/core/common/dfx/hidumper_adapter/softbus_hidumper_disc.c b/core/common/dfx/hidumper_adapter/softbus_hidumper_disc.c index 3aa460f38..65e0cb6f6 100644 --- a/core/common/dfx/hidumper_adapter/softbus_hidumper_disc.c +++ b/core/common/dfx/hidumper_adapter/softbus_hidumper_disc.c @@ -15,10 +15,10 @@ #include #include +#include "comm_log.h" #include "softbus_errcode.h" #include "softbus_adapter_mem.h" #include "softbus_def.h" -#include "softbus_log_old.h" #include "softbus_hidumper_disc.h" #define SOFTBUS_DISC_MODULE_NAME "disc" @@ -29,7 +29,7 @@ static LIST_HEAD(g_disc_var_list); int32_t SoftBusRegDiscVarDump(char *dumpVar, SoftBusVarDumpCb cb) { if (dumpVar == NULL || strlen(dumpVar) >= SOFTBUS_DUMP_VAR_NAME_LEN || cb == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusRegDiscDumpCb invalid param"); + COMM_LOGE(COMM_DFX, "SoftBusRegDiscDumpCb invalid param"); return SOFTBUS_ERR; } return SoftBusAddDumpVarToList(dumpVar, cb, &g_disc_var_list); @@ -38,7 +38,7 @@ int32_t SoftBusRegDiscVarDump(char *dumpVar, SoftBusVarDumpCb cb) static int32_t SoftBusDiscDumpHander(int fd, int32_t argc, const char **argv) { if (fd < 0 || argc < 0 || argv == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusDiscDumpHander invalid param"); + COMM_LOGE(COMM_DFX, "SoftBusDiscDumpHander invalid param"); return SOFTBUS_ERR; } @@ -77,7 +77,7 @@ int32_t SoftBusDiscHiDumperInit(void) int32_t ret = SoftBusRegHiDumperHandler(SOFTBUS_DISC_MODULE_NAME, SOFTBUS_DISC_MODULE_HELP, &SoftBusDiscDumpHander); if (ret != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusRegDiscDumpCb registe fail"); + COMM_LOGE(COMM_INIT, "SoftBusRegDiscDumpCb registe fail"); } return ret; } diff --git a/core/common/dfx/hidumper_adapter/softbus_hidumper_interface.c b/core/common/dfx/hidumper_adapter/softbus_hidumper_interface.c index b64618990..d211c9f7c 100644 --- a/core/common/dfx/hidumper_adapter/softbus_hidumper_interface.c +++ b/core/common/dfx/hidumper_adapter/softbus_hidumper_interface.c @@ -13,9 +13,9 @@ * limitations under the License. */ #include +#include "comm_log.h" #include "softbus_def.h" #include "softbus_errcode.h" -#include "softbus_log_old.h" #include "softbus_hidumper_alarm.h" #include "softbus_hidumper_stats.h" #include "softbus_hidumper_util.h" @@ -24,7 +24,7 @@ int32_t SoftBusDumpProcess(int fd, int32_t argc, const char **argv) { if (fd < 0 || argc < 0 || argv == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusDumpProcess: param invalid "); + COMM_LOGE(COMM_DFX, "SoftBusDumpProcess: param invalid "); return SOFTBUS_ERR; } return SoftBusDumpDispatch(fd, argc, argv); @@ -33,17 +33,17 @@ int32_t SoftBusDumpProcess(int fd, int32_t argc, const char **argv) int32_t SoftBusHiDumperInit(void) { if (SoftBusAlarmHiDumperInit() != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "init Alarm HiDumper fail!"); + COMM_LOGE(COMM_INIT, "init Alarm HiDumper fail!"); return SOFTBUS_ERR; } if (SoftBusHidumperUtilInit() != SOFTBUS_OK || SoftBusHiDumperModuleInit() != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusHiDumperInit fail!"); + COMM_LOGE(COMM_INIT, "SoftBusHiDumperInit fail!"); return SOFTBUS_ERR; } if (SoftBusStatsHiDumperInit() != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "init Stats HiDumper fail!"); + COMM_LOGE(COMM_INIT, "init Stats HiDumper fail!"); return SOFTBUS_ERR; } return SOFTBUS_OK; diff --git a/core/common/dfx/hidumper_adapter/softbus_hidumper_nstack.c b/core/common/dfx/hidumper_adapter/softbus_hidumper_nstack.c index 71e61a673..68a1f0507 100644 --- a/core/common/dfx/hidumper_adapter/softbus_hidumper_nstack.c +++ b/core/common/dfx/hidumper_adapter/softbus_hidumper_nstack.c @@ -14,8 +14,8 @@ */ #include #include +#include "comm_log.h" #include "softbus_errcode.h" -#include "softbus_log_old.h" #include "softbus_hidumper.h" #include "fillpinc.h" #include "nstackx.h" @@ -38,8 +38,7 @@ void SoftBufNstackDumpFunc(void *softObj, const char *data, uint32_t len) int fd = *(int *)softObj; size_t dataLen = strnlen(data, SOFTBUF_NSTACK_DUMP_BUF_LEN); if (dataLen == 0 || dataLen == SOFTBUF_NSTACK_DUMP_BUF_LEN || dataLen != len) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, - "SoftBufNstackDumpFunc len error, data strlen %d, len %d.", dataLen, len); + COMM_LOGE(COMM_DFX, "SoftBufNstackDumpFunc len error, data strlen %d, len %d.", dataLen, len); return; } SOFTBUS_DPRINTF(fd, "%s", data); @@ -48,12 +47,12 @@ void SoftBufNstackDumpFunc(void *softObj, const char *data, uint32_t len) static int32_t SoftBusNStackDstreamDumpHander(int fd, int32_t argc, const char **argv) { if (fd < 0 || argc < 0 || argv == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusNStackDstreamDumpHander invalid input"); + COMM_LOGE(COMM_DFX, "SoftBusNStackDstreamDumpHander invalid input"); return SOFTBUS_ERR; } #ifdef FILLP_ENHANCED if (FtDfxHiDumper((uint32_t)argc, argv, &fd, SoftBufNstackDumpFunc) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "call FtDfxHiDumper failed!"); + COMM_LOGE(COMM_DFX, "call FtDfxHiDumper failed!"); return SOFTBUS_ERR; } #endif @@ -62,12 +61,12 @@ static int32_t SoftBusNStackDstreamDumpHander(int fd, int32_t argc, const char * static int32_t SoftBusNStackDfileDumpHander(int fd, int32_t argc, const char **argv) { if (fd < 0 || argc < 0 || argv == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusNStackDfileDumpHander invalid input"); + COMM_LOGE(COMM_DFX, "SoftBusNStackDfileDumpHander invalid input"); return SOFTBUS_ERR; } #ifdef FILLP_ENHANCED if (NSTACKX_DFileDump((uint32_t)argc, argv, &fd, SoftBufNstackDumpFunc) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "call NSTACKX_DFileDump failed!"); + COMM_LOGE(COMM_DFX, "call NSTACKX_DFileDump failed!"); return SOFTBUS_ERR; } #endif @@ -76,12 +75,12 @@ static int32_t SoftBusNStackDfileDumpHander(int fd, int32_t argc, const char **a static int32_t SoftBusNStackDumpDfinderHander(int fd, int32_t argc, const char **argv) { if (fd < 0 || argc < 0 || argv == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "NSTACKX_DFinderDump invalid input!"); + COMM_LOGE(COMM_DFX, "NSTACKX_DFinderDump invalid input!"); return SOFTBUS_ERR; } #ifdef FILLP_ENHANCED if (NSTACKX_DFinderDump(argv, (uint32_t)argc, &fd, SoftBufNstackDumpFunc) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "call NSTACKX_DFinderDump failed!"); + COMM_LOGE(COMM_DFX, "call NSTACKX_DFinderDump failed!"); return SOFTBUS_ERR; } #endif @@ -102,28 +101,28 @@ int32_t SoftBusNStackHiDumperInit(void) int32_t ret = SoftBusRegHiDumperHandler(SOFTBUS_DSTREAM_MODULE_NAME, SOFTBUS_DSTREAM_MODULE_HELP, &SoftBusNStackDstreamDumpHander); if (ret != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusNStackHiDumperInit regist dstream handler fail"); + COMM_LOGE(COMM_INIT, "SoftBusNStackHiDumperInit regist dstream handler fail"); return ret; } ret = SoftBusRegHiDumperHandler(SOFTBUS_DFILE_MODULE_NAME, SOFTBUS_DFILE_MODULE_HELP, &SoftBusNStackDfileDumpHander); if (ret != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusNStackHiDumperInit regist dstream handler fail"); + COMM_LOGE(COMM_INIT, "SoftBusNStackHiDumperInit regist dstream handler fail"); return ret; } ret = SoftBusRegHiDumperHandler(SOFTBUS_DFINDLER_MODULE_NAME, SOFTBUS_DFINDLER_MODULE_HELP, &SoftBusNStackDumpDfinderHander); if (ret != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusNStackHiDumperInit regist dstream handler fail"); + COMM_LOGE(COMM_INIT, "SoftBusNStackHiDumperInit regist dstream handler fail"); return ret; } ret = SoftBusRegHiDumperHandler(SOFTBUS_DMSG_MODULE_NAME, SOFTBUS_DMSG_MODULE_HELP, &SoftBusNStackDmsgDumpHander); if (ret != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusNStackHiDumperInit regist dstream handler fail"); + COMM_LOGE(COMM_INIT, "SoftBusNStackHiDumperInit regist dstream handler fail"); return ret; } return ret; diff --git a/core/common/dfx/hidumper_adapter/softbus_hidumper_trans.c b/core/common/dfx/hidumper_adapter/softbus_hidumper_trans.c index cc63f98e6..043740625 100644 --- a/core/common/dfx/hidumper_adapter/softbus_hidumper_trans.c +++ b/core/common/dfx/hidumper_adapter/softbus_hidumper_trans.c @@ -17,10 +17,10 @@ #include #include +#include "comm_log.h" #include "securec.h" #include "softbus_adapter_mem.h" #include "softbus_error_code.h" -#include "softbus_log_old.h" #include "softbus_utils.h" #define MAX_ID_LEN (10) @@ -48,7 +48,7 @@ static LIST_HEAD(g_trans_var_list); int32_t SoftBusRegTransVarDump(const char *dumpVar, SoftBusVarDumpCb cb) { if (dumpVar == NULL || strlen(dumpVar) >= SOFTBUS_DUMP_VAR_NAME_LEN || cb == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusRegTransVarDump invalid param"); + COMM_LOGE(COMM_DFX, "SoftBusRegTransVarDump invalid param"); return SOFTBUS_ERR; } return SoftBusAddDumpVarToList(dumpVar, cb, &g_trans_var_list); @@ -58,7 +58,7 @@ void SoftBusTransDumpRegisterSession(int fd, const char* pkgName, const char* se int uid, int pid) { if (fd < 0 || pkgName == NULL || sessionName == NULL || uid < 0 || pid < 0) { - SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "param is invalid"); + COMM_LOGE(COMM_DFX, "param is invalid"); return; } @@ -67,7 +67,7 @@ void SoftBusTransDumpRegisterSession(int fd, const char* pkgName, const char* se char uidStr[MAX_ID_LEN] = {0}; char pidStr[MAX_ID_LEN] = {0}; if (sprintf_s(uidArr, MAX_ID_LEN, "%d", uid) < 0 || sprintf_s(pidArr, MAX_ID_LEN, "%d", pid) < 0) { - SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "set uidArr or pidArr failed"); + COMM_LOGE(COMM_DFX, "set uidArr or pidArr failed"); return; } @@ -82,7 +82,7 @@ void SoftBusTransDumpRegisterSession(int fd, const char* pkgName, const char* se void SoftBusTransDumpRunningSession(int fd, TransDumpLaneLinkType type, AppInfo* appInfo) { if (fd < 0 || type < DUMPER_LANE_BR || type >= DUMPER_LANE_LINK_TYPE_BUTT || appInfo == NULL) { - SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "param is invalid"); + COMM_LOGE(COMM_DFX, "param is invalid"); return; } @@ -105,7 +105,7 @@ void SoftBusTransDumpRunningSession(int fd, TransDumpLaneLinkType type, AppInfo* static int SoftBusTransDumpHandler(int fd, int argc, const char **argv) { if (fd < 0 || argv == NULL || argc < 0) { - SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "param is invalid "); + COMM_LOGE(COMM_DFX, "param is invalid "); return SOFTBUS_ERR; } if (argc == 0 || ((argc == 1) && (strcmp(argv[0], "-h") == 0)) || (argc == 1 && strcmp(argv[0], "-l") == 0)) { @@ -138,7 +138,7 @@ int32_t SoftBusTransDumpHandlerInit(void) int32_t ret = SoftBusRegHiDumperHandler((char*)MODULE_NAME_TRAN, (char*)SOFTBUS_TRANS_MODULE_HELP, &SoftBusTransDumpHandler); if (ret != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "SoftBusTransDumpHander regist fail"); + COMM_LOGE(COMM_INIT, "SoftBusTransDumpHander regist fail"); } return ret; } diff --git a/core/common/dfx/hidumper_adapter/softbus_hidumper_trans_virtual.c b/core/common/dfx/hidumper_adapter/softbus_hidumper_trans_virtual.c index 6467569de..22fdca01f 100644 --- a/core/common/dfx/hidumper_adapter/softbus_hidumper_trans_virtual.c +++ b/core/common/dfx/hidumper_adapter/softbus_hidumper_trans_virtual.c @@ -44,11 +44,11 @@ void SoftBusTransDumpRunningSession(int fd, TransDumpLaneLinkType type, AppInfo* return; } -int32_t SoftBusTransDumpHanderInit() +int32_t SoftBusTransDumpHanderInit(void) { return SOFTBUS_OK; } -void SoftBusHiDumperTransDeInit() +void SoftBusHiDumperTransDeInit(void) { } diff --git a/core/common/dfx/hidumper_adapter/softbus_hidumper_util.c b/core/common/dfx/hidumper_adapter/softbus_hidumper_util.c index d3d8c0b8e..b5db379b8 100644 --- a/core/common/dfx/hidumper_adapter/softbus_hidumper_util.c +++ b/core/common/dfx/hidumper_adapter/softbus_hidumper_util.c @@ -29,7 +29,6 @@ #include "softbus_def.h" #include "softbus_error_code.h" #include "softbus_event.h" -#include "softbus_log_old.h" #include "stats_event.h" #include "hisysevent_manager_c.h" @@ -206,11 +205,11 @@ static void GetLocalTime(char* time, uint64_t timestamp) (void)strftime(time, SOFTBUS_ALARM_TIME_LEN, "%Y-%m-%d %H:%M:%S", tmInfo); } -static void ConnStatsLinkType(int32_t linkType, bool success) +static void ConnStatsLinkType(int32_t linkTypePara, bool success) { + int32_t linkType = linkTypePara; if (linkType < CONNECT_TCP || linkType >= CONNECT_TYPE_MAX) { - COMM_LOGE(COMM_DFX, "linkType:%d is unexpected.", linkType); - return; + linkType = SOFTBUS_ZERO; } g_connStatsInfo.linkTypeTotal[linkType]++; if (success) { @@ -254,11 +253,11 @@ static void OnCompleteConn(int32_t reason, int32_t total) g_isConnQueryEnd = true; } -static void LnnStatsAuthLinkType(int32_t authLinkType, bool success) +static void LnnStatsAuthLinkType(int32_t authLinkTypePara, bool success) { + int32_t authLinkType = authLinkTypePara; if (authLinkType < AUTH_LINK_TYPE_WIFI || authLinkType >= AUTH_LINK_TYPE_MAX) { - COMM_LOGE(COMM_DFX, "authLinkType:%d is unexpected.", authLinkType); - return; + authLinkType = SOFTBUS_ZERO; } g_lnnStatsInfo.authLinkTypeTotal[authLinkType]++; if (success) { @@ -324,23 +323,11 @@ static void OnCompleteLnn(int32_t reason, int32_t total) g_isLnnQueryEnd = true; } -static void TransStatsSuccessDetail(int32_t scene, int32_t stage, int32_t stageRes, const char *socketName, - int32_t linkType) +static void TransStatsSuccessDetail(bool success, const char *socketName, int32_t linkTypePara) { - if (stageRes == EVENT_STAGE_RESULT_OK && - (scene != EVENT_SCENE_OPEN_CHANNEL || stage != EVENT_STAGE_OPEN_CHANNEL_END)) { - return; - } - if (stageRes == EVENT_STAGE_RESULT_FAILED && scene != EVENT_SCENE_OPEN_CHANNEL) { - return; - } - if (socketName == NULL || strlen(socketName) == 0) { - COMM_LOGE(COMM_DFX, "socketName is NULL or length is 0"); - return; - } + int linkType = linkTypePara; if (linkType < CONNECT_TCP || linkType >= CONNECT_TYPE_MAX) { - COMM_LOGE(COMM_DFX, "linkType:%d is unexpected.", linkType); - return; + linkType = SOFTBUS_ZERO; } char keyStr[SESSION_NAME_SIZE_MAX + 3] = {0}; @@ -359,27 +346,28 @@ static void TransStatsSuccessDetail(int32_t scene, int32_t stage, int32_t stageR TransStatsSuccessRateDetail newResult; newResult.successTotal = 0; newResult.total = 1; - if (stageRes == EVENT_STAGE_RESULT_OK) { + if (success) { newResult.successTotal = 1; } if (LnnMapSet(&g_transStatsInfo.sessionNameLinkTypeMap, keyStr, (const void *)&newResult, sizeof(TransStatsSuccessRateDetail)) != SOFTBUS_OK) { - COMM_LOGE(COMM_DFX, "insert socketName:%s fail", socketName); + COMM_LOGE(COMM_DFX, "insert keyStr:%s fail", keyStr); } TransMapUnlock(); return; } data->total++; - if (stageRes == EVENT_STAGE_RESULT_OK) { + if (success) { data->successTotal++; } TransMapUnlock(); } -static void TransStats(int32_t scene, int32_t stage, int32_t stageRes) +static void TransStats(int32_t scene, int32_t stage, int32_t stageRes, const char *socketName, int32_t linkType) { if (scene == EVENT_SCENE_OPEN_CHANNEL && stage == EVENT_STAGE_OPEN_CHANNEL_END && stageRes == EVENT_STAGE_RESULT_OK) { + TransStatsSuccessDetail(true, socketName, linkType); g_transStatsInfo.openSessionSuccessTotal++; g_transStatsInfo.currentParaSessionNum++; return; @@ -387,6 +375,7 @@ static void TransStats(int32_t scene, int32_t stage, int32_t stageRes) if (scene == EVENT_SCENE_OPEN_CHANNEL && stage == EVENT_STAGE_OPEN_CHANNEL_END && stageRes == EVENT_STAGE_RESULT_FAILED) { + TransStatsSuccessDetail(false, socketName, linkType); g_transStatsInfo.openSessionFailTotal++; return; } @@ -428,10 +417,9 @@ static void OnQueryTrans(HiSysEventRecordC srcRecord[], size_t size) continue; } - TransStats(scene, stage, stageRes); char* socketName = GetStringValueByRecord(&srcRecord[i], SOCKET_KEY_NAME); int32_t linkType = GetInt32ValueByRecord(&srcRecord[i], LINK_TYPE_NAME); - TransStatsSuccessDetail(scene, stage, stageRes, socketName, linkType); + TransStats(scene, stage, stageRes, socketName, linkType); cJSON_free(socketName); if (scene == EVENT_SCENE_CLOSE_CHANNEL_ACTIVE && stage == EVENT_STAGE_CLOSE_CHANNEL && stageRes == EVENT_STAGE_RESULT_OK && g_transStatsInfo.currentParaSessionNum > 0) { @@ -442,7 +430,7 @@ static void OnQueryTrans(HiSysEventRecordC srcRecord[], size_t size) maxParaSessionNum : g_transStatsInfo.currentParaSessionNum; int32_t timeConsuming = GetInt32ValueByRecord(&srcRecord[i], TIME_CONSUMING_NAME); - if (timeConsuming != SOFTBUS_ERR) { + if (timeConsuming != SOFTBUS_ERR && stageRes == EVENT_STAGE_RESULT_OK) { g_transStatsInfo.delayTimeTotal += timeConsuming; g_transStatsInfo.delayNum++; } @@ -594,7 +582,7 @@ void FillConnSuccessRateDetail(cJSON *connObj) COMM_LOGE(COMM_DFX, "%s json is add to root fail", MODULE_NAME_CONN); return; } - for (int i = CONNECT_TCP; i < CONNECT_TYPE_MAX; i++) { + for (int i = SOFTBUS_ZERO; i < CONNECT_TYPE_MAX; i++) { float rate = 0; if (g_connStatsInfo.linkTypeTotal[i] > 0) { rate = 1.0 * g_connStatsInfo.linkTypeSuccessTotal[i] / g_connStatsInfo.linkTypeTotal[i] * RATE_HUNDRED; @@ -616,7 +604,7 @@ void FillAuthSuccessRateDetail(cJSON *authObj) COMM_LOGE(COMM_DFX, "%s json is add to root fail", MODULE_NAME_AUTH); return; } - for (int i = AUTH_LINK_TYPE_WIFI; i < AUTH_LINK_TYPE_MAX; i++) { + for (int i = SOFTBUS_ZERO; i < AUTH_LINK_TYPE_MAX; i++) { float rate = 0; if (g_lnnStatsInfo.authLinkTypeTotal[i] > 0) { rate = @@ -678,11 +666,11 @@ static void SoftBusProcessStatsQueryData(SoftBusStatsResult* result) result->laneScoreOverTimes = g_transStatsInfo.laneScoreOverTimes; result->detectionTimes = g_transStatsInfo.detectionTimes; - if (memset_s(&g_connStatsInfo, sizeof(g_connStatsInfo), 0, sizeof(g_connStatsInfo)) != SOFTBUS_OK) { + if (memset_s(&g_connStatsInfo, sizeof(g_connStatsInfo), 0, sizeof(g_connStatsInfo)) != EOK) { COMM_LOGE(COMM_DFX, "memset g_connStatsInfo fail!"); return; } - if (memset_s(&g_lnnStatsInfo, sizeof(g_lnnStatsInfo), 0, sizeof(g_lnnStatsInfo)) != SOFTBUS_OK) { + if (memset_s(&g_lnnStatsInfo, sizeof(g_lnnStatsInfo), 0, sizeof(g_lnnStatsInfo)) != EOK) { COMM_LOGE(COMM_DFX, "memset g_lnnStatsInfo fail!"); return; } @@ -691,7 +679,7 @@ static void SoftBusProcessStatsQueryData(SoftBusStatsResult* result) } LnnMapDelete(&g_transStatsInfo.sessionNameLinkTypeMap); TransMapUnlock(); - if (memset_s(&g_transStatsInfo, sizeof(g_transStatsInfo), 0, sizeof(g_transStatsInfo)) != SOFTBUS_OK) { + if (memset_s(&g_transStatsInfo, sizeof(g_transStatsInfo), 0, sizeof(g_transStatsInfo)) != EOK) { COMM_LOGE(COMM_DFX, "memset g_transStatsInfo fail!"); return; } @@ -767,8 +755,9 @@ int32_t SoftBusQueryAlarmInfo(int time, int type, SoftBusAlarmEvtResult* result) } g_alarmEvtResult.recordSize = 0; if (memset_s(g_alarmEvtResult.records, sizeof(AlarmRecord) * MAX_NUM_OF_EVENT_RESULT, 0, - sizeof(AlarmRecord) * MAX_NUM_OF_EVENT_RESULT) != SOFTBUS_OK) { + sizeof(AlarmRecord) * MAX_NUM_OF_EVENT_RESULT) != EOK) { COMM_LOGE(COMM_DFX, "memset g_alarmEvtResult records fail!"); + (void)SoftBusMutexUnlock(&g_alarmQueryLock); return SOFTBUS_ERR; } SoftBusEventQueryInfo(time, &g_queryAlarmParam[type]); @@ -825,10 +814,10 @@ static int32_t InitDumperUtilMutexLock(void) static void UpdateSysEventQueryParam(HiSysEventQueryParam* param, char* eventName) { HiSysEventQueryRule* queryRule = ¶m->queryRules[SOFTBUS_ZERO]; - if (strcpy_s(queryRule->domain, MAX_LENGTH_OF_EVENT_DOMAIN, SOFTBUS_EVENT_DOMAIN) != SOFTBUS_OK) { + if (strcpy_s(queryRule->domain, MAX_LENGTH_OF_EVENT_DOMAIN, SOFTBUS_EVENT_DOMAIN) != EOK) { COMM_LOGE(COMM_DFX, "UpdateSysEventQueryParam copy domain fail"); } - if (strcpy_s(queryRule->eventList[SOFTBUS_ZERO], MAX_LENGTH_OF_EVENT_NAME, eventName) != SOFTBUS_OK) { + if (strcpy_s(queryRule->eventList[SOFTBUS_ZERO], MAX_LENGTH_OF_EVENT_NAME, eventName) != EOK) { COMM_LOGE(COMM_DFX, "UpdateSysEventQueryParam copy domain fail"); } queryRule->eventListSize = SOFTBUS_ONE; @@ -836,7 +825,7 @@ static void UpdateSysEventQueryParam(HiSysEventQueryParam* param, char* eventNam param->eventSize = SOFTBUS_ONE; } -static void InitSoftBusQueryEventParam() +static void InitSoftBusQueryEventParam(void) { HiSysEventQueryParam* connParam = &g_queryStatsParam[SOFTBUS_CONNECTION_STATS_TYPE]; UpdateSysEventQueryParam(connParam, CONN_EVENT_NAME); @@ -963,7 +952,7 @@ static int32_t CreateAndQueryMsgDelay(SoftBusLooper* looper, HandleMessageFunc c static void QueryStatisticInfoPeriod(SoftBusMessage* msg) { QueryStatisticInfo(msg); - CreateAndQueryMsgDelay(GetLooper(LOOP_TYPE_DEFAULT), QueryStatisticInfoPeriod, DAY_TIME); + CreateAndQueryMsgDelay(GetLooper(LOOP_TYPE_HANDLE_FILE), QueryStatisticInfoPeriod, DAY_TIME); } int32_t SoftBusHidumperUtilInit(void) @@ -983,7 +972,7 @@ int32_t SoftBusHidumperUtilInit(void) } InitSoftBusQueryEventParam(); g_isDumperInit = true; - if (CreateAndQueryMsgDelay(GetLooper(LOOP_TYPE_DEFAULT), QueryStatisticInfoPeriod, DAY_TIME) != SOFTBUS_OK) { + if (CreateAndQueryMsgDelay(GetLooper(LOOP_TYPE_HANDLE_FILE), QueryStatisticInfoPeriod, DAY_TIME) != SOFTBUS_OK) { COMM_LOGE(COMM_DFX, "CreateAndQueryMsgDelay fail"); } return SOFTBUS_OK; @@ -1002,6 +991,7 @@ void SoftBusHidumperUtilDeInit(void) LnnMapDelete(&g_transStatsInfo.sessionNameLinkTypeMap); TransMapUnlock(); SoftBusMutexDestroy(&g_transMapLock); + g_isTransMapInit = false; SoftBusMutexDestroy(&g_statsQueryLock); SoftBusMutexDestroy(&g_alarmQueryLock); SoftBusMutexDestroy(&g_connOnQueryLock); diff --git a/core/common/dfx/hidumper_adapter/softbus_hidumper_util_virtual.c b/core/common/dfx/hidumper_adapter/softbus_hidumper_util_virtual.c index aa915cc79..f505bcde5 100644 --- a/core/common/dfx/hidumper_adapter/softbus_hidumper_util_virtual.c +++ b/core/common/dfx/hidumper_adapter/softbus_hidumper_util_virtual.c @@ -15,7 +15,6 @@ #include "softbus_hidumper_util.h" #include "softbus_errcode.h" -#include "softbus_log_old.h" int32_t SoftBusQueryStatsInfo(int time, SoftBusStatsResult* result) { diff --git a/core/common/dfx/hisysevent_adapter/softbus_hisysevt_discreporter.c b/core/common/dfx/hisysevent_adapter/softbus_hisysevt_discreporter.c index fd576a5aa..eb6970945 100644 --- a/core/common/dfx/hisysevent_adapter/softbus_hisysevt_discreporter.c +++ b/core/common/dfx/hisysevent_adapter/softbus_hisysevt_discreporter.c @@ -24,7 +24,7 @@ #include "softbus_hisysevt_common.h" #include "softbus_utils.h" -#define MODULE_NAME_MAX_LEN 33 +#define MODULE_NAME_MAX_LEN 65 #define FIRST_DISC_DURATION_PARAM_NUM 10 #define SOFT_BUS_VERSION_KEY "SOFT_BUS_VERSION" @@ -583,4 +583,4 @@ void DeinitDiscStatisticSysEvt(void) { ClearDiscDetails(); DestroyMutex(); -} \ No newline at end of file +} diff --git a/core/common/dfx/hisysevent_adapter/softbus_hisysevt_nstack.c b/core/common/dfx/hisysevent_adapter/softbus_hisysevt_nstack.c index c09680748..c43f3130f 100644 --- a/core/common/dfx/hisysevent_adapter/softbus_hisysevt_nstack.c +++ b/core/common/dfx/hisysevent_adapter/softbus_hisysevt_nstack.c @@ -14,10 +14,10 @@ */ #include +#include "comm_log.h" #include "fillpinc.h" #include "nstackx.h" #include "nstackx_dfile.h" -#include "softbus_adapter_log.h" #include "softbus_adapter_mem.h" #include "softbus_def.h" #include "softbus_errcode.h" @@ -98,13 +98,13 @@ static int32_t CopyEventParamVal(SoftBusEvtParamType type, void *dst, const void break; case SOFTBUS_EVT_PARAMTYPE_STRING: if (strcpy_s(dst, SOFTBUS_HISYSEVT_PARAM_LEN, src) != EOK) { - LOG_ERR("softbus param string max %d, nstack param string %s", + COMM_LOGE(COMM_DFX, "softbus param string max %d, nstack param string %s", SOFTBUS_HISYSEVT_PARAM_LEN, (char *)src); return SOFTBUS_ERR; } break; default: - LOG_ERR("unknow param type"); + COMM_LOGE(COMM_DFX, "unknow param type"); return SOFTBUS_ERR; } return SOFTBUS_OK; @@ -113,13 +113,13 @@ static int32_t CopyEventParamVal(SoftBusEvtParamType type, void *dst, const void static int32_t NstackEventParaToSoftBusEventPara(SoftBusEvtParam *dst, const NstackDfxEvtParam *src) { if (src->type >= SOFTBUS_EVT_PARAMTYPE_BUTT) { - LOG_ERR("softbus paramType max %d, nstack paramType %d", + COMM_LOGE(COMM_DFX, "softbus paramType max %d, nstack paramType %d", SOFTBUS_EVT_PARAMTYPE_BUTT, src->type); return SOFTBUS_ERR; } dst->paramType = (SoftBusEvtParamType)src->type; if (strcpy_s(dst->paramName, SOFTBUS_HISYSEVT_NAME_LEN, src->paramName) != EOK) { - LOG_ERR("softbus paramName max size %d, nstack paramName name %s", + COMM_LOGE(COMM_DFX, "softbus paramName max size %d, nstack paramName name %s", SOFTBUS_HISYSEVT_NAME_LEN, src->paramName); return SOFTBUS_ERR; } @@ -132,16 +132,16 @@ static int32_t NstackEventParaToSoftBusEventPara(SoftBusEvtParam *dst, const Nst static int32_t NstackDfxEvtToSoftBusReportMsg(SoftBusEvtReportMsg *msg, const NstackDfxEvent *info) { if (strcpy_s(msg->evtName, SOFTBUS_HISYSEVT_NAME_LEN, info->eventName) != EOK) { - LOG_ERR("eventName mismatch, nstack event name %s", info->eventName); + COMM_LOGE(COMM_DFX, "eventName mismatch, nstack event name %s", info->eventName); return SOFTBUS_ERR; } if (info->type >= SOFTBUS_EVT_TYPE_BUTT) { - LOG_ERR("eventType mismatch, nstack event type %d", info->type); + COMM_LOGE(COMM_DFX, "eventType mismatch, nstack event type %d", info->type); return SOFTBUS_ERR; } msg->evtType = (SoftBusEvtType)(info->type); if (info->paramNum != 0 && info->paramArray == NULL) { - LOG_ERR("param mismatch, nstack paramNum %u paramArray is NULL", info->paramNum); + COMM_LOGE(COMM_DFX, "param mismatch, nstack paramNum %u paramArray is NULL", info->paramNum); return SOFTBUS_ERR; } msg->paramNum = info->paramNum; @@ -150,7 +150,7 @@ static int32_t NstackDfxEvtToSoftBusReportMsg(SoftBusEvtReportMsg *msg, const Ns } msg->paramArray = (SoftBusEvtParam *)SoftBusCalloc(msg->paramNum * sizeof(SoftBusEvtParam)); if (msg->paramArray == NULL) { - LOG_ERR("SoftBusCalloc paramArray failed! paramNum %u", info->paramNum); + COMM_LOGE(COMM_DFX, "SoftBusCalloc paramArray failed! paramNum %u", info->paramNum); return SOFTBUS_ERR; } for (uint8_t i = 0; i < info->paramNum; i++) { @@ -165,7 +165,7 @@ static void NstackHiEventCb(void *softObj, const NstackDfxEvent *info) { (void)softObj; if (info == NULL) { - LOG_ERR("info is NULL"); + COMM_LOGE(COMM_DFX, "info is NULL"); return; } SoftBusEvtReportMsg msg; @@ -174,7 +174,7 @@ static void NstackHiEventCb(void *softObj, const NstackDfxEvent *info) if (msg.paramArray != NULL) { SoftBusFree(msg.paramArray); } - LOG_ERR("change NstackDfxEvent to SoftBusEvtReportMsg failed!"); + COMM_LOGE(COMM_DFX, "change NstackDfxEvent to SoftBusEvtReportMsg failed!"); return; } (void)SoftbusWriteHisEvt(&msg); @@ -186,12 +186,12 @@ static void NstackHiEventCb(void *softObj, const NstackDfxEvent *info) void DstreamHiEventCb(void *softObj, const FillpDfxEvent *info) { if (softObj == NULL || info == NULL) { - LOG_ERR("param is NULL"); + COMM_LOGE(COMM_DFX, "param is NULL"); return; } NstackDfxEvent nstackInfo; if (memcpy_s(&nstackInfo, sizeof(NstackDfxEvent), info, sizeof(FillpDfxEvent)) != EOK) { - LOG_ERR("change FillpDfxEvent to NstackDfxEvent failed!"); + COMM_LOGE(COMM_DFX, "change FillpDfxEvent to NstackDfxEvent failed!"); return; } NstackHiEventCb(softObj, &nstackInfo); @@ -201,7 +201,7 @@ static void DFileHiEventCb(void *softObj, const DFileEvent *info) { NstackDfxEvent nstackInfo; if (memcpy_s(&nstackInfo, sizeof(NstackDfxEvent), info, sizeof(DFileEvent)) != EOK) { - LOG_ERR("change DFileEvent to NstackDfxEvent failed!"); + COMM_LOGE(COMM_DFX, "change DFileEvent to NstackDfxEvent failed!"); return; } NstackHiEventCb(softObj, &nstackInfo); @@ -212,7 +212,7 @@ static void DFinderHiEventCb(void *softObj, const DFinderEvent *info) NstackDfxEvent nstackInfo; if (memcpy_s(nstackInfo.eventName, sizeof(nstackInfo.eventName), info->eventName, sizeof(info->eventName)) != EOK) { - LOG_ERR("change DFinderEvent to NstackDfxEvent failed!"); + COMM_LOGE(COMM_DFX, "change DFinderEvent to NstackDfxEvent failed!"); return; } @@ -227,7 +227,7 @@ void NstackInitHiEvent(void) { NSTACKX_DFileSetEventFunc(NULL, DFileHiEventCb); if (NSTACKX_DFinderSetEventFunc(NULL, DFinderHiEventCb) != 0) { - LOG_ERR("NSTACKX_DFinderSetEventFunc failed!"); + COMM_LOGE(COMM_DFX, "NSTACKX_DFinderSetEventFunc failed!"); } } #endif /* FILLP_ENHANCED */ diff --git a/core/common/dfx/interface/include/auth_log.h b/core/common/dfx/interface/include/auth_log.h index 92eacd9cd..003733431 100644 --- a/core/common/dfx/interface/include/auth_log.h +++ b/core/common/dfx/interface/include/auth_log.h @@ -40,11 +40,11 @@ static const SoftBusLogLabel AUTH_LABELS[MODULE_DOMAIN_MAX_LEN] = { { AUTH_TEST, DOMAIN_ID_TEST, "AuthTest" }, }; -#define AUTH_LOGF(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_FATAL, AUTH_LABELS[label], ##__VA_ARGS__) -#define AUTH_LOGE(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_ERROR, AUTH_LABELS[label], ##__VA_ARGS__) -#define AUTH_LOGW(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_WARN, AUTH_LABELS[label], ##__VA_ARGS__) -#define AUTH_LOGI(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_INFO, AUTH_LABELS[label], ##__VA_ARGS__) -#define AUTH_LOGD(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_DEBUG, AUTH_LABELS[label], ##__VA_ARGS__) +#define AUTH_LOGF(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_FATAL, AUTH_LABELS[label], ##__VA_ARGS__) +#define AUTH_LOGE(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_ERROR, AUTH_LABELS[label], ##__VA_ARGS__) +#define AUTH_LOGW(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_WARN, AUTH_LABELS[label], ##__VA_ARGS__) +#define AUTH_LOGI(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_INFO, AUTH_LABELS[label], ##__VA_ARGS__) +#define AUTH_LOGD(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_DEBUG, AUTH_LABELS[label], ##__VA_ARGS__) #define AUTH_CHECK_AND_RETURN_RET_LOGW(cond, ret, label, fmt, ...) \ CHECK_AND_RETURN_RET_LOG_INNER(cond, ret, AUTH_LOGW, label, fmt, ##__VA_ARGS__) diff --git a/core/common/dfx/interface/include/comm_log.h b/core/common/dfx/interface/include/comm_log.h index 9fff3b8c2..7cc6e2b0e 100644 --- a/core/common/dfx/interface/include/comm_log.h +++ b/core/common/dfx/interface/include/comm_log.h @@ -48,11 +48,11 @@ static const SoftBusLogLabel COMM_LABELS[MODULE_DOMAIN_MAX_LEN] = { { COMM_TEST, DOMAIN_ID_TEST, "CommTest" }, }; -#define COMM_LOGF(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_FATAL, COMM_LABELS[label], ##__VA_ARGS__) -#define COMM_LOGE(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_ERROR, COMM_LABELS[label], ##__VA_ARGS__) -#define COMM_LOGW(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_WARN, COMM_LABELS[label], ##__VA_ARGS__) -#define COMM_LOGI(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_INFO, COMM_LABELS[label], ##__VA_ARGS__) -#define COMM_LOGD(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_DEBUG, COMM_LABELS[label], ##__VA_ARGS__) +#define COMM_LOGF(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_FATAL, COMM_LABELS[label], ##__VA_ARGS__) +#define COMM_LOGE(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_ERROR, COMM_LABELS[label], ##__VA_ARGS__) +#define COMM_LOGW(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_WARN, COMM_LABELS[label], ##__VA_ARGS__) +#define COMM_LOGI(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_INFO, COMM_LABELS[label], ##__VA_ARGS__) +#define COMM_LOGD(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_DEBUG, COMM_LABELS[label], ##__VA_ARGS__) #define COMM_CHECK_AND_RETURN_RET_LOGW(cond, ret, label, fmt, ...) \ CHECK_AND_RETURN_RET_LOG_INNER(cond, ret, COMM_LOGW, label, fmt, ##__VA_ARGS__) diff --git a/core/common/dfx/interface/include/conn_log.h b/core/common/dfx/interface/include/conn_log.h index 4b5b8e6f8..7e90eecf2 100644 --- a/core/common/dfx/interface/include/conn_log.h +++ b/core/common/dfx/interface/include/conn_log.h @@ -48,11 +48,11 @@ static const SoftBusLogLabel CONN_LABELS[MODULE_DOMAIN_MAX_LEN] = { {CONN_TEST, DOMAIN_ID_TEST, "ConnTest"}, }; -#define CONN_LOGF(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_FATAL, CONN_LABELS[label], ##__VA_ARGS__) -#define CONN_LOGE(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_ERROR, CONN_LABELS[label], ##__VA_ARGS__) -#define CONN_LOGW(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_WARN, CONN_LABELS[label], ##__VA_ARGS__) -#define CONN_LOGI(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_INFO, CONN_LABELS[label], ##__VA_ARGS__) -#define CONN_LOGD(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_DEBUG, CONN_LABELS[label], ##__VA_ARGS__) +#define CONN_LOGF(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_FATAL, CONN_LABELS[label], ##__VA_ARGS__) +#define CONN_LOGE(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_ERROR, CONN_LABELS[label], ##__VA_ARGS__) +#define CONN_LOGW(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_WARN, CONN_LABELS[label], ##__VA_ARGS__) +#define CONN_LOGI(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_INFO, CONN_LABELS[label], ##__VA_ARGS__) +#define CONN_LOGD(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_DEBUG, CONN_LABELS[label], ##__VA_ARGS__) #define CONN_CHECK_AND_RETURN_RET_LOGW(cond, ret, label, fmt, ...) \ CHECK_AND_RETURN_RET_LOG_INNER(cond, ret, CONN_LOGW, label, fmt, ##__VA_ARGS__) diff --git a/core/common/dfx/interface/include/disc_log.h b/core/common/dfx/interface/include/disc_log.h index f0a080358..6601f425c 100644 --- a/core/common/dfx/interface/include/disc_log.h +++ b/core/common/dfx/interface/include/disc_log.h @@ -52,16 +52,20 @@ static const SoftBusLogLabel DISC_LABELS[MODULE_DOMAIN_MAX_LEN] = { { DISC_TEST, DOMAIN_ID_TEST, "DiscTest" }, }; -#define DISC_LOGF(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_FATAL, DISC_LABELS[label], ##__VA_ARGS__) -#define DISC_LOGE(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_ERROR, DISC_LABELS[label], ##__VA_ARGS__) -#define DISC_LOGW(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_WARN, DISC_LABELS[label], ##__VA_ARGS__) -#define DISC_LOGI(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_INFO, DISC_LABELS[label], ##__VA_ARGS__) -#define DISC_LOGD(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_DEBUG, DISC_LABELS[label], ##__VA_ARGS__) +#define DISC_LOGF(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_FATAL, DISC_LABELS[label], ##__VA_ARGS__) +#define DISC_LOGE(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_ERROR, DISC_LABELS[label], ##__VA_ARGS__) +#define DISC_LOGW(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_WARN, DISC_LABELS[label], ##__VA_ARGS__) +#define DISC_LOGI(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_INFO, DISC_LABELS[label], ##__VA_ARGS__) +#define DISC_LOGD(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_DEBUG, DISC_LABELS[label], ##__VA_ARGS__) +#define DISC_CHECK_AND_RETURN_RET_LOGD(cond, ret, label, fmt, ...) \ + CHECK_AND_RETURN_RET_LOG_INNER(cond, ret, DISC_LOGD, label, fmt, ##__VA_ARGS__) #define DISC_CHECK_AND_RETURN_RET_LOGW(cond, ret, label, fmt, ...) \ CHECK_AND_RETURN_RET_LOG_INNER(cond, ret, DISC_LOGW, label, fmt, ##__VA_ARGS__) #define DISC_CHECK_AND_RETURN_RET_LOGE(cond, ret, label, fmt, ...) \ CHECK_AND_RETURN_RET_LOG_INNER(cond, ret, DISC_LOGE, label, fmt, ##__VA_ARGS__) +#define DISC_CHECK_AND_RETURN_LOGD(cond, label, fmt, ...) \ + CHECK_AND_RETURN_LOG_INNER(cond, DISC_LOGD, label, fmt, ##__VA_ARGS__) #define DISC_CHECK_AND_RETURN_LOGW(cond, label, fmt, ...) \ CHECK_AND_RETURN_LOG_INNER(cond, DISC_LOGW, label, fmt, ##__VA_ARGS__) #define DISC_CHECK_AND_RETURN_LOGE(cond, label, fmt, ...) \ diff --git a/core/common/dfx/interface/include/lnn_log.h b/core/common/dfx/interface/include/lnn_log.h index 93bd29e22..b5f2748c9 100644 --- a/core/common/dfx/interface/include/lnn_log.h +++ b/core/common/dfx/interface/include/lnn_log.h @@ -50,11 +50,11 @@ static const SoftBusLogLabel LNN_LABELS[MODULE_DOMAIN_MAX_LEN] = { { LNN_TEST, DOMAIN_ID_TEST, "LnnTest" }, }; -#define LNN_LOGF(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_FATAL, LNN_LABELS[label], ##__VA_ARGS__) -#define LNN_LOGE(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_ERROR, LNN_LABELS[label], ##__VA_ARGS__) -#define LNN_LOGW(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_WARN, LNN_LABELS[label], ##__VA_ARGS__) -#define LNN_LOGI(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_INFO, LNN_LABELS[label], ##__VA_ARGS__) -#define LNN_LOGD(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_DEBUG, LNN_LABELS[label], ##__VA_ARGS__) +#define LNN_LOGF(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_FATAL, LNN_LABELS[label], ##__VA_ARGS__) +#define LNN_LOGE(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_ERROR, LNN_LABELS[label], ##__VA_ARGS__) +#define LNN_LOGW(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_WARN, LNN_LABELS[label], ##__VA_ARGS__) +#define LNN_LOGI(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_INFO, LNN_LABELS[label], ##__VA_ARGS__) +#define LNN_LOGD(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_DEBUG, LNN_LABELS[label], ##__VA_ARGS__) #define LNN_CHECK_AND_RETURN_RET_LOGW(cond, ret, label, fmt, ...) \ CHECK_AND_RETURN_RET_LOG_INNER(cond, ret, LNN_LOGW, label, fmt, ##__VA_ARGS__) diff --git a/core/common/dfx/interface/include/softbus_log.h b/core/common/dfx/interface/include/softbus_log.h index 7accbe657..67cb46bc5 100644 --- a/core/common/dfx/interface/include/softbus_log.h +++ b/core/common/dfx/interface/include/softbus_log.h @@ -42,12 +42,12 @@ extern "C" { SoftBusLogInnerImpl(Level, Label, FILE_NAME, __LINE__, __FUNCTION__, Fmt, ##Args) typedef enum { - SOFTBUS_DFX_LOG_DEBUG = 3, - SOFTBUS_DFX_LOG_INFO = 4, - SOFTBUS_DFX_LOG_WARN = 5, - SOFTBUS_DFX_LOG_ERROR = 6, - SOFTBUS_DFX_LOG_FATAL = 7, -} SoftBusDfxLogLevel; + SOFTBUS_LOG_DEBUG = 3, + SOFTBUS_LOG_INFO = 4, + SOFTBUS_LOG_WARN = 5, + SOFTBUS_LOG_ERROR = 6, + SOFTBUS_LOG_FATAL = 7, +} SoftBusLogLevel; typedef struct { int32_t label; @@ -55,7 +55,7 @@ typedef struct { char tag[LOG_TAG_MAX_LEN]; } SoftBusLogLabel; -void SoftBusLogInnerImpl(SoftBusDfxLogLevel level, SoftBusLogLabel label, const char *fileName, int32_t lineNum, +void SoftBusLogInnerImpl(SoftBusLogLevel level, SoftBusLogLabel label, const char *fileName, int32_t lineNum, const char *funName, const char *fmt, ...); void NstackxLogInnerImpl(const char *moduleName, uint32_t logLevel, const char *fmt, ...); diff --git a/core/common/dfx/interface/include/trans_log.h b/core/common/dfx/interface/include/trans_log.h index 772efd5ee..ab09f376d 100644 --- a/core/common/dfx/interface/include/trans_log.h +++ b/core/common/dfx/interface/include/trans_log.h @@ -49,11 +49,11 @@ static const SoftBusLogLabel TRANS_LABELS[MODULE_DOMAIN_MAX_LEN] = { { TRANS_TEST, DOMAIN_ID_TEST, "TransTest" }, }; -#define TRANS_LOGF(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_FATAL, TRANS_LABELS[label], ##__VA_ARGS__) -#define TRANS_LOGE(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_ERROR, TRANS_LABELS[label], ##__VA_ARGS__) -#define TRANS_LOGW(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_WARN, TRANS_LABELS[label], ##__VA_ARGS__) -#define TRANS_LOGI(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_INFO, TRANS_LABELS[label], ##__VA_ARGS__) -#define TRANS_LOGD(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_DFX_LOG_DEBUG, TRANS_LABELS[label], ##__VA_ARGS__) +#define TRANS_LOGF(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_FATAL, TRANS_LABELS[label], ##__VA_ARGS__) +#define TRANS_LOGE(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_ERROR, TRANS_LABELS[label], ##__VA_ARGS__) +#define TRANS_LOGW(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_WARN, TRANS_LABELS[label], ##__VA_ARGS__) +#define TRANS_LOGI(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_INFO, TRANS_LABELS[label], ##__VA_ARGS__) +#define TRANS_LOGD(label, ...) (void)SOFTBUS_LOG_INNER(SOFTBUS_LOG_DEBUG, TRANS_LABELS[label], ##__VA_ARGS__) #define TRANS_CHECK_AND_RETURN_RET_LOGW(cond, ret, label, fmt, ...) \ CHECK_AND_RETURN_RET_LOG_INNER(cond, ret, TRANS_LOGW, label, fmt, ##__VA_ARGS__) @@ -63,6 +63,8 @@ static const SoftBusLogLabel TRANS_LABELS[MODULE_DOMAIN_MAX_LEN] = { CHECK_AND_RETURN_LOG_INNER(cond, TRANS_LOGW, label, fmt, ##__VA_ARGS__) #define TRANS_CHECK_AND_RETURN_LOGE(cond, label, fmt, ...) \ CHECK_AND_RETURN_LOG_INNER(cond, TRANS_LOGE, label, fmt, ##__VA_ARGS__) +#define TRANS_CHECK_AND_RETURN_LOGD(cond, label, fmt, ...) \ + CHECK_AND_RETURN_LOG_INNER(cond, TRANS_LOGD, label, fmt, ##__VA_ARGS__) #ifdef __cplusplus } diff --git a/core/common/dfx/log/src/softbus_log.c b/core/common/dfx/log/src/softbus_log.c index d364bef25..d69ea70da 100644 --- a/core/common/dfx/log/src/softbus_log.c +++ b/core/common/dfx/log/src/softbus_log.c @@ -32,7 +32,7 @@ static void SoftBusLogExtraInfoFormat(char *line, const char *fileName, int line (void)sprintf_s(line, LOG_LINE_MAX_LENGTH + 1, "[%s:%d] %s# ", fileName, lineNum, funName); } -static void SoftBusLogPrint(const char *line, SoftBusDfxLogLevel level, uint32_t domain, const char *tag) +static void SoftBusLogPrint(const char *line, SoftBusLogLevel level, uint32_t domain, const char *tag) { #ifdef SOFTBUS_PRINTF (void)level; @@ -44,7 +44,7 @@ static void SoftBusLogPrint(const char *line, SoftBusDfxLogLevel level, uint32_t #endif } -void SoftBusLogInnerImpl(SoftBusDfxLogLevel level, SoftBusLogLabel label, const char *fileName, int lineNum, +void SoftBusLogInnerImpl(SoftBusLogLevel level, SoftBusLogLabel label, const char *fileName, int lineNum, const char *funName, const char *fmt, ...) { uint32_t pos; @@ -63,7 +63,7 @@ void SoftBusLogInnerImpl(SoftBusDfxLogLevel level, SoftBusLogLabel label, const void NstackxLogInnerImpl(const char *moduleName, uint32_t logLevel, const char *fmt, ...) { - SoftBusDfxLogLevel level = NSTACKX_LOG_LEVEL_CONVERT_BASE - logLevel; + SoftBusLogLevel level = NSTACKX_LOG_LEVEL_CONVERT_BASE - logLevel; va_list args = { 0 }; char line[LOG_LINE_MAX_LENGTH + 1] = { 0 }; va_start(args, fmt); diff --git a/core/common/include/message_handler.h b/core/common/include/message_handler.h index 506ff59af..58715e4f3 100644 --- a/core/common/include/message_handler.h +++ b/core/common/include/message_handler.h @@ -64,7 +64,8 @@ enum LooperType { LOOP_TYPE_BR_SEND, LOOP_TYPE_BR_RECV, LOOP_TYPE_P2P, - LOOP_TYPE_LANE + LOOP_TYPE_LANE, + LOOP_TYPE_HANDLE_FILE }; SoftBusLooper *GetLooper(int looper); diff --git a/core/common/include/softbus_json_utils.h b/core/common/include/softbus_json_utils.h index 33cd7269c..acee50a69 100644 --- a/core/common/include/softbus_json_utils.h +++ b/core/common/include/softbus_json_utils.h @@ -20,7 +20,6 @@ #include "cJSON.h" #include "string.h" #include "stdbool.h" -#include "softbus_log_old.h" #ifdef __cplusplus #if __cplusplus diff --git a/core/common/include/softbus_log_old.h b/core/common/include/softbus_log_old.h deleted file mode 100644 index ccb74f325..000000000 --- a/core/common/include/softbus_log_old.h +++ /dev/null @@ -1,182 +0,0 @@ -/* - * 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 SOFTBUS_LOG_H -#define SOFTBUS_LOG_H - -#include -#include -#include -#include "softbus_adapter_log.h" - -#ifdef __cplusplus -#if __cplusplus -extern "C" { -#endif -#endif - -#if defined(__ICCARM__) || defined(__LITEOS_M__) -#define SOFTBUS_DPRINTF(fd, fmt, ...) -#else -#define SOFTBUS_DPRINTF(fd, fmt, ...) dprintf(fd, fmt, ##__VA_ARGS__) -#endif - -typedef enum { - SOFTBUS_LOG_AUTH, - SOFTBUS_LOG_TRAN, - SOFTBUS_LOG_CONN, - SOFTBUS_LOG_LNN, - SOFTBUS_LOG_DISC, - SOFTBUS_LOG_COMM, - SOFTBUS_LOG_MODULE_MAX, -} SoftBusLogModule; - -#define SoftBusLog(Module, Level, Fmt, Args...) SoftBusLogImpl(Module, Level, __func__, __LINE__, Fmt, ##Args) - -void SoftBusLogImpl(SoftBusLogModule module, SoftBusLogLevel level, const char* funcName, - int lineNo, const char *fmt, ...); - -void AnonyPacketPrintout(SoftBusLogModule module, const char *msg, const char *packet, size_t packetLen); - -const char *AnonyDevId(char **outName, const char *inName); - -/* Note: need call SoftBusFree(*outputStr) */ -const char *ToSecureStrDeviceID(const char *deviceId, char **outputStr); - -#define UUID_ANONYMIZED_LENGTH 4 -#define NETWORKID_ANONYMIZED_LENGTH 4 -#define UDID_ANONYMIZED_LENGTH 4 -#define MACADDR_ANONYMIZED_LENGTH 5 -#define IP_ANONYMIZED_LENGTH 4 - -const char *Anonymizes(const char *target, const uint8_t expectAnonymizedLength); - -static inline const char *AnonymizesUUID(const char *input) -{ - return Anonymizes(input, UUID_ANONYMIZED_LENGTH); -} - -static inline const char *AnonymizesNetworkID(const char *input) -{ - return Anonymizes(input, NETWORKID_ANONYMIZED_LENGTH); -} - -static inline const char *AnonymizesUDID(const char *input) -{ - return Anonymizes(input, UDID_ANONYMIZED_LENGTH); -} - -static inline const char *AnonymizesMac(const char *input) -{ - return Anonymizes(input, MACADDR_ANONYMIZED_LENGTH); -} - -inline const char *AnonymizesIp(const char *input) -{ - if (input == NULL) { - return "NULL"; - } - return Anonymizes(input, IP_ANONYMIZED_LENGTH); -} - -// discovery log print macro -#define DLOGD(fmt, ...) SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_DBG, fmt, ##__VA_ARGS__) -#define DLOGI(fmt, ...) SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_INFO, fmt, ##__VA_ARGS__) -#define DLOGW(fmt, ...) SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_WARN, fmt, ##__VA_ARGS__) -#define DLOGE(fmt, ...) SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, fmt, ##__VA_ARGS__) - -// connection log print macro -#define CLOGD(fmt, ...) SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_DBG, fmt, ##__VA_ARGS__) -#define CLOGI(fmt, ...) SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, fmt, ##__VA_ARGS__) -#define CLOGW(fmt, ...) SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_WARN, fmt, ##__VA_ARGS__) -#define CLOGE(fmt, ...) SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, fmt, ##__VA_ARGS__) - -// bus center lnn log print macro -#define LLOGD(fmt, ...) SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_DBG, fmt, ##__VA_ARGS__) -#define LLOGI(fmt, ...) SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_INFO, fmt, ##__VA_ARGS__) -#define LLOGW(fmt, ...) SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_WARN, fmt, ##__VA_ARGS__) -#define LLOGE(fmt, ...) SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, fmt, ##__VA_ARGS__) - -// transmission log print macro -#define TLOGD(fmt, ...) SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_DBG, fmt, ##__VA_ARGS__) -#define TLOGI(fmt, ...) SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, fmt, ##__VA_ARGS__) -#define TLOGW(fmt, ...) SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_WARN, fmt, ##__VA_ARGS__) -#define TLOGE(fmt, ...) SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, fmt, ##__VA_ARGS__) - -// authority log print macro -#define ALOGD(fmt, ...) SoftBusLog(SOFTBUS_LOG_AUTH, SOFTBUS_LOG_DBG, fmt, ##__VA_ARGS__) -#define ALOGI(fmt, ...) SoftBusLog(SOFTBUS_LOG_AUTH, SOFTBUS_LOG_INFO, fmt, ##__VA_ARGS__) -#define ALOGW(fmt, ...) SoftBusLog(SOFTBUS_LOG_AUTH, SOFTBUS_LOG_WARN, fmt, ##__VA_ARGS__) -#define ALOGE(fmt, ...) SoftBusLog(SOFTBUS_LOG_AUTH, SOFTBUS_LOG_ERROR, fmt, ##__VA_ARGS__) - -// common log print macro -#define MLOGD(fmt, ...) SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_DBG, fmt, ##__VA_ARGS__) -#define MLOGI(fmt, ...) SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_INFO, fmt, ##__VA_ARGS__) -#define MLOGW(fmt, ...) SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_WARN, fmt, ##__VA_ARGS__) -#define MLOGE(fmt, ...) SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, fmt, ##__VA_ARGS__) - -#define CHECK_AND_RETURN_RET_LOG(cond, ret, log, fmt, ...) \ - do { \ - if (!(cond)) { \ - log(fmt, ##__VA_ARGS__); \ - return ret; \ - } \ - } while (0) - -#define CHECK_AND_RETURN_LOG(cond, log, fmt, ...) \ - do { \ - if (!(cond)) { \ - log(fmt, ##__VA_ARGS__); \ - return; \ - } \ - } while (0) - -#define DISC_CHECK_AND_RETURN_RET_LOG(cond, ret, fmt, ...) \ - CHECK_AND_RETURN_RET_LOG(cond, ret, DLOGE, fmt, ##__VA_ARGS__) -#define DISC_CHECK_AND_RETURN_LOG(cond, fmt, ...) \ - CHECK_AND_RETURN_LOG(cond, DLOGE, fmt, ##__VA_ARGS__) - -#define CONN_CHECK_AND_RETURN_RET_LOG(cond, ret, fmt, ...) \ - CHECK_AND_RETURN_RET_LOG(cond, ret, CLOGE, fmt, ##__VA_ARGS__) -#define CONN_CHECK_AND_RETURN_LOG(cond, fmt, ...) \ - CHECK_AND_RETURN_LOG(cond, CLOGE, fmt, ##__VA_ARGS__) - -#define LNN_CHECK_AND_RETURN_RET_LOG(cond, ret, fmt, ...) \ - CHECK_AND_RETURN_RET_LOG(cond, ret, LLOGE, fmt, ##__VA_ARGS__) -#define LNN_CHECK_AND_RETURN_LOG(cond, fmt, ...) \ - CHECK_AND_RETURN_LOG(cond, LLOGE, fmt, ##__VA_ARGS__) - -#define TRAN_CHECK_AND_RETURN_RET_LOG(cond, ret, fmt, ...) \ - CHECK_AND_RETURN_RET_LOG(cond, ret, TLOGE, fmt, ##__VA_ARGS__) -#define TRAN_CHECK_AND_RETURN_LOG(cond, fmt, ...) \ - CHECK_AND_RETURN_LOG(cond, TLOGE, fmt, ##__VA_ARGS__) - -#define AUTH_CHECK_AND_RETURN_RET_LOG(cond, ret, fmt, ...) \ - CHECK_AND_RETURN_RET_LOG(cond, ret, ALOGE, fmt, ##__VA_ARGS__) -#define AUTH_CHECK_AND_RETURN_LOG(cond, fmt, ...) \ - CHECK_AND_RETURN_LOG(cond, ALOGE, fmt, ##__VA_ARGS__) - -#define COMM_CHECK_AND_RETURN_RET_LOG(cond, ret, fmt, ...) \ - CHECK_AND_RETURN_RET_LOG(cond, ret, MLOGE, fmt, ##__VA_ARGS__) -#define COMM_CHECK_AND_RETURN_LOG(cond, fmt, ...) \ - CHECK_AND_RETURN_LOG(cond, MLOGE, fmt, ##__VA_ARGS__) - -#ifdef __cplusplus -#if __cplusplus -} -#endif /* __cplusplus */ -#endif /* __cplusplus */ - -#endif /* SOFTBUS_LOG_H */ \ No newline at end of file diff --git a/core/common/json_utils/softbus_json_utils.c b/core/common/json_utils/softbus_json_utils.c index a5dfb38cc..a2a3916cb 100644 --- a/core/common/json_utils/softbus_json_utils.c +++ b/core/common/json_utils/softbus_json_utils.c @@ -30,7 +30,7 @@ int32_t GetStringItemByJsonObject(const cJSON *json, const char * const string, } cJSON *item = cJSON_GetObjectItemCaseSensitive(json, string); if (item == NULL || !cJSON_IsString(item)) { - COMM_LOGE(COMM_UTILS, "Cannot find or invalid [%s]", string); + COMM_LOGD(COMM_UTILS, "Cannot find or invalid [%s]", string); return SOFTBUS_ERR; } uint32_t length = strlen(item->valuestring); @@ -55,7 +55,7 @@ bool GetJsonObjectStringItem(const cJSON *json, const char * const string, char } cJSON *item = cJSON_GetObjectItemCaseSensitive(json, string); if (item == NULL || !cJSON_IsString(item)) { - COMM_LOGE(COMM_UTILS, "Cannot find or invalid [%s]", string); + COMM_LOGD(COMM_UTILS, "Cannot find or invalid [%s]", string); return false; } uint32_t length = strlen(item->valuestring); @@ -79,7 +79,7 @@ bool GetJsonObjectNumberItem(const cJSON *json, const char * const string, int32 } cJSON *item = cJSON_GetObjectItemCaseSensitive(json, string); if (item == NULL || !cJSON_IsNumber(item) || (item->valuedouble < 0)) { - COMM_LOGE(COMM_UTILS, "Cannot find or invalid [%s]", string); + COMM_LOGD(COMM_UTILS, "Cannot find or invalid [%s]", string); return false; } *target = (int32_t)item->valuedouble; @@ -94,7 +94,7 @@ bool GetJsonObjectSignedNumberItem(const cJSON *json, const char * const string, } cJSON *item = cJSON_GetObjectItemCaseSensitive(json, string); if (item == NULL || !cJSON_IsNumber(item)) { - COMM_LOGE(COMM_UTILS, "Cannot find or invalid [%s]", string); + COMM_LOGD(COMM_UTILS, "Cannot find or invalid [%s]", string); return false; } *target = (int32_t)item->valuedouble; @@ -109,7 +109,7 @@ bool GetJsonObjectDoubleItem(const cJSON *json, const char * const string, doubl } cJSON* item = cJSON_GetObjectItemCaseSensitive(json, string); if (item == NULL || !cJSON_IsNumber(item)) { - COMM_LOGE(COMM_UTILS, "Cannot find or invalid [%s]", string); + COMM_LOGD(COMM_UTILS, "Cannot find or invalid [%s]", string); return false; } *target = item->valuedouble; @@ -124,7 +124,7 @@ bool GetJsonObjectNumber16Item(const cJSON *json, const char * const string, uin } cJSON *item = cJSON_GetObjectItemCaseSensitive(json, string); if (item == NULL || !cJSON_IsNumber(item) || (item->valuedouble < 0)) { - COMM_LOGE(COMM_UTILS, "Cannot find or invalid [%s]", string); + COMM_LOGD(COMM_UTILS, "Cannot find or invalid [%s]", string); return false; } *target = (uint16_t)item->valuedouble; @@ -139,7 +139,7 @@ bool GetJsonObjectNumber64Item(const cJSON *json, const char * const string, int } cJSON *item = cJSON_GetObjectItemCaseSensitive(json, string); if (item == NULL || !cJSON_IsNumber(item) || (item->valuedouble < 0)) { - COMM_LOGE(COMM_UTILS, "Cannot find or invalid [%s]", string); + COMM_LOGD(COMM_UTILS, "Cannot find or invalid [%s]", string); return false; } *target = (int64_t)item->valuedouble; @@ -154,7 +154,7 @@ bool GetJsonObjectSignedNumber64Item(const cJSON *json, const char * const strin } cJSON *item = cJSON_GetObjectItemCaseSensitive(json, string); if (item == NULL || !cJSON_IsNumber(item)) { - COMM_LOGE(COMM_UTILS, "Cannot find or invalid [%s]", string); + COMM_LOGD(COMM_UTILS, "Cannot find or invalid [%s]", string); return false; } *target = (int64_t)item->valuedouble; @@ -169,7 +169,7 @@ bool GetJsonObjectInt32Item(const cJSON *json, const char * const string, int32_ } cJSON *item = cJSON_GetObjectItemCaseSensitive(json, string); if (item == NULL || !cJSON_IsNumber(item)) { - COMM_LOGE(COMM_UTILS, "Cannot find or invalid [%s]", string); + COMM_LOGD(COMM_UTILS, "Cannot find or invalid [%s]", string); return false; } *target = (int32_t)item->valuedouble; @@ -184,7 +184,7 @@ bool GetJsonObjectBoolItem(const cJSON *json, const char * const string, bool *t } cJSON *item = cJSON_GetObjectItemCaseSensitive(json, string); if (item == NULL || !cJSON_IsBool(item)) { - COMM_LOGE(COMM_UTILS, "Cannot find or invalid [%s]", string); + COMM_LOGD(COMM_UTILS, "Cannot find or invalid [%s]", string); return false; } *target = (bool)item->valueint; @@ -199,7 +199,7 @@ bool AddStringToJsonObject(cJSON *json, const char * const string, const char *v } cJSON *item = cJSON_CreateString(value); if (item == NULL) { - COMM_LOGE(COMM_UTILS, "Cannot create cJSON string object [%s]", string); + COMM_LOGD(COMM_UTILS, "Cannot create cJSON string object [%s]", string); return false; } if (!cJSON_AddItemToObject(json, string, item)) { @@ -314,7 +314,7 @@ char *GetDynamicStringItemByJsonObject(const cJSON * const json, const char * co cJSON *item = cJSON_GetObjectItemCaseSensitive(json, string); if (item == NULL || !cJSON_IsString(item)) { - COMM_LOGE(COMM_EVENT, "Cannot find or invalid [%s]", string); + COMM_LOGD(COMM_EVENT, "Cannot find or invalid [%s]", string); return NULL; } uint32_t length = strlen(item->valuestring); diff --git a/core/common/log/softbus_log_old.c b/core/common/log/softbus_log_old.c deleted file mode 100644 index 260d89d8c..000000000 --- a/core/common/log/softbus_log_old.c +++ /dev/null @@ -1,308 +0,0 @@ -/* - * 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 "softbus_log_old.h" - -#include -#include -#include - -#include "softbus_adapter_mem.h" -#include "softbus_common.h" -#include "softbus_errcode.h" -#include "softbus_feature_config.h" -#include "softbus_utils.h" - -#define LOG_NAME_MAX_LEN 12 -#ifndef SOFTBUS_DEBUG -#define LOG_PRINT_MAX_LEN 256 -#else -#define LOG_PRINT_MAX_LEN 512 -#endif - -// anonymize should mask more than half of the string -#define EXPECTED_ANONYMIZED_TIMES 2 - -#define PMATCH_SIZE 2 -#define REG_ID_PATTERN "[0-9A-Za-z]{64}" -#define REG_IDT_PATTERN "\\\"[0-9A-Za-z]{32}\\\"" -#define REG_IP_PATTERN "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}" -#define REG_MAC_PATTERN "([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}" -#define REG_KEY_PATTERN "[0-9A-Za-z+-//]{43}=" -#define REG_PATTERN_MAX_LEN 256 -#define INLEN_MULTIPLE_FACTOR 2 - -#define PLAINTEXT_LEN_SHORT 1 -#define PLAINTEXT_LEN_NORMAL 4 -#define ANONYMIZE_LEN 6 -#define SHORT_ID_LENGTH 20 -#define SESSION_NAME_DEVICE_ID_LEN 96 -#define SESSION_NAME_DEVICE_PATTERN "([0-9A-Z]{32}){1,3}" -#define CUST_NSTACKX_DFINDER_LOG 5 - -static int32_t g_logLevel; - -typedef struct { - SoftBusLogModule mod; - char name[LOG_NAME_MAX_LEN]; -} LogInfo; - -typedef enum { - ANONYMIZE_NORMAL = 1, - ANONYMIZE_ENHANCE -} AnonymizeMode; - -static LogInfo g_logInfo[SOFTBUS_LOG_MODULE_MAX] = { - {SOFTBUS_LOG_AUTH, "Auth"}, - {SOFTBUS_LOG_TRAN, "Tran"}, - {SOFTBUS_LOG_CONN, "Conn"}, - {SOFTBUS_LOG_LNN, "Lnn"}, - {SOFTBUS_LOG_DISC, "Disc"}, - {SOFTBUS_LOG_COMM, "Comm"}, -}; - -void SoftBusLogImpl(SoftBusLogModule module, SoftBusLogLevel level, const char* funcName, - int lineNo, const char *fmt, ...) -{ - uint32_t ulPos; - char szStr[LOG_PRINT_MAX_LEN] = {0}; - va_list arg; - int32_t ret; - - if (module >= SOFTBUS_LOG_MODULE_MAX || level >= SOFTBUS_LOG_LEVEL_MAX) { - HILOG_ERROR(SOFTBUS_HILOG_ID, "[COMM]softbus log type or module error"); - return; - } - - SoftbusGetConfig(SOFTBUS_INT_ADAPTER_LOG_LEVEL, (unsigned char *)&g_logLevel, sizeof(g_logLevel)); - if ((int32_t)level < g_logLevel) { - return; - } - - ret = sprintf_s(szStr, sizeof(szStr), "[%s][%s:%d]", g_logInfo[module].name, funcName, lineNo); - if (ret < 0) { - HILOG_ERROR(SOFTBUS_HILOG_ID, "[COMM]softbus log error"); - return; - } - ulPos = strlen(szStr); - (void)memset_s(&arg, sizeof(va_list), 0, sizeof(va_list)); - va_start(arg, fmt); - ret = vsprintf_s(&szStr[ulPos], sizeof(szStr) - ulPos, fmt, arg); - va_end(arg); - if (ret < 0) { - HILOG_WARN(SOFTBUS_HILOG_ID, "[COMM]softbus log len error"); - return; - } - SoftBusOutPrint(szStr, level); - - return; -} - -const char *Anonymizes(const char *target, const uint8_t expectAnonymizedLength) -{ - if (target == NULL) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "Anonymizes target is null"); - return "NULL"; - } - if (expectAnonymizedLength == 0) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "Anonymizes expectAnonymizedLength=0"); - return "BADLENGTH"; - } - size_t targetLen = strlen(target); - if (targetLen / expectAnonymizedLength < EXPECTED_ANONYMIZED_TIMES) { - return "TOOSHORT"; - } - - return target + (targetLen - expectAnonymizedLength); -} - -static int32_t AnonymizeRegInit(regex_t *preg, const char *pattern) -{ - if (regcomp(preg, pattern, REG_EXTENDED) != 0) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "init anonymize reg: compile reg pattern fail"); - return SOFTBUS_ERR; - } - return SOFTBUS_OK; -} - -static void AnonymizeRegDeinit(regex_t *preg) -{ - regfree(preg); -} - -static int32_t AnonymizeStringProcess(char *str, size_t len, AnonymizeMode mode) -{ - if (len < ANONYMIZE_LEN || mode == ANONYMIZE_ENHANCE) { - if (strcpy_s(str, len, "******") != EOK) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "anonymize string: strncpy fail."); - return SOFTBUS_MEM_ERR; - } - } else { - uint32_t plaintextLen = len < SHORT_ID_LENGTH ? PLAINTEXT_LEN_SHORT : PLAINTEXT_LEN_NORMAL; - if (memset_s(str + plaintextLen, len - plaintextLen, '*', ANONYMIZE_LEN) != EOK) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "anonymize string: memset fail."); - return SOFTBUS_MEM_ERR; - } - uint32_t offset = plaintextLen + ANONYMIZE_LEN; - if (strncpy_s(str + offset, len - offset, str + len - plaintextLen, plaintextLen) != EOK) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "anonymize string: strncpy fail."); - return SOFTBUS_MEM_ERR; - } - } - return SOFTBUS_OK; -} - -static int32_t AnonymizeString(char **output, const char *in, size_t inLen, const char *pattern, AnonymizeMode mode) -{ - if (in == NULL) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "anonymize string: in is null"); - return SOFTBUS_INVALID_PARAM; - } - - char *str = (char *)SoftBusCalloc(inLen + 1); - if (str == NULL) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "anonymize string: malloc fail."); - return SOFTBUS_MEM_ERR; - } - if (strcpy_s(str, inLen + 1, in) != EOK) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "anonymize string: strcpy fail."); - SoftBusFree(str); - return SOFTBUS_MEM_ERR; - } - regex_t preg; - if (AnonymizeRegInit(&preg, pattern) != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "anonymize string: init reg failed."); - SoftBusFree(str); - return SOFTBUS_ERR; - } - regmatch_t pmatch[PMATCH_SIZE]; - (void)memset_s(pmatch, sizeof(regmatch_t) * PMATCH_SIZE, 0, sizeof(regmatch_t) * PMATCH_SIZE); - char *outexec = str; - do { - if (regexec(&preg, outexec, PMATCH_SIZE, pmatch, 0) != 0) { - break; - } - regoff_t start = pmatch[0].rm_so; - regoff_t end = pmatch[0].rm_eo; - if (start != end) { - if (AnonymizeStringProcess(outexec + start, end - start, mode) != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "anonymizeStringProcess fail"); - SoftBusFree(str); - AnonymizeRegDeinit(&preg); - return SOFTBUS_ERR; - } - int32_t offset = start + (int32_t)strlen(outexec + start); - char tmpStr[inLen + 1]; - if (strcpy_s(tmpStr, inLen + 1, outexec + end) != EOK || strcat_s(str, inLen, tmpStr) != EOK) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "anonymize string: strcat fail."); - break; - } - outexec += offset; - } - } while (true); - *output = str; - AnonymizeRegDeinit(&preg); - return SOFTBUS_OK; -} - -void AnonyPacketPrintout(SoftBusLogModule module, const char *msg, const char *packet, - size_t packetLen) -{ - if (!GetSignalingMsgSwitch()) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "anonymize packet: GetSignalingMsgSwitch fail"); - return; - } - if (msg == NULL) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "anonymize packet: msg is null."); - return; - } - if (packet == NULL || packetLen == 0) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "anonymize packet: packet is null."); - return; - } - if (packetLen > LOG_PRINT_MAX_LEN * INLEN_MULTIPLE_FACTOR) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "anonymize packet: packet is too long."); - return; - } - -#ifdef __LITEOS_M__ - SoftBusLog(module, SOFTBUS_LOG_INFO, "%s******", msg); -#else - char pattern[REG_PATTERN_MAX_LEN] = {0}; - if (sprintf_s(pattern, REG_PATTERN_MAX_LEN, "%s|%s|%s|%s|%s", - REG_ID_PATTERN, REG_IDT_PATTERN, REG_IP_PATTERN, REG_MAC_PATTERN, REG_KEY_PATTERN) < 0) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "anonymize packet: concatenate reg pattern fail"); - return; - } - char *anonymizedOut = NULL; - int32_t ret = AnonymizeString(&anonymizedOut, packet, packetLen, pattern, ANONYMIZE_NORMAL); - if (ret == SOFTBUS_OK) { - SoftBusLog(module, SOFTBUS_LOG_INFO, "%s%s", msg, anonymizedOut); - SoftBusFree(anonymizedOut); - } -#endif -} - -const char *AnonyDevId(char **outName, const char *inName) -{ - if (inName == NULL) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "inName is null."); - return "null"; - } - if (strlen(inName) < SESSION_NAME_DEVICE_ID_LEN) { - return inName; - } -#ifdef __LITEOS_M__ - return "******"; -#else - if (AnonymizeString(outName, inName, strlen(inName), SESSION_NAME_DEVICE_PATTERN, ANONYMIZE_NORMAL) != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "anony sessionname fail."); - return "******"; - } - return *outName; -#endif -} - -static inline void StringAppend(char *dst, uint32_t size, const char *src, uint32_t start, uint32_t nSize) -{ - uint32_t len = strlen(dst); - if (strncpy_s(dst + len, size - len, src + start, nSize) != EOK) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "strncpy_s outputStr fail."); - } -} - -const char *ToSecureStrDeviceID(const char *deviceId, char **outputStr) -{ -#define SECURE_PRINT_PREFIX_LEN 4 -#define SECURE_PRINT_SUFFIX_LEN 4 -#define SECURE_PRINT_STARKEY_SIZE 3 - if (deviceId == NULL || outputStr == NULL) { - return "unknown"; - } - uint32_t deviceIdLen = strlen(deviceId); - if (deviceIdLen < SECURE_PRINT_PREFIX_LEN + SECURE_PRINT_SUFFIX_LEN) { - return "unknown"; - } - uint32_t outputSize = SECURE_PRINT_PREFIX_LEN + SECURE_PRINT_SUFFIX_LEN + SECURE_PRINT_STARKEY_SIZE + 1; - *outputStr = (char *)SoftBusCalloc(outputSize); - if (*outputStr == NULL) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "malloc outputStr fail."); - return "unknown"; - } - StringAppend(*outputStr, outputSize, deviceId, 0, SECURE_PRINT_PREFIX_LEN); - StringAppend(*outputStr, outputSize, "***", 0, SECURE_PRINT_STARKEY_SIZE); - StringAppend(*outputStr, outputSize, deviceId, deviceIdLen - SECURE_PRINT_SUFFIX_LEN, SECURE_PRINT_SUFFIX_LEN); - return *outputStr; -} diff --git a/core/common/message_handler/message_handler.c b/core/common/message_handler/message_handler.c index 0ee3b402d..dade19b8e 100644 --- a/core/common/message_handler/message_handler.c +++ b/core/common/message_handler/message_handler.c @@ -96,7 +96,7 @@ static void *LoopTask(void *arg) return NULL; } - COMM_LOGI(COMM_UTILS, "LoopTask[%s] running", context->name); + COMM_LOGD(COMM_UTILS, "LoopTask[%s] running", context->name); if (SoftBusMutexLock(&context->lock) != 0) { COMM_LOGE(COMM_UTILS, "lock failed"); @@ -454,7 +454,7 @@ SoftBusLooper *CreateNewLooper(const char *name) return NULL; } g_looperCnt++; - COMM_LOGI(COMM_UTILS, "[%s]wait looper start ok", context->name); + COMM_LOGD(COMM_UTILS, "[%s]wait looper start ok", context->name); return looper; } @@ -468,7 +468,8 @@ static struct LoopConfigItem g_loopConfig[] = { {LOOP_TYPE_BR_SEND, NULL}, {LOOP_TYPE_BR_RECV, NULL}, {LOOP_TYPE_P2P, NULL}, - {LOOP_TYPE_LANE, NULL} + {LOOP_TYPE_LANE, NULL}, + {LOOP_TYPE_HANDLE_FILE, NULL} }; SoftBusLooper *GetLooper(int type) @@ -558,11 +559,18 @@ int LooperInit(void) { SoftBusLooper *looper = CreateNewLooper("BusCenter"); if (!looper) { - COMM_LOGE(COMM_UTILS, "init looper fail."); + COMM_LOGE(COMM_UTILS, "init BusCenter looper fail."); return SOFTBUS_ERR; } SetLooper(LOOP_TYPE_DEFAULT, looper); - COMM_LOGI(COMM_UTILS, "init looper success."); + + SoftBusLooper *handleFileLooper = CreateNewLooper("HandleFile"); + if (!handleFileLooper) { + COMM_LOGE(COMM_UTILS, "init HandleFile looper fail."); + return SOFTBUS_ERR; + } + SetLooper(LOOP_TYPE_HANDLE_FILE, handleFileLooper); + COMM_LOGD(COMM_UTILS, "init looper success."); return SOFTBUS_OK; } diff --git a/core/common/security/permission/common/permission_entry.c b/core/common/security/permission/common/permission_entry.c index 90d838e8b..506ec488a 100644 --- a/core/common/security/permission/common/permission_entry.c +++ b/core/common/security/permission/common/permission_entry.c @@ -183,7 +183,7 @@ static SoftBusAppInfo *ProcessAppInfo(cJSON *object) COMM_LOGE(COMM_PERM, "pkgname is too long"); goto EXIT; } - COMM_LOGI(COMM_PERM, "appInfo has no pkgname"); + COMM_LOGD(COMM_PERM, "appInfo has no pkgname"); } if (GetJsonObjectStringItem(object, APP_INFO_TYPE_STR, mapKey, TEMP_STR_MAX_LEN)) { appInfo->type = GetPeMapValue(mapKey); @@ -276,14 +276,14 @@ static int32_t CompareString(const char *src, const char *dest, bool regexp) return SOFTBUS_PERMISSION_DENIED; } if (regexec(®Comp, dest, 0, NULL, 0) == 0) { - COMM_LOGI(COMM_PERM, "src:%s dest:%s", src, dest); + COMM_LOGD(COMM_PERM, "src:%s dest:%s", src, dest); regfree(®Comp); return SOFTBUS_OK; } regfree(®Comp); } else { if (strcmp(src, dest) == 0) { - COMM_LOGI(COMM_PERM, "src:%s dest:%s", src, dest); + COMM_LOGD(COMM_PERM, "src:%s dest:%s", src, dest); return SOFTBUS_OK; } } @@ -553,7 +553,7 @@ bool PermIsSecLevelPublic(const char *sessionName) } } (void)SoftBusMutexUnlock(&g_permissionEntryList->lock); - COMM_LOGI(COMM_PERM, "PermIsSecLevelPublic: %s is %d", sessionName, ret); + COMM_LOGD(COMM_PERM, "PermIsSecLevelPublic: %s is %d", sessionName, ret); return ret; } @@ -628,14 +628,14 @@ int32_t AddDynamicPermission(int32_t callingUid, int32_t callingPid, const char } if (HaveGrantedPermission(sessionName)) { - COMM_LOGE(COMM_PERM, "dynamic permission already granted"); + COMM_LOGD(COMM_PERM, "dynamic permission already granted"); SoftBusMutexUnlock(&g_dynamicPermissionList->lock); return SOFTBUS_OK; } SoftBusPermissionEntry *permissionEntry = (SoftBusPermissionEntry *)SoftBusCalloc(sizeof(SoftBusPermissionEntry)); if (permissionEntry == NULL) { - SoftBusLog(SOFTBUS_LOG_LNN, SOFTBUS_LOG_ERROR, "AddDynamicPermission malloc failed!"); + COMM_LOGE(COMM_PERM, "AddDynamicPermission malloc failed!"); SoftBusMutexUnlock(&g_dynamicPermissionList->lock); return SOFTBUS_MALLOC_ERR; } @@ -652,7 +652,7 @@ int32_t AddDynamicPermission(int32_t callingUid, int32_t callingPid, const char g_dynamicPermissionList->cnt++; SoftBusMutexUnlock(&g_dynamicPermissionList->lock); - COMM_LOGI(COMM_PERM, "%s dynamic permission granted", sessionName); + COMM_LOGD(COMM_PERM, "%s dynamic permission granted", sessionName); return SOFTBUS_OK; } @@ -677,4 +677,4 @@ int32_t DeleteDynamicPermission(const char *sessionName) } SoftBusMutexUnlock(&g_dynamicPermissionList->lock); return SOFTBUS_NOT_FIND; -} \ No newline at end of file +} diff --git a/core/common/security/permission/include/access_control.h b/core/common/security/permission/include/access_control.h new file mode 100644 index 000000000..17ae1e8f6 --- /dev/null +++ b/core/common/security/permission/include/access_control.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2023 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 ACCESS_CONTROL_H +#define ACCESS_CONTROL_H + +int32_t TransCheckAccessControl(const char *peerDeviceId); + +#endif /* ACCESS_CONTROL_H */ diff --git a/core/common/security/permission/permission.gni b/core/common/security/permission/permission.gni index eb60fce9c..583d2a930 100644 --- a/core/common/security/permission/permission.gni +++ b/core/common/security/permission/permission.gni @@ -47,4 +47,14 @@ if (defined(ohos_lite)) { ] softbus_permission_deps = [ "//third_party/cJSON:cjson" ] softbus_permission_external_deps += [ "c_utils:utils" ] + if (!defined(global_parts_info) || + defined(global_parts_info.deviceprofile_device_info_manager)) { + softbus_permission_external_deps += [ + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", + ] + softbus_permission_src += [ "$dsoftbus_core_path/common/security/permission/standard/access_control.cpp" ] + } else { + softbus_permission_src += [ "$dsoftbus_core_path/common/security/permission/standard/access_control_virtual.cpp" ] + } } diff --git a/core/common/security/permission/softbus_trans_permission.json b/core/common/security/permission/softbus_trans_permission.json index 4e28d12bf..6e32e2f19 100644 --- a/core/common/security/permission/softbus_trans_permission.json +++ b/core/common/security/permission/softbus_trans_permission.json @@ -12,7 +12,7 @@ ] }, { - "SESSION_NAME": "distributeddata-default", + "SESSION_NAME": "distributeddata-default*", "REGEXP": "true", "DEVID": "UUID", "SEC_LEVEL": "public", diff --git a/core/common/security/permission/standard/access_control.cpp b/core/common/security/permission/standard/access_control.cpp new file mode 100644 index 000000000..655de46de --- /dev/null +++ b/core/common/security/permission/standard/access_control.cpp @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2023 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 +#include +#include + +#include "accesstoken_kit.h" +#include "access_control_profile.h" +#include "anonymizer.h" +#include "bus_center_info_key.h" +#include "bus_center_manager.h" +#include "comm_log.h" +#include "distributed_device_profile_client.h" +#include "distributed_device_profile_enums.h" +#include "ipc_skeleton.h" +#include "softbus_adapter_mem.h" +#include "softbus_def.h" +#include "softbus_errcode.h" + +using namespace OHOS::DistributedDeviceProfile; +int32_t TransCheckAccessControl(const char *peerDeviceId) +{ + if (peerDeviceId == nullptr) { + COMM_LOGE(COMM_PERM, "peerDeviceId is null"); + return SOFTBUS_ERR; + } + + int32_t firstCallingId = OHOS::IPCSkeleton::GetFirstTokenID(); + COMM_LOGI(COMM_PERM, "FirstCaller:%d", firstCallingId); + if (firstCallingId == 0) { + return SOFTBUS_OK; + } + + char *tmpName = nullptr; + Anonymize(peerDeviceId, &tmpName); + COMM_LOGI(COMM_PERM, "peerDeviceId:%s", tmpName); + AnonymizeFree(tmpName); + + char deviceId[UDID_BUF_LEN] = {0}; + if (LnnGetRemoteStrInfo(peerDeviceId, STRING_KEY_DEV_UDID, deviceId, sizeof(deviceId)) != SOFTBUS_OK) { + COMM_LOGE(COMM_PERM, "LnnGetRemoteStrInfo udid failed"); + return SOFTBUS_ERR; + } + Anonymize(deviceId, &tmpName); + COMM_LOGI(COMM_PERM, "deviceId:%s", tmpName); + AnonymizeFree(tmpName); + + std::string active = std::to_string(static_cast(Status::ACTIVE)); + std::vector profile; + std::map parms; + std::string firstTokenIdStr = std::to_string(firstCallingId); + parms.insert({{"tokenId", firstTokenIdStr}, {"trustDeviceId", deviceId}, {"status", active}}); + + int32_t ret = DistributedDeviceProfileClient::GetInstance().GetAccessControlProfile(parms, profile); + COMM_LOGI(COMM_PERM, "profile size:%d ret:%d", profile.size(), ret); + if (profile.empty()) { + return SOFTBUS_ERR; + } + for (auto &item : profile) { + COMM_LOGI(COMM_PERM, "GetBindLevel:%d GetBindType:%d", item.GetBindLevel(), item.GetBindType()); + } + + return SOFTBUS_OK; +} diff --git a/core/common/security/permission/standard/access_control_virtual.cpp b/core/common/security/permission/standard/access_control_virtual.cpp new file mode 100644 index 000000000..e32c90c4c --- /dev/null +++ b/core/common/security/permission/standard/access_control_virtual.cpp @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2023 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 "stdint.h" +#include "access_control.h" +#include "softbus_error_code.h" + +int32_t TransCheckAccessControl(const char *peerDeviceId) +{ + (void)peerDeviceId; + return SOFTBUS_OK; +} diff --git a/core/common/security/permission/standard/permission_utils.cpp b/core/common/security/permission/standard/permission_utils.cpp index 6019db4d6..84f717e25 100644 --- a/core/common/security/permission/standard/permission_utils.cpp +++ b/core/common/security/permission/standard/permission_utils.cpp @@ -17,7 +17,6 @@ #include "comm_log.h" #include "softbus_errcode.h" -#include "softbus_log_old.h" extern "C" int32_t IsValidPkgName(int32_t uid, const char *pkgName) { diff --git a/core/common/security/permission/standard/softbus_permission.cpp b/core/common/security/permission/standard/softbus_permission.cpp index 661f1bb0f..ee23adf40 100644 --- a/core/common/security/permission/standard/softbus_permission.cpp +++ b/core/common/security/permission/standard/softbus_permission.cpp @@ -25,7 +25,6 @@ #include "softbus_adapter_mem.h" #include "softbus_def.h" #include "softbus_errcode.h" -#include "softbus_log_old.h" #include "system_ability_definition.h" #include "trans_session_manager.h" diff --git a/core/common/utils/softbus_utils.c b/core/common/utils/softbus_utils.c index b0c2b92f7..bdc3df81d 100644 --- a/core/common/utils/softbus_utils.c +++ b/core/common/utils/softbus_utils.c @@ -26,7 +26,6 @@ #include "softbus_common.h" #include "softbus_def.h" #include "softbus_errcode.h" -#include "softbus_log_old.h" #define MAC_BIT_ZERO 0 @@ -213,7 +212,7 @@ int32_t ConvertBytesToHexString(char *outBuf, uint32_t outBufLen, const unsigned uint32_t inLen) { if ((outBuf == NULL) || (inBuf == NULL) || (outBufLen < HEXIFY_LEN(inLen))) { - COMM_LOGE(COMM_UTILS, "outBufLen=%d inLen=%d", outBufLen, inLen); + COMM_LOGD(COMM_UTILS, "outBufLen=%d inLen=%d", outBufLen, inLen); return SOFTBUS_ERR; } @@ -487,16 +486,12 @@ void SignalingMsgPrint(const char *distinguish, unsigned char *data, unsigned ch COMM_LOGE(COMM_UTILS, "intercept signaling msg faile"); return; } - if (module == SOFTBUS_LOG_DISC) { - SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_INFO, "[signaling]:%s, len:%d, data:%s", - distinguish, dataLen, signalingMsgBuf); - } } void MacInstead(char *data, uint32_t length, char delimiter) { if (length > MAX_MAC_LEN) { - SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "MacInstead len is invalid"); + COMM_LOGE(COMM_UTILS, "MacInstead len is invalid"); return; } int delimiterCnt = 0; @@ -516,7 +511,7 @@ void MacInstead(char *data, uint32_t length, char delimiter) void IpInstead(char *data, uint32_t length, char delimiter) { if (length > MAX_IP_LEN) { - SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "IpInstead len is invalid"); + COMM_LOGE(COMM_UTILS, "IpInstead len is invalid"); return; } int delimiterCnt = 0; @@ -536,7 +531,7 @@ void IpInstead(char *data, uint32_t length, char delimiter) void IdInstead(char *data, uint32_t length) { if (length > MAX_ID_LEN) { - SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "IdInstead len is invalid"); + COMM_LOGE(COMM_UTILS, "IdInstead len is invalid"); return; } uint32_t halfLen = length / GET_ID_HALF_LEN; @@ -597,4 +592,4 @@ int32_t GenerateStrHashAndConvertToHexString(const unsigned char *str, uint32_t return ret; } return SOFTBUS_OK; -} \ No newline at end of file +} diff --git a/core/common/utils/sqlite3_utils.c b/core/common/utils/sqlite3_utils.c index 03167e1be..5e64dafaa 100644 --- a/core/common/utils/sqlite3_utils.c +++ b/core/common/utils/sqlite3_utils.c @@ -433,7 +433,7 @@ int32_t GetRecordNumByKey(DbContext *ctx, TableNameID id, uint8_t *data) } int32_t QueryRecordByKey(DbContext *ctx, TableNameID id, uint8_t *data, - uint8_t **replyInfo, int infoNum) + uint8_t **replyInfo, int32_t infoNum) { int32_t rc; int32_t num = 0; diff --git a/core/connection/ble/src/ble_protocol_interface_factory.c b/core/connection/ble/src/ble_protocol_interface_factory.c index 6fdc69353..edd14bdda 100644 --- a/core/connection/ble/src/ble_protocol_interface_factory.c +++ b/core/connection/ble/src/ble_protocol_interface_factory.c @@ -14,6 +14,7 @@ */ #include "ble_protocol_interface_factory.h" +#include "conn_log.h" #include "softbus_common.h" #include "softbus_conn_ble_connection.h" #include "softbus_conn_ble_client.h" @@ -38,6 +39,7 @@ static BleUnifyInterface g_bleUnifyInterface[BLE_PROTOCOL_MAX] = { const BleUnifyInterface *ConnBleGetUnifyInterface(BleProtocolType type) { if (type != BLE_GATT) { + CONN_LOGE(CONN_BLE, "Failed to return type."); return NULL; } return &g_bleUnifyInterface[type]; diff --git a/core/connection/ble/src/softbus_conn_ble_client.c b/core/connection/ble/src/softbus_conn_ble_client.c index 6de186b1e..4b0d5f974 100644 --- a/core/connection/ble/src/softbus_conn_ble_client.c +++ b/core/connection/ble/src/softbus_conn_ble_client.c @@ -15,7 +15,8 @@ #include "softbus_conn_ble_client.h" -#include "securec.h" +#include + #include "conn_log.h" #include "message_handler.h" #include "softbus_adapter_ble_gatt_client.h" @@ -24,8 +25,6 @@ #include "softbus_conn_ble_manager.h" #include "softbus_conn_common.h" #include "softbus_def.h" -#include "softbus_errcode.h" -#include "softbus_type_def.h" #include "softbus_utils.h" #include "legacy_ble_channel.h" #include "conn_event.h" @@ -400,6 +399,7 @@ static void BleGattcRegisterNotificationCallback(int32_t underlayerHandle, int32 SoftBusFree(ctx); } } + static int32_t SwitchNotifacatedHandler( enum ConnBleConnectionState state, const CommonStatusContext *ctx, ConnBleConnection *connection) { @@ -422,6 +422,7 @@ static int32_t SwitchNotifacatedHandler( } return rc; } + static void NotificatedMsgHandler(const CommonStatusContext *ctx) { GattServiceType serviceId = GATT_SERVICE_TYPE_UNKOWN; diff --git a/core/connection/ble/src/softbus_conn_ble_connection.c b/core/connection/ble/src/softbus_conn_ble_connection.c index 736ef6559..c16ac5a32 100644 --- a/core/connection/ble/src/softbus_conn_ble_connection.c +++ b/core/connection/ble/src/softbus_conn_ble_connection.c @@ -20,9 +20,7 @@ #include "conn_log.h" #include "bus_center_manager.h" #include "softbus_adapter_mem.h" -#include "softbus_conn_ble_client.h" #include "softbus_conn_ble_manager.h" -#include "softbus_conn_ble_server.h" #include "softbus_conn_ble_trans.h" #include "softbus_conn_common.h" #include "softbus_datahead_transform.h" @@ -98,7 +96,6 @@ ConnBleConnection *ConnBleCreateConnection( return NULL; } connection->sequence = 0; - connection->buffer.seq = 0; connection->buffer.total = 0; ListInit(&connection->buffer.packets); @@ -117,7 +114,6 @@ ConnBleConnection *ConnBleCreateConnection( // ble connection need exchange connection reference even if establish first time, so the init value is 0 connection->connectionRc = 0; connection->objectRc = 1; - connection->retrySearchServiceCnt = 0; SoftBusBtUuid serviceUuid = { @@ -299,7 +295,7 @@ int32_t ConnBleDisconnectNow(ConnBleConnection *connection, enum ConnBleDisconne const BleUnifyInterface *interface = ConnBleGetUnifyInterface(connection->protocol); CONN_CHECK_AND_RETURN_RET_LOGW(interface != NULL, SOFTBUS_ERR, CONN_BLE, "ble connection disconnect failed, protocol not support"); - CONN_LOGW(CONN_BLE, "receive ble disconnect now, connId=%u, side=%d, reason=%d", connection->connectionId, + CONN_LOGI(CONN_BLE, "receive ble disconnect now, connId=%u, side=%d, reason=%d", connection->connectionId, connection->side, reason); ConnRemoveMsgFromLooper( &g_bleConnectionAsyncHandler, MSG_CONNECTION_IDLE_DISCONNECT_TIMEOUT, connection->connectionId, 0, NULL); @@ -311,7 +307,6 @@ int32_t ConnBleDisconnectNow(ConnBleConnection *connection, enum ConnBleDisconne return interface->bleServerDisconnect(connection); } - static void OnDisconnectedDataFinished(uint32_t connectionId, int32_t error) { if (error != SOFTBUS_OK) { @@ -329,6 +324,7 @@ int32_t ConnBleUpdateConnectionRc(ConnBleConnection *connection, uint16_t challe { int32_t status = SoftBusMutexLock(&connection->lock); if (status != SOFTBUS_OK) { + CONN_LOGE(CONN_BLE, "Lock faild, err=%d", status); return SOFTBUS_LOCK_ERR; } int32_t underlayerHandle = connection->underlayerHandle; @@ -441,7 +437,7 @@ int32_t ConnBleOnReferenceRequest(ConnBleConnection *connection, const cJSON *js uint32_t dataLen = 0; int64_t seq = ConnBlePackCtlMessage(ctx, &data, &dataLen); if (seq < 0) { - CONN_LOGI(CONN_BLE, "connId=%u, pack reply message faild, err=%d", connection->connectionId, (int32_t)seq); + CONN_LOGE(CONN_BLE, "connId=%u, pack reply message faild, err=%d", connection->connectionId, (int32_t)seq); return (int32_t)seq; } status = ConnBlePostBytesInner(connection->connectionId, data, dataLen, 0, flag, MODULE_CONNECTION, seq, NULL); @@ -812,9 +808,8 @@ void BleOnServerStarted(BleProtocolType protocol, int32_t status) "on server start event handle failed, try to lock failed"); g_serverCoordination.status[protocol] = status; g_serverCoordination.actual = - (g_serverCoordination.status[BLE_GATT] == SOFTBUS_OK && g_serverCoordination.status[BLE_COC] == SOFTBUS_OK ? - BLE_SERVER_STATE_STARTED : - BLE_SERVER_STATE_STOPPED); + ((g_serverCoordination.status[BLE_GATT] == SOFTBUS_OK) && (g_serverCoordination.status[BLE_COC] == SOFTBUS_OK ? + BLE_SERVER_STATE_STARTED : BLE_SERVER_STATE_STOPPED)); if (g_serverCoordination.expect != g_serverCoordination.actual) { ConnPostMsgToLooper(&g_bleConnectionAsyncHandler, MSG_CONNECTION_RETRY_SERVER_STATE_CONSISTENT, 0, 0, NULL, RETRY_SERVER_STATE_CONSISTENT_MILLIS); @@ -831,8 +826,7 @@ void BleOnServerClosed(BleProtocolType protocol, int32_t status) g_serverCoordination.status[protocol] = status; g_serverCoordination.actual = (g_serverCoordination.status[BLE_GATT] == SOFTBUS_OK && g_serverCoordination.status[BLE_COC] == SOFTBUS_OK ? - BLE_SERVER_STATE_STOPPED : - BLE_SERVER_STATE_STARTED); + BLE_SERVER_STATE_STOPPED : BLE_SERVER_STATE_STARTED); if (g_serverCoordination.expect != g_serverCoordination.actual) { ConnPostMsgToLooper(&g_bleConnectionAsyncHandler, MSG_CONNECTION_RETRY_SERVER_STATE_CONSISTENT, 0, 0, NULL, RETRY_SERVER_STATE_CONSISTENT_MILLIS); diff --git a/core/connection/ble/src/softbus_conn_ble_manager.c b/core/connection/ble/src/softbus_conn_ble_manager.c index 3618a2343..c790393b4 100644 --- a/core/connection/ble/src/softbus_conn_ble_manager.c +++ b/core/connection/ble/src/softbus_conn_ble_manager.c @@ -220,6 +220,7 @@ static int32_t NewRequest(ConnBleRequest **outRequest, const ConnBleConnectReque { ConnBleRequest *request = (ConnBleRequest *)SoftBusCalloc(sizeof(ConnBleRequest)); if (request == NULL) { + CONN_LOGE(CONN_BLE, "request calloc faild"); return SOFTBUS_MALLOC_ERR; } ListInit(&request->node); @@ -236,6 +237,7 @@ static int32_t NewDevice(ConnBleDevice **outDevice, const ConnBleConnectRequestC { ConnBleDevice *device = (ConnBleDevice *)SoftBusCalloc(sizeof(ConnBleDevice)); if (device == NULL) { + CONN_LOGE(CONN_BLE, "device calloc faild"); return SOFTBUS_MALLOC_ERR; } ListInit(&device->node); @@ -275,6 +277,7 @@ static int32_t ConvertCtxToDevice(ConnBleDevice **outDevice, const ConnBleConnec ConnBleRequest *request = NULL; int32_t status = NewRequest(&request, ctx); if (status != SOFTBUS_OK) { + CONN_LOGE(CONN_BLE, "newrequest is failed, err=%d", status); return status; } ConnBleDevice *device = NULL; diff --git a/core/connection/ble/src/softbus_conn_ble_send_queue.c b/core/connection/ble/src/softbus_conn_ble_send_queue.c index 9a12f1447..feeb7cc4c 100644 --- a/core/connection/ble/src/softbus_conn_ble_send_queue.c +++ b/core/connection/ble/src/softbus_conn_ble_send_queue.c @@ -14,8 +14,6 @@ */ #include -#include -#include #include "common_list.h" #include "securec.h" @@ -25,9 +23,7 @@ #include "softbus_conn_common.h" #include "softbus_conn_manager.h" #include "softbus_def.h" -#include "softbus_errcode.h" #include "softbus_queue.h" -#include "softbus_type_def.h" static LIST_HEAD(g_bleQueueList); static SoftBusMutex g_bleQueueLock; @@ -87,6 +83,7 @@ int32_t ConnBleEnqueueNonBlock(const void *msg) SendQueueNode *queueNode = (SendQueueNode *)msg; int32_t priority = GetPriority(queueNode->flag); if (SoftBusMutexLock(&g_bleQueueLock) != EOK) { + CONN_LOGE(CONN_BLE, "Lock failed"); return SOFTBUS_LOCK_ERR; } bool isListEmpty = true; @@ -139,6 +136,7 @@ int32_t ConnBleDequeueBlock(void **msg) ConnectionQueue *item = NULL; ConnectionQueue *next = NULL; if (msg == NULL) { + CONN_LOGE(CONN_BLE, "msg is null"); return SOFTBUS_INVALID_PARAM; } if (SoftBusMutexLock(&g_bleQueueLock) != EOK) { @@ -182,9 +180,11 @@ int32_t ConnBleDequeueBlock(void **msg) int32_t ConnBleInitSendQueue(void) { if (SoftBusMutexInit(&g_bleQueueLock, NULL) != 0) { + CONN_LOGE(CONN_INIT, "Mutex Init failed"); return SOFTBUS_ERR; } if (SoftBusCondInit(&g_sendWaitCond) != SOFTBUS_OK) { + CONN_LOGE(CONN_INIT, "cond Init failed"); (void)SoftBusMutexDestroy(&g_bleQueueLock); return SOFTBUS_ERR; } diff --git a/core/connection/ble/src/softbus_conn_ble_server.c b/core/connection/ble/src/softbus_conn_ble_server.c index 20001fee7..0a7466238 100644 --- a/core/connection/ble/src/softbus_conn_ble_server.c +++ b/core/connection/ble/src/softbus_conn_ble_server.c @@ -24,8 +24,6 @@ #include "softbus_conn_ble_manager.h" #include "softbus_conn_common.h" #include "softbus_def.h" -#include "softbus_errcode.h" -#include "softbus_type_def.h" #include "softbus_utils.h" #include "legacy_ble_channel.h" @@ -1164,7 +1162,7 @@ int32_t ConnGattServerSend(ConnBleConnection *connection, const uint8_t *data, u .connectId = underlayerHandle, .attrHandle = GetBleAttrHandle(module, connection->serviceId), .confirm = 0, - .valueLen = dataLen, + .valueLen = (int)dataLen, .value = (char *)data, }; return SoftBusGattsSendNotify(¬ify); @@ -1490,7 +1488,7 @@ int32_t ConnGattInitServerModule(SoftBusLooper *looper, CONN_CHECK_AND_RETURN_RET_LOGW(listener != NULL, SOFTBUS_INVALID_PARAM, CONN_INIT, "init ble server failed, invalid param, listener is null"); CONN_CHECK_AND_RETURN_RET_LOGW(listener->onServerStarted != NULL, SOFTBUS_INVALID_PARAM, CONN_INIT, - "init ble server failed, invalid param, listener is null"); + "init ble server failed, invalid param, listener onServerStarted is null"); CONN_CHECK_AND_RETURN_RET_LOGW(listener->onServerClosed != NULL, SOFTBUS_INVALID_PARAM, CONN_INIT, "init ble server failed, invalid param, listener onServerClosed is null"); CONN_CHECK_AND_RETURN_RET_LOGW(listener->onServerAccepted != NULL, SOFTBUS_INVALID_PARAM, CONN_INIT, diff --git a/core/connection/ble/src/softbus_conn_ble_trans.c b/core/connection/ble/src/softbus_conn_ble_trans.c index 0010eb4e7..b38630224 100644 --- a/core/connection/ble/src/softbus_conn_ble_trans.c +++ b/core/connection/ble/src/softbus_conn_ble_trans.c @@ -27,7 +27,6 @@ #include "softbus_conn_common.h" #include "softbus_datahead_transform.h" #include "softbus_def.h" -#include "softbus_errcode.h" static const int32_t MTU_HEADER_SIZE = 3; static const size_t BLE_TRANS_HEADER_SIZE = sizeof(BleTransHeader); @@ -487,7 +486,7 @@ uint8_t *ConnCocTransRecv(uint32_t connectionId, LimitedBuffer *buffer, int32_t buffer->length -= packLen; CONN_LOGI(CONN_BLE, "coc socket read limited buffer: left length=%d", buffer->length); - *outLen = packLen; + *outLen = (int32_t)packLen; return dataCopy; } diff --git a/core/connection/br/src/softbus_conn_br_connection.c b/core/connection/br/src/softbus_conn_br_connection.c index bb9ded176..81b4e31a1 100644 --- a/core/connection/br/src/softbus_conn_br_connection.c +++ b/core/connection/br/src/softbus_conn_br_connection.c @@ -492,7 +492,7 @@ static void *ListenTask(void *arg) serverState->serverId = -1; } (void)SoftBusMutexUnlock(&serverState->mutex); - int32_t serverId = g_sppDriver->OpenSppServer(name, strlen(name), UUID, 0); + int32_t serverId = g_sppDriver->OpenSppServer(name, (int32_t)strlen(name), UUID, 0); if (serverId == -1) { CONN_LOGE(CONN_BR, "open br server failed, trace id=%u, retry after %d ms", serverState->traceId, BR_ACCEPET_WAIT_TIME); diff --git a/core/connection/br/src/softbus_conn_br_manager.c b/core/connection/br/src/softbus_conn_br_manager.c index e47f02033..0116f42d0 100644 --- a/core/connection/br/src/softbus_conn_br_manager.c +++ b/core/connection/br/src/softbus_conn_br_manager.c @@ -19,10 +19,8 @@ #include "bus_center_decision_center.h" #include "conn_log.h" -#include "lnn_distributed_net_ledger.h" #include "lnn_node_info.h" #include "message_handler.h" -#include "softbus_adapter_crypto.h" #include "softbus_adapter_mem.h" #include "softbus_adapter_timer.h" #include "softbus_conn_ble_manager.h" @@ -791,10 +789,10 @@ static void DataReceived(ConnBrDataReceivedContext *ctx) if (head->module == MODULE_CONNECTION) { ReceivedControlData(connection, ctx->data + ConnGetHeadSize(), ctx->dataLen - ConnGetHeadSize()); } else if (head->module == MODULE_NIP_BR_CHANNEL && head->seq == (int64_t)BR_NIP_SEQ) { - NipRecvDataFromBr(ctx->connectionId, (char *)ctx->data, ctx->dataLen); + NipRecvDataFromBr(ctx->connectionId, (char *)ctx->data, (int32_t)(ctx->dataLen)); } else { g_connectCallback.OnDataReceived( - ctx->connectionId, (ConnModule)head->module, head->seq, (char *)ctx->data, ctx->dataLen); + ctx->connectionId, (ConnModule)head->module, head->seq, (char *)ctx->data, (int32_t)(ctx->dataLen)); } SoftBusFree(ctx->data); ctx->data = NULL; diff --git a/core/connection/br/src/softbus_conn_br_pending_packet.c b/core/connection/br/src/softbus_conn_br_pending_packet.c index f94a4cfdb..8d4c5e957 100644 --- a/core/connection/br/src/softbus_conn_br_pending_packet.c +++ b/core/connection/br/src/softbus_conn_br_pending_packet.c @@ -14,21 +14,15 @@ */ #include -#include -#include #include "softbus_conn_br_pending_packet.h" #include "common_list.h" #include "conn_log.h" -#include "securec.h" #include "softbus_adapter_mem.h" #include "softbus_conn_br_connection.h" #include "softbus_conn_br_trans.h" -#include "softbus_conn_manager.h" #include "softbus_def.h" -#include "softbus_errcode.h" -#include "softbus_type_def.h" typedef struct { ListNode node; @@ -117,6 +111,7 @@ int32_t ConnBrGetBrPendingPacket(uint32_t id, int64_t seq, uint32_t waitMillis, { #define USECTONSEC 1000LL if (data == NULL || SoftBusMutexLock(&g_pendingLock) != SOFTBUS_OK) { + CONN_LOGE(CONN_BR, "Lock failed"); return SOFTBUS_ERR; } PendingPacket *pending = NULL; @@ -240,7 +235,7 @@ int32_t ConnBrOnAckResponse(ConnBrConnection *connection, const cJSON *json) return SOFTBUS_PARSE_JSON_ERR; } CONN_LOGD(CONN_BR, "conn id=%u, peer window=%d, seq=%"PRId64, connection->connectionId, peerWindows, seq); - int32_t status = ConnBrSetBrPendingPacket(connection->connectionId, seq, NULL); + int32_t status = ConnBrSetBrPendingPacket(connection->connectionId, (int64_t)seq, NULL); if (status != SOFTBUS_OK) { CONN_LOGE(CONN_BR, "set br pending packet failed, conn id=%u, error=%d", connection->connectionId, status); } diff --git a/core/connection/br/src/softbus_conn_br_send_queue.c b/core/connection/br/src/softbus_conn_br_send_queue.c index bfe4d4ba8..f79689083 100644 --- a/core/connection/br/src/softbus_conn_br_send_queue.c +++ b/core/connection/br/src/softbus_conn_br_send_queue.c @@ -15,19 +15,14 @@ #include "softbus_conn_br_send_queue.h" #include -#include -#include #include "common_list.h" #include "conn_log.h" -#include "securec.h" #include "softbus_adapter_mem.h" #include "softbus_conn_common.h" #include "softbus_conn_manager.h" #include "softbus_def.h" -#include "softbus_errcode.h" #include "softbus_queue.h" -#include "softbus_type_def.h" static LIST_HEAD(g_brQueueList); static SoftBusMutex g_brQueueLock; diff --git a/core/connection/br/src/softbus_conn_br_trans.c b/core/connection/br/src/softbus_conn_br_trans.c index e9c4da2c3..c8d6a90c8 100644 --- a/core/connection/br/src/softbus_conn_br_trans.c +++ b/core/connection/br/src/softbus_conn_br_trans.c @@ -21,11 +21,9 @@ #include "softbus_conn_br_pending_packet.h" #include "softbus_conn_br_send_queue.h" #include "softbus_conn_common.h" -#include "softbus_conn_interface.h" #include "softbus_conn_manager.h" #include "softbus_datahead_transform.h" #include "softbus_def.h" -#include "softbus_errcode.h" #include "softbus_json_utils.h" #include "conn_event.h" @@ -78,7 +76,7 @@ static uint8_t *BrRecvDataParse(uint32_t connectionId, LimitedBuffer *buffer, in CONN_LOGI(CONN_BR, "br receive data, connection id=%u, cached length=%u, payload (Len/Flg/Module/Seq)=" "(%u/%d/%d/%" PRId64 ")", connectionId, buffer->length, packLen, head->flag, head->module, head->seq); buffer->length -= packLen; - *outLen = packLen; + *outLen = (int32_t)packLen; return dataCopy; } @@ -91,8 +89,8 @@ int32_t ConnBrTransReadOneFrame(uint32_t connectionId, int32_t socketHandle, Lim *outData = data; return dataLen; } - int32_t recvLen = - g_sppDriver->Read(socketHandle, buffer->buffer + buffer->length, buffer->capacity - buffer->length); + int32_t recvLen = g_sppDriver->Read( + socketHandle, buffer->buffer + buffer->length, (int32_t)(buffer->capacity - buffer->length)); if (recvLen == BR_READ_SOCKET_CLOSED) { CONN_LOGW(CONN_BR, "br connection read return, connection id=%u, socket handle=%d, connection closed", connectionId, socketHandle); @@ -125,7 +123,7 @@ int32_t BrTransSend( uint32_t waitWriteLen = dataLen; while (waitWriteLen > 0) { uint32_t len = waitWriteLen > mtu ? mtu : waitWriteLen; - int32_t writeLen = g_sppDriver->Write(socketHandle, data, len); + int32_t writeLen = g_sppDriver->Write(socketHandle, data, (int32_t)len); if (writeLen < 0) { CONN_LOGE(CONN_BR, "br connection %u send data failed: underlayer bluetooth write failed, socketHandle=%d, " "mtu=%d, total len=%d, wait write len=%d, already write len=%d, error=%d", diff --git a/core/connection/common/src/softbus_base_listener.c b/core/connection/common/src/softbus_base_listener.c index f7dba978d..16248b29f 100644 --- a/core/connection/common/src/softbus_base_listener.c +++ b/core/connection/common/src/softbus_base_listener.c @@ -83,27 +83,32 @@ static int32_t ShutdownBaseListener(SoftbusListenerNode *node); static int32_t StartSelectThread(void); static int32_t StopSelectThread(void); static void WakeupSelectThread(void); +static SoftbusListenerNode *CreateSpecifiedListenerModule(ListenerModule module); static SoftBusMutex g_listenerListLock = { 0 }; static SoftbusListenerNode *g_listenerList[UNUSE_BUTT] = { 0 }; static SoftBusMutex g_selectThreadStateLock = { 0 }; static SelectThreadState *g_selectThreadState = NULL; -static SoftbusListenerNode *GetListenerNode(ListenerModule module) +static SoftbusListenerNode *GetListenerNodeCommon(ListenerModule module, bool create) { int32_t status = SoftBusMutexLock(&g_listenerListLock); - CONN_CHECK_AND_RETURN_RET_LOGE(status == SOFTBUS_OK, NULL, CONN_COMMON, - "ATTENTION UNEXPECTED ERROR! request listener node failed: try to lock listener lists failed, module=%d, " - "error=%d", module, status); + CONN_CHECK_AND_RETURN_RET_LOGE( + status == SOFTBUS_OK, NULL, CONN_COMMON, "lock listener lists failed, module=%d, error=%d", module, status); SoftbusListenerNode *node = g_listenerList[module]; do { if (node == NULL) { - break; + if (create) { + node = CreateSpecifiedListenerModule(module); + } + if (node == NULL) { + break; + } + g_listenerList[module] = node; } status = SoftBusMutexLock(&node->lock); if (status != SOFTBUS_OK) { - CONN_LOGE(CONN_COMMON, "ATTENTION UNEXPECTED ERROR! request listener node failed: try to lock " - "listener failed, module=%d, error=%d", module, status); + CONN_LOGE(CONN_COMMON, "lock listener failed, module=%d, error=%d", module, status); node = NULL; break; } @@ -114,22 +119,29 @@ static SoftbusListenerNode *GetListenerNode(ListenerModule module) return node; } +static SoftbusListenerNode *GetListenerNode(ListenerModule module) +{ + return GetListenerNodeCommon(module, false); +} + +static SoftbusListenerNode *GetOrCreateListenerNode(ListenerModule module) +{ + return GetListenerNodeCommon(module, true); +} + static void RemoveListenerNode(SoftbusListenerNode *node) { int32_t status = SoftBusMutexLock(&g_listenerListLock); - CONN_CHECK_AND_RETURN_LOGE(status == SOFTBUS_OK, CONN_COMMON, - "ATTENTION UNEXPECTED ERROR! remove listener node failed: try to lock listener lists failed, module=%d, " - "error=%d", node->module, status); + CONN_CHECK_AND_RETURN_LOGE( + status == SOFTBUS_OK, CONN_COMMON, "lock listener lists failed, module=%d, error=%d", node->module, status); do { if (g_listenerList[node->module] != node) { - CONN_LOGW(CONN_COMMON, "ATTENTION! remove listener node warning: listener node is not in " - "listener list, repeat remove? just skip, module=%d", node->module); + CONN_LOGW(CONN_COMMON, "listener node is not in listener list, just skip, module=%d", node->module); break; } status = SoftBusMutexLock(&node->lock); if (status != SOFTBUS_OK) { - CONN_LOGE(CONN_COMMON, "ATTENTION UNEXPECT ERROR! remove listener node failed: " - "try to lock listener node failed, module=%d", node->module); + CONN_LOGE(CONN_COMMON, "lock listener node failed, module=%d", node->module); break; } // decrease root object reference @@ -146,8 +158,7 @@ static void ReturnListenerNode(SoftbusListenerNode **nodePtr) do { int32_t status = SoftBusMutexLock(&node->lock); if (status != SOFTBUS_OK) { - CONN_LOGE(CONN_COMMON, "ATTENTION UNEXPECT ERROR! return listener node failed: " - "try to lock listener node failed, module=%d", node->module); + CONN_LOGE(CONN_COMMON, "lock listener node failed, module=%d", node->module); break; } node->objectRc -= 1; @@ -157,8 +168,7 @@ static void ReturnListenerNode(SoftbusListenerNode **nodePtr) if (objectRc > 0) { break; } - CONN_LOGI(CONN_COMMON, - "release listener node, object reference count <= 0, free listener node, module=%d, object reference=%d", + CONN_LOGI(CONN_COMMON, "object reference count <= 0, free listener node, module=%d, object reference=%d", node->module, objectRc); (void)ShutdownBaseListener(node); SoftBusFree(node); @@ -170,19 +180,14 @@ static void ReturnListenerNode(SoftbusListenerNode **nodePtr) static SoftbusListenerNode *CreateSpecifiedListenerModule(ListenerModule module) { SoftbusListenerNode *node = (SoftbusListenerNode *)SoftBusCalloc(sizeof(SoftbusListenerNode)); - CONN_CHECK_AND_RETURN_RET_LOGE(node != NULL, NULL, CONN_COMMON, - "ATTENTION UNEXPECTED ERROR! create specified listener module failed: calloc listener node object failed, " - "module=%d", - module); + CONN_CHECK_AND_RETURN_RET_LOGE( + node != NULL, NULL, CONN_COMMON, "calloc listener node object failed, module=%d", module); node->module = module; // NOT apply recursive lock on purpose, problem will be exposes quickly if exist int32_t status = SoftBusMutexInit(&node->lock, NULL); if (status != SOFTBUS_OK) { - CONN_LOGE(CONN_COMMON, - "ATTENTION UNEXPECTED ERROR! create specified listener module failed: init lock failed, module=%d, " - "error=%d", - module, status); + CONN_LOGE(CONN_COMMON, "init lock failed, module=%d, error=%d", module, status); SoftBusFree(node); return NULL; } @@ -196,31 +201,6 @@ static SoftbusListenerNode *CreateSpecifiedListenerModule(ListenerModule module) return node; } -static int32_t CreateStaticModulesUnsafe(void) -{ - ListenerModule module = 0; - for (; module < LISTENER_MODULE_DYNAMIC_START; module++) { - SoftbusListenerNode *node = CreateSpecifiedListenerModule(module); - if (node == NULL) { - CONN_LOGW(CONN_COMMON, "create static module failed: create module listener node failed, module=%d", - module); - goto CLEANUP; - } - CONN_LOGI(CONN_COMMON, "create static module, create module listener node success, module=%d", module); - g_listenerList[module] = node; - } - return SOFTBUS_OK; -CLEANUP: - for (ListenerModule i = module - 1; i >= 0; i--) { - SoftbusListenerNode *node = g_listenerList[i]; - g_listenerList[i] = NULL; - // cleanup - ReturnListenerNode(&node); - CONN_LOGI(CONN_COMMON, "create static module failed: clean up listener node done, module=%d", module); - } - return SOFTBUS_ERR; -} - int32_t InitBaseListener(void) { // stop select thread need re-enter lock @@ -229,36 +209,28 @@ int32_t InitBaseListener(void) }; int32_t status = SoftBusMutexInit(&g_selectThreadStateLock, &attr); if (status != SOFTBUS_OK) { - CONN_LOGE(CONN_INIT, - "ATTENTION UNEXPECTED ERROR! init base listener failed: init select thread lock failed, error=%d", - status); + CONN_LOGE(CONN_INIT, "init select thread lock failed, error=%d", status); return SOFTBUS_LOCK_ERR; } // NOT apply recursive lock on purpose, problem will be exposes quickly if exist status = SoftBusMutexInit(&g_listenerListLock, NULL); if (status != SOFTBUS_OK) { SoftBusMutexDestroy(&g_selectThreadStateLock); - CONN_LOGE(CONN_INIT, - "ATTENTION UNEXPECTED ERROR! init base listener failed: init listener list lock failed, error=%d", - status); + CONN_LOGE(CONN_INIT, "init listener list lock failed, error=%d", status); return SOFTBUS_LOCK_ERR; } status = SoftBusMutexLock(&g_listenerListLock); if (status != SOFTBUS_OK) { - CONN_LOGE(CONN_INIT, - "ATTENTION UNEXPECTED ERROR! init base listener failed: try to lock listener list failed, error=%d", - status); + CONN_LOGE(CONN_INIT, "lock listener list failed, error=%d", status); SoftBusMutexDestroy(&g_selectThreadStateLock); SoftBusMutexDestroy(&g_listenerListLock); return SOFTBUS_LOCK_ERR; } (void)memset_s(g_listenerList, sizeof(g_listenerList), 0, sizeof(g_listenerList)); - status = CreateStaticModulesUnsafe(); (void)SoftBusMutexUnlock(&g_listenerListLock); if (status != SOFTBUS_OK) { - CONN_LOGE(CONN_INIT, "init base listener failed: create static module listener failed, error=%d", - status); + CONN_LOGE(CONN_INIT, "create static module listener failed, error=%d", status); SoftBusMutexDestroy(&g_selectThreadStateLock); SoftBusMutexDestroy(&g_listenerListLock); return status; @@ -282,9 +254,8 @@ void DeinitBaseListener(void) uint32_t CreateListenerModule(void) { int32_t status = SoftBusMutexLock(&g_listenerListLock); - CONN_CHECK_AND_RETURN_RET_LOGE(status == SOFTBUS_OK, UNUSE_BUTT, CONN_COMMON, - "ATTENTION UNEXPECTED ERROR! create listener module failed: try to lock listener list failed, error=%d", - status); + CONN_CHECK_AND_RETURN_RET_LOGE( + status == SOFTBUS_OK, UNUSE_BUTT, CONN_COMMON, "lock listener list failed, error=%d", status); ListenerModule module = LISTENER_MODULE_DYNAMIC_START; for (; module <= LISTENER_MODULE_DYNAMIC_END; module++) { @@ -293,8 +264,7 @@ uint32_t CreateListenerModule(void) } SoftbusListenerNode *node = CreateSpecifiedListenerModule(module); if (node == NULL) { - CONN_LOGE(CONN_COMMON, "create listener module failed, create specified listener module failed, module=%d", - module); + CONN_LOGE(CONN_COMMON, "create specified listener module failed, module=%d", module); module = UNUSE_BUTT; } else { CONN_LOGI(CONN_COMMON, "create listener module success, module=%d", module); @@ -309,12 +279,12 @@ uint32_t CreateListenerModule(void) void DestroyBaseListener(ListenerModule module) { CONN_CHECK_AND_RETURN_LOGW(module >= LISTENER_MODULE_DYNAMIC_START && module <= LISTENER_MODULE_DYNAMIC_END, - CONN_COMMON, "destroy base listener failed: only dynamic module support destroy, module=%d", module); + CONN_COMMON, "only dynamic module support destroy, module=%d", module); - CONN_LOGI(CONN_COMMON, "receive destroy base listener request, module=%d", module); + CONN_LOGI(CONN_COMMON, "receive request, module=%d", module); SoftbusListenerNode *node = GetListenerNode(module); if (node == NULL) { - CONN_LOGW(CONN_COMMON, "destroy base listener warning, listener not exist, module=%d", module); + CONN_LOGW(CONN_COMMON, "listener not exist, module=%d", module); return; } RemoveListenerNode(node); @@ -324,34 +294,29 @@ void DestroyBaseListener(ListenerModule module) int32_t StartBaseClient(ListenerModule module, const SoftbusBaseListener *listener) { CONN_CHECK_AND_RETURN_RET_LOGW(module >= 0 && module < UNUSE_BUTT, SOFTBUS_INVALID_PARAM, CONN_COMMON, - "start base client listener failed: invalid module, module=%d", module); + "invalid module, module=%d", module); CONN_CHECK_AND_RETURN_RET_LOGW(listener != NULL, SOFTBUS_INVALID_PARAM, CONN_COMMON, - "start base client listener failed: listener is null, module=%d", module); + "listener is null, module=%d", module); CONN_CHECK_AND_RETURN_RET_LOGW(listener->onConnectEvent != NULL, SOFTBUS_INVALID_PARAM, CONN_COMMON, - "start base client listener failed: listener onConnectEvent is null, module=%d", module); + "listener onConnectEvent is null, module=%d", module); CONN_CHECK_AND_RETURN_RET_LOGW(listener->onDataEvent != NULL, SOFTBUS_INVALID_PARAM, CONN_COMMON, - "start base client listener failed: listener onDataEvent is null, module=%d", module); + "listener onDataEvent is null, module=%d", module); - CONN_LOGI(CONN_COMMON, "receive start base client listener request, module=%d", module); + CONN_LOGI(CONN_COMMON, "receive request, module=%d", module); - SoftbusListenerNode *node = GetListenerNode(module); - CONN_CHECK_AND_RETURN_RET_LOGW(node != NULL, SOFTBUS_NOT_FIND, CONN_COMMON, - "start base client listener failed: get listener node failed, dynamic module forgot register " - "first? or static module start before base listener init? module=%d", - module); + SoftbusListenerNode *node = GetOrCreateListenerNode(module); + CONN_CHECK_AND_RETURN_RET_LOGW( + node != NULL, SOFTBUS_NOT_FIND, CONN_COMMON, "get listener node failed, module=%d", module); int32_t status = SoftBusMutexLock(&node->lock); if (status != SOFTBUS_OK) { - CONN_LOGE(CONN_COMMON, "ATTENTION UNEXPECTED ERROR! start base client listener failed: try to lock " - "listener node failed, module=%d, error=%d", - module, status); + CONN_LOGE(CONN_COMMON, "lock listener node failed, module=%d, error=%d", module, status); ReturnListenerNode(&node); return SOFTBUS_LOCK_ERR; } do { if (node->info.status != LISTENER_IDLE) { - CONN_LOGE(CONN_COMMON, "start base client listener failed: listener is not idle status, module=%d, " - "status=%d", module, node->info.status); + CONN_LOGE(CONN_COMMON, "listener is not idle status, module=%d, status=%d", module, node->info.status); status = SOFTBUS_ERR; break; } @@ -359,7 +324,7 @@ int32_t StartBaseClient(ListenerModule module, const SoftbusBaseListener *listen node->listener.onDataEvent = listener->onDataEvent; status = StartSelectThread(); if (status != SOFTBUS_OK) { - CONN_LOGE(CONN_COMMON, "start base client listener failed: start select thread failed, module=%d, " + CONN_LOGE(CONN_COMMON, "start select thread failed, module=%d, " "status=%d", module, status); break; } @@ -377,9 +342,7 @@ static int32_t StartServerListenUnsafe(SoftbusListenerNode *node, const LocalLis ProtocolType protocol = info->socketOption.protocol; const SocketInterface *socketIf = GetSocketInterface(protocol); if (socketIf == NULL) { - CONN_LOGE(CONN_COMMON, - "not find protocal implement, protocal implement should register first, module=%d, protocal=%d", - module, protocol); + CONN_LOGE(CONN_COMMON, "not find protocal implement, module=%d, protocal=%d", module, protocol); return SOFTBUS_NOT_FIND; } node->socketIf = socketIf; @@ -434,33 +397,29 @@ static void CleanupServerListenInfoUnsafe(SoftbusListenerNode *node) int32_t StartBaseListener(const LocalListenerInfo *info, const SoftbusBaseListener *listener) { - CONN_CHECK_AND_RETURN_RET_LOGW(info != NULL, SOFTBUS_INVALID_PARAM, CONN_COMMON, - "start base listener failed: info is null"); + CONN_CHECK_AND_RETURN_RET_LOGW(info != NULL, SOFTBUS_INVALID_PARAM, CONN_COMMON, "info is null"); CONN_CHECK_AND_RETURN_RET_LOGW(info->type == CONNECT_TCP || info->type == CONNECT_P2P, SOFTBUS_INVALID_PARAM, - CONN_COMMON, "start base listener failed: only CONNECT_TCP(%d) and CONNECT_P2P(%d) is permitted, type=%d", + CONN_COMMON, "only CONNECT_TCP(%d) and CONNECT_P2P(%d) is permitted, type=%d", CONNECT_TCP, CONNECT_P2P, info->type); CONN_CHECK_AND_RETURN_RET_LOGW(info->socketOption.port >= 0, SOFTBUS_INVALID_PARAM, CONN_COMMON, - "start base listener failed: port is invalid, port=%d", info->socketOption.port); + "port is invalid, port=%d", info->socketOption.port); CONN_CHECK_AND_RETURN_RET_LOGW(info->socketOption.moduleId >= 0 && info->socketOption.moduleId < UNUSE_BUTT, - SOFTBUS_INVALID_PARAM, CONN_COMMON, "start base client listener failed: invalid module, module=%d", - info->socketOption.moduleId); + SOFTBUS_INVALID_PARAM, CONN_COMMON, "invalid module, module=%d", info->socketOption.moduleId); CONN_CHECK_AND_RETURN_RET_LOGW(listener != NULL, SOFTBUS_INVALID_PARAM, CONN_COMMON, - "start base listener failed: listener is null, module=%d", info->socketOption.moduleId); + "listener is null, module=%d", info->socketOption.moduleId); CONN_CHECK_AND_RETURN_RET_LOGW(listener->onConnectEvent != NULL, SOFTBUS_INVALID_PARAM, CONN_COMMON, - "start base listener failed: listener is null, module=%d", info->socketOption.moduleId); + "listener onConnectEvent is null, module=%d", info->socketOption.moduleId); CONN_CHECK_AND_RETURN_RET_LOGW(listener->onDataEvent != NULL, SOFTBUS_INVALID_PARAM, CONN_COMMON, - "start base listener failed: listener is null, module=%d", info->socketOption.moduleId); + "listener onDataEvent is null, module=%d", info->socketOption.moduleId); ListenerModule module = info->socketOption.moduleId; - CONN_LOGI(CONN_COMMON, "receive start base listener request, module=%d", module); - SoftbusListenerNode *node = GetListenerNode(module); - CONN_CHECK_AND_RETURN_RET_LOGW(node != NULL, SOFTBUS_NOT_FIND, CONN_COMMON, - "start base listener failed: get listener node failed, dynamic module should register first, module=%d", - module); + CONN_LOGI(CONN_COMMON, "receive request, module=%d", module); + SoftbusListenerNode *node = GetOrCreateListenerNode(module); + CONN_CHECK_AND_RETURN_RET_LOGW( + node != NULL, SOFTBUS_NOT_FIND, CONN_COMMON, "get listener node failed, module=%d", module); int32_t status = SoftBusMutexLock(&node->lock); if (status != SOFTBUS_OK) { - CONN_LOGE(CONN_COMMON, "ATTENTION UNEXPECTED ERROR! start base listener failed: try to lock listener node " - "failed, module=%d, error=%d", module, status); + CONN_LOGE(CONN_COMMON, "lock listener node failed, module=%d, error=%d", module, status); ReturnListenerNode(&node); return SOFTBUS_LOCK_ERR; } @@ -468,8 +427,7 @@ int32_t StartBaseListener(const LocalListenerInfo *info, const SoftbusBaseListen int32_t listenPort = -1; do { if (node->info.status != LISTENER_IDLE) { - CONN_LOGE(CONN_COMMON, "start base listener failed: listener is not idle status, module=%d, status=%d", - module, node->info.status); + CONN_LOGE(CONN_COMMON, "listener is not idle status, module=%d, status=%d", module, node->info.status); status = SOFTBUS_ERR; break; } @@ -477,22 +435,20 @@ int32_t StartBaseListener(const LocalListenerInfo *info, const SoftbusBaseListen node->listener.onConnectEvent = listener->onConnectEvent; node->listener.onDataEvent = listener->onDataEvent; if (memcpy_s(&node->info.listenerInfo, sizeof(LocalListenerInfo), info, sizeof(LocalListenerInfo)) != EOK) { - CONN_LOGE(CONN_COMMON, "start base listener failed: memcpy_s listener info failed, module=%d", - node->module); + CONN_LOGE(CONN_COMMON, "memcpy_s listener info failed, module=%d", node->module); status = SOFTBUS_LOCK_ERR; break; } listenPort = StartServerListenUnsafe(node, info); if (listenPort <= 0) { - CONN_LOGE(CONN_COMMON, "start base listener failed: start server failed, module=%d, invalid listen " - "port=%d", module, listenPort); + CONN_LOGE(CONN_COMMON, "start server failed, module=%d, invalid listen port=%d", module, listenPort); status = SOFTBUS_ERR; break; } status = StartSelectThread(); if (status != SOFTBUS_OK) { - CONN_LOGE(CONN_COMMON, "start base listener failed: start listener thread failed, module=%d, status=%d", + CONN_LOGE(CONN_COMMON, "start listener thread failed, module=%d, status=%d", module, status); CleanupServerListenInfoUnsafe(node); break; @@ -508,18 +464,17 @@ int32_t StartBaseListener(const LocalListenerInfo *info, const SoftbusBaseListen int32_t StopBaseListener(ListenerModule module) { - CONN_CHECK_AND_RETURN_RET_LOGW(module >= 0 && module < UNUSE_BUTT, SOFTBUS_INVALID_PARAM, CONN_COMMON, - "stop base listener failed: invalid module, module=%d", module); + CONN_CHECK_AND_RETURN_RET_LOGW( + module >= 0 && module < UNUSE_BUTT, SOFTBUS_INVALID_PARAM, CONN_COMMON, "invalid module, module=%d", module); - CONN_LOGI(CONN_COMMON, "receive stop base listener request, module=%d", module); + CONN_LOGI(CONN_COMMON, "receive request, module=%d", module); SoftbusListenerNode *node = GetListenerNode(module); - CONN_CHECK_AND_RETURN_RET_LOGW(node != NULL, SOFTBUS_NOT_FIND, CONN_COMMON, - "stop base listener failed: listener node not exist, module=%d", module); + CONN_CHECK_AND_RETURN_RET_LOGW( + node != NULL, SOFTBUS_NOT_FIND, CONN_COMMON, "listener node not exist, module=%d", module); int32_t status = ShutdownBaseListener(node); if (status != SOFTBUS_OK) { - CONN_LOGE(CONN_COMMON, "stop base listener failed: stop listen thread failed, module=%d, error=%d", - module, status); + CONN_LOGE(CONN_COMMON, "stop listen thread failed, module=%d, error=%d", module, status); } ReturnListenerNode(&node); return status; @@ -529,21 +484,17 @@ static int32_t ShutdownBaseListener(SoftbusListenerNode *node) { int32_t status = SoftBusMutexLock(&node->lock); CONN_CHECK_AND_RETURN_RET_LOGE(status == SOFTBUS_OK, SOFTBUS_LOCK_ERR, CONN_COMMON, - "ATTENTION UNEXPECTED ERROR! shutdown base listener failed: try to lock listener node failed, " - "module=%d, error=%d", - node->module, status); + "lock listener node failed, module=%d, error=%d", node->module, status); do { if (node->info.status != LISTENER_RUNNING) { - CONN_LOGW(CONN_COMMON, - "shutdown base listener warning, listener is not running, just skip, module=%d, error=%d", - node->module, node->info.status); + CONN_LOGW(CONN_COMMON, "listener is not running, just skip, module=%d, error=%d", node->module, + node->info.status); break; } status = StopSelectThread(); if (status != SOFTBUS_OK) { - CONN_LOGE(CONN_COMMON, "shutdown base listener failed: stop select thread failed, module=%d, error=%d", - node->module, status); + CONN_LOGE(CONN_COMMON, "stop select thread failed, module=%d, error=%d", node->module, status); break; } node->info.status = LISTENER_IDLE; @@ -551,9 +502,7 @@ static int32_t ShutdownBaseListener(SoftbusListenerNode *node) FdNode *it = NULL; FdNode *next = NULL; LIST_FOR_EACH_ENTRY_SAFE(it, next, &node->info.waitEventFds, FdNode, node) { - CONN_LOGE(CONN_COMMON, - "ATTENTION, shutdown base listener warning: listener node there is fd not close, module=%d, fd=%d, " - "trigger set=%u", + CONN_LOGE(CONN_COMMON, "listener node there is fd not close, module=%d, fd=%d, trigger set=%u", node->module, it->fd, it->triggerSet); // not close fd, repeat close will crash process ListDelete(&it->node); @@ -564,8 +513,8 @@ static int32_t ShutdownBaseListener(SoftbusListenerNode *node) int32_t listenFd = node->info.listenFd; int32_t listenPort = node->info.listenPort; if (node->info.modeType == SERVER_MODE && listenFd > 0) { - CONN_LOGE(CONN_COMMON, "shutdown base listener, close server, module=%d, listen fd=%d, port=%d", - node->module, listenFd, listenPort); + CONN_LOGE( + CONN_COMMON, "close server, module=%d, listen fd=%d, port=%d", node->module, listenFd, listenPort); ConnCloseSocket(listenFd); } node->info.modeType = UNSET_MODE; @@ -594,22 +543,21 @@ static bool IsValidTriggerType(TriggerType trigger) int32_t AddTrigger(ListenerModule module, int32_t fd, TriggerType trigger) { CONN_CHECK_AND_RETURN_RET_LOGW(module >= 0 && module < UNUSE_BUTT, SOFTBUS_INVALID_PARAM, CONN_COMMON, - "add trigger failed: invalid module, module=%d", module); - CONN_CHECK_AND_RETURN_RET_LOGW(fd > 0, SOFTBUS_INVALID_PARAM, CONN_COMMON, - "add trigger failed: invalid fd, module=%d, fd=%d", module, fd); + "invalid module, module=%d", module); + CONN_CHECK_AND_RETURN_RET_LOGW( + fd > 0, SOFTBUS_INVALID_PARAM, CONN_COMMON, "invalid fd, module=%d, fd=%d", module, fd); CONN_CHECK_AND_RETURN_RET_LOGW(IsValidTriggerType(trigger), SOFTBUS_INVALID_PARAM, CONN_COMMON, - "add trigger failed: invalid trigger, module=%d, fd=%d, trigger=%d", module, fd, trigger); + "invalid trigger, module=%d, fd=%d, trigger=%d", module, fd, trigger); - CONN_LOGI(CONN_COMMON, "receive add trigger request, module=%d, fd=%d, trigger=%d", module, fd, trigger); + CONN_LOGI(CONN_COMMON, "receive request, module=%d, fd=%d, trigger=%d", module, fd, trigger); SoftbusListenerNode *node = GetListenerNode(module); CONN_CHECK_AND_RETURN_RET_LOGW(node != NULL, SOFTBUS_NOT_FIND, CONN_COMMON, - "add trigger failed: listener node not exist, module=%d, fd=%d, trigger=%d", module, fd, trigger); + "listener node not exist, module=%d, fd=%d, trigger=%d", module, fd, trigger); int32_t status = SoftBusMutexLock(&node->lock); if (status != SOFTBUS_OK) { - CONN_LOGE(CONN_COMMON, "ATTENTION UNEXPECTED ERROR! add trigger failed: try to lock listener node failed, " - "module=%d, fd=%d, trigger=%d, error=%d", - module, fd, trigger, status); + CONN_LOGE(CONN_COMMON, "lock listener node failed, module=%d, fd=%d, trigger=%d, error=%d", module, fd, trigger, + status); ReturnListenerNode(&node); return SOFTBUS_LOCK_ERR; } @@ -617,16 +565,14 @@ int32_t AddTrigger(ListenerModule module, int32_t fd, TriggerType trigger) bool wakeup = false; do { if (node->info.status != LISTENER_RUNNING) { - CONN_LOGE(CONN_COMMON, "add trigger failed: module is not running, call 'StartBaseListener' or " - "'StartBaseClient' first, module=%d, fd=%d, trigger=%d", - module, fd, trigger); + CONN_LOGE(CONN_COMMON, "module is not running, module=%d, fd=%d, trigger=%d", module, fd, trigger); status = SOFTBUS_ERR; break; } if (node->info.waitEventFdsLen > MAX_LISTEN_EVENTS) { - CONN_LOGE(CONN_COMMON, "add trigger failed: can not trigger more, fd exceed more than %d, module=%d, " - "fd=%d, trigger=%d, wait event fds len=%d", + CONN_LOGE(CONN_COMMON, + "can not trigger more, fd exceed more than %d, module=%d, fd=%d, trigger=%d, wait event fds len=%d", MAX_LISTEN_EVENTS, module, fd, trigger, node->info.waitEventFdsLen); status = SOFTBUS_ERR; break; @@ -657,9 +603,7 @@ int32_t AddTrigger(ListenerModule module, int32_t fd, TriggerType trigger) FdNode *fdNode = (FdNode *)SoftBusCalloc(sizeof(FdNode)); if (fdNode == NULL) { - CONN_LOGE(CONN_COMMON, "ATTENTION UNEXPECTED ERROR! add trigger failed: calloc fd node object failed, " - "module=%d, fd=%d, trigger=%d", - module, fd, trigger); + CONN_LOGE(CONN_COMMON, "calloc fd node object failed, module=%d, fd=%d, trigger=%d", module, fd, trigger); status = SOFTBUS_MALLOC_ERR; break; } @@ -684,23 +628,21 @@ int32_t AddTrigger(ListenerModule module, int32_t fd, TriggerType trigger) int32_t DelTrigger(ListenerModule module, int32_t fd, TriggerType trigger) { CONN_CHECK_AND_RETURN_RET_LOGW(module >= 0 && module < UNUSE_BUTT, SOFTBUS_INVALID_PARAM, CONN_COMMON, - "delete trigger failed: invalid module, module=%d", module); + "invalid module, module=%d", module); CONN_CHECK_AND_RETURN_RET_LOGW(fd > 0, SOFTBUS_INVALID_PARAM, CONN_COMMON, - "delete trigger failed: invalid fd, module=%d, fd=%d", module, fd); + "invalid fd, module=%d, fd=%d", module, fd); CONN_CHECK_AND_RETURN_RET_LOGW(IsValidTriggerType(trigger), SOFTBUS_INVALID_PARAM, CONN_COMMON, - "delete trigger failed: invalid trigger, module=%d, fd=%d, trigger=%d", module, fd, trigger); + "invalid trigger, module=%d, fd=%d, trigger=%d", module, fd, trigger); - CONN_LOGI(CONN_COMMON, "receive delete trigger request, module=%d, fd=%d, trigger=%d", module, fd, trigger); + CONN_LOGI(CONN_COMMON, "receive request, module=%d, fd=%d, trigger=%d", module, fd, trigger); SoftbusListenerNode *node = GetListenerNode(module); CONN_CHECK_AND_RETURN_RET_LOGW(node != NULL, SOFTBUS_NOT_FIND, CONN_COMMON, - "delete trigger failed: listener node not exist, module=%d, fd=%d, trigger=%d", - module, fd, trigger); + "listener node not exist, module=%d, fd=%d, trigger=%d", module, fd, trigger); int32_t status = SoftBusMutexLock(&node->lock); if (status != SOFTBUS_OK) { - CONN_LOGE(CONN_COMMON, "ATTENTION UNEXPECTED ERROR! delete trigger failed: try to lock listener node failed, " - "module=%d, fd=%d, trigger=%d, error=%d", - module, fd, trigger, status); + CONN_LOGE(CONN_COMMON, "lock listener node failed, module=%d, fd=%d, trigger=%d, error=%d", module, fd, trigger, + status); ReturnListenerNode(&node); return SOFTBUS_LOCK_ERR; } @@ -717,10 +659,7 @@ int32_t DelTrigger(ListenerModule module, int32_t fd, TriggerType trigger) } if (target == NULL) { - CONN_LOGW(CONN_COMMON, - "delete trigger warning, fd node not exist, call delete trigger without add trigger before or mismatch " - "module. You are warned, fix it quickly! module=%d, fd=%d, trigger=%d", - module, fd, trigger); + CONN_LOGW(CONN_COMMON, "fd node not exist, module=%d, fd=%d, trigger=%d", module, fd, trigger); // consider delete trigger success, status = SOFTBUS_OK; break; @@ -728,8 +667,8 @@ int32_t DelTrigger(ListenerModule module, int32_t fd, TriggerType trigger) if ((target->triggerSet & trigger) == 0) { CONN_LOGW(CONN_COMMON, - "delete trigger warning, without add trigger before, repeat delete trigger or mismatch module. You are " - "warned, fix it quickly! module=%d, fd=%d, want delete trigger=%d, exist trigger set=%u", + "without add trigger before, repeat delete trigger or mismatch module. module=%d, fd=%d, want delete " + "trigger=%d, exist trigger set=%u", module, fd, trigger, it->triggerSet); // consider delete trigger success, status = SOFTBUS_OK; @@ -744,9 +683,8 @@ int32_t DelTrigger(ListenerModule module, int32_t fd, TriggerType trigger) status = SOFTBUS_OK; break; } - CONN_LOGI(CONN_COMMON, - "delete trigger success, there is not exist any trigger, free fd node now, module=%d, fd=%d, trigger=%d", - module, fd, trigger); + CONN_LOGI( + CONN_COMMON, "delete trigger success, free fd node now, module=%d, fd=%d, trigger=%d", module, fd, trigger); ListDelete(&target->node); SoftBusFree(target); node->info.waitEventFdsLen -= 1; @@ -791,14 +729,12 @@ static void ProcessCtrlFdEvent(int32_t fd, int32_t wakeupTrace) } else if (status == EAGAIN) { break; } else { - CONN_LOGE(CONN_COMMON, - "process ctrl fd event failed: wakeup trace=%d, fd=%d, invalid read len=%d, error=%d", - wakeupTrace, fd, len, status); + CONN_LOGE( + CONN_COMMON, "wakeup trace=%d, fd=%d, invalid read len=%d, error=%d", wakeupTrace, fd, len, status); break; } } - CONN_LOGI(CONN_COMMON, "process ctrl fd event, wakeup ctrl message received, wakeup trace=%d, fd=%d, " - "ctrl trace=%d, read length=%d", + CONN_LOGI(CONN_COMMON, "wakeup ctrl message received, wakeup trace=%d, fd=%d, ctrl trace=%d, read length=%d", wakeupTrace, fd, ctrlTraceId, len); } #endif @@ -811,7 +747,7 @@ static void DispatchFdEvent( listener->onDataEvent(module, event, fd); } else { CONN_LOGE(CONN_COMMON, - "process fd event, new event coming, but event listener not registered, to avoid repeat wakeup " + "new event coming, but event listener not registered, to avoid repeat wakeup " "select(LEVEL MODE), close it, wakeup trace=%d, module=%d, fd=%d, event=%d", wakeupTrace, module, fd, event); ConnCloseSocket(fd); @@ -822,12 +758,9 @@ static int32_t ProcessSpecifiedServerAcceptEvent(ListenerModule module, int32_t const SocketInterface *socketIf, const SoftbusBaseListener *listener, int32_t wakeupTrace) { CONN_CHECK_AND_RETURN_RET_LOGW(socketIf != NULL, SOFTBUS_INVALID_PARAM, CONN_COMMON, - "process spectified listener node event failed: socket interface implement is null, wakeup trace=%d module=%d", - wakeupTrace, module); + "socket interface implement is null, wakeup trace=%d module=%d", wakeupTrace, module); CONN_CHECK_AND_RETURN_RET_LOGW(socketIf->AcceptClient != NULL, SOFTBUS_INVALID_PARAM, CONN_COMMON, - "process spectified listener node event failed: socket interface implement not support " - "AcceptClient method, wakeup trace=%d, module=%d", - wakeupTrace, module); + "socket interface implement not support AcceptClient method, wakeup trace=%d, module=%d", wakeupTrace, module); int32_t status = SOFTBUS_OK; while (true) { @@ -850,13 +783,14 @@ static int32_t ProcessSpecifiedServerAcceptEvent(ListenerModule module, int32_t char animizedIp[IP_LEN] = { 0 }; ConvertAnonymizeIpAddress(animizedIp, IP_LEN, clientAddr.socketOption.addr, IP_LEN); if (listener->onConnectEvent != NULL) { - CONN_LOGI(CONN_COMMON, "process spectified listener node event trace, trigger ACCEPT event, wakeup " - "trace=%d, module=%d, listen fd=%d, client ip=%s, client fd=%d", + CONN_LOGI(CONN_COMMON, + "trigger ACCEPT event, wakeup trace=%d, module=%d, listen fd=%d, client ip=%s, client fd=%d", wakeupTrace, module, listenFd, animizedIp, clientFd); listener->onConnectEvent(module, clientFd, &clientAddr); } else { - CONN_LOGE(CONN_COMMON, "process spectified listener node event trace, trigger ACCEPT event, but event " - "listener not registered, wakeup trace=%d, module=%d, listen fd=%d, client ip=%s, client fd=%d", + CONN_LOGE(CONN_COMMON, + "trigger ACCEPT event, but event listener not registered, wakeup trace=%d, module=%d, listen fd=%d, " + "client ip=%s, client fd=%d", wakeupTrace, module, listenFd, animizedIp, clientFd); ConnCloseSocket(clientFd); } @@ -875,8 +809,7 @@ static int32_t CopyWaitEventFdsUnsafe(const SoftbusListenerNode *node, FdNode ** uint32_t fdArrayLen = node->info.waitEventFdsLen; FdNode *fdArray = (FdNode *)SoftBusCalloc(fdArrayLen * sizeof(FdNode)); CONN_CHECK_AND_RETURN_RET_LOGE(fdArray != NULL, SOFTBUS_MALLOC_ERR, CONN_COMMON, - "ATTENTION UNEXPECTED ERROR! copy wait event fds failed: calloc fd node array object failed, module=%d, " - "wait event len=%u", node->module, fdArrayLen); + "calloc fd node array object failed, module=%d, wait event len=%u", node->module, fdArrayLen); uint32_t i = 0; FdNode *item = NULL; @@ -886,9 +819,7 @@ static int32_t CopyWaitEventFdsUnsafe(const SoftbusListenerNode *node, FdNode ** uint32_t tmpLen = fdArrayLen * FDARR_EXPAND_BASE; FdNode *tmp = (FdNode *)SoftBusCalloc(tmpLen * sizeof(FdNode)); if (tmp == NULL) { - CONN_LOGE(CONN_COMMON, - "copy wait event fds failed: expand calloc fd node array object failed, module=%d, wait event " - "len=%u", + CONN_LOGE(CONN_COMMON, "expand calloc fd node array object failed, module=%d, wait event len=%u", node->module, tmpLen); SoftBusFree(fdArray); return SOFTBUS_MALLOC_ERR; @@ -910,14 +841,12 @@ static int32_t CopyWaitEventFdsUnsafe(const SoftbusListenerNode *node, FdNode ** // diagnose by the way if (expand) { CONN_LOGE(CONN_COMMON, - "ATTENTION! copy wait event fds warining, listener node 'waitEventFdsLen' field is unexpected, actual " - "wait event fd size larget than it, forgot maintain while update fd? fix it quickly. module=%d, " + "listener node 'waitEventFdsLen' field is unexpected, actual wait event fd size larger than it, module=%d, " "wait event fds len=%u, actual wait event fds len=%u", node->module, node->info.waitEventFdsLen, i); } else if (i != fdArrayLen) { CONN_LOGE(CONN_COMMON, - "ATTENTION! copy wait event fds warining, listener node 'waitEventFdsLen' field is unexpected, actual " - "wait event fd size lower than it, forgot maintain while update fd? fix it quickly. module=%d, " + "listener node 'waitEventFdsLen' field is unexpected, actual wait event fd size lower than it, module=%d, " "wait event fds len=%u, actual wait event fds len=%u", node->module, node->info.waitEventFdsLen, i); } @@ -930,15 +859,14 @@ static int32_t CopyWaitEventFdsUnsafe(const SoftbusListenerNode *node, FdNode ** static void CloseInvalidListenForcely(SoftbusListenerNode *node, int32_t listenFd, const char *anomizedIp, int32_t reason) { - CONN_CHECK_AND_RETURN_LOGE(SoftBusMutexLock(&node->lock) == SOFTBUS_OK, CONN_COMMON, - "ATTENTION UNEXPECTED ERROR! close invalid listen forcely failed: try to lock listener node failed, module=%d", - node->module); + CONN_CHECK_AND_RETURN_LOGE( + SoftBusMutexLock(&node->lock) == SOFTBUS_OK, CONN_COMMON, "lock listener node failed, module=%d", node->module); do { if (node->info.status != LISTENER_RUNNING || node->info.modeType != SERVER_MODE || node->info.listenFd != listenFd) { break; } - CONN_LOGW(CONN_COMMON, "ATTENTION, forcely close to prevent repeat wakeup select, module=%d, invalid listen " + CONN_LOGW(CONN_COMMON, "forcely close to prevent repeat wakeup select, module=%d, invalid listen " "fd=%d port=%d, ip=%s, error=%d", node->module, node->info.listenFd, node->info.listenPort, anomizedIp, reason); ConnCloseSocket(node->info.listenFd); @@ -952,8 +880,7 @@ static void ProcessSpecifiedListenerNodeEvent(SoftbusListenerNode *node, SoftBus SoftBusFdSet *exceptSet, int32_t wakeupTrace) { CONN_CHECK_AND_RETURN_LOGE(SoftBusMutexLock(&node->lock) == SOFTBUS_OK, CONN_COMMON, - "ATTENTION UNEXPECTED ERROR! try to lock listener node failed, wakeup trace=%d, module=%d", - wakeupTrace, node->module); + "lock listener node failed, wakeup trace=%d, module=%d", wakeupTrace, node->module); if (node->info.status != LISTENER_RUNNING) { SoftBusMutexUnlock(&node->lock); return; @@ -976,10 +903,8 @@ static void ProcessSpecifiedListenerNodeEvent(SoftbusListenerNode *node, SoftBus int32_t status = CopyWaitEventFdsUnsafe(node, &fdArray, &fdArrayLen); SoftBusMutexUnlock(&node->lock); if (status != SOFTBUS_OK) { - CONN_LOGE(CONN_COMMON, - "process spectified listener node event failed: copy wait event fds failed, wakeup trace=%d, module=%d, " - "error=%d", - wakeupTrace, node->module, status); + CONN_LOGE(CONN_COMMON, "copy wait event fds failed, wakeup trace=%d, module=%d, error=%d", wakeupTrace, + node->module, status); return; } @@ -996,8 +921,7 @@ static void ProcessSpecifiedListenerNodeEvent(SoftbusListenerNode *node, SoftBus break; default: CONN_LOGD(CONN_COMMON, - "process spectified listener node event failed: accept client failed, wakeup trace=%d, " - "module=%d, listen fd=%d, port=%d, ip=%s, error=%d", + "accept client failed, wakeup trace=%d, module=%d, listen fd=%d, port=%d, ip=%s, error=%d", wakeupTrace, node->module, listenFd, listenPort, animizedIp, status); break; } @@ -1009,23 +933,18 @@ static void ProcessSpecifiedListenerNodeEvent(SoftbusListenerNode *node, SoftBus for (uint32_t i = 0; i < fdArrayLen; i++) { if ((fdArray[i].triggerSet & READ_TRIGGER) != 0 && SoftBusSocketFdIsset(fdArray[i].fd, readSet)) { - CONN_LOGD(CONN_COMMON, - "process spectified listener node event trace, trigger IN event, wakeup trace=%d, module=%d, fd=%d, " - "trigger set=%u", - wakeupTrace, node->module, fdArray[i].fd, fdArray[i].triggerSet); + CONN_LOGD(CONN_COMMON, "trigger IN event, wakeup trace=%d, module=%d, fd=%d, trigger set=%u", wakeupTrace, + node->module, fdArray[i].fd, fdArray[i].triggerSet); DispatchFdEvent(fdArray[i].fd, node->module, SOFTBUS_SOCKET_IN, &listener, wakeupTrace); } if ((fdArray[i].triggerSet & WRITE_TRIGGER) != 0 && SoftBusSocketFdIsset(fdArray[i].fd, writeSet)) { - CONN_LOGD(CONN_COMMON, - "process spectified listener node event trace, trigger OUT event, wakeup trace=%d, module=%d, fd=%d, " - "trigger set=%u", - wakeupTrace, node->module, fdArray[i].fd, fdArray[i].triggerSet); + CONN_LOGD(CONN_COMMON, "trigger OUT event, wakeup trace=%d, module=%d, fd=%d, trigger set=%u", wakeupTrace, + node->module, fdArray[i].fd, fdArray[i].triggerSet); DispatchFdEvent(fdArray[i].fd, node->module, SOFTBUS_SOCKET_OUT, &listener, wakeupTrace); } if ((fdArray[i].triggerSet & EXCEPT_TRIGGER) != 0 && SoftBusSocketFdIsset(fdArray[i].fd, exceptSet)) { CONN_LOGW(CONN_COMMON, - "process spectified listener node event trace, trigger EXCEPTION(out-of-band data) event, wakeup " - "trace=%d, module=%d, fd=%d, trigger set=%u", + "trigger EXCEPTION(out-of-band data) event, wakeup trace=%d, module=%d, fd=%d, trigger set=%u", wakeupTrace, node->module, fdArray[i].fd, fdArray[i].triggerSet); DispatchFdEvent(fdArray[i].fd, node->module, SOFTBUS_SOCKET_EXCEPTION, &listener, wakeupTrace); } @@ -1055,8 +974,7 @@ static int32_t CollectSpecifiedModuleListenerEvents( SoftbusListenerNode *node, SoftBusFdSet *readSet, SoftBusFdSet *writeSet, SoftBusFdSet *exceptSet) { CONN_CHECK_AND_RETURN_RET_LOGE(SoftBusMutexLock(&node->lock) == SOFTBUS_OK, SOFTBUS_LOCK_ERR, CONN_COMMON, - "ATTENTION UNEXPECTED ERROR! collect wait event fd set failed: try to lock listener node failed, module=%d", - node->module); + "lock listener node failed, module=%d", node->module); if (node->info.status != LISTENER_RUNNING) { (void)SoftBusMutexUnlock(&node->lock); @@ -1129,9 +1047,7 @@ static void *SelectTask(void *arg) while (true) { int status = SoftBusMutexLock(&selectState->lock); if (status != SOFTBUS_OK) { - CONN_LOGE(CONN_COMMON, - "ATTENTION UNEXPECTED ERROR! try to lock select thread state self failed, retry after %d ms, " - "select trace=%d, error=%d", + CONN_LOGE(CONN_COMMON, "lock select thread state self failed, retry after %d ms, select trace=%d, error=%d", SELECT_UNEXPECT_FAIL_RETRY_WAIT_MILLIS, selectState->traceId, status); SoftBusSleepMs(SELECT_UNEXPECT_FAIL_RETRY_WAIT_MILLIS); continue; @@ -1153,8 +1069,7 @@ static void *SelectTask(void *arg) SoftBusSocketFdZero(&exceptSet); int32_t maxFdOrStatus = CollectWaitEventFdSet(&readSet, &writeSet, &exceptSet); if (maxFdOrStatus < 0) { - CONN_LOGE(CONN_COMMON, - "select task failed: collect wait event fd set failed, retry after %d ms, select trace=%d, error=%d", + CONN_LOGE(CONN_COMMON, "collect wait event fd set failed, retry after %d ms, select trace=%d, error=%d", SELECT_UNEXPECT_FAIL_RETRY_WAIT_MILLIS, selectState->traceId, maxFdOrStatus); SoftBusSocketFdZero(&readSet); SoftBusSocketFdZero(&writeSet); @@ -1167,8 +1082,7 @@ static void *SelectTask(void *arg) int32_t nEvents = SoftBusSocketSelect(maxFd + 1, &readSet, &writeSet, &exceptSet, NULL); int32_t wakeupTraceId = ++wakeupTraceIdGenerator; if (nEvents <= 0) { - CONN_LOGE(CONN_COMMON, - "ATTENTION, select task failed: unexpect wakeup, retry after %d ms, wakeup trace id=%d, events=%d", + CONN_LOGE(CONN_COMMON, "unexpect wakeup, retry after %d ms, wakeup trace id=%d, events=%d", SELECT_UNEXPECT_FAIL_RETRY_WAIT_MILLIS, wakeupTraceId, nEvents); SoftBusSleepMs(SELECT_UNEXPECT_FAIL_RETRY_WAIT_MILLIS); continue; @@ -1186,16 +1100,14 @@ static int32_t StartSelectThread(void) static int32_t selectThreadTraceIdGenerator = 1; int32_t status = SoftBusMutexLock(&g_selectThreadStateLock); - CONN_CHECK_AND_RETURN_RET_LOGE(status == SOFTBUS_OK, SOFTBUS_LOCK_ERR, CONN_COMMON, - "ATTENTION UNEXPECTED ERROR! start select thread failed: try to lock global select thread state failed"); + CONN_CHECK_AND_RETURN_RET_LOGE( + status == SOFTBUS_OK, SOFTBUS_LOCK_ERR, CONN_COMMON, "lock global select thread state failed"); do { if (g_selectThreadState != NULL) { status = SoftBusMutexLock(&g_selectThreadState->lock); if (status != SOFTBUS_OK) { - CONN_LOGE(CONN_COMMON, "ATTENTION UNEXPECTED ERROR! start select thread failed: try to lock select " - "thread state self failed, error=%d", - status); + CONN_LOGE(CONN_COMMON, "lock select thread state self failed, error=%d", status); status = SOFTBUS_LOCK_ERR; break; } @@ -1204,7 +1116,7 @@ static int32_t StartSelectThread(void) WakeupSelectThread(); CONN_LOGW(CONN_COMMON, - "start select thread, select thread is already start, select trace=%d, ctrl read fd=%d, ctrl write " + "select thread is already start, select trace=%d, ctrl read fd=%d, ctrl write " "fd=%d, reference count=%d", g_selectThreadState->traceId, g_selectThreadState->ctrlRfd, g_selectThreadState->ctrlWfd, referenceCount); @@ -1223,7 +1135,7 @@ static int32_t StartSelectThread(void) rc = pipe2(fds, O_CLOEXEC | O_NONBLOCK); #endif if (rc != 0) { - CONN_LOGE(CONN_COMMON, "start select thread failed: create ctrl pipe failed, error=%s", strerror(errno)); + CONN_LOGE(CONN_COMMON, "create ctrl pipe failed, error=%s", strerror(errno)); SoftBusFree(state); status = SOFTBUS_ERR; break; @@ -1233,14 +1145,14 @@ static int32_t StartSelectThread(void) status = SoftBusMutexInit(&state->lock, NULL); if (status != SOFTBUS_OK) { - CONN_LOGE(CONN_COMMON, "start select thread failed: start select task async failed, error=%d", status); + CONN_LOGE(CONN_COMMON, "start select task async failed, error=%d", status); CleanupSelectThreadState(&state); break; } state->referenceCount = 1; status = ConnStartActionAsync(state, SelectTask, "OS_selectTsk"); if (status != SOFTBUS_OK) { - CONN_LOGE(CONN_COMMON, "start select thread failed: init lock failed, error=%d", status); + CONN_LOGE(CONN_COMMON, "init lock failed, error=%d", status); CleanupSelectThreadState(&state); break; } @@ -1255,26 +1167,24 @@ static int32_t StartSelectThread(void) static int32_t StopSelectThread(void) { int32_t status = SoftBusMutexLock(&g_selectThreadStateLock); - CONN_CHECK_AND_RETURN_RET_LOGE(status == SOFTBUS_OK, SOFTBUS_LOCK_ERR, CONN_COMMON, - "ATTENTION UNEXPECTED ERROR! stop select thread failed: try to lock global select thread state " - "failed"); + CONN_CHECK_AND_RETURN_RET_LOGE( + status == SOFTBUS_OK, SOFTBUS_LOCK_ERR, CONN_COMMON, "lock global select thread state failed"); do { if (g_selectThreadState == NULL) { - CONN_LOGW(CONN_COMMON, "stop select thread, select thread is already stop or never start"); + CONN_LOGW(CONN_COMMON, "select thread is already stop or never start"); break; } status = SoftBusMutexLock(&g_selectThreadState->lock); if (status != SOFTBUS_OK) { - CONN_LOGE(CONN_COMMON, "ATTENTION UNEXPECTED ERROR! stop select thread, try to lock select thread state " - "self"); + CONN_LOGE(CONN_COMMON, "lock select thread state self"); break; } g_selectThreadState->referenceCount -= 1; int32_t referenceCount = g_selectThreadState->referenceCount; (void)SoftBusMutexUnlock(&g_selectThreadState->lock); if (referenceCount <= 0) { - CONN_LOGI(CONN_COMMON, "stop select thread, select thread is not used by other module any more, notify " + CONN_LOGI(CONN_COMMON, "select thread is not used by other module any more, notify " "exit, thread reference count=%d", referenceCount); WakeupSelectThread(); g_selectThreadState = NULL; @@ -1290,19 +1200,16 @@ static void WakeupSelectThread(void) static int32_t selectWakeupTraceIdGenerator = 0; int32_t status = SoftBusMutexLock(&g_selectThreadStateLock); - CONN_CHECK_AND_RETURN_LOGE(status == SOFTBUS_OK, CONN_COMMON, - "ATTENTION UNEXPECTED ERROR! wakeup select thread failed: try to lock global select thread state " - "failed, error=%d", - status); + CONN_CHECK_AND_RETURN_LOGE( + status == SOFTBUS_OK, CONN_COMMON, "lock global select thread state failed, error=%d", status); do { if (g_selectThreadState == NULL) { - CONN_LOGW(CONN_COMMON, "wakeup select thread warning: select thread is not running, just skip"); + CONN_LOGW(CONN_COMMON, "select thread is not running, just skip"); break; } int32_t ctrlTraceId = selectWakeupTraceIdGenerator++; ssize_t len = write(g_selectThreadState->ctrlWfd, &ctrlTraceId, sizeof(ctrlTraceId)); - CONN_LOGI(CONN_COMMON, "wakeup select thread, wakeup ctrl message sent, write length=%d, ctrl trace=%d", len, - ctrlTraceId); + CONN_LOGI(CONN_COMMON, "wakeup ctrl message sent, write length=%d, ctrl trace=%d", len, ctrlTraceId); } while (false); SoftBusMutexUnlock(&g_selectThreadStateLock); #endif diff --git a/core/connection/interface/softbus_conn_interface.h b/core/connection/interface/softbus_conn_interface.h index 61f71a812..c4a8d22b0 100644 --- a/core/connection/interface/softbus_conn_interface.h +++ b/core/connection/interface/softbus_conn_interface.h @@ -45,6 +45,7 @@ typedef enum { MODULE_TIME_SYNC = 18, MODULE_PKG_VERIFY = 20, MODULE_META_AUTH = 21, + MODULE_P2P_NEGO = 22, MODULE_BLE_NET = 100, MODULE_BLE_CONN = 101, MODULE_NIP_BR_CHANNEL = 201, @@ -69,11 +70,14 @@ typedef enum { #define BT_LINK_TYPE_BR 1 #define BT_LINK_TYPE_BLE 2 #define HML_INDEX 3 +#define AUTH_ENHANCED_P2P_NUM 4 typedef enum { PROXY = 0, AUTH, AUTH_P2P, + AUTH_ENHANCED_P2P_START, + AUTH_ENHANCED_P2P_END = AUTH_ENHANCED_P2P_START + AUTH_ENHANCED_P2P_NUM - 1, DIRECT_CHANNEL_SERVER_P2P, DIRECT_CHANNEL_CLIENT, DIRECT_CHANNEL_SERVER_WIFI, @@ -415,4 +419,4 @@ int32_t ConnGetTypeByConnectionId(uint32_t connectionId, ConnectType *type); #endif /* __cplusplus */ #endif /* __cplusplus */ -#endif +#endif \ No newline at end of file diff --git a/core/connection/manager/softbus_conn_manager.c b/core/connection/manager/softbus_conn_manager.c index 0137148d4..498dcf96f 100644 --- a/core/connection/manager/softbus_conn_manager.c +++ b/core/connection/manager/softbus_conn_manager.c @@ -154,7 +154,7 @@ static int32_t ModuleCheck(ConnModule moduleId) ConnModule id[] = { MODULE_TRUST_ENGINE, MODULE_HICHAIN, MODULE_AUTH_SDK, MODULE_AUTH_CONNECTION, MODULE_MESSAGE_SERVICE, MODULE_AUTH_CHANNEL, MODULE_AUTH_MSG, MODULE_BLUETOOTH_MANAGER, MODULE_CONNECTION, MODULE_DIRECT_CHANNEL, MODULE_PROXY_CHANNEL, MODULE_DEVICE_AUTH, MODULE_P2P_LINK, MODULE_UDP_INFO, - MODULE_PKG_VERIFY, MODULE_META_AUTH, MODULE_BLE_NET, MODULE_BLE_CONN }; + MODULE_PKG_VERIFY, MODULE_META_AUTH, MODULE_P2P_NEGO, MODULE_BLE_NET, MODULE_BLE_CONN }; int32_t i; int32_t idNum = sizeof(id) / sizeof(ConnModule); @@ -337,7 +337,7 @@ void ConnManagerRecvData(uint32_t connectionId, ConnModule moduleId, int64_t seq "dispatch data failed: get module listener failed or not register, connection id=%u, module=%d, dataLen=%d, " "err=%d", connectionId, moduleId, len, status); - int32_t pktLen = len - sizeof(ConnPktHead); + int32_t pktLen = len - (int32_t)sizeof(ConnPktHead); char *pkt = data + sizeof(ConnPktHead); listener.callback.OnDataReceived(connectionId, moduleId, seq, pkt, pktLen); } @@ -416,7 +416,7 @@ void ConnManagerConnected(uint32_t connectionId, const ConnectionInfo *info) int32_t num = GetAllListener(&node); if (num == 0 || node == NULL) { - CONN_LOGE(CONN_COMMON, "get node failed connId=%u", connectionId); + CONN_LOGE(CONN_COMMON, "get node failed, connId=%u", connectionId); return; } @@ -436,7 +436,7 @@ void ConnManagerReusedConnected(uint32_t connectionId, const ConnectionInfo *inf int32_t num = GetAllListener(&node); if (num == 0 || node == NULL) { - CONN_LOGE(CONN_COMMON, "get node failed connId=%u", connectionId); + CONN_LOGE(CONN_COMMON, "get node failed, connId=%u", connectionId); return; } @@ -458,7 +458,7 @@ void ConnManagerDisconnected(uint32_t connectionId, const ConnectionInfo *info) int32_t num = GetAllListener(&node); if (num == 0 || node == NULL) { - CONN_LOGE(CONN_COMMON, "get node failed connId=%u", connectionId); + CONN_LOGE(CONN_COMMON, "get node failed, connId=%u", connectionId); return; } for (int32_t i = 0; i < num; i++) { @@ -472,7 +472,7 @@ void ConnManagerDisconnected(uint32_t connectionId, const ConnectionInfo *info) int32_t ConnSetConnectCallback(ConnModule moduleId, const ConnectCallback *callback) { if (ModuleCheck(moduleId) != SOFTBUS_OK) { - CONN_LOGE(CONN_COMMON, "module check failed moduleId=%d", moduleId); + CONN_LOGE(CONN_COMMON, "module check failed, moduleId=%d", moduleId); return SOFTBUS_INVALID_PARAM; } diff --git a/core/connection/tcp/src/softbus_tcp_connect_manager.c b/core/connection/tcp/src/softbus_tcp_connect_manager.c index 22a48bf09..69031abc1 100644 --- a/core/connection/tcp/src/softbus_tcp_connect_manager.c +++ b/core/connection/tcp/src/softbus_tcp_connect_manager.c @@ -199,6 +199,14 @@ static void DelTcpConnNode(uint32_t connectionId) return; } +static bool IsEnhanceP2pModuleId(ListenerModule moduleId) +{ + if (moduleId >= AUTH_ENHANCED_P2P_START && moduleId <= AUTH_ENHANCED_P2P_END) { + return true; + } + return false; +} + static int32_t TcpOnConnectEvent(ListenerModule module, int32_t cfd, const ConnectOption *clientAddr) { if (cfd < 0 || clientAddr == NULL) { @@ -206,7 +214,7 @@ static int32_t TcpOnConnectEvent(ListenerModule module, int32_t cfd, const Conne return SOFTBUS_INVALID_PARAM; } - if (module == AUTH_P2P) { + if (module == AUTH_P2P || IsEnhanceP2pModuleId(module)) { CONN_LOGI(CONN_COMMON, "recv p2p conned %d", cfd); if (ConnSetTcpKeepAlive(cfd, AUTH_P2P_KEEP_ALIVE_TIME) != 0) { CONN_LOGE(CONN_COMMON, "set keepalive fail"); diff --git a/core/connection/wifi_direct/adapter/single/resource_manager_broadcast_handler.c b/core/connection/wifi_direct/adapter/single/resource_manager_broadcast_handler.c index e11946b55..4c14db9e1 100644 --- a/core/connection/wifi_direct/adapter/single/resource_manager_broadcast_handler.c +++ b/core/connection/wifi_direct/adapter/single/resource_manager_broadcast_handler.c @@ -62,7 +62,7 @@ static void ResetInterfaceInfo(void) int32_t port = oldInfo->getInt(oldInfo, II_KEY_PORT, -1); if (port > 0) { CONN_LOGI(CONN_WIFI_DIRECT, "stop auth listening"); - StopListeningForDefaultChannel(); + StopListeningForDefaultChannel(AUTH_LINK_TYPE_P2P, AUTH_P2P); } struct InterfaceInfo info; diff --git a/core/connection/wifi_direct/channel/default_negotiate_channel.c b/core/connection/wifi_direct/channel/default_negotiate_channel.c index c27fbc88a..03e041552 100644 --- a/core/connection/wifi_direct/channel/default_negotiate_channel.c +++ b/core/connection/wifi_direct/channel/default_negotiate_channel.c @@ -19,9 +19,9 @@ #include "conn_log.h" #include "softbus_adapter_mem.h" #include "softbus_adapter_thread.h" -#include "auth_interface.h" #include "auth_manager.h" #include "bus_center_manager.h" +#include "lnn_distributed_net_ledger.h" #include "wifi_direct_negotiator.h" #include "utils/wifi_direct_work_queue.h" #include "utils/wifi_direct_anonymous.h" @@ -133,7 +133,7 @@ static int32_t PostDataWithFlag(struct DefaultNegotiateChannel *self, const uint }; CONN_CHECK_AND_RETURN_RET_LOGE(AuthPostTransData(self->authId, &dataInfo) == SOFTBUS_OK, SOFTBUS_ERR, - CONN_WIFI_DIRECT, "post data failed"); + CONN_WIFI_DIRECT, "post data failed"); return SOFTBUS_OK; } @@ -249,28 +249,40 @@ void DefaultNegotiateChannelDelete(struct DefaultNegotiateChannel *self) SoftBusFree(self); } -int32_t OpenDefaultNegotiateChannel(const char *remoteIp, int32_t remotePort, +int32_t OpenDefaultNegotiateChannel(struct DefaultNegoChannelParam *param, struct WifiDirectNegotiateChannel *srcChannel, struct DefaultNegoChannelOpenCallback *callback) { - CONN_CHECK_AND_RETURN_RET_LOGW(remoteIp != NULL, SOFTBUS_ERR, CONN_WIFI_DIRECT, "remoteIp is null"); + CONN_CHECK_AND_RETURN_RET_LOGW(param != NULL, SOFTBUS_ERR, CONN_WIFI_DIRECT, "param is null"); + CONN_CHECK_AND_RETURN_RET_LOGW(param->remoteUuid != NULL, SOFTBUS_ERR, CONN_WIFI_DIRECT, "remoteUuid is null"); + CONN_CHECK_AND_RETURN_RET_LOGW(param->remoteIp != NULL, SOFTBUS_ERR, CONN_WIFI_DIRECT, "remoteIp is null"); CONN_CHECK_AND_RETURN_RET_LOGW(callback != NULL, SOFTBUS_ERR, CONN_WIFI_DIRECT, "callback is null"); + bool isMeta = false; if ((srcChannel != NULL) && (srcChannel->isMetaChannel != NULL)) { isMeta = srcChannel->isMetaChannel(srcChannel); } - CONN_LOGI(CONN_WIFI_DIRECT, "remoteIp=%s remotePort=%d isMeta=%d", WifiDirectAnonymizeIp(remoteIp), remotePort, - isMeta); + CONN_LOGI(CONN_WIFI_DIRECT, "remoteUuid=%s remoteIp=%s remotePort=%d isMeta=%d", + WifiDirectAnonymizeDeviceId(param->remoteUuid), WifiDirectAnonymizeIp(param->remoteIp), + param->remotePort, isMeta); + + const char *remoteUdid = LnnConvertDLidToUdid(param->remoteUuid, CATEGORY_UUID); + CONN_CHECK_AND_RETURN_RET_LOGE(remoteUdid != NULL && strlen(remoteUdid) != 0, SOFTBUS_ERR, CONN_WIFI_DIRECT, + "get remote udid failed"); + CONN_LOGI(CONN_WIFI_DIRECT, "remoteUdid=%s", WifiDirectAnonymizeDeviceId(remoteUdid)); AuthConnInfo authConnInfo; (void)memset_s(&authConnInfo, sizeof(authConnInfo), 0, sizeof(authConnInfo)); - authConnInfo.type = AUTH_LINK_TYPE_P2P; - authConnInfo.info.ipInfo.port = remotePort; + authConnInfo.type = param->type; + authConnInfo.info.ipInfo.port = param->remotePort; + authConnInfo.info.ipInfo.moduleId = param->localModuleId; if (isMeta) { authConnInfo.info.ipInfo.authId = ((struct DefaultNegotiateChannel*)srcChannel)->authId; } - int32_t ret = strcpy_s(authConnInfo.info.ipInfo.ip, sizeof(authConnInfo.info.ipInfo.ip), remoteIp); + int32_t ret = strcpy_s(authConnInfo.info.ipInfo.ip, sizeof(authConnInfo.info.ipInfo.ip), param->remoteIp); CONN_CHECK_AND_RETURN_RET_LOGW(ret == EOK, SOFTBUS_ERR, CONN_WIFI_DIRECT, "copy ip failed"); + ret = strcpy_s(authConnInfo.info.ipInfo.udid, UDID_BUF_LEN, remoteUdid); + CONN_CHECK_AND_RETURN_RET_LOGE(ret == EOK, SOFTBUS_ERR, CONN_WIFI_DIRECT, "copy udid failed"); AuthConnCallback authConnCallback = { .onConnOpened = callback->onConnectSuccess, @@ -289,14 +301,16 @@ void CloseDefaultNegotiateChannel(struct DefaultNegotiateChannel *self) AuthCloseConn(self->authId); } -int32_t StartListeningForDefaultChannel(const char *localIp, int32_t port) +int32_t StartListeningForDefaultChannel(AuthLinkType type, const char *localIp, int32_t port, ListenerModule *moduleId) { - int32_t ret = AuthStartListening(AUTH_LINK_TYPE_P2P, localIp, port); - CONN_LOGI(CONN_WIFI_DIRECT, "localIp=%s port=%d", WifiDirectAnonymizeIp(localIp), ret); + int32_t ret = AuthStartListeningForWifiDirect(type, localIp, port, moduleId); + CONN_LOGI(CONN_WIFI_DIRECT, "type=%d localIp=%s port=%d moduleId=%d", + type, WifiDirectAnonymizeIp(localIp), ret, *moduleId); return ret; } -void StopListeningForDefaultChannel(void) +void StopListeningForDefaultChannel(AuthLinkType type, ListenerModule moduleId) { - AuthStopListening(AUTH_LINK_TYPE_P2P); + CONN_LOGI(CONN_WIFI_DIRECT, "type=%d moduleId=%d", type, moduleId); + AuthStopListeningForWifiDirect(type, moduleId); } \ No newline at end of file diff --git a/core/connection/wifi_direct/channel/default_negotiate_channel.h b/core/connection/wifi_direct/channel/default_negotiate_channel.h index 1cbb74e0b..17ef92342 100644 --- a/core/connection/wifi_direct/channel/default_negotiate_channel.h +++ b/core/connection/wifi_direct/channel/default_negotiate_channel.h @@ -17,6 +17,7 @@ #define DEFAULT_NEGOTIATE_CHANNEL_H #include "wifi_direct_negotiate_channel.h" +#include "auth_interface.h" #ifdef __cplusplus extern "C" { @@ -36,17 +37,25 @@ void DefaultNegotiateChannelDestructor(struct DefaultNegotiateChannel *self); struct DefaultNegotiateChannel* DefaultNegotiateChannelNew(int64_t authId); void DefaultNegotiateChannelDelete(struct DefaultNegotiateChannel *self); +struct DefaultNegoChannelParam { + AuthLinkType type; + char *remoteUuid; + char *remoteIp; + int32_t remotePort; + ListenerModule localModuleId; +}; + struct DefaultNegoChannelOpenCallback { void (*onConnectSuccess)(uint32_t requestId, int64_t authId); void (*onConnectFailure)(uint32_t requestId, int32_t reason); }; -int32_t OpenDefaultNegotiateChannel(const char *remoteIp, int32_t remotePort, +int32_t OpenDefaultNegotiateChannel(struct DefaultNegoChannelParam *param, struct WifiDirectNegotiateChannel *srcChannel, struct DefaultNegoChannelOpenCallback *callback); void CloseDefaultNegotiateChannel(struct DefaultNegotiateChannel *self); -int32_t StartListeningForDefaultChannel(const char *localIp, int32_t port); -void StopListeningForDefaultChannel(void); +int32_t StartListeningForDefaultChannel(AuthLinkType type, const char *localIp, int32_t port, ListenerModule *moduleId); +void StopListeningForDefaultChannel(AuthLinkType type, ListenerModule moduleId); int32_t DefaultNegotiateChannelInit(void); diff --git a/core/connection/wifi_direct/channel/default_negotiate_channel_virtual.c b/core/connection/wifi_direct/channel/default_negotiate_channel_virtual.c index bb1a579f6..bb16fbdf1 100644 --- a/core/connection/wifi_direct/channel/default_negotiate_channel_virtual.c +++ b/core/connection/wifi_direct/channel/default_negotiate_channel_virtual.c @@ -37,12 +37,11 @@ void DefaultNegotiateChannelDelete(struct DefaultNegotiateChannel *self) (void)self; } -int32_t OpenDefaultNegotiateChannel(const char *remoteIp, int32_t remotePort, +int32_t OpenDefaultNegotiateChannel(struct DefaultNegoChannelParam *param, struct WifiDirectNegotiateChannel *srcChannel, struct DefaultNegoChannelOpenCallback *callback) { - (void)remoteIp; - (void)remotePort; + (void)param; (void)srcChannel; (void)callback; return 0; @@ -53,15 +52,19 @@ void CloseDefaultNegotiateChannel(struct DefaultNegotiateChannel *self) (void)self; } -int32_t StartListeningForDefaultChannel(const char *localIp, int32_t port) +int32_t StartListeningForDefaultChannel(AuthLinkType type, const char *localIp, int32_t port, ListenerModule *moduleId) { + (void)type; (void)localIp; (void)port; + (void)moduleId; return 0; } -void StopListeningForDefaultChannel(void) +void StopListeningForDefaultChannel(AuthLinkType type, ListenerModule moduleId) { + (void)type; + (void)moduleId; } int32_t DefaultNegotiateChannelInit(void) diff --git a/core/connection/wifi_direct/command/wifi_direct_negotiate_command.c b/core/connection/wifi_direct/command/wifi_direct_negotiate_command.c index 834b3d5d5..93b5ca6b1 100644 --- a/core/connection/wifi_direct/command/wifi_direct_negotiate_command.c +++ b/core/connection/wifi_direct/command/wifi_direct_negotiate_command.c @@ -16,13 +16,23 @@ #include "conn_log.h" #include "softbus_adapter_mem.h" #include "wifi_direct_negotiator.h" +#include "wifi_direct_decision_center.h" #include "channel/wifi_direct_negotiate_channel.h" +#include "data/link_info.h" #include "data/link_manager.h" #include "data/resource_manager.h" static void ExecuteProcessRemoteNegotiateMessage(struct WifiDirectCommand *base) { struct WifiDirectNegotiateCommand *self = (struct WifiDirectNegotiateCommand *)base; + struct LinkInfo *linkInfo = self->msg->getContainer(self->msg, NM_KEY_LINK_INFO); + if (linkInfo != NULL) { + self->msg->remove(self->msg, NM_KEY_LINK_INFO); + } + struct WifiDirectProcessor *processor = GetWifiDirectDecisionCenter()->getProcessorByNegotiateMessage(self->msg); + if (processor != NULL) { + base->processor = processor; + } struct WifiDirectNegotiator *negotiator = GetWifiDirectNegotiator(); negotiator->currentCommand = base; negotiator->currentProcessor = base->processor; @@ -93,4 +103,4 @@ void WifiDirectNegotiateCommandDelete(struct WifiDirectCommand *base) CONN_LOGI(CONN_WIFI_DIRECT, "enter"); WifiDirectNegotiateCommandDestructor((struct WifiDirectNegotiateCommand *)base); SoftBusFree(base); -} \ No newline at end of file +} diff --git a/core/connection/wifi_direct/data/inner_link.c b/core/connection/wifi_direct/data/inner_link.c index 4d12010fd..1a9be64c8 100644 --- a/core/connection/wifi_direct/data/inner_link.c +++ b/core/connection/wifi_direct/data/inner_link.c @@ -43,6 +43,8 @@ #define IL_TAG_STATE_CHANGE_TIME 16 #define IL_TAG_DEVICE_ID 17 #define IL_TAG_AUTH_CONNECTION 18 +#define IL_TAG_LOCAL_PORT 19 +#define IL_TAG_LISTENER_MODULE_ID 20 IC_DECLARE_KEY_PROPERTIES(InnerLink, IL_KEY_MAX) = { IC_KEY_PROPERTY(IL_KEY_LINK_TYPE, IL_TAG_CONNECT_TYPE, "CONNECT_TYPE", INT, DUMP_FLAG), @@ -64,6 +66,8 @@ IC_DECLARE_KEY_PROPERTIES(InnerLink, IL_KEY_MAX) = { IC_KEY_PROPERTY(IL_KEY_STATE_CHANGE_TIME, IL_TAG_STATE_CHANGE_TIME, "STATE_CHANGE_TIME", LONG, 0), IC_KEY_PROPERTY(IL_KEY_DEVICE_ID, IL_TAG_DEVICE_ID, "DEVICE_ID", STRING, DEVICE_ID_FLAG | DUMP_FLAG), IC_KEY_PROPERTY(IL_KEY_NEGO_CHANNEL, IL_TAG_AUTH_CONNECTION, "AUTH_CONNECTION", AUTH_CONNECTION, 0), + IC_KEY_PROPERTY(IL_KEY_LOCAL_PORT, IL_TAG_LOCAL_PORT, "LOCAL_PORT", INT, 0), + IC_KEY_PROPERTY(IL_KEY_LISTENER_MODULE_ID, IL_TAG_LISTENER_MODULE_ID, "LISTENER_MODULE_ID", INT, 0), }; struct LinkIdStruct { @@ -91,7 +95,7 @@ static const char *GetContainerName(void) static bool Marshalling(struct InnerLink *self, struct WifiDirectProtocol *protocol) { for (size_t key = 0; key < IL_KEY_MAX; key++) { - if (key == IL_KEY_DEVICE_ID) { + if (key == IL_KEY_DEVICE_ID || key == IL_KEY_LOCAL_PORT || key == IL_KEY_LISTENER_MODULE_ID) { continue; } diff --git a/core/connection/wifi_direct/data/inner_link.h b/core/connection/wifi_direct/data/inner_link.h index fac07a99a..2de786fa1 100644 --- a/core/connection/wifi_direct/data/inner_link.h +++ b/core/connection/wifi_direct/data/inner_link.h @@ -42,6 +42,8 @@ enum InnerLinkKey { IL_KEY_STATE_CHANGE_TIME = 14, IL_KEY_DEVICE_ID = 15, IL_KEY_NEGO_CHANNEL = 16, + IL_KEY_LOCAL_PORT = 17, + IL_KEY_LISTENER_MODULE_ID = 18, IL_KEY_MAX }; diff --git a/core/connection/wifi_direct/data/link_info.c b/core/connection/wifi_direct/data/link_info.c index cb17723e0..202c41c4b 100644 --- a/core/connection/wifi_direct/data/link_info.c +++ b/core/connection/wifi_direct/data/link_info.c @@ -279,8 +279,8 @@ void LinkInfoConstructorWithNameAndMode(struct LinkInfo* self, const char *local LinkInfoConstructor(self); self->putString(self, LI_KEY_LOCAL_INTERFACE, localName); self->putString(self, LI_KEY_REMOTE_INTERFACE, remoteName); - self->putInt(self, LI_KEY_LOCAL_LINK_MODE, localMode); - self->putInt(self, LI_KEY_REMOTE_LINK_MODE, remoteMode); + self->putInt(self, LI_KEY_LOCAL_LINK_MODE, (int32_t)localMode); + self->putInt(self, LI_KEY_REMOTE_LINK_MODE, (int32_t)remoteMode); } /* new and delete */ diff --git a/core/connection/wifi_direct/data/link_manager.c b/core/connection/wifi_direct/data/link_manager.c index f73601065..ee5561709 100644 --- a/core/connection/wifi_direct/data/link_manager.c +++ b/core/connection/wifi_direct/data/link_manager.c @@ -353,7 +353,7 @@ static void ClearNegotiateChannelForLink(struct WifiDirectNegotiateChannel *chan for (size_t type = 0; type < WIFI_DIRECT_LINK_TYPE_MAX; type++) { LIST_FOR_EACH_ENTRY(target, &self->linkLists[type], struct InnerLink, node) { struct WifiDirectNegotiateChannel *targetChannel = target->getPointer(target, IL_KEY_NEGO_CHANNEL, NULL); - if (channel->equal(channel, targetChannel)) { + if ((targetChannel != NULL) && (channel->equal(channel, targetChannel))) { CONN_LOGI(CONN_WIFI_DIRECT, "find"); found = true; break; @@ -593,6 +593,15 @@ static void CloseP2pNegotiateChannel(struct InnerLink *innerLink) if (channel != NULL) { CONN_LOGD(CONN_WIFI_DIRECT, "enter"); CloseDefaultNegotiateChannel(channel); + enum WifiDirectLinkType type = innerLink->getInt(innerLink, IL_KEY_LINK_TYPE, WIFI_DIRECT_LINK_TYPE_INVALID); + ListenerModule module = innerLink->getInt(innerLink, IL_KEY_LISTENER_MODULE_ID, -1); + if (module > 0) { + if (type == WIFI_DIRECT_LINK_TYPE_P2P) { + StopListeningForDefaultChannel(AUTH_LINK_TYPE_P2P, module); + } else if (type == WIFI_DIRECT_LINK_TYPE_HML) { + StopListeningForDefaultChannel(AUTH_LINK_TYPE_ENHANCED_P2P, module); + } + } DefaultNegotiateChannelDelete(channel); innerLink->remove(innerLink, IL_KEY_NEGO_CHANNEL); } diff --git a/core/connection/wifi_direct/data/negotiate_message.h b/core/connection/wifi_direct/data/negotiate_message.h index f6c2388d2..a45fdc38d 100644 --- a/core/connection/wifi_direct/data/negotiate_message.h +++ b/core/connection/wifi_direct/data/negotiate_message.h @@ -65,7 +65,9 @@ enum NegotiateMessageKey { NM_KEY_GC_CHANNEL_SCORE = 37, NM_KEY_COMMAND_TYPE = 38, NM_KEY_INTERFACE_NAME = 39, - NM_KEY_CHANNEL_ID = 40, + + /* H2.0 */ + NM_KEY_P2P_GROUP_CONFIG = 40, NM_KEY_MAX }; diff --git a/core/connection/wifi_direct/entity/wifi_direct_entity.h b/core/connection/wifi_direct/entity/wifi_direct_entity.h index cb8a646ed..f85eb849c 100755 --- a/core/connection/wifi_direct/entity/wifi_direct_entity.h +++ b/core/connection/wifi_direct/entity/wifi_direct_entity.h @@ -60,6 +60,7 @@ enum EntityOperationEvent { ENTITY_EVENT_HML_REMOVE_COMPLETE, ENTITY_EVENT_HML_NOTIFY_COMPLETE, ENTITY_EVENT_HML_JOIN_COMPLETE, + ENTITY_EVENT_HML_SWITCH_NOTIFY_COMPLETE, ENTITY_EVENT_HML_END, }; @@ -75,6 +76,7 @@ struct EntityListener { int32_t (*reuseLink)(struct WifiDirectConnectParams *params); \ int32_t (*disconnect)(struct WifiDirectConnectParams *params); \ int32_t (*destroyServer)(struct WifiDirectConnectParams *params); \ + int32_t (*switchNotify)(struct WifiDirectConnectParams *params); \ void (*notifyNewClientJoining)(struct WifiDirectConnectParams *params); \ void (*notifyNewClientJoinFail)(struct WifiDirectConnectParams *params); \ void (*cancelNewClientJoining)(struct WifiDirectConnectParams *params); \ diff --git a/core/connection/wifi_direct/processor/p2p_v1_processor.c b/core/connection/wifi_direct/processor/p2p_v1_processor.c index c71d4153c..fc16c0cbb 100644 --- a/core/connection/wifi_direct/processor/p2p_v1_processor.c +++ b/core/connection/wifi_direct/processor/p2p_v1_processor.c @@ -1327,7 +1327,8 @@ static void StartAuthListening(const char *localIp) return; } - port = StartListeningForDefaultChannel(localIp, 0); + ListenerModule module = 0; + port = StartListeningForDefaultChannel(AUTH_LINK_TYPE_P2P, localIp, 0, &module); info->putInt(info, II_KEY_PORT, port); } @@ -1357,8 +1358,6 @@ static void SendHandShakeToGoAsync(void *data) static void OnAuthConnectSuccess(uint32_t authRequestId, int64_t p2pAuthId) { - GetWifiDirectNegotiator()->onWifiDirectAuthOpened(authRequestId, p2pAuthId); - struct DefaultNegotiateChannel *channel = DefaultNegotiateChannelNew(p2pAuthId); CONN_CHECK_AND_RETURN_LOGW(channel, CONN_WIFI_DIRECT, "new channel failed"); @@ -1379,14 +1378,22 @@ static void OpenAuthConnection(struct WifiDirectNegotiateChannel *channel, struc int32_t ret = link->getRemoteIpString(link, remoteIp, sizeof(remoteIp)); CONN_CHECK_AND_RETURN_LOGW(ret == SOFTBUS_OK, CONN_WIFI_DIRECT, "get remote ip failed"); char *remoteMac = link->getString(link, IL_KEY_REMOTE_BASE_MAC, ""); - CONN_LOGI(CONN_WIFI_DIRECT, "remoteMac=%s remoteIp=%s remotePort=%d", WifiDirectAnonymizeMac(remoteMac), - WifiDirectAnonymizeIp(remoteIp), remotePort); + char *remoteUuid = link->getString(link, IL_KEY_DEVICE_ID, ""); + CONN_LOGI(CONN_WIFI_DIRECT, "remoteMac=%s remoteUuid=%s remoteIp=%s remotePort=%d", + WifiDirectAnonymizeMac(remoteMac), WifiDirectAnonymizeDeviceId(remoteUuid), + WifiDirectAnonymizeIp(remoteIp), remotePort); + struct DefaultNegoChannelParam param = { + .type = AUTH_LINK_TYPE_P2P, + .remoteUuid = remoteUuid, + .remoteIp = remoteIp, + .remotePort = remotePort, + }; struct DefaultNegoChannelOpenCallback callback = { .onConnectSuccess = OnAuthConnectSuccess, .onConnectFailure = OnAuthConnectFailure, }; - ret = OpenDefaultNegotiateChannel(remoteIp, remotePort, channel, &callback); + ret = OpenDefaultNegotiateChannel(¶m, channel, &callback); CONN_CHECK_AND_RETURN_LOGW(ret == SOFTBUS_OK, CONN_WIFI_DIRECT, "open p2p auth failed"); } diff --git a/core/connection/wifi_direct/processor/wifi_direct_processor_factory.c b/core/connection/wifi_direct/processor/wifi_direct_processor_factory.c index 4853388c0..874cdcdab 100644 --- a/core/connection/wifi_direct/processor/wifi_direct_processor_factory.c +++ b/core/connection/wifi_direct/processor/wifi_direct_processor_factory.c @@ -15,7 +15,6 @@ #include "wifi_direct_processor_factory.h" #include "processor/p2p_v1_processor.h" -#include "wifi_direct_negotiator.h" static struct WifiDirectProcessor* CreateProcessor(enum WifiDirectProcessorType type) { diff --git a/core/connection/wifi_direct/protocol/tlv_protocol.c b/core/connection/wifi_direct/protocol/tlv_protocol.c index 0dc270199..ab438780e 100644 --- a/core/connection/wifi_direct/protocol/tlv_protocol.c +++ b/core/connection/wifi_direct/protocol/tlv_protocol.c @@ -90,6 +90,7 @@ static bool ReadData(struct WifiDirectProtocol *base, struct InfoContainerKeyPro return false; } if (self->size - self->readPos < self->format.tagSize + self->format.lengthSize) { + CONN_LOGE(CONN_WIFI_DIRECT, "size sub readPos invalid"); return false; } diff --git a/core/connection/wifi_direct/protocol/wifi_direct_protocol_factory.c b/core/connection/wifi_direct/protocol/wifi_direct_protocol_factory.c index 91da1f31b..f7f90f289 100644 --- a/core/connection/wifi_direct/protocol/wifi_direct_protocol_factory.c +++ b/core/connection/wifi_direct/protocol/wifi_direct_protocol_factory.c @@ -20,7 +20,7 @@ static struct WifiDirectTlvProtocol* NewWifiDirectTlvProtocol(void) { struct WifiDirectTlvProtocol *self = (struct WifiDirectTlvProtocol*)SoftBusCalloc(sizeof(*self)); - if (self) { + if (self != NULL) { if (!WifiDirectTlvProtocolConstructor(self)) { SoftBusFree(self); self = NULL; @@ -33,7 +33,7 @@ static struct WifiDirectTlvProtocol* NewWifiDirectTlvProtocol(void) static struct WifiDirectJsonProtocol* NewWifiDirectJsonProtocol(void) { struct WifiDirectJsonProtocol *self = (struct WifiDirectJsonProtocol*)SoftBusCalloc(sizeof(*self)); - if (self) { + if (self != NULL) { if (!WifiDirectJsonProtocolConstructor(self)) { SoftBusFree(self); self = NULL; diff --git a/core/connection/wifi_direct/utils/wifi_direct_network_utils.c b/core/connection/wifi_direct/utils/wifi_direct_network_utils.c index e99be306c..d3c974d0f 100644 --- a/core/connection/wifi_direct/utils/wifi_direct_network_utils.c +++ b/core/connection/wifi_direct/utils/wifi_direct_network_utils.c @@ -180,6 +180,10 @@ static int32_t GetInterfaceIpString(const char *interface, char *ipString, int32 int32_t IpAddrToString(uint32_t addr, char *addrString, size_t addrStringSize) { + if (addrString == NULL) { + CONN_LOGE(CONN_WIFI_DIRECT, "param invalid"); + return SOFTBUS_INVALID_PARAM; + } addr = ntohl(addr); const char *ret = inet_ntop(AF_INET, &addr, addrString, addrStringSize); CONN_CHECK_AND_RETURN_RET_LOGW(ret, SOFTBUS_ERR, CONN_WIFI_DIRECT, "inet_ntop failed"); diff --git a/core/connection/wifi_direct/utils/wifi_direct_perf_recorder.c b/core/connection/wifi_direct/utils/wifi_direct_perf_recorder.c index f314b0003..bac7ce01d 100755 --- a/core/connection/wifi_direct/utils/wifi_direct_perf_recorder.c +++ b/core/connection/wifi_direct/utils/wifi_direct_perf_recorder.c @@ -75,25 +75,25 @@ static void Calculate(void) uint64_t start = self->timePoints[TP_P2P_CONNECT_START]; uint64_t end = self->timePoints[TP_P2P_CONNECT_END]; - if (end && start) { + if (end != 0 && start != 0) { self->timeCosts[TC_TOTAL] = end - start; } start = self->timePoints[TP_P2P_CREATE_GROUP_START]; end = self->timePoints[TP_P2P_CREATE_GROUP_END]; - if (end && start) { + if (end != 0 && start != 0) { self->timeCosts[TC_CREATE_GROUP] = end - start; } start = self->timePoints[TP_P2P_CONNECT_GROUP_START]; end = self->timePoints[TP_P2P_CONNECT_GROUP_END]; - if (end && start) { + if (end != 0 && start != 0) { self->timeCosts[TC_CONNECT_GROUP] = end - start; } start = self->timePoints[TP_P2P_GET_WIFI_CONFIG_START]; end = self->timePoints[TP_P2P_GET_WIFI_CONFIG_END]; - if (end && start) { + if (end != 0 && start != 0) { self->timeCosts[TC_GET_WIFI_CONFIG] = end - start; } diff --git a/core/connection/wifi_direct/utils/wifi_direct_work_queue.c b/core/connection/wifi_direct/utils/wifi_direct_work_queue.c index ebeb1e336..f321c6ed7 100644 --- a/core/connection/wifi_direct/utils/wifi_direct_work_queue.c +++ b/core/connection/wifi_direct/utils/wifi_direct_work_queue.c @@ -14,7 +14,7 @@ */ #include "wifi_direct_work_queue.h" -#include + #include "conn_log.h" #include "message_handler.h" #include "softbus_error_code.h" @@ -28,12 +28,13 @@ struct WifiDirectWork { static void DeleteMessage(SoftBusMessage *msg) { SoftBusFree(msg->obj); + SoftBusFree(msg); } static SoftBusMessage* NewMessage(struct WifiDirectWork *work) { SoftBusMessage *msg = SoftBusCalloc(sizeof(*msg)); - if (!msg) { + if (msg == NULL) { return msg; } @@ -47,7 +48,7 @@ static void ScheduleWork(struct WifiDirectWork *work) { struct WifiDirectWorkQueue *self = GetWifiDirectWorkQueue(); SoftBusMessage *msg = NewMessage(work); - if (msg) { + if (msg != NULL) { SoftBusLooper *looper = self->handler.looper; looper->PostMessage(looper, msg); } @@ -57,7 +58,7 @@ static void ScheduleDelayWork(struct WifiDirectWork *work, int64_t timeMs) { struct WifiDirectWorkQueue *self = GetWifiDirectWorkQueue(); SoftBusMessage *msg = NewMessage(work); - if (msg) { + if (msg != NULL) { SoftBusLooper *looper = self->handler.looper; looper->PostMessageDelay(looper, msg, timeMs); } @@ -96,7 +97,7 @@ static struct WifiDirectWorkQueue g_queue = { struct WifiDirectWork* ObtainWifiDirectWork(WorkFunction function, void *data) { struct WifiDirectWork *work = SoftBusCalloc(sizeof(*work)); - if (!work) { + if (work == NULL) { return work; } @@ -130,7 +131,7 @@ int32_t WifiDirectWorkQueueInit(void) { CONN_LOGI(CONN_INIT, "init enter"); SoftBusLooper *looper = CreateNewLooper("WDWQLooper"); - if (!looper) { + if (looper == NULL) { CONN_LOGE(CONN_INIT, "create looper failed"); return SOFTBUS_ERR; } diff --git a/core/connection/wifi_direct/wifi_direct_error_code.h b/core/connection/wifi_direct/wifi_direct_error_code.h index 2a6c5f292..b84454e8b 100644 --- a/core/connection/wifi_direct/wifi_direct_error_code.h +++ b/core/connection/wifi_direct/wifi_direct_error_code.h @@ -306,6 +306,12 @@ enum WifiDirectErrorCode { /* Error code representing remote client join failed */ ERROR_HML_CLIENT_JOIN_FAIL = ERROR_BASE - 6608, + /* Error code representing switch notify failed */ + ERROR_HML_SWITCH_NOTIFY_FAIL = ERROR_BASE - 6609, + + /* Error code representing switch notify failed */ + ERROR_HML_RENEGO_TO_P2P = ERROR_BASE - 6610, + /* Error code representing end position of wifi direct errors */ ERROR_WIFI_DIRECT_END = ERROR_BASE - 6999, }; diff --git a/core/connection/wifi_direct/wifi_direct_negotiator.c b/core/connection/wifi_direct/wifi_direct_negotiator.c index a817ca386..8778894f2 100644 --- a/core/connection/wifi_direct/wifi_direct_negotiator.c +++ b/core/connection/wifi_direct/wifi_direct_negotiator.c @@ -70,7 +70,7 @@ static int32_t HandleMessageFromProcessor(struct NegotiateMessage *msg) struct WifiDirectNegotiator *self = GetWifiDirectNegotiator(); int32_t ret = SOFTBUS_OK; - if (msg) { + if (msg != NULL) { msg->dump(msg, 0); struct WifiDirectNegotiateChannel *channel = msg->getPointer(msg, NM_KEY_NEGO_CHANNEL, NULL); CONN_CHECK_AND_RETURN_RET_LOGW(channel != NULL, SOFTBUS_ERR, CONN_WIFI_DIRECT, "channel is null"); @@ -585,11 +585,6 @@ static int32_t PrejudgeAvailability(const char *remoteNetworkId, enum WifiDirect return SOFTBUS_OK; } -static void OnWifiDirectAuthOpened(uint32_t requestId, int64_t authId) -{ - CONN_LOGI(CONN_WIFI_DIRECT, "requestId=%u authId=%zd", requestId, authId); -} - static struct EntityListener g_entityListener = { .onOperationComplete = OnOperationComplete, .onEntityChanged = OnEntityChanged, @@ -610,7 +605,6 @@ static struct WifiDirectNegotiator g_negotiator = { .onDefaultTriggerChannelDataReceived = OnDefaultTriggerChannelDataReceived, .syncLnnInfo = SyncLnnInfo, .prejudgeAvailability = PrejudgeAvailability, - .onWifiDirectAuthOpened = OnWifiDirectAuthOpened, .currentCommand = NULL, .currentProcessor = NULL, diff --git a/core/connection/wifi_direct/wifi_direct_negotiator.h b/core/connection/wifi_direct/wifi_direct_negotiator.h index 9f462e475..95c02f770 100644 --- a/core/connection/wifi_direct/wifi_direct_negotiator.h +++ b/core/connection/wifi_direct/wifi_direct_negotiator.h @@ -50,9 +50,7 @@ struct WifiDirectNegotiator { void (*onDefaultTriggerChannelDataReceived)(struct WifiDirectNegotiateChannel *channel, const uint8_t *data, size_t len); - void (*onWifiDirectAuthOpened)(uint32_t requestId, int64_t authId); void (*syncLnnInfo)(struct InnerLink *innerLink); - int32_t (*prejudgeAvailability)(const char *remoteNetworkId, enum WifiDirectLinkType linkType); char currentRemoteMac[MAC_ADDR_STR_LEN]; diff --git a/core/discovery/ble/dispatcher/src/disc_ble_dispatcher.c b/core/discovery/ble/dispatcher/src/disc_ble_dispatcher.c index 65cfd71aa..7bf043476 100644 --- a/core/discovery/ble/dispatcher/src/disc_ble_dispatcher.c +++ b/core/discovery/ble/dispatcher/src/disc_ble_dispatcher.c @@ -20,7 +20,6 @@ #include "disc_log.h" #include "disc_manager.h" #include "disc_share_ble.h" -#include "softbus_def.h" #include "softbus_errcode.h" #define DISPATCHER_SIZE 3 diff --git a/core/discovery/ble/share_ble/src/disc_share_ble_virtual.c b/core/discovery/ble/share_ble/src/disc_share_ble_virtual.c index c73d3f78b..d46784461 100644 --- a/core/discovery/ble/share_ble/src/disc_share_ble_virtual.c +++ b/core/discovery/ble/share_ble/src/disc_share_ble_virtual.c @@ -13,13 +13,10 @@ * limitations under the License. */ -#include "disc_ble.h" #include "disc_ble_dispatcher.h" #include "disc_manager.h" #include "disc_share_ble.h" -#include "softbus_def.h" #include "softbus_errcode.h" -#include "stddef.h" static int32_t Publish(const PublishOption *option) { diff --git a/core/discovery/ble/softbus_ble/include/disc_ble_constant.h b/core/discovery/ble/softbus_ble/include/disc_ble_constant.h index 5bada0dd9..55d681eb8 100644 --- a/core/discovery/ble/softbus_ble/include/disc_ble_constant.h +++ b/core/discovery/ble/softbus_ble/include/disc_ble_constant.h @@ -19,8 +19,7 @@ #define INT32_MAX_BIT_NUM 32 #define MAX_CAP_NUM (CAPABILITY_NUM * INT32_MAX_BIT_NUM) -#define BLE_SCAN_FILTER_LEN 7 -#define CUST_DATA_MAX_LEN 14 +#define BLE_SCAN_FILTER_LEN 5 #define SOFTBUS_BLE_CLIENT_ID 0x1 #define SHA_HASH_LEN 32 diff --git a/core/discovery/ble/softbus_ble/include/disc_ble_utils.h b/core/discovery/ble/softbus_ble/include/disc_ble_utils.h index af470462f..cc2f79352 100644 --- a/core/discovery/ble/softbus_ble/include/disc_ble_utils.h +++ b/core/discovery/ble/softbus_ble/include/disc_ble_utils.h @@ -71,7 +71,7 @@ int32_t DiscBleGetDeviceIdHash(unsigned char *devIdHash, uint32_t len); int32_t DiscBleGetShortUserIdHash(unsigned char *hashStr, uint32_t len); int32_t AssembleTLV(BroadcastData *broadcastData, unsigned char dataType, const void *data, uint32_t dataLen); -int32_t GetDeviceInfoFromDisAdvData(DeviceWrapper *info, const unsigned char *data, uint32_t dataLen); +int32_t GetDeviceInfoFromDisAdvData(DeviceWrapper *device, const uint8_t *data, uint32_t dataLen); #ifdef __cplusplus #if __cplusplus diff --git a/core/discovery/ble/softbus_ble/src/disc_ble.c b/core/discovery/ble/softbus_ble/src/disc_ble.c index 852cde946..ea8f7fc3f 100644 --- a/core/discovery/ble/softbus_ble/src/disc_ble.c +++ b/core/discovery/ble/softbus_ble/src/disc_ble.c @@ -35,11 +35,12 @@ #include "softbus_adapter_mem.h" #include "softbus_adapter_range.h" #include "softbus_bitmap.h" +#include "softbus_broadcast_manager.h" +#include "softbus_broadcast_utils.h" #include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_hidumper_disc.h" #include "softbus_hisysevt_discreporter.h" -#include "softbus_log_old.h" #include "softbus_utils.h" #define BLE_PUBLISH 0x0 @@ -77,7 +78,6 @@ #define BlE_ADVERTISER "bleAdvertiser" #define RECV_MESSAGE_INFO "recvMessageInfo" -static int32_t g_bleScannerId = -1; typedef enum { PUBLISH_ACTIVE_SERVICE, PUBLISH_PASSIVE_SERVICE, @@ -150,10 +150,10 @@ typedef struct { } BleOption; static ScanSetting g_scanTable[FREQ_BUTT] = { - {SOFTBUS_BLE_SCAN_WINDOW_P2, SOFTBUS_BLE_SCAN_INTERVAL_P2}, - {SOFTBUS_BLE_SCAN_WINDOW_P10, SOFTBUS_BLE_SCAN_INTERVAL_P10}, - {SOFTBUS_BLE_SCAN_WINDOW_P25, SOFTBUS_BLE_SCAN_INTERVAL_P25}, - {SOFTBUS_BLE_SCAN_WINDOW_P100, SOFTBUS_BLE_SCAN_INTERVAL_P100} + {SOFTBUS_BC_SCAN_WINDOW_P2, SOFTBUS_BC_SCAN_INTERVAL_P2}, + {SOFTBUS_BC_SCAN_WINDOW_P10, SOFTBUS_BC_SCAN_INTERVAL_P10}, + {SOFTBUS_BC_SCAN_WINDOW_P25, SOFTBUS_BC_SCAN_INTERVAL_P25}, + {SOFTBUS_BC_SCAN_WINDOW_P100, SOFTBUS_BC_SCAN_INTERVAL_P100} }; static DiscInnerCallback *g_discBleInnerCb = NULL; @@ -161,8 +161,8 @@ static DiscBleInfo g_bleInfoManager[BLE_INFO_COUNT]; static SoftBusMutex g_bleInfoLock = {0}; static DiscBleAdvertiser g_bleAdvertiser[NUM_ADVERTISER]; static bool g_isScanning = false; -static SoftBusHandler g_discBleHandler = {0}; -static RecvMessageInfo g_recvMessageInfo = {0}; +static SoftBusHandler g_discBleHandler = {}; +static RecvMessageInfo g_recvMessageInfo = {}; static DiscBleListener g_bleListener = { .stateListenerId = -1, .scanListenerId = -1 @@ -235,7 +235,7 @@ static void DeConvertBitMap(unsigned int *dstCap, unsigned int *srcCap, int nums SoftbusBitmapSet(dstCap, bleCapability); } } - DISC_LOGI(DISC_BLE, "old= %u, new= %u", *srcCap, *dstCap); + DISC_LOGD(DISC_BLE, "old= %u, new= %u", *srcCap, *dstCap); } static void UpdateInfoManager(int adv, bool needUpdate) @@ -310,30 +310,29 @@ static bool CheckScanner(void) return scanCapBit != 0; } -static int32_t ScanFilter(const SoftBusBleScanResult *scanResultData) +static int32_t ScanFilter(const BroadcastReportInfo *reportInfo) { - uint32_t advLen = scanResultData->advLen; - uint8_t *advData = scanResultData->advData; - DISC_CHECK_AND_RETURN_RET_LOGW(scanResultData->dataStatus == SOFTBUS_BLE_DATA_COMPLETE, SOFTBUS_INVALID_PARAM, - DISC_BLE, "dataStatus[%u] is invalid", scanResultData->dataStatus); - DISC_CHECK_AND_RETURN_RET_LOGW(advLen >= (POS_TLV + ADV_HEAD_LEN), SOFTBUS_INVALID_PARAM, DISC_BLE, + uint32_t advLen = reportInfo->packet.bcData.payloadLen; + uint8_t *advData = reportInfo->packet.bcData.payload; + + DISC_CHECK_AND_RETURN_RET_LOGE(reportInfo->dataStatus == SOFTBUS_BLE_DATA_COMPLETE, SOFTBUS_ERR, DISC_BLE, + "dataStatus[%u] is invalid", reportInfo->dataStatus); + DISC_CHECK_AND_RETURN_RET_LOGE(advData != NULL, SOFTBUS_ERR, DISC_BLE, "advData is null", advLen); + DISC_CHECK_AND_RETURN_RET_LOGE(advLen >= POS_TLV, SOFTBUS_ERR, DISC_BLE, "advLen[%u] is too short, less than adv header length", advLen); - uint32_t broadcastAdvLen = advData[POS_PACKET_LENGTH]; - DISC_CHECK_AND_RETURN_RET_LOGE(broadcastAdvLen >= (ADV_HEAD_LEN + RSP_HEAD_LEN - 1), SOFTBUS_INVALID_PARAM, - DISC_BLE, "broadcastAdvLen[%u] is too short, less than adv header length", broadcastAdvLen); - DISC_CHECK_AND_RETURN_RET_LOGE(advLen > (POS_PACKET_LENGTH + broadcastAdvLen + 1), SOFTBUS_INVALID_PARAM, - DISC_BLE, "advLen[%u] is too short, less than adv packet length", advLen); - uint32_t broadcastRspLen = advData[POS_PACKET_LENGTH + broadcastAdvLen + 1]; - DISC_CHECK_AND_RETURN_RET_LOGE(advLen >= (POS_PACKET_LENGTH + broadcastAdvLen + 1 + broadcastRspLen + 1), - SOFTBUS_INVALID_PARAM, DISC_BLE, "advLen[%u] is too short, less than adv+rsp packet length", advLen); - - DISC_CHECK_AND_RETURN_RET_LOGE(advData[POS_UUID] == (uint8_t)(BLE_UUID & BYTE_MASK), SOFTBUS_INVALID_PARAM, - DISC_BLE, "uuid low byte[%hhu] is invalid", advData[POS_UUID]); - DISC_CHECK_AND_RETURN_RET_LOGE(advData[POS_UUID + 1] == (uint8_t)((BLE_UUID >> BYTE_SHIFT_BIT) & BYTE_MASK), - SOFTBUS_INVALID_PARAM, DISC_BLE, "uuid high byte[%hhu] is invalid", advData[POS_UUID + 1]); - DISC_CHECK_AND_RETURN_RET_LOGE(advData[POS_VERSION + ADV_HEAD_LEN] == BLE_VERSION, SOFTBUS_INVALID_PARAM, - DISC_BLE, "adv version[%hhu] is invalid", advData[POS_VERSION + ADV_HEAD_LEN]); + DISC_CHECK_AND_RETURN_RET_LOGE(reportInfo->packet.bcData.type == BC_DATA_TYPE_SERVICE, SOFTBUS_ERR, DISC_BLE, + "type [%u] is invalid", reportInfo->packet.bcData.type); + DISC_CHECK_AND_RETURN_RET_LOGE(reportInfo->packet.bcData.id == BLE_UUID, SOFTBUS_ERR, DISC_BLE, + "uuid [%u] is invalid", reportInfo->packet.bcData.id); + DISC_CHECK_AND_RETURN_RET_LOGE(advData[POS_VERSION] == BLE_VERSION, SOFTBUS_ERR, DISC_BLE, + "adv version[%hhu] is invalid", advData[POS_VERSION]); + if (reportInfo->packet.rspData.payload != NULL && reportInfo->packet.rspData.payloadLen != 0) { + DISC_CHECK_AND_RETURN_RET_LOGE(reportInfo->packet.rspData.type == BC_DATA_TYPE_MANUFACTURER, SOFTBUS_ERR, DISC_BLE, + "type [%u] is invalid", reportInfo->packet.rspData.type); + DISC_CHECK_AND_RETURN_RET_LOGE(reportInfo->packet.rspData.id == COMPANY_ID, SOFTBUS_ERR, DISC_BLE, + "companyId [%u] is invalid", reportInfo->packet.rspData.id); + } if (!CheckScanner()) { DISC_LOGI(DISC_BLE, "no need to scan"); @@ -343,13 +342,13 @@ static int32_t ScanFilter(const SoftBusBleScanResult *scanResultData) return SOFTBUS_OK; } -static void ProcessDisConPacket(const uint8_t *advData, uint32_t advLen, DeviceInfo *foundInfo) +static void ProcessDisConPacket(const BroadcastReportInfo *reportInfo, DeviceInfo *foundInfo) { DeviceWrapper device = { .info = foundInfo, .power = SOFTBUS_ILLEGAL_BLE_POWER }; - if (GetDeviceInfoFromDisAdvData(&device, advData, advLen) != SOFTBUS_OK) { + if (GetDeviceInfoFromDisAdvData(&device, (uint8_t *)reportInfo, sizeof(BroadcastReportInfo)) != SOFTBUS_OK) { DISC_LOGE(DISC_BLE, "GetDeviceInfoFromDisAdvData failed"); return; } @@ -361,7 +360,8 @@ static void ProcessDisConPacket(const uint8_t *advData, uint32_t advLen, DeviceI } (void)SoftBusMutexUnlock(&g_bleInfoLock); char key[SHA_HASH_LEN]; - if (SoftBusGenerateStrHash(advData, advLen, (uint8_t *)key) != SOFTBUS_OK) { + if (SoftBusGenerateStrHash(reportInfo->packet.bcData.payload, reportInfo->packet.bcData.payloadLen, + (uint8_t *)key) != SOFTBUS_OK) { DISC_LOGE(DISC_BLE, "GenerateStrHash failed"); return; } @@ -447,14 +447,13 @@ static int32_t RangeDevice(DeviceInfo *device, char rssi, int8_t power) return SOFTBUS_OK; } -static void ProcessDisNonPacket(const uint8_t *advData, uint32_t advLen, char rssi, - DeviceInfo *foundInfo) +static void ProcessDisNonPacket(const BroadcastReportInfo *reportInfo, char rssi, DeviceInfo *foundInfo) { DeviceWrapper device = { .info = foundInfo, .power = SOFTBUS_ILLEGAL_BLE_POWER }; - if (GetDeviceInfoFromDisAdvData(&device, advData, advLen) != SOFTBUS_OK) { + if (GetDeviceInfoFromDisAdvData(&device, (uint8_t *)reportInfo, sizeof(BroadcastReportInfo)) != SOFTBUS_OK) { DISC_LOGE(DISC_BLE, "GetDeviceInfoFromDisAdvData failed"); return; } @@ -497,44 +496,44 @@ static void ProcessDisNonPacket(const uint8_t *advData, uint32_t advLen, char rs } } -static void ProcessDistributePacket(const SoftBusBleScanResult *scanResultData) +static void ProcessDistributePacket(const BroadcastReportInfo *reportInfo) { - uint32_t advLen = scanResultData->advLen; - uint8_t *advData = scanResultData->advData; + uint32_t advLen = reportInfo->packet.bcData.payloadLen; + uint8_t *advData = reportInfo->packet.bcData.payload; DeviceInfo foundInfo; + + if (advData == NULL || advLen <= POS_BUSINESS_EXTENSION) { + DISC_LOGE(DISC_BLE, "scan report data null,len=[%d]", advLen); + return; + } (void)memset_s(&foundInfo, sizeof(foundInfo), 0, sizeof(foundInfo)); foundInfo.addrNum = 1; foundInfo.addr[0].type = CONNECTION_ADDR_BLE; - if (memcpy_s(foundInfo.addr[0].info.ble.bleMac, BT_ADDR_LEN, scanResultData->addr.addr, BT_ADDR_LEN) != EOK) { + if (memcpy_s(foundInfo.addr[0].info.ble.bleMac, BT_ADDR_LEN, reportInfo->addr.addr, BC_ADDR_MAC_LEN) != EOK) { DISC_LOGE(DISC_BLE, "memcpy_s failed"); return; } - if ((advData[POS_BUSINESS_EXTENSION + ADV_HEAD_LEN] & BIT_HEART_BIT) != 0) { + if ((advData[POS_BUSINESS_EXTENSION] & BIT_HEART_BIT) != 0) { return; } - if ((advData[POS_BUSINESS_EXTENSION + ADV_HEAD_LEN] & BIT_CON) != 0) { - ProcessDisConPacket(advData, advLen, &foundInfo); + if ((advData[POS_BUSINESS_EXTENSION] & BIT_CON) != 0) { + ProcessDisConPacket(reportInfo, &foundInfo); } else { - ProcessDisNonPacket(advData, advLen, scanResultData->rssi, &foundInfo); + ProcessDisNonPacket(reportInfo, reportInfo->rssi, &foundInfo); } } -static inline bool IsDistributedBusiness(const uint8_t *data) -{ - return data[POS_BUSINESS + ADV_HEAD_LEN] == DISTRIBUTE_BUSINESS; -} - -static void BleScanResultCallback(int listenerId, const SoftBusBleScanResult *scanResultData) +static void BleScanResultCallback(int listenerId, const BroadcastReportInfo *reportInfo) { (void)listenerId; - DISC_CHECK_AND_RETURN_LOGW(scanResultData != NULL, DISC_BLE, "scan result is null"); - DISC_CHECK_AND_RETURN_LOGW(scanResultData->advData != NULL, DISC_BLE, "scan result advData is null"); - DISC_CHECK_AND_RETURN_LOGE(ScanFilter(scanResultData) == SOFTBUS_OK, DISC_BLE, "scan filter failed"); + DISC_CHECK_AND_RETURN_LOGW(listenerId == g_bleListener.scanListenerId, DISC_BLE, "listenerId not match"); + DISC_CHECK_AND_RETURN_LOGW(reportInfo != NULL, DISC_BLE, "scan result is null"); + DISC_CHECK_AND_RETURN_LOGD(ScanFilter(reportInfo) == SOFTBUS_OK, DISC_BLE, "scan filter failed"); - uint8_t *advData = scanResultData->advData; - if (IsDistributedBusiness(advData)) { - SignalingMsgPrint("ble rcv", advData, scanResultData->advLen, SOFTBUS_LOG_DISC); - ProcessDistributePacket(scanResultData); + uint8_t *advData = reportInfo->packet.bcData.payload; + if ((reportInfo->packet.bcData.id == BLE_UUID) && (advData[POS_BUSINESS] == DISTRIBUTE_BUSINESS)) { + SignalingMsgPrint("ble adv rcv", advData, reportInfo->packet.bcData.payloadLen, DISC_BLE); + ProcessDistributePacket(reportInfo); } else { DISC_LOGI(DISC_BLE, "ignore other business"); } @@ -578,19 +577,17 @@ static void BleOnStateChanged(int32_t listenerId, int32_t state) } } -static SoftBusAdvCallback g_advCallback = { - .AdvEnableCallback = BleAdvEnableCallback, - .AdvDisableCallback = BleAdvDisableCallback, - .AdvDataCallback = BleAdvDataCallback, - .AdvUpdateCallback = BleAdvUpdateCallback, - .LpDeviceInfoCallback = NULL +static BroadcastCallback g_advCallback = { + .OnStartBroadcastingCallback = BleAdvEnableCallback, + .OnStopBroadcastingCallback = BleAdvDisableCallback, + .OnSetBroadcastingCallback = BleAdvDataCallback, + .OnUpdateBroadcastingCallback = BleAdvUpdateCallback, }; -static SoftBusScanListener g_scanListener = { - .OnScanStart = BleOnScanStart, - .OnScanStop = BleOnScanStop, - .OnScanResult = BleScanResultCallback, - .OnScanStateChanged = NULL +static ScanCallback g_scanListener = { + .OnStartScanCallback = BleOnScanStart, + .OnStopScanCallback = BleOnScanStop, + .OnReportScanDataCallback = BleScanResultCallback, }; static SoftBusBtStateListener g_stateChangedListener = { @@ -656,6 +653,7 @@ static int32_t GetNonDeviceInfo(DeviceInfo *info) if (DiscBleGetDeviceIdHash((uint8_t *)info->devId, DISC_MAX_DEVICE_ID_LEN) != SOFTBUS_OK) { DISC_LOGE(DISC_BLE, "get deviceId failed"); } + if (DiscBleGetDeviceName(info->devName) != SOFTBUS_OK) { DISC_LOGE(DISC_BLE, "get deviceName failed"); } @@ -682,61 +680,66 @@ static int32_t GetNonDeviceInfo(DeviceInfo *info) return SOFTBUS_OK; } -static int32_t BuildBleConfigAdvData(SoftBusBleAdvData *advData, const BroadcastData *broadcastData) +static int32_t BuildBleConfigAdvData(BroadcastPacket *packet, const BroadcastData *broadcastData) { - if (advData == NULL || broadcastData == NULL) { - return SOFTBUS_INVALID_PARAM; + if (packet->bcData.payload != NULL || packet->rspData.payload != NULL) { + SoftBusFree(packet->bcData.payload); + SoftBusFree(packet->rspData.payload); + packet->bcData.payload = NULL; + packet->rspData.payload = NULL; } - advData->advData = (uint8_t *)SoftBusCalloc(ADV_DATA_MAX_LEN + ADV_HEAD_LEN); - if (advData->advData == NULL) { - DISC_LOGE(DISC_BLE, "malloc failed"); + packet->bcData.payload = (uint8_t *)SoftBusCalloc(ADV_DATA_MAX_LEN); + if (packet->bcData.payload == NULL) { + DISC_LOGE(DISC_BLE, "malloc serviceData failed"); return SOFTBUS_MALLOC_ERR; } - advData->scanRspData = (uint8_t *)SoftBusCalloc(RESP_DATA_MAX_LEN + RSP_HEAD_LEN); - if (advData->scanRspData == NULL) { - DISC_LOGE(DISC_BLE, "malloc failed"); - SoftBusFree(advData->advData); - advData->advData = NULL; - return SOFTBUS_MALLOC_ERR; - } - unsigned short advLength = (broadcastData->dataLen > ADV_DATA_MAX_LEN) ? ADV_DATA_MAX_LEN : broadcastData->dataLen; - advData->advLength = advLength + ADV_HEAD_LEN; - advData->advData[POS_FLAG_BYTE_LEN] = FLAG_BYTE_LEN; - advData->advData[POS_FLAG_AD_TYPE] = FLAG_AD_TYPE; - advData->advData[POS_FLAG_AD_DATA] = FLAG_AD_DATA; - advData->advData[POS_AD_TYPE] = AD_TYPE; - advData->advData[POS_UUID] = (char)(BLE_UUID & BYTE_MASK); - advData->advData[POS_UUID + 1] = (char)((BLE_UUID >> BYTE_SHIFT_BIT) & BYTE_MASK); - advData->advData[POS_PACKET_LENGTH] = advData->advLength - POS_PACKET_LENGTH - 1; - DISC_LOGI(DISC_BLE, "advData->advLength=%d advLength=%d", advData->advLength, advLength); - if (memcpy_s(&advData->advData[ADV_HEAD_LEN], advLength, broadcastData->data.advData, advLength) != EOK) { + + packet->isSupportFlag = true; + packet->flag = FLAG_AD_DATA; + packet->bcData.type = BC_DATA_TYPE_SERVICE; + packet->bcData.id = BLE_UUID; + packet->bcData.payloadLen = (broadcastData->dataLen > ADV_DATA_MAX_LEN) ? ADV_DATA_MAX_LEN : broadcastData->dataLen; + if (memcpy_s(&packet->bcData.payload[0], ADV_DATA_MAX_LEN, broadcastData->data.advData, + packet->bcData.payloadLen) != EOK) { DISC_LOGE(DISC_BLE, "memcpy err"); + SoftBusFree(packet->bcData.payload); + packet->bcData.payload = NULL; return SOFTBUS_MEM_ERR; } - advData->scanRspLength = broadcastData->dataLen - advLength + RSP_HEAD_LEN; - advData->scanRspData[POS_RSP_TYPE] = RSP_TYPE; - advData->scanRspData[POS_COMPANY_ID] = COMPANY_ID & BYTE_MASK; - advData->scanRspData[POS_COMPANY_ID + 1] = (COMPANY_ID >> BYTE_SHIFT_BIT) & BYTE_MASK; - if (advData->scanRspLength > RSP_HEAD_LEN) { - if (memcpy_s(&advData->scanRspData[RSP_HEAD_LEN], RESP_DATA_MAX_LEN, - broadcastData->data.rspData, advData->scanRspLength - RSP_HEAD_LEN) != EOK) { - DISC_LOGE(DISC_BLE, "memcpy err"); - return SOFTBUS_MEM_ERR; - } + + packet->rspData.payloadLen = broadcastData->dataLen - packet->bcData.payloadLen; + if (packet->rspData.payloadLen == 0) { + packet->rspData.payload = NULL; + return SOFTBUS_OK; } - advData->scanRspData[POS_RSP_LENGTH] = advData->scanRspLength - POS_RSP_LENGTH - 1; - DISC_LOGI(DISC_BLE, "advData->scanRspLength=%d POS_RSP_LENGTH=%d", - advData->scanRspLength, advData->scanRspData[POS_RSP_LENGTH]); + + packet->rspData.payload = (uint8_t *)SoftBusCalloc(RESP_DATA_MAX_LEN); + if (packet->rspData.payload == NULL) { + DISC_LOGE(DISC_BLE, "malloc failed"); + SoftBusFree(packet->bcData.payload); + packet->bcData.payload = NULL; + return SOFTBUS_MALLOC_ERR; + } + packet->rspData.type = BC_DATA_TYPE_MANUFACTURER; + packet->rspData.id = COMPANY_ID; + if (memcpy_s(&packet->rspData.payload[0], RESP_DATA_MAX_LEN, broadcastData->data.rspData, + packet->rspData.payloadLen) != EOK) { + DISC_LOGE(DISC_BLE, "memcpy err"); + SoftBusFree(packet->bcData.payload); + SoftBusFree(packet->rspData.payload); + packet->bcData.payload = NULL; + packet->rspData.payload = NULL; + return SOFTBUS_MEM_ERR; + } + + DISC_LOGI(DISC_BLE, "packet->rspData.payloadLen=%d", packet->rspData.payloadLen); return SOFTBUS_OK; } -static void DestroyBleConfigAdvData(SoftBusBleAdvData *advData) +static void DestroyBleConfigAdvData(BroadcastPacket *packet) { - if (advData == NULL) { - return; - } - SoftBusFree(advData->advData); - SoftBusFree(advData->scanRspData); + SoftBusFree(packet->bcData.payload); + SoftBusFree(packet->rspData.payload); } static void AssembleNonOptionalTlv(DeviceInfo *info, BroadcastData *broadcastData) @@ -809,20 +812,20 @@ static int32_t GetBroadcastData(DeviceInfo *info, int32_t advId, BroadcastData * return SOFTBUS_OK; } -static void BuildAdvParam(SoftBusBleAdvParams *advParam) +static void BuildAdvParam(BroadcastParam *advParam) { advParam->minInterval = ADV_INTERNAL; advParam->maxInterval = ADV_INTERNAL; - advParam->advType = SOFTBUS_BLE_ADV_IND; - advParam->ownAddrType = SOFTBUS_BLE_PUBLIC_DEVICE_ADDRESS; - advParam->peerAddrType = SOFTBUS_BLE_PUBLIC_DEVICE_ADDRESS; + advParam->advType = SOFTBUS_BC_ADV_IND; + advParam->ownAddrType = SOFTBUS_BC_PUBLIC_DEVICE_ADDRESS; + advParam->peerAddrType = SOFTBUS_BC_PUBLIC_DEVICE_ADDRESS; advParam->channelMap = BLE_CHANNLE_MAP; advParam->txPower = BLE_ADV_TX_POWER_DEFAULT; } static int32_t StartAdvertiser(int32_t adv) { - DISC_LOGI(DISC_BLE, "enter"); + DISC_LOGD(DISC_BLE, "enter"); DiscBleAdvertiser *advertiser = &g_bleAdvertiser[adv]; if (advertiser->isAdvertising) { if (GetNeedUpdateAdvertiser(adv)) { @@ -844,32 +847,29 @@ static int32_t StartAdvertiser(int32_t adv) DISC_LOGE(DISC_BLE, "get broadcast data failed"); return SOFTBUS_DISCOVER_BLE_GET_BROADCAST_DATA_FAIL; } - SoftBusBleAdvData advData = {0}; - if (BuildBleConfigAdvData(&advData, &broadcastData) != SOFTBUS_OK) { - DestroyBleConfigAdvData(&advData); + BroadcastPacket packet = {}; + if (BuildBleConfigAdvData(&packet, &broadcastData) != SOFTBUS_OK) { DISC_LOGE(DISC_BLE, "BuildBleConfigAdvData failed"); return SOFTBUS_DISCOVER_BLE_BUILD_CONFIG_ADV_DATA_FAIL; } - SoftBusBleAdvParams advParam = {0}; + BroadcastParam advParam = {}; BuildAdvParam(&advParam); - if (SoftBusSetAdvData(adv, &advData) != SOFTBUS_OK) { - DISC_LOGE(DISC_BLE, "set ble adv adv=%d data failed", adv); - DestroyBleConfigAdvData(&advData); - return SOFTBUS_ERR; - } - SignalingMsgPrint("ble send", (uint8_t *)advData.advData, (uint8_t)advData.advLength, SOFTBUS_LOG_DISC); + + SignalingMsgPrint("ble adv send", (uint8_t *)packet.bcData.payload, (uint8_t)packet.bcData.payloadLen, + DISC_BLE); DiscEventExtra discEventExtra = { .broadcastType = BLE }; DISC_EVENT(EVENT_SCENE_BROADCAST, EVENT_STAGE_BROADCAST, discEventExtra); - if (SoftBusStartAdv(advertiser->channel, &advParam) != SOFTBUS_OK) { + + if (StartBroadcasting(advertiser->channel, &advParam, &packet) != SOFTBUS_OK) { discEventExtra.result = EVENT_STAGE_RESULT_FAILED; discEventExtra.errcode = SOFTBUS_DISCOVER_START_BROADCAST_FAIL; DISC_EVENT(EVENT_SCENE_BROADCAST, EVENT_STAGE_BROADCAST, discEventExtra); - DestroyBleConfigAdvData(&advData); + DestroyBleConfigAdvData(&packet); DISC_LOGE(DISC_BLE, "start adv adv=%d failed", adv); return SOFTBUS_DISCOVER_START_BROADCAST_FAIL; } UpdateInfoManager(adv, false); - DestroyBleConfigAdvData(&advData); + DestroyBleConfigAdvData(&packet); return SOFTBUS_OK; } @@ -882,7 +882,7 @@ static int32_t StopAdvertiser(int32_t adv) } DiscEventExtra discEventExtra = { .broadcastType = BLE, .result = EVENT_STAGE_RESULT_OK }; DISC_EVENT(EVENT_SCENE_BROADCAST, EVENT_STAGE_BROADCAST, discEventExtra); - if (SoftBusStopAdv(advertiser->channel) != SOFTBUS_OK) { + if (StopBroadcasting(advertiser->channel) != SOFTBUS_OK) { discEventExtra.result = EVENT_STAGE_RESULT_FAILED; discEventExtra.errcode = SOFTBUS_DISCOVER_END_BROADCAST_FAIL; DISC_EVENT(EVENT_SCENE_BROADCAST, EVENT_STAGE_BROADCAST, discEventExtra); @@ -904,30 +904,30 @@ static int32_t UpdateAdvertiser(int32_t adv) DISC_LOGE(DISC_BLE, "advertiser adv=%d GetConDeviceInfo failed", adv); return StopAdvertiser(adv); } - BroadcastData broadcastData; + BroadcastData broadcastData = {}; if (GetBroadcastData(&advertiser->deviceInfo, adv, &broadcastData) != SOFTBUS_OK) { return SOFTBUS_DISCOVER_BLE_GET_BROADCAST_DATA_FAIL; } - SoftBusBleAdvData advData = {0}; - if (BuildBleConfigAdvData(&advData, &broadcastData) != SOFTBUS_OK) { - DestroyBleConfigAdvData(&advData); + + BroadcastPacket packet = {}; + if (BuildBleConfigAdvData(&packet, &broadcastData) != SOFTBUS_OK) { DISC_LOGE(DISC_BLE, "BuildBleConfigAdvData failed"); return SOFTBUS_DISCOVER_BLE_BUILD_CONFIG_ADV_DATA_FAIL; } - SoftBusBleAdvParams advParam = {0}; + BroadcastParam advParam = {}; BuildAdvParam(&advParam); DiscEventExtra discEventExtra = { .broadcastType = BLE }; DISC_EVENT(EVENT_SCENE_BROADCAST, EVENT_STAGE_BROADCAST, discEventExtra); - if (SoftBusUpdateAdv(advertiser->channel, &advData, &advParam) != SOFTBUS_OK) { + if (UpdateBroadcasting(advertiser->channel, &advParam, &packet) != SOFTBUS_OK) { discEventExtra.result = EVENT_STAGE_RESULT_FAILED; discEventExtra.errcode = SOFTBUS_DISCOVER_START_BROADCAST_FAIL; DISC_EVENT(EVENT_SCENE_BROADCAST, EVENT_STAGE_BROADCAST, discEventExtra); - DestroyBleConfigAdvData(&advData); + DestroyBleConfigAdvData(&packet); DISC_LOGE(DISC_BLE, "UpdateAdv failed"); return SOFTBUS_DISCOVER_START_BROADCAST_FAIL; } UpdateInfoManager(adv, false); - DestroyBleConfigAdvData(&advData); + DestroyBleConfigAdvData(&packet); return SOFTBUS_OK; } @@ -936,13 +936,13 @@ static void InitScanner(void) g_isScanning = false; } -static int32_t GetScannerParam(int32_t freq, SoftBusBleScanParams *scanParam) +static int32_t GetScannerParam(int32_t freq, BcScanParams *scanParam) { scanParam->scanInterval = (uint16_t)g_scanTable[freq].scanInterval; scanParam->scanWindow = (uint16_t)g_scanTable[freq].scanWindow; - scanParam->scanType = SOFTBUS_BLE_SCAN_TYPE_ACTIVE; - scanParam->scanPhy = SOFTBUS_BLE_SCAN_PHY_1M; - scanParam->scanFilterPolicy = SOFTBUS_BLE_SCAN_FILTER_POLICY_ACCEPT_ALL; + scanParam->scanType = SOFTBUS_BC_SCAN_TYPE_ACTIVE; + scanParam->scanPhy = SOFTBUS_BC_SCAN_PHY_1M; + scanParam->scanFilterPolicy = SOFTBUS_BC_SCAN_FILTER_POLICY_ACCEPT_ALL; return SOFTBUS_OK; } @@ -957,7 +957,7 @@ static void StartScaner(void) DISC_LOGI(DISC_BLE, "scanner already start, no need start again"); return; } - SoftBusBleScanParams scanParam; + BcScanParams scanParam; int32_t maxFreq = GetMaxExchangeFreq(); DiscEventExtra discEventExtra = { .scanType = BLE }; DISC_EVENT(EVENT_SCENE_SCAN, EVENT_STAGE_SCAN_START, discEventExtra); @@ -968,7 +968,7 @@ static void StartScaner(void) DISC_LOGE(DISC_BLE, "GetScannerParam failed"); return; } - if (SoftBusStartScan(g_bleListener.scanListenerId, g_bleScannerId, &scanParam) != SOFTBUS_OK) { + if (StartScan(g_bleListener.scanListenerId, &scanParam) != SOFTBUS_OK) { discEventExtra.result = EVENT_STAGE_RESULT_FAILED; discEventExtra.errcode = SOFTBUS_DISCOVER_START_SCAN_FAIL; DISC_EVENT(EVENT_SCENE_SCAN, EVENT_STAGE_SCAN_START, discEventExtra); @@ -986,7 +986,7 @@ static int32_t StopScaner(void) } DiscEventExtra discEventExtra = { .scanType = BLE, .result = EVENT_STAGE_RESULT_OK }; DISC_EVENT(EVENT_SCENE_SCAN, EVENT_STAGE_SCAN_START, discEventExtra); - if (SoftBusStopScan(g_bleListener.scanListenerId, g_bleScannerId) != SOFTBUS_OK) { + if (StopScan(g_bleListener.scanListenerId) != SOFTBUS_OK) { discEventExtra.result = EVENT_STAGE_RESULT_FAILED; discEventExtra.errcode = SOFTBUS_DISCOVER_END_SCAN_FAIL; DISC_EVENT(EVENT_SCENE_SCAN, EVENT_STAGE_SCAN_START, discEventExtra); @@ -1046,13 +1046,14 @@ static int32_t RegisterCapability(DiscBleInfo *info, const DiscBleOption *option continue; } if (info->capabilityData[pos] == NULL) { - info->capabilityData[pos] = (uint8_t *)SoftBusCalloc(CUST_DATA_MAX_LEN); + info->capabilityData[pos] = (uint8_t *)SoftBusCalloc(MAX_CAPABILITYDATA_LEN); if (info->capabilityData[pos] == NULL) { return SOFTBUS_MALLOC_ERR; } } - if (memcpy_s(info->capabilityData[pos], CUST_DATA_MAX_LEN, custData, custDataLen) != EOK) { + if (memcpy_s(info->capabilityData[pos], MAX_CAPABILITYDATA_LEN, custData, custDataLen) != EOK) { SoftBusFree(info->capabilityData[pos]); + info->capabilityData[pos] = NULL; return SOFTBUS_MEM_ERR; } info->capDataLen[pos] = custDataLen; @@ -1270,12 +1271,21 @@ static DiscoveryBleDispatcherInterface g_discBleDispatcherInterface = { static int32_t InitAdvertiser(void) { - int32_t conChannel = SoftBusGetAdvChannel(&g_advCallback, &g_bleScannerId, false); - int32_t nonChannel = SoftBusGetAdvChannel(&g_advCallback, &g_bleScannerId, false); + int32_t conChannel = -1; + int32_t nonChannel = -1; + int32_t ret = RegisterBroadcaster(SRV_TYPE_DIS, &conChannel, &g_advCallback); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, DISC_BLE, "register broadcaster con fail"); + + ret = RegisterBroadcaster(SRV_TYPE_DIS, &nonChannel, &g_advCallback); + if (ret != SOFTBUS_OK) { + DISC_LOGE(DISC_INIT, "register broadcaster non fail"); + (void)UnRegisterBroadcaster(conChannel); + return SOFTBUS_ERR; + } if (conChannel < 0 || nonChannel < 0) { - DISC_LOGE(DISC_INIT, "get adv channel failed"); - (void)SoftBusReleaseAdvChannel(conChannel); - (void)SoftBusReleaseAdvChannel(nonChannel); + DISC_LOGE(DISC_INIT, "register broadcaster con[%d]-non[%d] fail", conChannel, nonChannel); + (void)UnRegisterBroadcaster(conChannel); + (void)UnRegisterBroadcaster(nonChannel); return SOFTBUS_ERR; } DISC_LOGI(DISC_INIT, "conChannel=%d nonChannel=%d", conChannel, nonChannel); @@ -1313,59 +1323,59 @@ static void DiscBleInitSubscribe(void) static void StartActivePublish(SoftBusMessage *msg) { - DISC_LOGI(DISC_BLE, "enter"); + DISC_LOGD(DISC_BLE, "enter"); (void)StartAdvertiser(NON_ADV_ID); - DISC_LOGI(DISC_BLE, "end"); + DISC_LOGD(DISC_BLE, "end"); } static void StartPassivePublish(SoftBusMessage *msg) { - DISC_LOGI(DISC_BLE, "enter"); + DISC_LOGD(DISC_BLE, "enter"); if (g_bleAdvertiser[NON_ADV_ID].isAdvertising) { DISC_LOGI(DISC_BLE, "UpdateAdvertiser %d", NON_ADV_ID); UpdateAdvertiser(NON_ADV_ID); } StartScaner(); - DISC_LOGI(DISC_BLE, "end"); + DISC_LOGD(DISC_BLE, "end"); } static void StartActiveDiscovery(SoftBusMessage *msg) { - DISC_LOGI(DISC_BLE, "enter"); + DISC_LOGD(DISC_BLE, "enter"); if (StartAdvertiser(CON_ADV_ID) == SOFTBUS_OK) { StartScaner(); } - DISC_LOGI(DISC_BLE, "end"); + DISC_LOGD(DISC_BLE, "end"); } static void StartPassiveDiscovery(SoftBusMessage *msg) { - DISC_LOGI(DISC_BLE, "enter"); + DISC_LOGD(DISC_BLE, "enter"); StartScaner(); - DISC_LOGI(DISC_BLE, "end"); + DISC_LOGD(DISC_BLE, "end"); } static void Recovery(SoftBusMessage *msg) { - DISC_LOGI(DISC_BLE, "enter"); + DISC_LOGD(DISC_BLE, "enter"); (void)StartAdvertiser(CON_ADV_ID); (void)StartAdvertiser(NON_ADV_ID); StartScaner(); - DISC_LOGI(DISC_BLE, "end"); + DISC_LOGD(DISC_BLE, "end"); } static void BleDiscTurnOff(SoftBusMessage *msg) { - DISC_LOGI(DISC_BLE, "enter"); + DISC_LOGD(DISC_BLE, "enter"); (void)StopAdvertiser(NON_ADV_ID); (void)StopAdvertiser(CON_ADV_ID); (void)StopScaner(); - DISC_LOGI(DISC_BLE, "end"); + DISC_LOGD(DISC_BLE, "end"); } static int32_t ReplyPassiveNonBroadcast(void) { - DISC_LOGI(DISC_BLE, "enter"); + DISC_LOGD(DISC_BLE, "enter"); SoftBusMessage *msg = CreateBleHandlerMsg(REPLY_PASSIVE_NON_BROADCAST, 0, 0, NULL); if (msg == NULL) { return SOFTBUS_MALLOC_ERR; @@ -1376,7 +1386,7 @@ static int32_t ReplyPassiveNonBroadcast(void) static int32_t MessageRemovePredicate(const SoftBusMessage *msg, void *args) { - DISC_LOGI(DISC_BLE, "enter"); + DISC_LOGD(DISC_BLE, "enter"); uintptr_t key = (uintptr_t)args; if (msg->what == PROCESS_TIME_OUT && msg->arg1 == key) { DISC_LOGI(DISC_BLE, "find key"); @@ -1413,7 +1423,7 @@ static int32_t MatchRecvMessage(const uint32_t *publishInfoMap, uint32_t *capBit static void StartTimeout(const char *key) { - DISC_LOGI(DISC_BLE, "enter"); + DISC_LOGD(DISC_BLE, "enter"); if (SoftBusMutexLock(&g_recvMessageInfo.lock) != 0) { DISC_LOGE(DISC_BLE, "lock failed"); return; @@ -1434,7 +1444,7 @@ static void StartTimeout(const char *key) static void RemoveTimeout(const char *key) { - DISC_LOGI(DISC_BLE, "enter"); + DISC_LOGD(DISC_BLE, "enter"); if (SoftBusMutexLock(&g_recvMessageInfo.lock) != 0) { DISC_LOGE(DISC_BLE, "lock failed"); return; @@ -1463,7 +1473,7 @@ static uint32_t RecvMsgAggregateCap(void) static int32_t AddRecvMessage(const char *key, const uint32_t *capBitMap, bool needBrMac) { - DISC_LOGI(DISC_BLE, "enter"); + DISC_LOGD(DISC_BLE, "enter"); if (SoftBusMutexLock(&g_recvMessageInfo.lock) != 0) { DISC_LOGE(DISC_BLE, "lock failed"); return SOFTBUS_LOCK_ERR; @@ -1506,7 +1516,7 @@ static int32_t AddRecvMessage(const char *key, const uint32_t *capBitMap, bool n static void RemoveRecvMessage(uint64_t key) { - DISC_LOGI(DISC_BLE, "enter"); + DISC_LOGD(DISC_BLE, "enter"); if (SoftBusMutexLock(&g_recvMessageInfo.lock) != 0) { DISC_LOGE(DISC_BLE, "lock failed"); return; @@ -1542,7 +1552,7 @@ static void ClearRecvMessage(void) static void ProcessTimeout(SoftBusMessage *msg) { - DISC_LOGI(DISC_BLE, "enter"); + DISC_LOGD(DISC_BLE, "enter"); RemoveRecvMessage(msg->arg1); UpdateAdvertiser(NON_ADV_ID); } @@ -1607,9 +1617,9 @@ static int32_t DiscBleLooperInit(void) return SOFTBUS_OK; } -static void DiscFreeBleScanFilter(SoftBusBleScanFilter *filter) +static void DiscFreeBleScanFilter(BcScanFilter *filter) { - if (filter) { + if (filter != NULL) { SoftBusFree(filter->serviceData); SoftBusFree(filter->serviceDataMask); SoftBusFree(filter); @@ -1618,7 +1628,7 @@ static void DiscFreeBleScanFilter(SoftBusBleScanFilter *filter) static void DiscBleSetScanFilter(int32_t listenerId) { - SoftBusBleScanFilter *filter = (SoftBusBleScanFilter *)SoftBusCalloc(sizeof(SoftBusBleScanFilter)); + BcScanFilter *filter = (BcScanFilter *)SoftBusCalloc(sizeof(BcScanFilter)); DISC_CHECK_AND_RETURN_LOGW(filter != NULL, DISC_BLE, "malloc filter failed"); filter->serviceData = (uint8_t *)SoftBusCalloc(BLE_SCAN_FILTER_LEN); @@ -1629,17 +1639,14 @@ static void DiscBleSetScanFilter(int32_t listenerId) return; } + filter->serviceUuid = BLE_UUID; filter->serviceDataLength = BLE_SCAN_FILTER_LEN; - filter->serviceData[0] = BLE_UUID & BYTE_MASK; - filter->serviceData[1] = (BLE_UUID >> BYTE_SHIFT_BIT) & BYTE_MASK; - filter->serviceData[UUID_LEN + POS_VERSION] = BLE_VERSION; - filter->serviceData[UUID_LEN + POS_BUSINESS] = DISTRIBUTE_BUSINESS; - filter->serviceDataMask[0] = BYTE_MASK; - filter->serviceDataMask[1] = BYTE_MASK; - filter->serviceDataMask[UUID_LEN + POS_VERSION] = BYTE_MASK; - filter->serviceDataMask[UUID_LEN + POS_BUSINESS] = BYTE_MASK; + filter->serviceData[POS_VERSION] = BLE_VERSION; + filter->serviceData[POS_BUSINESS] = DISTRIBUTE_BUSINESS; + filter->serviceDataMask[POS_VERSION] = BYTE_MASK; + filter->serviceDataMask[POS_BUSINESS] = BYTE_MASK; - if (SoftBusSetScanFilter(listenerId, filter, 1) != SOFTBUS_OK) { + if (SetScanFilter(listenerId, filter, 1) != SOFTBUS_OK) { DISC_LOGE(DISC_BLE, "set scan filter failed"); DiscFreeBleScanFilter(filter); } @@ -1647,7 +1654,8 @@ static void DiscBleSetScanFilter(int32_t listenerId) static int32_t InitBleListener(void) { - g_bleListener.scanListenerId = SoftBusAddScanListener(&g_scanListener, &g_bleScannerId, false); + int32_t ret = RegisterScanListener(SRV_TYPE_DIS, &g_bleListener.scanListenerId, &g_scanListener); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, DISC_BLE, "register scanner listener fail"); g_bleListener.stateListenerId = SoftBusAddBtStateListener(&g_stateChangedListener); if (g_bleListener.stateListenerId < 0 || g_bleListener.scanListenerId < 0) { return SOFTBUS_ERR; @@ -1676,6 +1684,10 @@ DiscoveryBleDispatcherInterface *DiscSoftBusBleInit(DiscInnerCallback *callback) DiscBleInitPublish(); DiscBleInitSubscribe(); InitScanner(); + if (InitBroadcastMgr() != SOFTBUS_OK) { + DISC_LOGE(DISC_INIT, "init broadcast mgr failed"); + return NULL; + } if (DiscBleLooperInit() != SOFTBUS_OK || InitBleListener() != SOFTBUS_OK || InitAdvertiser() != SOFTBUS_OK) { DiscSoftBusBleDeinit(); @@ -1711,8 +1723,8 @@ static void RecvMessageDeinit(void) static void AdvertiserDeinit(void) { - (void)SoftBusReleaseAdvChannel(g_bleAdvertiser[CON_ADV_ID].channel); - (void)SoftBusReleaseAdvChannel(g_bleAdvertiser[NON_ADV_ID].channel); + (void)UnRegisterBroadcaster(g_bleAdvertiser[CON_ADV_ID].channel); + (void)UnRegisterBroadcaster(g_bleAdvertiser[NON_ADV_ID].channel); for (uint32_t index = 0; index < NUM_ADVERTISER; index++) { (void)memset_s(&g_bleAdvertiser[index], sizeof(DiscBleAdvertiser), 0x0, sizeof(DiscBleAdvertiser)); } @@ -1721,8 +1733,7 @@ static void AdvertiserDeinit(void) static void BleListenerDeinit(void) { (void)SoftBusRemoveBtStateListener(g_bleListener.stateListenerId); - (void)SoftBusRemoveScanListener(g_bleListener.scanListenerId); - (void)SoftBusDeregisterScanCallbacks(g_bleScannerId); + (void)UnRegisterScanListener(g_bleListener.scanListenerId); } static void DiscBleInfoDeinit(void) @@ -1742,6 +1753,7 @@ void DiscSoftBusBleDeinit(void) RecvMessageDeinit(); DiscBleInfoDeinit(); AdvertiserDeinit(); + DeInitBroadcastMgr(); } static int32_t BleInfoDump(int fd) diff --git a/core/discovery/ble/softbus_ble/src/disc_ble_utils.c b/core/discovery/ble/softbus_ble/src/disc_ble_utils.c index 341904708..f60d2dffe 100644 --- a/core/discovery/ble/softbus_ble/src/disc_ble_utils.c +++ b/core/discovery/ble/softbus_ble/src/disc_ble_utils.c @@ -20,6 +20,7 @@ #include "bus_center_manager.h" #include "cJSON.h" #include "disc_ble_constant.h" +#include "softbus_broadcast_type.h" #include "disc_log.h" #include "lnn_device_info.h" #include "securec.h" @@ -94,7 +95,7 @@ static int32_t DiscBleGetDeviceUdid(char *udid, uint32_t len) int32_t DiscBleGetDeviceName(char *deviceName) { - if (LnnGetLocalStrInfo(STRING_KEY_DEV_NAME, deviceName, DEVICE_NAME_BUF_LEN) != SOFTBUS_OK) { + if (LnnGetLocalStrInfo(STRING_KEY_DEV_NAME, deviceName, DISC_MAX_DEVICE_NAME_LEN) != SOFTBUS_OK) { DISC_LOGE(DISC_BLE, "Get local device name failed."); return SOFTBUS_ERR; } @@ -305,7 +306,7 @@ static int32_t ParseCustData(DeviceWrapper *device, const uint8_t *data, const u static int32_t ParseRecvTlvs(DeviceWrapper *device, const uint8_t *data, uint32_t dataLen) { - uint32_t curLen = POS_TLV + ADV_HEAD_LEN; + uint32_t curLen = 0; int32_t ret = SOFTBUS_OK; while (curLen < dataLen) { uint8_t type = (data[curLen] & DATA_TYPE_MASK) >> BYTE_SHIFT; @@ -353,50 +354,49 @@ int32_t GetDeviceInfoFromDisAdvData(DeviceWrapper *device, const uint8_t *data, { DISC_CHECK_AND_RETURN_RET_LOGW(device != NULL && device->info != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, "device is invalid"); - DISC_CHECK_AND_RETURN_RET_LOGW(data != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, "data=NULL is invalid"); - DISC_CHECK_AND_RETURN_RET_LOGW(dataLen != 0, SOFTBUS_INVALID_PARAM, DISC_BLE, "dataLen=0 is invalid"); + BroadcastReportInfo *reportInfo = (BroadcastReportInfo *)data; + DISC_CHECK_AND_RETURN_RET_LOGW(reportInfo != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, "reportInfo=NULL is invalid"); + DISC_CHECK_AND_RETURN_RET_LOGW(dataLen == sizeof(BroadcastReportInfo), SOFTBUS_INVALID_PARAM, DISC_BLE, + "bcData.payload=NULL is invalid"); + DISC_CHECK_AND_RETURN_RET_LOGW( + reportInfo->packet.bcData.payload != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, "payload=NULL is invalid"); + uint16_t bcLen = reportInfo->packet.bcData.payloadLen; + uint16_t rspLen = reportInfo->packet.rspData.payloadLen; + if (bcLen > ADV_DATA_MAX_LEN || bcLen < POS_TLV || rspLen > RESP_DATA_MAX_LEN) { + DISC_LOGE(DISC_BLE, "get discovery adv data fail"); + return SOFTBUS_INVALID_PARAM; + } + + uint8_t *serviceData = reportInfo->packet.bcData.payload; if (memcpy_s(device->info->accountHash, SHORT_USER_ID_HASH_LEN, - &data[POS_USER_ID_HASH + ADV_HEAD_LEN], SHORT_USER_ID_HASH_LEN) != EOK) { + &serviceData[POS_USER_ID_HASH], SHORT_USER_ID_HASH_LEN) != EOK) { DISC_LOGE(DISC_BLE, "copy accountHash failed"); return SOFTBUS_MEM_ERR; } - device->info->capabilityBitmap[0] = data[POS_CAPABLITY + ADV_HEAD_LEN]; - // ble scan data consists of multiple ADStructures - // ADStructure format: - // More info about ADStructure, please ref Generic Access Profile Specification - // We only use Flag(0x01) + ServiceData(0x16) + Manufacture(0xff) in order, so we should join them together - // before parse - uint32_t scanRspPtr = 0; - uint32_t scanRspTlvLen = 0; - uint32_t nextAdsPtr = FLAG_BYTE_LEN + 1 + data[POS_PACKET_LENGTH] + 1; - while (nextAdsPtr + 1 < dataLen) { - if (data[nextAdsPtr + 1] == RSP_TYPE) { - scanRspPtr = nextAdsPtr; - DISC_CHECK_AND_RETURN_RET_LOGE(data[scanRspPtr] >= (RSP_HEAD_LEN - 1), SOFTBUS_ERR, DISC_BLE, - "rspLen[%hhu] is less than rsp head length", data[scanRspPtr]); - scanRspTlvLen = data[scanRspPtr] - (RSP_HEAD_LEN - 1); - DISC_CHECK_AND_RETURN_RET_LOGE(scanRspPtr + data[scanRspPtr] + 1 <= dataLen, SOFTBUS_ERR, DISC_BLE, - "curScanLen(%u) > dataLen(%u)", scanRspPtr + data[scanRspPtr] + 1, dataLen); - break; - } - nextAdsPtr += data[nextAdsPtr] + 1; + device->info->capabilityBitmap[0] = serviceData[POS_CAPABLITY]; + + uint32_t bcTlvLen = reportInfo->packet.bcData.payloadLen - POS_TLV; + + if (bcTlvLen == 0) { + return SOFTBUS_OK; } - uint32_t advLen = FLAG_BYTE_LEN + 1 + data[POS_PACKET_LENGTH] + 1; - uint8_t *copyData = SoftBusCalloc(advLen + scanRspTlvLen + 1); + uint8_t *copyData = SoftBusCalloc(bcTlvLen + rspLen); DISC_CHECK_AND_RETURN_RET_LOGE(copyData != NULL, SOFTBUS_MEM_ERR, DISC_BLE, "malloc failed."); - if (memcpy_s(copyData, advLen, data, advLen) != EOK) { - DISC_LOGE(DISC_BLE, "memcpy_s adv failed, advLen: %u", advLen); + if (memcpy_s(copyData, bcTlvLen, &serviceData[POS_TLV], bcTlvLen) != EOK) { + DISC_LOGE(DISC_BLE, "memcpy_s adv failed, bcTlvLen: %u", bcTlvLen); SoftBusFree(copyData); return SOFTBUS_MEM_ERR; } - if (scanRspTlvLen != 0) { - if (memcpy_s(copyData + advLen, scanRspTlvLen, data + scanRspPtr + RSP_HEAD_LEN, scanRspTlvLen) != EOK) { - DISC_LOGE(DISC_BLE, "memcpy_s scan resp failed, advLen: %u, scanRspTlvLen: %u.", advLen, scanRspTlvLen); + + if (rspLen > 0 && reportInfo->packet.rspData.payload != NULL) { + if (memcpy_s(copyData + bcTlvLen, rspLen, reportInfo->packet.rspData.payload, rspLen) != EOK) { + DISC_LOGE(DISC_BLE, "memcpy_s rsp data failed, rspLen: %u", rspLen); SoftBusFree(copyData); return SOFTBUS_MEM_ERR; } } - int32_t ret = ParseRecvTlvs(device, copyData, advLen + scanRspTlvLen); + + int32_t ret = ParseRecvTlvs(device, copyData, bcTlvLen + rspLen); SoftBusFree(copyData); return ret; } diff --git a/core/discovery/manager/src/disc_manager.c b/core/discovery/manager/src/disc_manager.c index b28c2b1dc..cb342b25c 100644 --- a/core/discovery/manager/src/disc_manager.c +++ b/core/discovery/manager/src/disc_manager.c @@ -28,6 +28,7 @@ #include "softbus_hisysevt_discreporter.h" #include "softbus_utils.h" +#define DEVICE_TYPE_SIZE_MAX 3 #define DUMP_STR_LEN 256 static bool g_isInited = false; @@ -91,39 +92,44 @@ typedef struct { char *pkgName; } IdContainer; -static void UpdateDiscEventByDeviceInfo(DiscEventExtra *discEventExtra, const DeviceInfo *device) +static void UpdateDiscEventAndReport(DiscEventExtra *extra, const DeviceInfo *device) { - if (discEventExtra == NULL || device == NULL) { + if (device == NULL) { + DISC_EVENT(EVENT_SCENE_SCAN, EVENT_STAGE_SCAN_END, *extra); DISC_LOGI(DISC_CONTROL, "discEventExtra or device is null"); return; } if (device->addrNum <= CONNECTION_ADDR_WLAN || device->addrNum > CONNECTION_ADDR_MAX) { + DISC_EVENT(EVENT_SCENE_SCAN, EVENT_STAGE_SCAN_END, *extra); DISC_LOGI(DISC_CONTROL, "unknow device info"); return; } - uint32_t index = device->addrNum - 1; - ConnectionAddr addr = device->addr[index]; - switch (addr.type) { - case CONNECTION_ADDR_BR: - discEventExtra->peerBrMac = addr.info.br.brMac; - break; - case CONNECTION_ADDR_BLE: - discEventExtra->peerBleMac = addr.info.ble.bleMac; - break; - case CONNECTION_ADDR_WLAN: - case CONNECTION_ADDR_ETH: - discEventExtra->peerIp = addr.info.ip.ip; - break; - default: - DISC_LOGI(DISC_CONTROL, "unknow param type!"); - break; + + for (uint32_t i = 0; i < device->addrNum; i++) { + switch (device->addr[i].type) { + case CONNECTION_ADDR_BR: + extra->peerBrMac = device->addr[i].info.br.brMac; + break; + case CONNECTION_ADDR_BLE: + extra->peerBleMac = device->addr[i].info.ble.bleMac; + break; + case CONNECTION_ADDR_WLAN: + /* fall-through */ + case CONNECTION_ADDR_ETH: + extra->peerIp = device->addr[i].info.ip.ip; + break; + default: + DISC_LOGI(DISC_CONTROL, "unknow param type!"); + break; + } } - char deviceType[DISC_MAX_DEVICE_NAME_LEN] = { 0 }; - if (sprintf_s(deviceType, DISC_MAX_DEVICE_NAME_LEN + 1, "%d", device->devType) < 0) { - DISC_LOGI(DISC_CONTROL, "sprintf_s fail, devType=%d", device->devType); - return; + + extra->peerNetworkId = device->devId; + char deviceType[DEVICE_TYPE_SIZE_MAX + 1] = { 0 }; + if (snprintf_s(deviceType, DEVICE_TYPE_SIZE_MAX + 1, DEVICE_TYPE_SIZE_MAX, "%03X", device->devType) >= 0) { + extra->peerDeviceType = deviceType; } - discEventExtra->peerDeviceType = deviceType; + DISC_EVENT(EVENT_SCENE_SCAN, EVENT_STAGE_SCAN_END, *extra); } static void DfxRecordStartDiscoveryDevice(DiscInfo *infoNode) @@ -140,13 +146,12 @@ static void DfxRecordDeviceFound(DiscInfo *infoNode, const DeviceInfo *device, c DiscEventExtra discEventExtra = { .discType = addtions->medium, .discMode = infoNode->mode, .result = EVENT_STAGE_RESULT_OK }; - UpdateDiscEventByDeviceInfo(&discEventExtra, device); if (infoNode->statistics.repTimes == 0) { uint64_t costTime = SoftBusGetSysTimeMs() - infoNode->statistics.startTime; SoftbusRecordFirstDiscTime((SoftBusDiscMedium)addtions->medium, costTime); discEventExtra.costTime = costTime; } - DISC_EVENT(EVENT_SCENE_SCAN, EVENT_STAGE_SCAN_END, discEventExtra); + UpdateDiscEventAndReport(&discEventExtra, device); infoNode->statistics.repTimes++; infoNode->statistics.devNum++; } @@ -267,13 +272,13 @@ static void FreeDiscInfo(DiscInfo *info, const ServiceType type) static bool IsInnerModule(const DiscInfo *infoNode) { for (uint32_t i = 0; i < MODULE_MAX; i++) { - DISC_LOGI(DISC_CONTROL, "%s", infoNode->item->packageName); + DISC_LOGD(DISC_CONTROL, "%s", infoNode->item->packageName); if (strcmp(infoNode->item->packageName, g_discModuleMap[i]) == 0) { - DISC_LOGI(DISC_CONTROL, "true"); + DISC_LOGD(DISC_CONTROL, "true"); return true; } } - DISC_LOGI(DISC_CONTROL, "false"); + DISC_LOGD(DISC_CONTROL, "false"); return false; } @@ -282,8 +287,7 @@ static void InnerDeviceFound(DiscInfo *infoNode, const DeviceInfo *device, { if (IsInnerModule(infoNode) == false) { DiscEventExtra discEventExtra = { .discMode = infoNode->mode, .result = EVENT_STAGE_RESULT_OK }; - UpdateDiscEventByDeviceInfo(&discEventExtra, device); - DISC_EVENT(EVENT_SCENE_SCAN, EVENT_STAGE_SCAN_END, discEventExtra); + UpdateDiscEventAndReport(&discEventExtra, device); (void)infoNode->item->callback.serverCb.OnServerDeviceFound(infoNode->item->packageName, device, additions); return; } diff --git a/core/frame/small/init/src/bus_center_server_stub.c b/core/frame/small/init/src/bus_center_server_stub.c index 96c83d4df..00e9d473d 100644 --- a/core/frame/small/init/src/bus_center_server_stub.c +++ b/core/frame/small/init/src/bus_center_server_stub.c @@ -301,7 +301,7 @@ int32_t ServerStopTimeSync(IpcIo *req, IpcIo *reply) LNN_LOGE(LNN_STATE, "ServerStopTimeSync no permission"); return SOFTBUS_PERMISSION_DENIED; } - int32_t ret = LnnIpcStopTimeSync(pkgName, targetNetworkId); + int32_t ret = LnnIpcStopTimeSync(pkgName, targetNetworkId, 0); if (ret != SOFTBUS_OK) { LNN_LOGE(LNN_STATE, "ServerStopTimeSync start time sync failed"); return SOFTBUS_ERR; diff --git a/core/frame/standard/client_manager/src/softbus_client_info_manager.cpp b/core/frame/standard/client_manager/src/softbus_client_info_manager.cpp index 8c926de6c..ca1598807 100644 --- a/core/frame/standard/client_manager/src/softbus_client_info_manager.cpp +++ b/core/frame/standard/client_manager/src/softbus_client_info_manager.cpp @@ -55,11 +55,11 @@ int32_t SoftbusClientInfoManager::SoftbusAddService(const std::string &pkgName, int32_t SoftbusClientInfoManager::SoftbusRemoveService(const sptr &object, std::string &pkgName, int32_t* pid) { - if (object == nullptr) { + if (object == nullptr || pid == nullptr) { COMM_LOGE(COMM_SVC, "RemoveService object is nullptr\n"); return SOFTBUS_INVALID_PARAM; } - COMM_LOGI(COMM_SVC, "SoftbusRemoveService, pid=%d, pkgname=%s", pid, pkgName.c_str()); + std::lock_guard autoLock(clientObjectMapLock_); for (auto iter = clientObjectMap_.begin(); iter != clientObjectMap_.end(); ++iter) { if (iter->second.second.first == object) { @@ -70,6 +70,7 @@ int32_t SoftbusClientInfoManager::SoftbusRemoveService(const sptr break; } } + COMM_LOGI(COMM_SVC, "SoftbusRemoveService, pid=%d, pkgname=%s", (*pid), pkgName.c_str()); return SOFTBUS_OK; } diff --git a/core/frame/standard/init/src/softbus_server.cpp b/core/frame/standard/init/src/softbus_server.cpp index 29dc695e2..721e07b18 100644 --- a/core/frame/standard/init/src/softbus_server.cpp +++ b/core/frame/standard/init/src/softbus_server.cpp @@ -230,7 +230,8 @@ int32_t SoftBusServer::StartTimeSync(const char *pkgName, const char *targetNetw int32_t SoftBusServer::StopTimeSync(const char *pkgName, const char *targetNetworkId) { - return LnnIpcStopTimeSync(pkgName, targetNetworkId); + pid_t callingPid = OHOS::IPCSkeleton::GetCallingPid(); + return LnnIpcStopTimeSync(pkgName, targetNetworkId, callingPid); } int32_t SoftBusServer::QosReport(int32_t channelId, int32_t chanType, int32_t appType, int32_t quality) diff --git a/core/frame/standard/init/src/softbus_server_death_recipient.cpp b/core/frame/standard/init/src/softbus_server_death_recipient.cpp index cb40dbca7..cc8fafdf0 100644 --- a/core/frame/standard/init/src/softbus_server_death_recipient.cpp +++ b/core/frame/standard/init/src/softbus_server_death_recipient.cpp @@ -23,7 +23,7 @@ namespace OHOS { void SoftBusDeathRecipient::OnRemoteDied(const wptr &remote) { std::string pkgName; - int32_t pid; + int32_t pid = 0; SoftbusClientInfoManager::GetInstance().SoftbusRemoveService(remote.promote(), pkgName, &pid); COMM_LOGI(COMM_SVC, "client service %s died, remove it from softbus server", pkgName.c_str()); ClientDeathCallback(pkgName.c_str(), pid); diff --git a/core/frame/standard/init/src/softbus_server_stub.cpp b/core/frame/standard/init/src/softbus_server_stub.cpp index 084df2740..b4e9df127 100644 --- a/core/frame/standard/init/src/softbus_server_stub.cpp +++ b/core/frame/standard/init/src/softbus_server_stub.cpp @@ -16,7 +16,9 @@ #include "softbus_server_stub.h" #include "accesstoken_kit.h" +#include "access_control.h" #include "access_token.h" +#include "anonymizer.h" #include "comm_log.h" #include "discovery_service.h" #include "ipc_skeleton.h" @@ -577,6 +579,14 @@ static void ReadQosInfo(MessageParcel& data, SessionParam ¶m) } } +static void ReadSessionInfo(MessageParcel& data, SessionParam ¶m) +{ + param.sessionName = data.ReadCString(); + param.peerSessionName = data.ReadCString(); + param.peerDeviceId = data.ReadCString(); + param.groupId = data.ReadCString(); +} + int32_t SoftBusServerStub::OpenSessionInner(MessageParcel &data, MessageParcel &reply) { COMM_LOGI(COMM_SVC, "enter"); @@ -590,10 +600,7 @@ int32_t SoftBusServerStub::OpenSessionInner(MessageParcel &data, MessageParcel & int64_t timeStart = 0; int64_t timediff = 0; SoftBusOpenSessionStatus isSucc = SOFTBUS_EVT_OPEN_SESSION_FAIL; - param.sessionName = data.ReadCString(); - param.peerSessionName = data.ReadCString(); - param.peerDeviceId = data.ReadCString(); - param.groupId = data.ReadCString(); + ReadSessionInfo(data, param); ReadSessionAttrs(data, &getAttr); param.attr = &getAttr; ReadQosInfo(data, param); @@ -603,6 +610,10 @@ int32_t SoftBusServerStub::OpenSessionInner(MessageParcel &data, MessageParcel & retReply = SOFTBUS_INVALID_PARAM; goto EXIT; } + if (TransCheckAccessControl(param.peerDeviceId) != SOFTBUS_OK) { + retReply = SOFTBUS_PERMISSION_DENIED; + goto EXIT; + } if (CheckOpenSessionPermission(¶m) != SOFTBUS_OK) { SoftbusReportTransErrorEvt(SOFTBUS_PERMISSION_DENIED); retReply = SOFTBUS_PERMISSION_DENIED; @@ -918,6 +929,14 @@ int32_t SoftBusServerStub::GetNodeKeyInfoLen(int32_t key) return LnnGetNodeKeyInfoLen(key); } +static void PrintNetworkId(const char *networkId) +{ + char *anonyNetworkId = nullptr; + Anonymize(networkId, &anonyNetworkId); + COMM_LOGI(COMM_SVC, "networkId = %s", anonyNetworkId); + AnonymizeFree(anonyNetworkId); +} + int32_t SoftBusServerStub::GetNodeKeyInfoInner(MessageParcel &data, MessageParcel &reply) { const char *clientName = data.ReadCString(); @@ -926,6 +945,7 @@ int32_t SoftBusServerStub::GetNodeKeyInfoInner(MessageParcel &data, MessageParce COMM_LOGE(COMM_SVC, "GetNodeKeyInfoInner read clientName or networkId failed!"); return SOFTBUS_IPC_ERR; } + PrintNetworkId(networkId); int32_t key; if (!data.ReadInt32(key)) { COMM_LOGE(COMM_SVC, "GetNodeKeyInfoInner read key failed!"); diff --git a/core/transmission/common/src/softbus_message_open_channel.c b/core/transmission/common/src/softbus_message_open_channel.c index 97716320c..b66c87792 100644 --- a/core/transmission/common/src/softbus_message_open_channel.c +++ b/core/transmission/common/src/softbus_message_open_channel.c @@ -111,13 +111,12 @@ char *PackRequest(const AppInfo *appInfo) cJSON_Delete(json); return NULL; } - if (appInfo->fastTransDataSize > 0) { - if (PackFirstData(appInfo, json) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "pack first data failed"); - cJSON_Delete(json); - return NULL; - } + if (appInfo->fastTransDataSize > 0 && PackFirstData(appInfo, json) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_CTRL, "pack first data failed"); + cJSON_Delete(json); + return NULL; } + unsigned char encodeSessionKey[BASE64KEY] = {0}; size_t keyLen = 0; int32_t ret = SoftBusBase64Encode(encodeSessionKey, BASE64KEY, &keyLen, (unsigned char*)appInfo->sessionKey, @@ -126,26 +125,25 @@ char *PackRequest(const AppInfo *appInfo) cJSON_Delete(json); return NULL; } - if (!AddNumberToJsonObject(json, CODE, CODE_OPEN_CHANNEL) || + bool addBRet = (!AddNumberToJsonObject(json, CODE, CODE_OPEN_CHANNEL) || !AddNumberToJsonObject(json, API_VERSION, appInfo->myData.apiVersion) || !AddStringToJsonObject(json, BUS_NAME, appInfo->peerData.sessionName) || !AddStringToJsonObject(json, GROUP_ID, appInfo->groupId) || !AddNumberToJsonObject(json, UID, appInfo->myData.uid) || !AddNumberToJsonObject(json, PID, appInfo->myData.pid) || !AddStringToJsonObject(json, SESSION_KEY, (char*)encodeSessionKey) || - !AddNumberToJsonObject(json, MTU_SIZE, (int)appInfo->myData.dataConfig)) { + !AddNumberToJsonObject(json, MTU_SIZE, (int)appInfo->myData.dataConfig)); + if (addBRet) { cJSON_Delete(json); return NULL; } char *authState = (char*)appInfo->myData.authState; - if (appInfo->myData.apiVersion != API_V1) { - if (!AddStringToJsonObject(json, PKG_NAME, appInfo->myData.pkgName) || - !AddStringToJsonObject(json, CLIENT_BUS_NAME, appInfo->myData.sessionName) || - !AddStringToJsonObject(json, AUTH_STATE, authState) || - !AddNumberToJsonObject(json, MSG_ROUTE_TYPE, appInfo->routeType)) { - cJSON_Delete(json); - return NULL; - } + if (appInfo->myData.apiVersion != API_V1 && (!AddStringToJsonObject(json, PKG_NAME, appInfo->myData.pkgName) || + !AddStringToJsonObject(json, CLIENT_BUS_NAME, appInfo->myData.sessionName) || + !AddStringToJsonObject(json, AUTH_STATE, authState) || + !AddNumberToJsonObject(json, MSG_ROUTE_TYPE, appInfo->routeType))) { + cJSON_Delete(json); + return NULL; } (void)AddNumberToJsonObject(json, BUSINESS_TYPE, appInfo->businessType); (void)AddNumberToJsonObject(json, AUTO_CLOSE_TIME, appInfo->autoCloseTime); diff --git a/core/transmission/session/src/trans_session_manager.c b/core/transmission/session/src/trans_session_manager.c index 5a7e68611..370d3c4bf 100644 --- a/core/transmission/session/src/trans_session_manager.c +++ b/core/transmission/session/src/trans_session_manager.c @@ -345,7 +345,10 @@ void TransOnLinkDown(const char *networkId, const char *uuid, const char *udid, if (networkId == NULL || g_sessionServerList == NULL) { return; } - TRANS_LOGI(TRANS_CTRL, "routeType=%d", routeType); + char *anonyNetworkId = NULL; + Anonymize(networkId, &anonyNetworkId); + TRANS_LOGI(TRANS_CTRL, "routeType=%d, networkId=%s", routeType, anonyNetworkId); + AnonymizeFree(anonyNetworkId); ListNode sessionServerList = {0}; ListInit(&sessionServerList); diff --git a/core/transmission/trans_channel/auth/src/trans_auth_manager.c b/core/transmission/trans_channel/auth/src/trans_auth_manager.c index d892d0661..5a5f19ea2 100644 --- a/core/transmission/trans_channel/auth/src/trans_auth_manager.c +++ b/core/transmission/trans_channel/auth/src/trans_auth_manager.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 @@ -65,12 +65,12 @@ static void DelAuthChannelInfoByAuthId(int32_t authId); static int32_t GetAuthChannelInfoByChanId(int32_t channelId, AuthChannelInfo *dstInfo) { - if (dstInfo == NULL || g_authChannelList == NULL) { + if (g_authChannelList == NULL) { TRANS_LOGE(TRANS_SVC, "invalid param"); return SOFTBUS_INVALID_PARAM; } - if (SoftBusMutexLock(&g_authChannelList->lock) != 0) { + if (SoftBusMutexLock(&g_authChannelList->lock) != SOFTBUS_OK) { TRANS_LOGE(TRANS_SVC, "lock failed"); return SOFTBUS_LOCK_ERR; } @@ -180,7 +180,7 @@ static int32_t NotifyOnDataReceived(int32_t authId, const void *data, uint32_t l return SOFTBUS_ERR; } TransReceiveData receiveData; - receiveData.data = (void*)data; + receiveData.data = (void *)data; receiveData.dataLen = len; receiveData.dataType = TRANS_SESSION_BYTES; @@ -190,9 +190,6 @@ static int32_t NotifyOnDataReceived(int32_t authId, const void *data, uint32_t l static int32_t CopyPeerAppInfo(AppInfo *recvAppInfo, AppInfo *channelAppInfo) { - if (recvAppInfo == NULL || channelAppInfo == NULL) { - return SOFTBUS_INVALID_PARAM; - } if (memcpy_s(channelAppInfo->peerData.deviceId, DEVICE_ID_SIZE_MAX, recvAppInfo->peerData.deviceId, DEVICE_ID_SIZE_MAX) != EOK || memcpy_s(recvAppInfo->myData.deviceId, DEVICE_ID_SIZE_MAX, @@ -210,9 +207,6 @@ static int32_t CopyPeerAppInfo(AppInfo *recvAppInfo, AppInfo *channelAppInfo) static int32_t OnRequsetUpdateAuthChannel(int32_t authId, AppInfo *appInfo) { - if (appInfo == NULL) { - return SOFTBUS_INVALID_PARAM; - } AuthChannelInfo *item = NULL; if (SoftBusMutexLock(&g_authChannelList->lock) != 0) { return SOFTBUS_LOCK_ERR; @@ -243,6 +237,7 @@ static int32_t OnRequsetUpdateAuthChannel(int32_t authId, AppInfo *appInfo) } if (CopyPeerAppInfo(appInfo, &item->appInfo) != SOFTBUS_OK) { TRANS_LOGE(TRANS_SVC, "CopyPeerAppInfo failed"); + ListDelete(&item->node); SoftBusFree(item); SoftBusMutexUnlock(&g_authChannelList->lock); return SOFTBUS_MEM_ERR; @@ -258,7 +253,8 @@ static const ConfigTypeMap g_configTypeMap[] = { static int32_t FindConfigType(int32_t channelType, int32_t businessType) { - for (uint32_t i = 0; i < sizeof(g_configTypeMap) / sizeof(ConfigTypeMap); i++) { + uint32_t size = (uint32_t)(sizeof(g_configTypeMap) / sizeof(g_configTypeMap[0])); + for (uint32_t i = 0; i < size; i++) { if ((g_configTypeMap[i].channelType == channelType) && (g_configTypeMap[i].businessType == businessType)) { return g_configTypeMap[i].configType; } @@ -294,6 +290,7 @@ static int32_t TransAuthFillDataConfig(AppInfo *appInfo) if (appInfo->peerData.dataConfig != 0) { uint32_t localDataConfig = 0; if (TransGetLocalConfig(CHANNEL_TYPE_AUTH, appInfo->businessType, &localDataConfig) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_SVC, "get local config failed"); return SOFTBUS_ERR; } appInfo->myData.dataConfig = MIN(localDataConfig, appInfo->peerData.dataConfig); @@ -331,7 +328,7 @@ static void OnRecvAuthChannelRequest(int32_t authId, const char *data, int32_t l } ret = AuthGetUidAndPidBySessionName(appInfo.myData.sessionName, &appInfo.myData.uid, &appInfo.myData.pid); if (ret != SOFTBUS_OK) { - TRANS_LOGE(TRANS_SVC, "AuthGetUidAndPidBySessionName failed"); + TRANS_LOGE(TRANS_SVC, "auth get id by sessionName failed"); goto EXIT_ERR; } ret = TransAuthFillDataConfig(&appInfo); @@ -417,9 +414,9 @@ static void OnRecvAuthChannelReply(int32_t authId, const char *data, int32_t len return; EXIT_ERR: AuthCloseChannel(authId); - DelAuthChannelInfoByChanId(info.appInfo.myData.channelId); - (void)NotifyOpenAuthChannelFailed(info.appInfo.myData.pkgName, info.appInfo.myData.pid, - info.appInfo.myData.channelId, ret); + DelAuthChannelInfoByChanId((int32_t)(info.appInfo.myData.channelId)); + (void)NotifyOpenAuthChannelFailed((const char *)(info.appInfo.myData.pkgName), + (int32_t)(info.appInfo.myData.pid), (int32_t)(info.appInfo.myData.channelId), ret); } static void OnAuthChannelDataRecv(int32_t authId, const AuthChannelData *data) @@ -430,9 +427,9 @@ static void OnAuthChannelDataRecv(int32_t authId, const AuthChannelData *data) } if (data->flag == AUTH_CHANNEL_REQ) { - OnRecvAuthChannelRequest(authId, (const char *)data->data, data->len); + OnRecvAuthChannelRequest(authId, (const char *)data->data, (int32_t)data->len); } else if (data->flag == AUTH_CHANNEL_REPLY) { - OnRecvAuthChannelReply(authId, (const char *)data->data, data->len); + OnRecvAuthChannelReply(authId, (const char *)data->data, (int32_t)data->len); } else { TRANS_LOGE(TRANS_SVC, "auth channel flags err, authId=%d", authId); } @@ -456,9 +453,9 @@ static void OnDisconnect(int32_t authId) return; } TRANS_LOGI(TRANS_SVC, "recv authId=%d channel disconnect event.", authId); - DelAuthChannelInfoByChanId(dstInfo.appInfo.myData.channelId); - (void)NofifyCloseAuthChannel(dstInfo.appInfo.myData.pkgName, dstInfo.appInfo.myData.pid, - dstInfo.appInfo.myData.channelId); + DelAuthChannelInfoByChanId((int32_t)(dstInfo.appInfo.myData.channelId)); + (void)NofifyCloseAuthChannel((const char *)dstInfo.appInfo.myData.pkgName, + (int32_t)dstInfo.appInfo.myData.pid, (int32_t)dstInfo.appInfo.myData.channelId); } static int32_t GetAppInfo(const char *sessionName, int32_t channelId, AppInfo *appInfo, bool isClient) @@ -473,7 +470,7 @@ static int32_t GetAppInfo(const char *sessionName, int32_t channelId, AppInfo *a appInfo->myData.apiVersion = API_V2; appInfo->peerData.apiVersion = API_V2; appInfo->autoCloseTime = 0; - if ((!IsNoPkgNameSession(sessionName)) || (isClient)) { + if (!IsNoPkgNameSession(sessionName) || isClient) { if (TransGetUidAndPid(sessionName, &appInfo->myData.uid, &appInfo->myData.pid) != SOFTBUS_OK) { TRANS_LOGE(TRANS_SVC, "TransGetUidAndPid failed"); return SOFTBUS_ERR; @@ -489,10 +486,11 @@ static int32_t GetAppInfo(const char *sessionName, int32_t channelId, AppInfo *a return SOFTBUS_ERR; } if (strcpy_s(appInfo->myData.sessionName, sizeof(appInfo->myData.sessionName), sessionName) != EOK) { + TRANS_LOGE(TRANS_SVC, "copy sessionName failed"); return SOFTBUS_ERR; } appInfo->peerData.apiVersion = API_V2; - if (strcpy_s(appInfo->peerData.sessionName, sizeof(appInfo->peerData.sessionName), sessionName) != 0) { + if (strcpy_s(appInfo->peerData.sessionName, sizeof(appInfo->peerData.sessionName), sessionName) != EOK) { return SOFTBUS_ERR; } if (TransGetLocalConfig(appInfo->channelType, appInfo->businessType, &appInfo->myData.dataConfig) != SOFTBUS_OK) { @@ -527,7 +525,7 @@ static void DelAuthChannelInfoByChanId(int32_t channelId) if (g_authChannelList == NULL) { return; } - if (SoftBusMutexLock(&g_authChannelList->lock) != 0) { + if (SoftBusMutexLock(&g_authChannelList->lock) != SOFTBUS_OK) { return; } AuthChannelInfo *item = NULL; @@ -548,7 +546,7 @@ static void DelAuthChannelInfoByAuthId(int32_t authId) if (g_authChannelList == NULL) { return; } - if (SoftBusMutexLock(&g_authChannelList->lock) != 0) { + if (SoftBusMutexLock(&g_authChannelList->lock) != SOFTBUS_OK) { return; } AuthChannelInfo *item = NULL; @@ -621,6 +619,8 @@ void TransAuthDeinit(void) { UnregAuthChannelListener(MODULE_AUTH_CHANNEL); UnregAuthChannelListener(MODULE_AUTH_MSG); + DestroySoftBusList(g_authChannelList); + g_authChannelList = NULL; g_cb = NULL; } @@ -637,15 +637,15 @@ static int32_t TransPostAuthChannelMsg(const AppInfo *appInfo, int32_t authId, i } if (TransAuthChannelMsgPack(msg, appInfo) != SOFTBUS_OK) { cJSON_Delete(msg); + TRANS_LOGE(TRANS_SVC, "tran channel msg pack failed"); return SOFTBUS_ERR; } char *data = cJSON_PrintUnformatted(msg); + cJSON_Delete(msg); if (data == NULL) { TRANS_LOGE(TRANS_SVC, "json failed"); - cJSON_Delete(msg); return SOFTBUS_PARSE_JSON_ERR; } - cJSON_Delete(msg); AuthChannelData channelData = { .module = MODULE_AUTH_CHANNEL, @@ -718,6 +718,7 @@ int32_t TransOpenAuthMsgChannel(const char *sessionName, const ConnectOption *co return SOFTBUS_ERR; } if (strcpy_s(channel->appInfo.reqId, REQ_ID_SIZE_MAX, reqId) != EOK) { + SoftBusFree(channel); TRANS_LOGE(TRANS_SVC, "TransOpenAuthMsgChannel strcpy_s reqId failed"); return SOFTBUS_ERR; } @@ -725,7 +726,7 @@ int32_t TransOpenAuthMsgChannel(const char *sessionName, const ConnectOption *co SoftBusFree(channel); return SOFTBUS_MEM_ERR; } - *channelId = channel->appInfo.myData.channelId; + *channelId = (int32_t)channel->appInfo.myData.channelId; int32_t authId = AuthOpenChannel(connOpt->socketOption.addr, connOpt->socketOption.port); if (authId < 0) { TRANS_LOGE(TRANS_SVC, "AuthOpenChannel failed"); diff --git a/core/transmission/trans_channel/auth/src/trans_auth_message.c b/core/transmission/trans_channel/auth/src/trans_auth_message.c index a14a71140..a233f1066 100644 --- a/core/transmission/trans_channel/auth/src/trans_auth_message.c +++ b/core/transmission/trans_channel/auth/src/trans_auth_message.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 @@ -16,7 +16,6 @@ #include "trans_auth_message.h" #include "securec.h" -#include "softbus_conn_interface.h" #include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_utils.h" @@ -40,7 +39,7 @@ int32_t TransAuthChannelMsgPack(cJSON *msg, const AppInfo *appInfo) !AddStringToJsonObject(msg, "SRC_BUS_NAME", appInfo->myData.sessionName) || !AddStringToJsonObject(msg, "DST_BUS_NAME", appInfo->peerData.sessionName) || !AddStringToJsonObject(msg, "REQ_ID", appInfo->reqId) || - !AddNumberToJsonObject(msg, "MTU_SIZE", appInfo->myData.dataConfig)) { + !AddNumberToJsonObject(msg, "MTU_SIZE", (int)appInfo->myData.dataConfig)) { TRANS_LOGE(TRANS_SVC, "failed"); return SOFTBUS_PARSE_JSON_ERR; } @@ -81,7 +80,6 @@ int32_t TransAuthChannelMsgUnpack(const char *msg, AppInfo *appInfo, int32_t len int32_t TransAuthChannelErrorPack(int32_t errcode, const char *errMsg, char *cJsonStr, int32_t maxLen) { - (void)maxLen; if (errMsg == NULL || cJsonStr == NULL) { return SOFTBUS_INVALID_PARAM; } @@ -97,16 +95,14 @@ int32_t TransAuthChannelErrorPack(int32_t errcode, const char *errMsg, char *cJs return SOFTBUS_PARSE_JSON_ERR; } char *data = cJSON_PrintUnformatted(obj); + cJSON_Delete(obj); if (data == NULL) { - cJSON_Delete(obj); return SOFTBUS_PARSE_JSON_ERR; } - if (memcpy_s(cJsonStr, ERR_MSG_MAX_LEN, data, strlen(data)) != EOK) { - cJSON_Delete(obj); + if (memcpy_s(cJsonStr, maxLen, data, strlen(data)) != EOK) { cJSON_free(data); return SOFTBUS_MEM_ERR; } - cJSON_Delete(obj); cJSON_free(data); return SOFTBUS_OK; } \ No newline at end of file diff --git a/core/transmission/trans_channel/common/src/trans_lane_pending_ctl.c b/core/transmission/trans_channel/common/src/trans_lane_pending_ctl.c index 86eb87c5b..86a53c662 100644 --- a/core/transmission/trans_channel/common/src/trans_lane_pending_ctl.c +++ b/core/transmission/trans_channel/common/src/trans_lane_pending_ctl.c @@ -17,7 +17,6 @@ #include #include "auth_interface.h" -#include "bus_center_info_key.h" #include "bus_center_manager.h" #include "common_list.h" #include "softbus_adapter_mem.h" @@ -84,7 +83,7 @@ void TransReqLanePendingDeinit(void) static int32_t TransDelLaneReqFromPendingList(uint32_t laneId) { - TRANS_LOGI(TRANS_SVC, "del tran request from pending laneId=%u.", laneId); + TRANS_LOGD(TRANS_SVC, "del tran request from pending laneId=%u.", laneId); if (g_reqLanePendingList == NULL) { TRANS_LOGE(TRANS_INIT, "lane request list hasn't init."); return SOFTBUS_ERR; @@ -128,7 +127,6 @@ static int32_t TransAddLaneReqFromPendingList(uint32_t laneId) item->laneId = laneId; item->bSucc = false; item->isFinished = false; - (void)memset_s(&(item->connInfo), sizeof(LaneConnInfo), 0, sizeof(LaneConnInfo)); if (SoftBusMutexLock(&g_reqLanePendingList->lock) != SOFTBUS_OK) { SoftBusFree(item); @@ -259,7 +257,7 @@ static LaneTransType GetStreamLaneType(int32_t streamType) LaneTransType TransGetLaneTransTypeBySession(const SessionParam *param) { - if (param == NULL) { + if (param == NULL || param->attr == NULL) { return LANE_T_BUTT; } int32_t type = param->attr->dataType; @@ -518,10 +516,6 @@ int32_t TransGetLaneInfoByOption(bool isQosLane, const LaneRequestOption *reques } *laneId = GetLaneManager()->applyLaneId(LANE_TYPE_TRANS); - if (*laneId <= 0) { - TRANS_LOGE(TRANS_SVC, "trans apply lane failed."); - return SOFTBUS_ERR; - } if (TransAddLaneReqToPendingAndWaiting(isQosLane, *laneId, requestOption) != SOFTBUS_OK) { TRANS_LOGE(TRANS_SVC, "trans add lane to pending list failed."); return SOFTBUS_ERR; diff --git a/core/transmission/trans_channel/manager/src/trans_channel_manager.c b/core/transmission/trans_channel/manager/src/trans_channel_manager.c index a1197c2ff..c8ea64564 100644 --- a/core/transmission/trans_channel/manager/src/trans_channel_manager.c +++ b/core/transmission/trans_channel/manager/src/trans_channel_manager.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 @@ -296,21 +296,21 @@ EXIT_ERR: return NULL; } -static ChannelType TransGetChannelType(const SessionParam *param, const LaneConnInfo *connInfo) +static ChannelType TransGetChannelType(const SessionParam *param, const int32_t type) { LaneTransType transType = TransGetLaneTransTypeBySession(param); if (transType == LANE_T_BUTT) { return CHANNEL_TYPE_BUTT; } - if (connInfo->type == LANE_BR || connInfo->type == LANE_BLE || connInfo->type == LANE_BLE_DIRECT || - connInfo->type == LANE_COC || connInfo->type == LANE_COC_DIRECT) { + if (type == LANE_BR || type == LANE_BLE || type == LANE_BLE_DIRECT || + type == LANE_COC || type == LANE_COC_DIRECT) { return CHANNEL_TYPE_PROXY; } else if (transType == LANE_T_FILE || transType == LANE_T_COMMON_VIDEO || transType == LANE_T_COMMON_VOICE || transType == LANE_T_RAW_STREAM) { return CHANNEL_TYPE_UDP; - } else if ((transType == LANE_T_MSG) && (connInfo->type != LANE_P2P) && (connInfo->type != LANE_P2P_REUSE) && - (connInfo->type != LANE_HML)) { + } else if ((transType == LANE_T_MSG) && (type != LANE_P2P) && (type != LANE_P2P_REUSE) && + (type != LANE_HML)) { return CHANNEL_TYPE_PROXY; } return CHANNEL_TYPE_TCP_DIRECT; @@ -383,11 +383,11 @@ static int TransGetLocalConfig(int32_t channelType, int32_t businessType, uint32 return SOFTBUS_OK; } -static void FillAppInfo(AppInfo *appInfo, ConnectOption *connOpt, const SessionParam *param, - TransInfo *transInfo, LaneConnInfo *connInfo) +static void FillAppInfo(AppInfo *appInfo, const SessionParam *param, + TransInfo *transInfo, int32_t type) { - transInfo->channelType = TransGetChannelType(param, connInfo); - appInfo->linkType = connInfo->type; + transInfo->channelType = TransGetChannelType(param, type); + appInfo->linkType = type; appInfo->channelType = transInfo->channelType; (void)TransGetLocalConfig(appInfo->channelType, appInfo->businessType, &appInfo->myData.dataConfig); } @@ -412,6 +412,10 @@ static void TransOpenChannelSetModule(int32_t channelType, ConnectOption *connOp int32_t TransOpenChannel(const SessionParam *param, TransInfo *transInfo) { + if (param == NULL || transInfo == NULL) { + TRANS_LOGE(TRANS_CTRL, "param invalid"); + return SOFTBUS_INVALID_PARAM; + } TRANS_LOGI(TRANS_CTRL, "server TransOpenChannel"); int64_t timeStart = GetSoftbusRecordTimeMillis(); transInfo->channelId = INVALID_CHANNEL_ID; @@ -451,7 +455,7 @@ int32_t TransOpenChannel(const SessionParam *param, TransInfo *transInfo) SOFTBUS_EVT_OPEN_SESSION_FAIL, GetSoftbusRecordTimeMillis() - timeStart); goto EXIT_ERR; } - FillAppInfo(appInfo, &connOpt, param, transInfo, &connInfo); + FillAppInfo(appInfo, param, transInfo, connInfo.type); TransOpenChannelSetModule(transInfo->channelType, &connOpt); TRANS_LOGI(TRANS_CTRL, "laneId=%u get channelType=%u.", laneId, transInfo->channelType); errCode = TransOpenChannelProc((ChannelType)transInfo->channelType, appInfo, &connOpt, @@ -576,6 +580,7 @@ int32_t TransOpenAuthChannel(const char *sessionName, const ConnectOption *connO } if (strcpy_s(appInfo->reqId, REQ_ID_SIZE_MAX, reqId) != EOK) { TRANS_LOGE(TRANS_CTRL, "strcpy_s reqId failed"); + SoftBusFree(appInfo); return INVALID_CHANNEL_ID; } if (TransProxyOpenProxyChannel(appInfo, connOpt, &channelId) != SOFTBUS_OK) { diff --git a/core/transmission/trans_channel/manager/src/trans_lane_manager.c b/core/transmission/trans_channel/manager/src/trans_lane_manager.c index bc18bdea1..5a68efa49 100644 --- a/core/transmission/trans_channel/manager/src/trans_lane_manager.c +++ b/core/transmission/trans_channel/manager/src/trans_lane_manager.c @@ -137,7 +137,7 @@ void TransLaneMgrDeinit(void) int32_t TransLaneMgrAddLane(int32_t channelId, int32_t channelType, LaneConnInfo *connInfo, uint32_t laneId, AppInfoData *myData) { - if (g_channelLaneList == NULL) { + if (g_channelLaneList == NULL || connInfo == NULL) { return SOFTBUS_ERR; } @@ -167,10 +167,10 @@ int32_t TransLaneMgrAddLane(int32_t channelId, int32_t channelType, LaneConnInfo TransLaneInfo *laneItem = NULL; LIST_FOR_EACH_ENTRY(laneItem, &(g_channelLaneList->list), TransLaneInfo, node) { if (laneItem->channelId == channelId && laneItem->channelType == channelType) { - TRANS_LOGI(TRANS_SVC, - "trans lane info has exited.channelId=%d, channelType=%d", channelId, channelType); SoftBusFree(newLane); (void)SoftBusMutexUnlock(&(g_channelLaneList->lock)); + TRANS_LOGI(TRANS_SVC, + "trans lane info has existed.channelId=%d, channelType=%d", channelId, channelType); return SOFTBUS_ERR; } } @@ -213,10 +213,11 @@ int32_t TransLaneMgrDelLane(int32_t channelId, int32_t channelType) void TransLaneMgrDeathCallback(const char *pkgName, int32_t pid) { - if (g_channelLaneList == NULL) { + if (pkgName == NULL || g_channelLaneList == NULL) { TRANS_LOGE(TRANS_INIT, "trans lane manager hasn't init."); return; } + TRANS_LOGW(TRANS_CTRL, "TransLaneMgrDeathCallback: pkgName=%s, pid=%d", pkgName, pid); if (SoftBusMutexLock(&(g_channelLaneList->lock)) != 0) { TRANS_LOGE(TRANS_SVC, "lock failed"); return; diff --git a/core/transmission/trans_channel/manager/src/trans_link_listener.c b/core/transmission/trans_channel/manager/src/trans_link_listener.c index e4f525b37..2e87d6bcc 100644 --- a/core/transmission/trans_channel/manager/src/trans_link_listener.c +++ b/core/transmission/trans_channel/manager/src/trans_link_listener.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 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 @@ -16,7 +16,6 @@ #include "lnn_distributed_net_ledger.h" #include "securec.h" -#include "softbus_app_info.h" #include "softbus_common.h" #include "softbus_def.h" #include "softbus_errcode.h" diff --git a/core/transmission/trans_channel/proxy/src/softbus_proxychannel_control.c b/core/transmission/trans_channel/proxy/src/softbus_proxychannel_control.c index 0aa746523..fe55929e1 100644 --- a/core/transmission/trans_channel/proxy/src/softbus_proxychannel_control.c +++ b/core/transmission/trans_channel/proxy/src/softbus_proxychannel_control.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 @@ -25,7 +25,6 @@ #include "softbus_proxychannel_manager.h" #include "softbus_proxychannel_message.h" #include "softbus_proxychannel_transceiver.h" -#include "softbus_utils.h" #include "trans_log.h" #include "trans_event.h" @@ -56,7 +55,7 @@ int32_t TransProxySendInnerMessage(ProxyChannelInfo *info, const char *payLoad, static int32_t SetCipherOfHandshakeMsg(uint32_t channelId, uint8_t *cipher) { - int64_t authId = TransProxyGetAuthId(channelId); + int64_t authId = TransProxyGetAuthId((int32_t)channelId); if (authId == AUTH_INVALID_ID) { TRANS_LOGE(TRANS_CTRL, "get authId fail"); return SOFTBUS_ERR; diff --git a/core/transmission/trans_channel/proxy/src/softbus_proxychannel_listener.c b/core/transmission/trans_channel/proxy/src/softbus_proxychannel_listener.c index b108d50ce..cf08038bb 100644 --- a/core/transmission/trans_channel/proxy/src/softbus_proxychannel_listener.c +++ b/core/transmission/trans_channel/proxy/src/softbus_proxychannel_listener.c @@ -66,7 +66,7 @@ static int32_t NotifyNormalChannelOpened(int32_t channelId, const AppInfo *appIn info.algorithm = appInfo->algorithm; info.crc = appInfo->crc; info.routeType = appInfo->routeType; - info.businessType = appInfo->appType == APP_TYPE_AUTH ? BUSINESS_TYPE_NOT_CARE : appInfo->businessType; + info.businessType = (int32_t)(appInfo->appType == APP_TYPE_AUTH ? BUSINESS_TYPE_NOT_CARE : appInfo->businessType); info.autoCloseTime = appInfo->autoCloseTime; info.myHandleId = appInfo->myHandleId; info.peerHandleId = appInfo->peerHandleId; @@ -258,11 +258,11 @@ static int32_t TransProxyGetAppInfo(const char *sessionName, const char *peerNet TRANS_LOGE(TRANS_CTRL, "get local uuid fail ret=%d", ret); return SOFTBUS_ERR; } - if (strcpy_s(appInfo->myData.sessionName, sizeof(appInfo->myData.sessionName), sessionName) != 0) { + if (strcpy_s(appInfo->myData.sessionName, sizeof(appInfo->myData.sessionName), sessionName) != EOK) { return SOFTBUS_ERR; } appInfo->peerData.apiVersion = API_V2; - if (strcpy_s(appInfo->peerData.sessionName, sizeof(appInfo->peerData.sessionName), sessionName) != 0) { + if (strcpy_s(appInfo->peerData.sessionName, sizeof(appInfo->peerData.sessionName), sessionName) != EOK) { return SOFTBUS_ERR; } diff --git a/core/transmission/trans_channel/proxy/src/softbus_proxychannel_manager.c b/core/transmission/trans_channel/proxy/src/softbus_proxychannel_manager.c index e0fd339e9..1444e0abc 100644 --- a/core/transmission/trans_channel/proxy/src/softbus_proxychannel_manager.c +++ b/core/transmission/trans_channel/proxy/src/softbus_proxychannel_manager.c @@ -25,14 +25,12 @@ #include "bus_center_manager.h" #include "common_list.h" #include "data_bus_native.h" -#include "lnn_lane_link.h" #include "softbus_adapter_crypto.h" #include "softbus_adapter_hitrace.h" #include "softbus_adapter_mem.h" #include "softbus_adapter_thread.h" #include "softbus_conn_interface.h" #include "softbus_def.h" -#include "softbus_errcode.h" #include "softbus_feature_config.h" #include "softbus_hisysevt_transreporter.h" #include "softbus_proxychannel_callback.h" @@ -45,7 +43,6 @@ #include "trans_channel_limit.h" #include "trans_channel_manager.h" #include "trans_log.h" -#include "trans_pending_pkt.h" #include "trans_session_manager.h" #include "trans_event.h" @@ -229,6 +226,10 @@ int32_t TransProxySpecialUpdateChanInfo(ProxyChannelInfo *channelInfo) int32_t TransProxyGetChanByChanId(int32_t chanId, ProxyChannelInfo *chan) { + if (chan == NULL) { + TRANS_LOGE(TRANS_CTRL, "param invalid"); + return SOFTBUS_INVALID_PARAM; + } ProxyChannelInfo *item = NULL; ProxyChannelInfo *nextNode = NULL; @@ -689,7 +690,8 @@ static const ConfigTypeMap g_configTypeMap[] = { static int32_t FindConfigType(int32_t channelType, int32_t businessType) { - for (uint32_t i = 0; i < sizeof(g_configTypeMap) / sizeof(ConfigTypeMap); i++) { + uint32_t size = (uint32_t)sizeof(g_configTypeMap) / sizeof(ConfigTypeMap); + for (uint32_t i = 0; i < size; i++) { if ((g_configTypeMap[i].channelType == channelType) && (g_configTypeMap[i].businessType == businessType)) { return g_configTypeMap[i].configType; } @@ -1001,7 +1003,7 @@ static int32_t TransProxyFillChannelInfo(const ProxyMessage *msg, ProxyChannelIn chan->appInfo.routeType = BT_BLE; } - int16_t newChanId = GenerateChannelId(false); + int16_t newChanId = (int16_t)(GenerateChannelId(false)); ConstructProxyChannelInfo(chan, msg, newChanId, &info); ret = TransProxyGetLocalInfo(chan); @@ -1068,6 +1070,10 @@ static void TransProxyFastDataRecv(ProxyChannelInfo *chan) void TransProxyProcessHandshakeMsg(const ProxyMessage *msg) { + if (msg == NULL) { + TRANS_LOGE(TRANS_CTRL, "param invalid"); + return; + } TRANS_LOGI(TRANS_CTRL, "recv Handshake myChannelId=%d peerChannelId=%d", msg->msgHead.myId, msg->msgHead.peerId); ProxyChannelInfo *chan = (ProxyChannelInfo *)SoftBusCalloc(sizeof(ProxyChannelInfo)); @@ -1301,7 +1307,7 @@ static inline AuthLinkType ConvertConnectType2AuthLinkType(ConnectType type) int32_t TransProxyCreateChanInfo(ProxyChannelInfo *chan, int32_t channelId, const AppInfo *appInfo) { - chan->myId = channelId; + chan->myId = (int16_t)channelId; chan->channelId = channelId; if (GenerateRandomStr(chan->identity, sizeof(chan->identity)) != SOFTBUS_OK) { @@ -1525,6 +1531,7 @@ static void TransWifiOnLineProc(const char *peerNetworkId) TRANS_LOGI(TRANS_CTRL, "wifi is online"); if (peerNetworkId == NULL) { TRANS_LOGE(TRANS_CTRL, "invalid networkId"); + return; } int ret = NotifyNearByOnMigrateEvents(peerNetworkId, WIFI_STA, true); if (ret == SOFTBUS_OK) { @@ -1539,6 +1546,7 @@ static void TransWifiOffLineProc(const char *peerNetworkId) TRANS_LOGI(TRANS_CTRL, "wifi is offline"); if (peerNetworkId == NULL) { TRANS_LOGE(TRANS_CTRL, "invalid networkId"); + return; } int ret = NotifyNearByOnMigrateEvents(peerNetworkId, WIFI_STA, false); if (ret == SOFTBUS_OK) { @@ -1555,7 +1563,7 @@ void TransWifiStateChange(const LnnEventBasicInfo *info) return; } - LnnOnlineStateEventInfo *onlineStateInfo = (LnnOnlineStateEventInfo*)info; + LnnOnlineStateEventInfo *onlineStateInfo = (LnnOnlineStateEventInfo *)info; if (onlineStateInfo->isOnline == true) { TransWifiOnLineProc(onlineStateInfo->networkId); } else { @@ -1585,8 +1593,8 @@ static void TransNotifyOffLine(const LnnEventBasicInfo *info) if ((info == NULL) || (info->event != LNN_EVENT_NODE_ONLINE_STATE_CHANGED)) { return; } - LnnOnlineStateEventInfo *onlineStateInfo = (LnnOnlineStateEventInfo*)info; - if (onlineStateInfo->isOnline == true) { + LnnOnlineStateEventInfo *onlineStateInfo = (LnnOnlineStateEventInfo *)info; + if (onlineStateInfo->isOnline) { return; } @@ -1726,7 +1734,7 @@ void TransProxyDeathCallback(const char *pkgName, int32_t pid) TRANS_LOGE(TRANS_CTRL, "pkgName or proxy channel list is null."); return; } - + TRANS_LOGW(TRANS_CTRL, "TransProxyDeathCallback: pkgName=%s, pid=%d", pkgName, pid); ListNode destroyList; ListInit(&destroyList); ProxyChannelInfo *item = NULL; @@ -1748,8 +1756,12 @@ void TransProxyDeathCallback(const char *pkgName, int32_t pid) TRANS_LOGD(TRANS_CTRL, "ok"); } -int32_t TransProxyGetAppInfoByChanId(int32_t chanId, AppInfo* appInfo) +int32_t TransProxyGetAppInfoByChanId(int32_t chanId, AppInfo *appInfo) { + if (appInfo == NULL) { + TRANS_LOGE(TRANS_CTRL, "param invalid"); + return SOFTBUS_INVALID_PARAM; + } ProxyChannelInfo *item = NULL; ProxyChannelInfo *nextNode = NULL; @@ -1775,6 +1787,10 @@ int32_t TransProxyGetAppInfoByChanId(int32_t chanId, AppInfo* appInfo) int32_t TransProxyGetConnIdByChanId(int32_t channelId, int32_t *connId) { + if (connId == NULL) { + TRANS_LOGE(TRANS_CTRL, "param invalid"); + return SOFTBUS_INVALID_PARAM; + } if (g_proxyChannelList == NULL) { return SOFTBUS_ERR; } @@ -1785,9 +1801,9 @@ int32_t TransProxyGetConnIdByChanId(int32_t channelId, int32_t *connId) } LIST_FOR_EACH_ENTRY(item, &g_proxyChannelList->list, ProxyChannelInfo, node) { if (item->channelId == channelId) { - if (item->status == PROXY_CHANNEL_STATUS_COMPLETED || item->status == - PROXY_CHANNEL_STATUS_KEEPLIVEING) { - *connId = item->connId; + if (item->status == PROXY_CHANNEL_STATUS_COMPLETED || + item->status == PROXY_CHANNEL_STATUS_KEEPLIVEING) { + *connId = (int32_t)item->connId; (void)SoftBusMutexUnlock(&g_proxyChannelList->lock); return SOFTBUS_OK; } else { diff --git a/core/transmission/trans_channel/proxy/src/softbus_proxychannel_message.c b/core/transmission/trans_channel/proxy/src/softbus_proxychannel_message.c index 111d80a7f..ffe78e2ec 100644 --- a/core/transmission/trans_channel/proxy/src/softbus_proxychannel_message.c +++ b/core/transmission/trans_channel/proxy/src/softbus_proxychannel_message.c @@ -79,7 +79,10 @@ static void TransProxyPackMessageHead(ProxyMessageHead *msgHead, uint8_t *buf, u static int32_t GetRemoteUdidByBtMac(const char *peerMac, char *udid, int32_t len) { char networkId[NETWORK_ID_BUF_LEN] = {0}; - TRANS_LOGI(TRANS_CTRL, "peerMac=%s", AnonymizesMac(peerMac)); + char *tmpMac = NULL; + Anonymize(peerMac, &tmpMac); + TRANS_LOGI(TRANS_CTRL, "peerMac=%s", tmpMac); + AnonymizeFree(tmpMac); if (LnnGetNetworkIdByBtMac(peerMac, networkId, sizeof(networkId)) != SOFTBUS_OK) { TRANS_LOGE(TRANS_CTRL, "LnnGetNetworkIdByBtMac fail"); return SOFTBUS_NOT_FIND; @@ -359,6 +362,7 @@ static int32_t PackHandshakeMsgForFastData(AppInfo *appInfo, cJSON *root) char *buf = TransProxyPackFastData(appInfo, &outLen); if (buf == NULL) { TRANS_LOGE(TRANS_CTRL, "failed to pack bytes."); + SoftBusFree(encodeFastData); return SOFTBUS_ERR; } int32_t ret = SoftBusBase64Encode(encodeFastData, BASE64_FAST_DATA_LEN, &fastDataSize, @@ -615,7 +619,7 @@ int32_t TransProxyUnpackHandshakeAckMsg(const char *msg, ProxyChannelInfo *chanI appInfo->algorithm = APP_INFO_ALGORITHM_AES_GCM_256; appInfo->crc = APP_INFO_FILE_FEATURES_NO_SUPPORT; int32_t appType = TransProxyGetAppInfoType(chanInfo->myId, chanInfo->identity); - if (appType == SOFTBUS_ERR) { + if (appType == SOFTBUS_ERR || appType == SOFTBUS_LOCK_ERR) { TRANS_LOGE(TRANS_CTRL, "fail to get app type"); cJSON_Delete(root); return SOFTBUS_TRANS_PROXY_ERROR_APP_TYPE; @@ -899,7 +903,7 @@ static int32_t TransProxyPackFastDataHead(ProxyDataInfo *dataInfo, const AppInfo { #define MAGIC_NUMBER 0xBABEFACE if (dataInfo == NULL || appInfo ==NULL) { - SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "invaild param."); + TRANS_LOGE(TRANS_CTRL, "invaild param."); return SOFTBUS_ERR; } dataInfo->outLen = dataInfo->inLen + OVERHEAD_LEN + sizeof(PacketFastHead); diff --git a/core/transmission/trans_channel/proxy/src/softbus_proxychannel_session.c b/core/transmission/trans_channel/proxy/src/softbus_proxychannel_session.c index d459149ad..13f4a40e2 100644 --- a/core/transmission/trans_channel/proxy/src/softbus_proxychannel_session.c +++ b/core/transmission/trans_channel/proxy/src/softbus_proxychannel_session.c @@ -17,11 +17,9 @@ #include -#include "softbus_adapter_crypto.h" #include "softbus_adapter_mem.h" -#include "softbus_adapter_socket.h" -#include "softbus_adapter_thread.h" #include "softbus_conn_interface.h" +#include "softbus_datahead_transform.h" #include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_property.h" @@ -29,12 +27,7 @@ #include "softbus_proxychannel_manager.h" #include "softbus_proxychannel_message.h" #include "softbus_proxychannel_transceiver.h" -#include "softbus_socket.h" -#include "softbus_transmission_interface.h" -#include "softbus_utils.h" -#include "softbus_datahead_transform.h" #include "trans_log.h" -#include "trans_pending_pkt.h" #define TIME_OUT 10 #define USECTONSEC 1000 @@ -47,6 +40,10 @@ int32_t TransProxyTransDataSendMsg(ProxyChannelInfo *chanInfo, const unsigned ch int32_t NotifyClientMsgReceived(const char *pkgName, int32_t pid, int32_t channelId, TransReceiveData *receiveData) { + if (pkgName == NULL) { + TRANS_LOGE(TRANS_MSG, "param invalid"); + return SOFTBUS_INVALID_PARAM; + } int32_t ret = TransProxyOnMsgReceived(pkgName, pid, channelId, receiveData); if (ret != SOFTBUS_OK) { TRANS_LOGE(TRANS_MSG, "notify ret=%d", ret); @@ -150,19 +147,23 @@ static char *TransProxyPackAppNormalMsg(const ProxyMessageHead *msg, const char buf = (char*)SoftBusCalloc(bufLen); if (buf == NULL) { + TRANS_LOGE(TRANS_MSG, "buf calloc failed"); return NULL; } if (memcpy_s(&proxyMessageHead, sizeof(ProxyMessageHead), msg, sizeof(ProxyMessageHead)) != EOK) { + TRANS_LOGE(TRANS_MSG, "message copy failed"); SoftBusFree(buf); return NULL; } PackProxyMessageHead(&proxyMessageHead); if (memcpy_s(buf + connHeadLen, bufLen - connHeadLen, &proxyMessageHead, sizeof(ProxyMessageHead)) != EOK) { + TRANS_LOGE(TRANS_MSG, "buf copy failed"); SoftBusFree(buf); return NULL; } dstLen = bufLen - connHeadLen - sizeof(ProxyMessageHead); if (memcpy_s(buf + connHeadLen + sizeof(ProxyMessageHead), dstLen, payLoad, datalen) != EOK) { + TRANS_LOGE(TRANS_MSG, "buf copy failed"); SoftBusFree(buf); return NULL; } @@ -200,6 +201,10 @@ static int32_t TransProxyTransNormalMsg(const ProxyChannelInfo *info, const char int32_t TransProxyTransDataSendMsg(ProxyChannelInfo *info, const unsigned char *payLoad, int payLoadLen, ProxyPacketType flag) { + if (info == NULL || payLoad == NULL) { + TRANS_LOGE(TRANS_MSG, "param invalid"); + return SOFTBUS_INVALID_PARAM; + } if ((info->status != PROXY_CHANNEL_STATUS_COMPLETED && info->status != PROXY_CHANNEL_STATUS_KEEPLIVEING)) { TRANS_LOGE(TRANS_MSG, "status is err status=%d", info->status); return SOFTBUS_TRANS_PROXY_CHANNLE_STATUS_INVALID; @@ -215,8 +220,8 @@ int32_t TransProxyTransDataSendMsg(ProxyChannelInfo *info, const unsigned char * int32_t TransOnNormalMsgReceived(const char *pkgName, int32_t pid, int32_t channelId, const char *data, uint32_t len) { - if (data == NULL) { - TRANS_LOGE(TRANS_MSG, "data null."); + if (data == NULL || pkgName == NULL) { + TRANS_LOGE(TRANS_MSG, "data or pkgname is null."); return SOFTBUS_ERR; } TRANS_LOGI(TRANS_MSG, "channelId= %d recv normal msg input len=%d, pid=%d", channelId, len, pid); diff --git a/core/transmission/trans_channel/proxy/src/softbus_proxychannel_transceiver.c b/core/transmission/trans_channel/proxy/src/softbus_proxychannel_transceiver.c index 9f15f72f6..a905cb291 100644 --- a/core/transmission/trans_channel/proxy/src/softbus_proxychannel_transceiver.c +++ b/core/transmission/trans_channel/proxy/src/softbus_proxychannel_transceiver.c @@ -19,13 +19,10 @@ #include "auth_device_common_key.h" #include "lnn_device_info_recovery.h" -#include "lnn_lane_link.h" -#include "lnn_network_manager.h" #include "message_handler.h" #include "softbus_adapter_hitrace.h" #include "softbus_adapter_mem.h" #include "softbus_adapter_thread.h" -#include "softbus_base_listener.h" #include "softbus_conn_interface.h" #include "softbus_def.h" #include "softbus_errcode.h" @@ -36,8 +33,8 @@ #include "softbus_proxychannel_pipeline.h" #include "softbus_utils.h" #include "trans_channel_manager.h" -#include "trans_log.h" #include "trans_event.h" +#include "trans_log.h" #define ID_OFFSET (1) @@ -59,6 +56,7 @@ int32_t TransDelConnByReqId(uint32_t reqId) ProxyConnInfo *tmpNode = NULL; if (g_proxyConnectionList == NULL) { + TRANS_LOGE(TRANS_CTRL, "g_proxyConnectionList is null!"); return SOFTBUS_ERR; } @@ -85,6 +83,7 @@ void TransDelConnByConnId(uint32_t connId) ProxyConnInfo *tmpNode = NULL; if ((g_proxyConnectionList == NULL) || (connId == 0)) { + TRANS_LOGE(TRANS_CTRL, "g_proxyConnectionList or connId is null"); return; } @@ -109,8 +108,8 @@ int32_t TransDecConnRefByConnId(uint32_t connId) { ProxyConnInfo *removeNode = NULL; ProxyConnInfo *tmpNode = NULL; - if ((g_proxyConnectionList == NULL) || (connId == 0)) { + TRANS_LOGE(TRANS_MSG, "g_proxyConnectionList or connId is null"); return SOFTBUS_ERR; } @@ -147,6 +146,7 @@ int32_t TransAddConnRefByConnId(uint32_t connId) ProxyConnInfo *item = NULL; if (g_proxyConnectionList == NULL) { + TRANS_LOGE(TRANS_MSG, "g_proxyConnectionList is null"); return SOFTBUS_ERR; } @@ -174,6 +174,7 @@ static void TransProxyLoopMsgHandler(SoftBusMessage *msg) ProxyChannelInfo *chan = NULL; if (msg == NULL) { + TRANS_LOGE(TRANS_MSG, "param invalid"); return; } TRANS_LOGI(TRANS_CTRL, "trans loop process msgType=%d", msg->what); @@ -189,6 +190,7 @@ static void TransProxyLoopMsgHandler(SoftBusMessage *msg) case LOOP_OPENFAIL_MSG: chan = (ProxyChannelInfo *)msg->obj; if (chan == NULL) { + TRANS_LOGE(TRANS_MSG, "LOOP_OPENFAIL_MSG,chan is null"); return; } TransProxyOpenProxyChannelFail(chan->channelId, &(chan->appInfo), (int32_t)msg->arg1); @@ -203,6 +205,7 @@ static void TransProxyLoopMsgHandler(SoftBusMessage *msg) case LOOP_KEEPALIVE_MSG: chan = (ProxyChannelInfo *)msg->obj; if (chan == NULL) { + TRANS_LOGE(TRANS_MSG, "LOOP_KEEPALIVE_MSG; chan is null"); return; } TransProxyKeepalive(chan->connId, chan); @@ -210,6 +213,7 @@ static void TransProxyLoopMsgHandler(SoftBusMessage *msg) case LOOP_RESETPEER_MSG: chan = (ProxyChannelInfo *)msg->obj; if (chan == NULL) { + TRANS_LOGE(TRANS_MSG, "LOOP_RESETPEER_MSG; chan is null"); return; } TransProxyResetPeer(chan); @@ -232,6 +236,7 @@ static SoftBusMessage *TransProxyCreateLoopMsg(int32_t what, uint64_t arg1, uint { SoftBusMessage *msg = (SoftBusMessage *)SoftBusCalloc(sizeof(SoftBusMessage)); if (msg == NULL) { + TRANS_LOGE(TRANS_MSG, "msg calloc failed"); return NULL; } msg->what = what; @@ -247,19 +252,20 @@ void TransProxyPostResetPeerMsgToLoop(const ProxyChannelInfo *chan) { SoftBusMessage *msg = TransProxyCreateLoopMsg(LOOP_RESETPEER_MSG, 0, 0, (char *)chan); if (msg == NULL) { + TRANS_LOGE(TRANS_MSG, "msg create failed"); if (chan != NULL) { SoftBusFree((void *)chan); } return; } g_transLoophandler.looper->PostMessage(g_transLoophandler.looper, msg); - return; } void TransProxyPostHandshakeMsgToLoop(int32_t chanId) { int32_t *chanIdMsg = (int32_t *)SoftBusCalloc(sizeof(int32_t)); if (chanIdMsg == NULL) { + TRANS_LOGE(TRANS_MSG, "chanIdMsg calloc failed"); return; } *chanIdMsg = chanId; @@ -269,56 +275,67 @@ void TransProxyPostHandshakeMsgToLoop(int32_t chanId) return; } g_transLoophandler.looper->PostMessage(g_transLoophandler.looper, msg); - return; } void TransProxyPostDisConnectMsgToLoop(uint32_t connId) { SoftBusMessage *msg = TransProxyCreateLoopMsg(LOOP_DISCONNECT_MSG, 0, connId, NULL); if (msg == NULL) { + TRANS_LOGE(TRANS_MSG, "msg create failed"); return; } g_transLoophandler.looper->PostMessage(g_transLoophandler.looper, msg); - return; } void TransProxyPostKeepAliveMsgToLoop(const ProxyChannelInfo *chan) { + if (chan == NULL) { + TRANS_LOGE(TRANS_MSG, "param invalid"); + return; + } SoftBusMessage *msg = TransProxyCreateLoopMsg(LOOP_KEEPALIVE_MSG, 0, 0, (char *)chan); if (msg == NULL) { + TRANS_LOGE(TRANS_MSG, "msg create failed"); if (chan != NULL) { SoftBusFree((void *)chan); } return; } g_transLoophandler.looper->PostMessage(g_transLoophandler.looper, msg); - return; } void TransProxyPostOpenFailMsgToLoop(const ProxyChannelInfo *chan, int32_t errCode) { + if (chan == NULL) { + TRANS_LOGE(TRANS_MSG, "param invalid"); + return; + } SoftBusMessage *msg = TransProxyCreateLoopMsg(LOOP_OPENFAIL_MSG, errCode, 0, (char *)chan); if (msg == NULL) { + TRANS_LOGE(TRANS_MSG, "msg create failed"); if (chan != NULL) { SoftBusFree((void *)chan); } return; } g_transLoophandler.looper->PostMessage(g_transLoophandler.looper, msg); - return; } void TransProxyPostOpenClosedMsgToLoop(const ProxyChannelInfo *chan) { + if (chan == NULL) { + TRANS_LOGE(TRANS_MSG, "param invalid"); + return; + } SoftBusMessage *msg = TransProxyCreateLoopMsg(LOOP_OPENCLOSE_MSG, 0, 0, (char *)chan); if (msg == NULL) { + TRANS_LOGE(TRANS_MSG, "msg create failed"); if (chan != NULL) { SoftBusFree((void *)chan); } return; } g_transLoophandler.looper->PostMessage(g_transLoophandler.looper, msg); - return; } static int32_t TransProxyLoopInit(void) @@ -359,7 +376,6 @@ static void TransProxyOnConnected(uint32_t connId, const ConnectionInfo *connInf { (void)connInfo; TRANS_LOGI(TRANS_CTRL, "connect enabled, connId=%u", connId); - return; } static void TransProxyOnDisConnect(uint32_t connId, const ConnectionInfo *connInfo) @@ -368,12 +384,12 @@ static void TransProxyOnDisConnect(uint32_t connId, const ConnectionInfo *connIn TRANS_LOGI(TRANS_CTRL, "connect disabled, connId=%u", connId); TransProxyDelByConnId(connId); TransDelConnByConnId(connId); - return; } static bool CompareConnectOption(const ConnectOption *itemConnInfo, const ConnectOption *connInfo) { if (connInfo->type == CONNECT_TCP) { + TRANS_LOGI(TRANS_CTRL, "CONNECT_TCP"); if (connInfo->socketOption.protocol == itemConnInfo->socketOption.protocol && strcasecmp(connInfo->socketOption.addr, itemConnInfo->socketOption.addr) == 0 && connInfo->socketOption.port == itemConnInfo->socketOption.port) { @@ -381,11 +397,13 @@ static bool CompareConnectOption(const ConnectOption *itemConnInfo, const Connec } return false; } else if (connInfo->type == CONNECT_BR) { + TRANS_LOGI(TRANS_CTRL, "CONNECT_BR"); if (strcasecmp(connInfo->brOption.brMac, itemConnInfo->brOption.brMac) == 0) { return true; } return false; } else if (connInfo->type == CONNECT_BLE) { + TRANS_LOGI(TRANS_CTRL, "CONNECT_BLE"); if (strcasecmp(connInfo->bleOption.bleMac, itemConnInfo->bleOption.bleMac) == 0 && (connInfo->bleOption.protocol == itemConnInfo->bleOption.protocol) && connInfo->bleOption.psm == itemConnInfo->bleOption.psm) { @@ -393,6 +411,7 @@ static bool CompareConnectOption(const ConnectOption *itemConnInfo, const Connec } return false; } else if (connInfo->type == CONNECT_BLE_DIRECT) { + TRANS_LOGI(TRANS_CTRL, "CONNECT_BLE_DIRECT"); if ((strcmp(connInfo->bleDirectOption.networkId, itemConnInfo->bleDirectOption.networkId) == 0) && (connInfo->bleDirectOption.protoType == itemConnInfo->bleDirectOption.protoType)) { return true; @@ -404,10 +423,15 @@ static bool CompareConnectOption(const ConnectOption *itemConnInfo, const Connec int32_t TransAddConnItem(ProxyConnInfo *chan) { + if (chan == NULL) { + TRANS_LOGE(TRANS_CTRL, "param invalid"); + return SOFTBUS_INVALID_PARAM; + } ProxyConnInfo *item = NULL; ProxyConnInfo *tmpItem = NULL; if (g_proxyConnectionList == NULL) { + TRANS_LOGE(TRANS_CTRL, "g_proxyConnectionList is null"); return SOFTBUS_ERR; } @@ -432,9 +456,11 @@ static void TransConnInfoToConnOpt(ConnectionInfo *connInfo, ConnectOption *conn { connOption->type = connInfo->type; if (connOption->type == CONNECT_BR) { + TRANS_LOGI(TRANS_CTRL, "CONNECT_BR"); (void)memcpy_s(connOption->brOption.brMac, sizeof(char) * BT_MAC_LEN, connInfo->brInfo.brMac, sizeof(char) * BT_MAC_LEN); } else if (connOption->type == CONNECT_BLE) { + TRANS_LOGI(TRANS_CTRL, "CONNECT_BLE"); (void)memcpy_s(connOption->bleOption.bleMac, sizeof(char) * BT_MAC_LEN, connInfo->bleInfo.bleMac, sizeof(char) * BT_MAC_LEN); (void)memcpy_s(connOption->bleOption.deviceIdHash, sizeof(char) * UDID_HASH_LEN, @@ -455,6 +481,7 @@ void TransCreateConnByConnId(uint32_t connId) ConnectionInfo info = {0}; if (g_proxyConnectionList == NULL) { + TRANS_LOGE(TRANS_CTRL, "g_proxyConnectionList is null"); return; } @@ -478,6 +505,7 @@ void TransCreateConnByConnId(uint32_t connId) item = (ProxyConnInfo *)SoftBusCalloc(sizeof(ProxyConnInfo)); if (item == NULL) { + TRANS_LOGE(TRANS_CTRL, "item calloc failed"); (void)SoftBusMutexUnlock(&g_proxyConnectionList->lock); return; } @@ -567,7 +595,7 @@ static void TransOnConnectSuccessed(uint32_t requestId, uint32_t connectionId, c }; TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL, EVENT_STAGE_START_CONNECT, extra); TRANS_LOGI(TRANS_CTRL, - "Connect Successe reqId=%d, connId=%d", requestId, connectionId); + "Connect Success reqId=%d, connId=%d", requestId, connectionId); TransSetConnStateByReqId(requestId, connectionId, PROXY_CHANNEL_STATUS_PYH_CONNECTED); TransProxyChanProcessByReqId((int32_t)requestId, connectionId); } @@ -615,6 +643,10 @@ int32_t TransProxyCloseConnChannelReset(uint32_t connectionId, bool isDisconnect int32_t TransProxyConnExistProc(ProxyConnInfo *conn, ProxyChannelInfo *chan, int32_t chanNewId) { + if (conn == NULL || chan == NULL) { + TRANS_LOGE(TRANS_CTRL, "invalid param"); + return SOFTBUS_INVALID_PARAM; + } SoftbusHitraceStart(SOFTBUS_HITRACE_ID_VALID, (uint64_t)(chanNewId + ID_OFFSET)); TRANS_LOGI(TRANS_CTRL, "SoftbusHitraceChainBegin: set hitraceId=%lx.", (uint64_t)(chanNewId + ID_OFFSET)); @@ -681,6 +713,7 @@ static int32_t TransProxyOpenNewConnChannel( ProxyConnInfo *connChan = (ProxyConnInfo *)SoftBusCalloc(sizeof(ProxyConnInfo)); if (connChan == NULL) { + TRANS_LOGE(TRANS_CTRL, "connChan calloc failed"); TransProxyDelChanByChanId(channelId); return SOFTBUS_MALLOC_ERR; } @@ -710,6 +743,10 @@ static int32_t TransProxyOpenNewConnChannel( int32_t TransProxyOpenConnChannel(const AppInfo *appInfo, const ConnectOption *connInfo, int32_t *channelId) { + if (appInfo == NULL || connInfo == NULL) { + TRANS_LOGE(TRANS_CTRL, "invalid param"); + return SOFTBUS_INVALID_PARAM; + } int ret = SOFTBUS_ERR; ProxyConnInfo conn; int32_t chanNewId = GenerateChannelId(false); @@ -789,14 +826,12 @@ static void TransProxyOnDataReceived( uint32_t connectionId, ConnModule moduleId, int64_t seq, char *data, int32_t len) { ProxyMessage msg; - TRANS_LOGI(TRANS_CTRL, "recv data connId=%u, moduleId=%d, seq=%" PRId64 " len=%d", connectionId, moduleId, seq, len); if (data == NULL || moduleId != MODULE_PROXY_CHANNEL) { - TRANS_LOGW(TRANS_CTRL, "invalid param"); + TRANS_LOGE(TRANS_CTRL, "invalid param"); return; } - (void)memset_s(&msg, sizeof(ProxyMessage), 0, sizeof(ProxyMessage)); msg.connId = connectionId; diff --git a/core/transmission/trans_channel/tcp_direct/include/trans_tcp_direct_manager.h b/core/transmission/trans_channel/tcp_direct/include/trans_tcp_direct_manager.h index 888d852ee..8145fc927 100644 --- a/core/transmission/trans_channel/tcp_direct/include/trans_tcp_direct_manager.h +++ b/core/transmission/trans_channel/tcp_direct/include/trans_tcp_direct_manager.h @@ -40,6 +40,7 @@ extern "C" { #define FLAG_BLE 4 #define FLAG_P2P 8 #define FLAG_AUTH_META 16 +#define FLAG_ENHANCE_P2P 32 #define AUTH_CONN_SERVER_SIDE 0x01 typedef struct { @@ -64,4 +65,4 @@ void TransTdcStopSessionProc(ListenerModule listenMod); } #endif /* __cplusplus */ -#endif +#endif \ No newline at end of file diff --git a/core/transmission/trans_channel/tcp_direct/src/trans_tcp_direct_callback.c b/core/transmission/trans_channel/tcp_direct/src/trans_tcp_direct_callback.c index 03dd90d3d..8ef658ef0 100644 --- a/core/transmission/trans_channel/tcp_direct/src/trans_tcp_direct_callback.c +++ b/core/transmission/trans_channel/tcp_direct/src/trans_tcp_direct_callback.c @@ -16,6 +16,7 @@ #include "trans_tcp_direct_callback.h" #include + #include "softbus_def.h" #include "softbus_errcode.h" @@ -29,6 +30,7 @@ int32_t TransTdcSetCallBack(const IServerChannelCallBack *cb) g_channelCb = *cb; return SOFTBUS_OK; } + int32_t TransTdcOnChannelOpened(const char *pkgName, int32_t pid, const char *sessionName, const ChannelInfo *channel) { diff --git a/core/transmission/trans_channel/tcp_direct/src/trans_tcp_direct_json.c b/core/transmission/trans_channel/tcp_direct/src/trans_tcp_direct_json.c index 605a6a832..5957ff56f 100644 --- a/core/transmission/trans_channel/tcp_direct/src/trans_tcp_direct_json.c +++ b/core/transmission/trans_channel/tcp_direct/src/trans_tcp_direct_json.c @@ -13,7 +13,7 @@ * limitations under the License. */ #include "trans_tcp_direct_json.h" -#include "softbus_def.h" + #include "softbus_errcode.h" #include "softbus_json_utils.h" #include "softbus_proxychannel_message.h" @@ -30,10 +30,12 @@ char *VerifyP2pPackError(int32_t code, int32_t errCode, const char *errDesc) { if (errDesc == NULL) { + TRANS_LOGE(TRANS_CTRL, "param invalid"); return NULL; } cJSON *json = cJSON_CreateObject(); if (json == NULL) { + TRANS_LOGE(TRANS_CTRL, "create object failed"); return NULL; } if (!AddNumberToJsonObject(json, MSG_CODE, code) || @@ -50,10 +52,12 @@ char *VerifyP2pPackError(int32_t code, int32_t errCode, const char *errDesc) char *VerifyP2pPack(const char *myIp, int32_t myPort, const char *peerIp) { if (myIp == NULL || myPort <= 0) { + TRANS_LOGE(TRANS_CTRL, "param invalid"); return NULL; } cJSON *json = cJSON_CreateObject(); if (json == NULL) { + TRANS_LOGE(TRANS_CTRL, "create object failed"); return NULL; } if (peerIp != NULL) { @@ -63,6 +67,7 @@ char *VerifyP2pPack(const char *myIp, int32_t myPort, const char *peerIp) !AddStringToJsonObject(json, P2P_IP, myIp) || !AddNumberToJsonObject(json, P2P_PORT, myPort)) { cJSON_Delete(json); + TRANS_LOGE(TRANS_CTRL, "add json object failed"); return NULL; } char *data = cJSON_PrintUnformatted(json); @@ -73,9 +78,10 @@ char *VerifyP2pPack(const char *myIp, int32_t myPort, const char *peerIp) int32_t VerifyP2pUnPack(const cJSON *json, char *ip, uint32_t ipLen, int32_t *port) { if (json == NULL || ip == NULL || port == NULL) { + TRANS_LOGE(TRANS_CTRL, "param invalid"); return SOFTBUS_INVALID_PARAM; } - int32_t errCode; + int32_t errCode = 0; if (GetJsonObjectNumberItem(json, JSON_KEY_TYPE, &errCode)) { TRANS_LOGE(TRANS_CTRL, "VerifyP2pUnPack peer proc fail: errCode=%d", errCode); return SOFTBUS_PEER_PROC_ERR; diff --git a/core/transmission/trans_channel/tcp_direct/src/trans_tcp_direct_listener.c b/core/transmission/trans_channel/tcp_direct/src/trans_tcp_direct_listener.c index 3a0ccacca..7a377e62e 100644 --- a/core/transmission/trans_channel/tcp_direct/src/trans_tcp_direct_listener.c +++ b/core/transmission/trans_channel/tcp_direct/src/trans_tcp_direct_listener.c @@ -15,8 +15,8 @@ #include "trans_tcp_direct_listener.h" -#include #include + #include "auth_interface.h" #include "bus_center_manager.h" #include "softbus_adapter_crypto.h" @@ -27,11 +27,11 @@ #include "softbus_errcode.h" #include "softbus_message_open_channel.h" #include "softbus_socket.h" +#include "trans_channel_manager.h" +#include "trans_event.h" +#include "trans_log.h" #include "trans_tcp_direct_message.h" #include "trans_tcp_direct_sessionconn.h" -#include "trans_channel_manager.h" -#include "trans_log.h" -#include "trans_event.h" #define ID_OFFSET (1) @@ -44,6 +44,8 @@ uint32_t SwitchAuthLinkTypeToFlagType(AuthLinkType type) return FLAG_BLE; case AUTH_LINK_TYPE_P2P: return FLAG_P2P; + case AUTH_LINK_TYPE_ENHANCED_P2P: + return FLAG_ENHANCE_P2P; default: return FLAG_WIFI; } @@ -51,6 +53,10 @@ uint32_t SwitchAuthLinkTypeToFlagType(AuthLinkType type) int32_t GetCipherFlagByAuthId(int64_t authId, uint32_t *flag, bool *isAuthServer) { + if (flag == NULL || isAuthServer == NULL) { + TRANS_LOGE(TRANS_CTRL, "param invalid"); + return SOFTBUS_INVALID_PARAM; + } AuthConnInfo info; if (AuthGetServerSide(authId, isAuthServer) != SOFTBUS_OK) { TRANS_LOGE(TRANS_CTRL, "get auth server side fail authId=%" PRId64, authId); @@ -73,7 +79,6 @@ static int32_t StartVerifySession(SessionConn *conn) return SOFTBUS_TRANS_TCP_GENERATE_SESSIONKEY_FAILED; } SetSessionKeyByChanId(conn->channelId, conn->appInfo.sessionKey, sizeof(conn->appInfo.sessionKey)); - bool isAuthServer = false; uint32_t cipherFlag = FLAG_WIFI; if (GetCipherFlagByAuthId(conn->authId, &cipherFlag, &isAuthServer)) { @@ -84,7 +89,6 @@ static int32_t StartVerifySession(SessionConn *conn) if (isAuthServer) { seq |= AUTH_CONN_SERVER_SIDE; } - char *bytes = PackRequest(&conn->appInfo); if (bytes == NULL) { TRANS_LOGE(TRANS_CTRL, "Pack Request failed"); @@ -131,14 +135,12 @@ static int32_t CreateSessionConnNode(ListenerModule module, int fd, int32_t chan module <= DIRECT_CHANNEL_SERVER_HML_END)) ? WIFI_P2P : WIFI_STA; conn->appInfo.routeType = (module == DIRECT_CHANNEL_SERVER_P2P) ? WIFI_P2P : WIFI_STA; conn->appInfo.peerData.port = clientAddr->socketOption.port; - if (LnnGetLocalStrInfo(STRING_KEY_UUID, conn->appInfo.myData.deviceId, sizeof(conn->appInfo.myData.deviceId)) != 0) { TRANS_LOGE(TRANS_CTRL, "get local deviceId failed."); SoftBusFree(conn); return SOFTBUS_ERR; } - if (strcpy_s(conn->appInfo.peerData.addr, sizeof(conn->appInfo.peerData.addr), clientAddr->socketOption.addr) != EOK) { TRANS_LOGE(TRANS_CTRL, "copy ip to app info failed."); @@ -153,13 +155,11 @@ static int32_t CreateSessionConnNode(ListenerModule module, int fd, int32_t chan SoftBusFree(conn); return SOFTBUS_MEM_ERR; } - if (TransTdcAddSessionConn(conn) != SOFTBUS_OK) { TRANS_LOGE(TRANS_CTRL, "add session conn node failed."); SoftBusFree(conn); return SOFTBUS_ERR; } - if (AddTrigger(conn->listenMod, fd, READ_TRIGGER) != SOFTBUS_OK) { TRANS_LOGE(TRANS_CTRL, "add trigger failed, delete session conn."); TransDelSessionConnById(chanId); @@ -175,7 +175,6 @@ static int32_t TdcOnConnectEvent(ListenerModule module, int cfd, const ConnectOp TRANS_LOGW(TRANS_CTRL, "invalid param, cfd=%d", cfd); return SOFTBUS_INVALID_PARAM; } - int32_t channelId = GenerateChannelId(true); int32_t ret = TransSrvAddDataBufNode(channelId, cfd); // fd != channelId if (ret != SOFTBUS_OK) { @@ -183,7 +182,6 @@ static int32_t TdcOnConnectEvent(ListenerModule module, int cfd, const ConnectOp ConnShutdownSocket(cfd); return ret; } - ret = CreateSessionConnNode(module, cfd, channelId, clientAddr); if (ret != SOFTBUS_OK) { TRANS_LOGE(TRANS_CTRL, "create session conn node fail, delete data buf node."); @@ -207,6 +205,7 @@ static void CloseTcpDirectFd(int fd) static void TransProcDataRes(ListenerModule module, int32_t ret, int32_t channelId, int32_t fd) { if (ret != SOFTBUS_OK) { + TRANS_LOGI(TRANS_CTRL, "unequal SOFTBUS_OK"); TransEventExtra extra = { .socketName = NULL, .peerNetworkId = NULL, @@ -228,6 +227,56 @@ static void TransProcDataRes(ListenerModule module, int32_t ret, int32_t channel TransSrvDelDataBufNode(channelId); } +static int32_t ProcessSocketInEvent(SessionConn *conn, int fd) +{ + int32_t ret = TransTdcSrvRecvData(conn->listenMod, conn->channelId); + TRANS_LOGE(TRANS_CTRL, "Trans Srv Recv Data ret=%d. ", ret); + if (ret == SOFTBUS_DATA_NOT_ENOUGH) { + return SOFTBUS_OK; + } + TransProcDataRes(conn->listenMod, ret, conn->channelId, fd); + return ret; +} + +static int32_t ProcessSocketOutEvent(SessionConn *conn, int fd) +{ + int32_t ret = SOFTBUS_ERR; + if (conn->serverSide) { + return ret; + } + DelTrigger(conn->listenMod, fd, WRITE_TRIGGER); + AddTrigger(conn->listenMod, fd, READ_TRIGGER); + ret = StartVerifySession(conn); + TransEventExtra extra = { .socketName = NULL, + .peerNetworkId = NULL, + .calleePkg = NULL, + .callerPkg = NULL, + .socketFd = fd, + .channelId = conn->channelId, + .authId = conn->authId, + .errcode = ret, + .result = (ret == SOFTBUS_OK) ? EVENT_STAGE_RESULT_OK : EVENT_STAGE_RESULT_FAILED }; + TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL, EVENT_STAGE_HANDSHAKE_START, extra); + if (ret != SOFTBUS_OK) { + TRANS_LOGE(TRANS_CTRL, "start verify session fail."); + DelTrigger(conn->listenMod, fd, READ_TRIGGER); + ConnShutdownSocket(fd); + NotifyChannelOpenFailed(conn->channelId, ret); + TransDelSessionConnById(conn->channelId); + TransSrvDelDataBufNode(conn->channelId); + } + return ret; +} + +static void ProcessSocketSocketExceptionEvent(SessionConn *conn, int fd) +{ + TRANS_LOGE(TRANS_CTRL, "exception occurred."); + DelTrigger(conn->listenMod, fd, EXCEPT_TRIGGER); + ConnShutdownSocket(fd); + TransDelSessionConnById(conn->channelId); + TransSrvDelDataBufNode(conn->channelId); +} + static int32_t TdcOnDataEvent(ListenerModule module, int events, int fd) { (void)module; @@ -250,47 +299,11 @@ static int32_t TdcOnDataEvent(ListenerModule module, int events, int fd) SoftbusHitraceStart(SOFTBUS_HITRACE_ID_VALID, (uint64_t)(conn->channelId + ID_OFFSET)); int32_t ret = SOFTBUS_ERR; if (events == SOFTBUS_SOCKET_IN) { - ret = TransTdcSrvRecvData(conn->listenMod, conn->channelId); - TRANS_LOGE(TRANS_CTRL, "Trans Srv Recv Data ret=%d. ", ret); - if (ret == SOFTBUS_DATA_NOT_ENOUGH) { - SoftBusFree(conn); - return SOFTBUS_OK; - } - TransProcDataRes(conn->listenMod, ret, conn->channelId, fd); + ret = ProcessSocketInEvent(conn, fd); } else if (events == SOFTBUS_SOCKET_OUT) { - if (conn->serverSide == true) { - SoftBusFree(conn); - return ret; - } - DelTrigger(conn->listenMod, fd, WRITE_TRIGGER); - AddTrigger(conn->listenMod, fd, READ_TRIGGER); - ret = StartVerifySession(conn); - TransEventExtra extra = { - .socketName = NULL, - .peerNetworkId = NULL, - .calleePkg = NULL, - .callerPkg = NULL, - .socketFd = fd, - .channelId = conn->channelId, - .authId = conn->authId, - .errcode = ret, - .result = (ret == SOFTBUS_OK) ? EVENT_STAGE_RESULT_OK : EVENT_STAGE_RESULT_FAILED - }; - TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL, EVENT_STAGE_HANDSHAKE_START, extra); - if (ret != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "start verify session fail."); - DelTrigger(conn->listenMod, fd, READ_TRIGGER); - ConnShutdownSocket(fd); - NotifyChannelOpenFailed(conn->channelId, ret); - TransDelSessionConnById(conn->channelId); - TransSrvDelDataBufNode(conn->channelId); - } + ret = ProcessSocketOutEvent(conn, fd); } else if (events == SOFTBUS_SOCKET_EXCEPTION) { - TRANS_LOGE(TRANS_CTRL, "exception occurred."); - DelTrigger(conn->listenMod, fd, EXCEPT_TRIGGER); - ConnShutdownSocket(fd); - TransDelSessionConnById(conn->channelId); - TransSrvDelDataBufNode(conn->channelId); + ProcessSocketSocketExceptionEvent(conn, fd); } SoftBusFree(conn); return ret; @@ -317,4 +330,4 @@ int32_t TransTdcStopSessionListener(ListenerModule module) { TransTdcStopSessionProc(module); return StopBaseListener(module); -} +} \ No newline at end of file diff --git a/core/transmission/trans_channel/tcp_direct/src/trans_tcp_direct_manager.c b/core/transmission/trans_channel/tcp_direct/src/trans_tcp_direct_manager.c index 514489057..53903bd13 100644 --- a/core/transmission/trans_channel/tcp_direct/src/trans_tcp_direct_manager.c +++ b/core/transmission/trans_channel/tcp_direct/src/trans_tcp_direct_manager.c @@ -17,14 +17,12 @@ #include -#include "auth_interface.h" -#include "bus_center_info_key.h" #include "bus_center_manager.h" #include "softbus_adapter_mem.h" -#include "softbus_adapter_thread.h" #include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_socket.h" +#include "trans_event.h" #include "trans_log.h" #include "trans_tcp_direct_callback.h" #include "trans_tcp_direct_message.h" @@ -32,7 +30,6 @@ #include "trans_tcp_direct_sessionconn.h" #include "trans_tcp_direct_wifi.h" #include "wifi_direct_manager.h" -#include "trans_event.h" #define HANDSHAKE_TIMEOUT 19 @@ -43,7 +40,7 @@ static void OnSessionOpenFailProc(const SessionConn *node, int32_t errCode) if (node->serverSide == false) { if (TransTdcOnChannelOpenFailed(node->appInfo.myData.pkgName, node->appInfo.myData.pid, node->channelId, errCode) != SOFTBUS_OK) { - TRANS_LOGW(TRANS_CTRL, "notify channel open fail err"); + TRANS_LOGE(TRANS_CTRL, "notify channel open fail err"); } } @@ -58,12 +55,11 @@ static void OnSessionOpenFailProc(const SessionConn *node, int32_t errCode) static void NotifyTdcChannelTimeOut(ListNode *tdcChannelList) { if (tdcChannelList == NULL) { + TRANS_LOGE(TRANS_CTRL, "param invalid"); return; } - SessionConn *item = NULL; SessionConn *nextItem = NULL; - LIST_FOR_EACH_ENTRY_SAFE(item, nextItem, tdcChannelList, SessionConn, node) { OnSessionOpenFailProc(item, SOFTBUS_TRANS_HANDSHAKE_TIMEOUT); TransSrvDelDataBufNode(item->channelId); @@ -77,9 +73,11 @@ static void TransTdcTimerProc(void) SessionConn *nextItem = NULL; SoftBusList *sessionList = GetSessionConnList(); if (sessionList == NULL) { + TRANS_LOGE(TRANS_CTRL, "get session conn list failed"); return; } if (GetSessionConnLock() != SOFTBUS_OK) { + TRANS_LOGE(TRANS_CTRL, "get session conn lock failed"); return; } @@ -105,6 +103,7 @@ static void TransTdcTimerProc(void) static void NotifyTdcChannelStopProc(ListNode *tdcChannelList) { if (tdcChannelList == NULL) { + TRANS_LOGE(TRANS_INIT, "param invalid"); return; } @@ -124,18 +123,17 @@ void TransTdcStopSessionProc(ListenerModule listenMod) TRANS_LOGD(TRANS_CTRL, "enter."); SessionConn *item = NULL; SessionConn *nextItem = NULL; - SoftBusList *sessionList = GetSessionConnList(); if (sessionList == NULL) { + TRANS_LOGE(TRANS_INIT, "get session conn list failed"); return; } if (GetSessionConnLock() != SOFTBUS_OK) { + TRANS_LOGE(TRANS_INIT, "get session conn lock failed"); return; } - ListNode tempTdcChannelList; ListInit(&tempTdcChannelList); - LIST_FOR_EACH_ENTRY_SAFE(item, nextItem, &sessionList->list, SessionConn, node) { if (listenMod != item->listenMod) { continue; @@ -146,13 +144,16 @@ void TransTdcStopSessionProc(ListenerModule listenMod) ListAdd(&tempTdcChannelList, &item->node); } ReleaseSessonConnLock(); - NotifyTdcChannelStopProc(&tempTdcChannelList); TRANS_LOGD(TRANS_CTRL, "ok"); } int32_t TransTcpDirectInit(const IServerChannelCallBack *cb) { + if (cb == NULL) { + TRANS_LOGE(TRANS_CTRL, "param invalid"); + return SOFTBUS_INVALID_PARAM; + } int32_t ret = P2pDirectChannelInit(); if (ret != SOFTBUS_OK) { if (ret != SOFTBUS_FUNC_NOT_SUPPORT) { @@ -189,16 +190,19 @@ void TransTcpDirectDeinit(void) void TransTdcDeathCallback(const char *pkgName, int32_t pid) { if (pkgName == NULL) { + TRANS_LOGE(TRANS_CTRL, "param invalid"); return; } - TRANS_LOGW(TRANS_CTRL, "TransTdcDeathCallback: pkgName=%s", pkgName); + TRANS_LOGW(TRANS_CTRL, "TransTdcDeathCallback: pkgName=%s, pid=%d", pkgName, pid); SessionConn *item = NULL; SessionConn *nextItem = NULL; if (GetSessionConnLock() != SOFTBUS_OK) { + TRANS_LOGE(TRANS_CTRL, "get session conn lock failed"); return; } SoftBusList *sessionList = GetSessionConnList(); if (sessionList == NULL) { + TRANS_LOGE(TRANS_CTRL, "get session conn list failed"); ReleaseSessonConnLock(); return; } @@ -221,10 +225,8 @@ static int32_t TransUpdAppInfo(AppInfo *appInfo, const ConnectOption *connInfo) TRANS_LOGE(TRANS_CTRL, "TransUpdAppInfo cpy fail"); return SOFTBUS_MEM_ERR; } - appInfo->routeType = connInfo->type == CONNECT_TCP ? WIFI_STA : WIFI_P2P; appInfo->protocol = connInfo->socketOption.protocol; - if (connInfo->socketOption.protocol == LNN_PROTOCOL_NIP) { if (LnnGetLocalStrInfo(STRING_KEY_NODE_ADDR, appInfo->myData.addr, sizeof(appInfo->myData.addr)) != SOFTBUS_OK) { @@ -261,15 +263,16 @@ int32_t TransOpenDirectChannel(AppInfo *appInfo, const ConnectOption *connInfo, TRANS_LOGE(TRANS_CTRL, "udp app fail"); return ret; } - if (connInfo->type == CONNECT_P2P || connInfo->type == CONNECT_HML) { appInfo->routeType = WIFI_P2P; ret = OpenP2pDirectChannel(appInfo, connInfo, channelId); } else if (connInfo->type == CONNECT_P2P_REUSE) { appInfo->routeType = WIFI_P2P_REUSE; + TRANS_LOGI(TRANS_CTRL, "goto WIFI_P2P_REUSE"); ret = OpenTcpDirectChannel(appInfo, connInfo, channelId); } else { appInfo->routeType = WIFI_STA; + TRANS_LOGI(TRANS_CTRL, "goto WIFI_STA"); ret = OpenTcpDirectChannel(appInfo, connInfo, channelId); } TransEventExtra extra = { @@ -283,7 +286,6 @@ int32_t TransOpenDirectChannel(AppInfo *appInfo, const ConnectOption *connInfo, .socketName = appInfo->myData.sessionName, .result = (ret == SOFTBUS_OK) ? EVENT_STAGE_RESULT_OK : EVENT_STAGE_RESULT_FAILED }; - SessionConn conn; if (GetSessionConnById(*channelId, &conn) != NULL) { extra.authId = conn.authId; diff --git a/core/transmission/trans_channel/tcp_direct/src/trans_tcp_direct_message.c b/core/transmission/trans_channel/tcp_direct/src/trans_tcp_direct_message.c index 7453d8f05..28ee5888a 100644 --- a/core/transmission/trans_channel/tcp_direct/src/trans_tcp_direct_message.c +++ b/core/transmission/trans_channel/tcp_direct/src/trans_tcp_direct_message.c @@ -22,31 +22,32 @@ #include "auth_interface.h" #include "bus_center_manager.h" #include "cJSON.h" -#include "softbus_app_info.h" +#include "data_bus_native.h" +#include "lnn_distributed_net_ledger.h" +#include "lnn_lane_link.h" +#include "lnn_net_builder.h" #include "softbus_adapter_crypto.h" #include "softbus_adapter_mem.h" -#include "softbus_adapter_thread.h" #include "softbus_adapter_socket.h" +#include "softbus_adapter_thread.h" +#include "softbus_app_info.h" #include "softbus_errcode.h" #include "softbus_feature_config.h" #include "softbus_hisysevt_transreporter.h" #include "softbus_message_open_channel.h" #include "softbus_socket.h" #include "softbus_tcp_socket.h" +#include "trans_event.h" #include "trans_log.h" #include "trans_tcp_direct_callback.h" #include "trans_tcp_direct_manager.h" #include "trans_tcp_direct_sessionconn.h" #include "wifi_direct_manager.h" -#include "data_bus_native.h" -#include "lnn_distributed_net_ledger.h" -#include "lnn_lane_link.h" -#include "lnn_net_builder.h" -#include "trans_event.h" #define MAX_PACKET_SIZE (64 * 1024) #define MIN_META_LEN 6 #define META_SESSION "IShare" +#define MAX_DATA_BUF 4096 typedef struct { ListNode node; @@ -76,6 +77,10 @@ static void PackTdcPacketHead(TdcPacketHead *data) static void UnpackTdcPacketHead(TdcPacketHead *data) { + if (data == NULL) { + TRANS_LOGE(TRANS_CTRL, "param invalid"); + return; + } data->magicNumber = SoftBusLtoHl(data->magicNumber); data->module = SoftBusLtoHl(data->module); data->seq = SoftBusLtoHll(data->seq); @@ -90,6 +95,7 @@ int32_t TransSrvDataListInit(void) } g_tcpSrvDataList = CreateSoftBusList(); if (g_tcpSrvDataList == NULL) { + TRANS_LOGE(TRANS_CTRL, "creat list failed"); return SOFTBUS_ERR; } return SOFTBUS_OK; @@ -98,12 +104,14 @@ int32_t TransSrvDataListInit(void) static void TransSrvDestroyDataBuf(void) { if (g_tcpSrvDataList == NULL) { + TRANS_LOGE(TRANS_CTRL, "g_tcpSrvDataList is null"); return; } ServerDataBuf *item = NULL; ServerDataBuf *next = NULL; if (SoftBusMutexLock(&g_tcpSrvDataList->lock) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_CTRL, "mutex lock failed"); return; } LIST_FOR_EACH_ENTRY_SAFE(item, next, &g_tcpSrvDataList->list, ServerDataBuf, node) { @@ -113,13 +121,12 @@ static void TransSrvDestroyDataBuf(void) g_tcpSrvDataList->cnt--; } SoftBusMutexUnlock(&g_tcpSrvDataList->lock); - - return; } void TransSrvDataListDeinit(void) { if (g_tcpSrvDataList == NULL) { + TRANS_LOGI(TRANS_BYTES, "g_tcpSrvDataList is null"); return; } TransSrvDestroyDataBuf(); @@ -129,7 +136,6 @@ void TransSrvDataListDeinit(void) int32_t TransSrvAddDataBufNode(int32_t channelId, int32_t fd) { -#define MAX_DATA_BUF 4096 ServerDataBuf *node = (ServerDataBuf *)SoftBusCalloc(sizeof(ServerDataBuf)); if (node == NULL) { TRANS_LOGE(TRANS_CTRL, "create server data buf node fail."); @@ -162,6 +168,7 @@ int32_t TransSrvAddDataBufNode(int32_t channelId, int32_t fd) void TransSrvDelDataBufNode(int channelId) { if (g_tcpSrvDataList == NULL) { + TRANS_LOGE(TRANS_BYTES, "g_tcpSrvDataList is null"); return; } @@ -195,6 +202,9 @@ static AuthLinkType SwitchCipherTypeToAuthLinkType(uint32_t cipherFlag) if (cipherFlag & FLAG_P2P) { return AUTH_LINK_TYPE_P2P; } + if (cipherFlag & FLAG_ENHANCE_P2P) { + return AUTH_LINK_TYPE_ENHANCED_P2P; + } return AUTH_LINK_TYPE_WIFI; } @@ -220,6 +230,7 @@ static int32_t PackBytes(int32_t channelId, const char *data, TdcPacketHead *pac PackTdcPacketHead(packetHead); if (memcpy_s(buffer, bufLen, packetHead, sizeof(TdcPacketHead)) != EOK) { + TRANS_LOGE(TRANS_BYTES, "buffer copy fail"); return SOFTBUS_MEM_ERR; } return SOFTBUS_OK; @@ -262,7 +273,6 @@ int32_t TransTdcPostBytes(int32_t channelId, TdcPacketHead *packetHead, const ch SoftBusFree(buffer); return SOFTBUS_MALLOC_ERR; } - if (GetSessionConnById(channelId, conn) == NULL) { TRANS_LOGE(TRANS_BYTES, "Get SessionConn fail"); SoftBusFree(buffer); @@ -281,6 +291,103 @@ int32_t TransTdcPostBytes(int32_t channelId, TdcPacketHead *packetHead, const ch return SOFTBUS_OK; } +static void GetChannelInfoFromConn(ChannelInfo *info, SessionConn *conn, int32_t channelId) +{ + info->channelId = channelId; + info->channelType = CHANNEL_TYPE_TCP_DIRECT; + info->isServer = conn->serverSide; + info->isEnabled = true; + info->fd = conn->appInfo.fd; + info->sessionKey = conn->appInfo.sessionKey; + info->myHandleId = conn->appInfo.myHandleId; + info->peerHandleId = conn->appInfo.peerHandleId; + info->peerSessionName = conn->appInfo.peerData.sessionName; + info->groupId = conn->appInfo.groupId; + info->isEncrypt = true; + info->keyLen = SESSION_KEY_LENGTH; + info->peerUid = conn->appInfo.peerData.uid; + info->peerPid = conn->appInfo.peerData.pid; + info->routeType = conn->appInfo.routeType; + info->businessType = conn->appInfo.businessType; + info->autoCloseTime = conn->appInfo.autoCloseTime; + info->peerIp = conn->appInfo.peerData.addr; + info->peerPort = conn->appInfo.peerData.port; + info->linkType = conn->appInfo.linkType; + info->dataConfig = conn->appInfo.myData.dataConfig; +} + +static int32_t GetServerSideIpInfo(SessionConn *conn, char *ip, uint32_t len) +{ + char myIp[IP_LEN] = { 0 }; + if (conn->appInfo.routeType == WIFI_STA) { + if (LnnGetLocalStrInfo(STRING_KEY_WLAN_IP, myIp, sizeof(myIp)) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_CTRL, "NotifyChannelOpened get local ip fail"); + return SOFTBUS_TRANS_GET_LOCAL_IP_FAILED; + } + if (LnnSetLocalStrInfo(STRING_KEY_WLAN_IP, myIp) != SOFTBUS_OK) { + TRANS_LOGW(TRANS_CTRL, "ServerSide wifi set local ip fail"); + } + if (LnnSetDLP2pIp(conn->appInfo.peerData.deviceId, CATEGORY_UUID, + conn->appInfo.peerData.addr) != SOFTBUS_OK) { + TRANS_LOGW(TRANS_CTRL, "ServerSide wifi set peer ip fail"); + } + } else if (conn->appInfo.routeType == WIFI_P2P) { + if (GetWifiDirectManager()->getLocalIpByUuid(conn->appInfo.peerData.deviceId, myIp, sizeof(myIp)) != + SOFTBUS_OK) { + TRANS_LOGE(TRANS_CTRL, "NotifyChannelOpened get p2p ip fail"); + return SOFTBUS_TRANS_GET_P2P_INFO_FAILED; + } + if (LnnSetLocalStrInfo(STRING_KEY_P2P_IP, myIp) != SOFTBUS_OK) { + TRANS_LOGW(TRANS_CTRL, "ServerSide set local p2p ip fail"); + } + if (LnnSetDLP2pIp(conn->appInfo.peerData.deviceId, CATEGORY_UUID, + conn->appInfo.peerData.addr) != SOFTBUS_OK) { + TRANS_LOGW(TRANS_CTRL, "ServerSide set peer p2p ip fail"); + } + } + if (strcpy_s(ip, len, myIp)) { + TRANS_LOGE(TRANS_CTRL, "copy str failed"); + return SOFTBUS_ERR; + } + return SOFTBUS_OK; +} + +static int32_t GetClientSideIpInfo(SessionConn *conn, char *ip, uint32_t len) +{ + char myIp[IP_LEN] = { 0 }; + if (conn->appInfo.routeType == WIFI_STA) { + if (LnnGetLocalStrInfo(STRING_KEY_WLAN_IP, myIp, sizeof(myIp)) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_CTRL, "NotifyChannelOpened get local ip fail"); + return SOFTBUS_TRANS_GET_LOCAL_IP_FAILED; + } + if (LnnSetLocalStrInfo(STRING_KEY_WLAN_IP, myIp) != SOFTBUS_OK) { + TRANS_LOGW(TRANS_CTRL, "Client wifi set local ip fail"); + } + if (LnnSetDLP2pIp(conn->appInfo.peerData.deviceId, CATEGORY_UUID, + conn->appInfo.peerData.addr) != SOFTBUS_OK) { + TRANS_LOGW(TRANS_CTRL, "Client wifi set peer ip fail"); + } + } else if (conn->appInfo.routeType == WIFI_P2P) { + if (GetWifiDirectManager()->getLocalIpByUuid(conn->appInfo.peerData.deviceId, myIp, sizeof(myIp)) != + SOFTBUS_OK) { + TRANS_LOGE(TRANS_CTRL, "NotifyChannelOpened get p2p ip fail"); + return SOFTBUS_TRANS_GET_P2P_INFO_FAILED; + } + if (LnnSetLocalStrInfo(STRING_KEY_P2P_IP, myIp) != SOFTBUS_OK) { + TRANS_LOGW(TRANS_CTRL, "Client set local p2p ip fail"); + } + if (LnnSetDLP2pIp(conn->appInfo.peerData.deviceId, CATEGORY_UUID, + conn->appInfo.peerData.addr) != SOFTBUS_OK) { + TRANS_LOGW(TRANS_CTRL, "Client set peer p2p ip fail"); + } + } + if (strcpy_s(ip, len, conn->appInfo.myData.addr)) { + TRANS_LOGE(TRANS_CTRL, "copy str failed"); + return SOFTBUS_ERR; + } + return SOFTBUS_OK; +} + static int32_t NotifyChannelOpened(int32_t channelId) { SessionConn conn; @@ -288,84 +395,18 @@ static int32_t NotifyChannelOpened(int32_t channelId) TRANS_LOGE(TRANS_CTRL, "notify channel open failed, get tdcInfo is null"); return SOFTBUS_ERR; } - ChannelInfo info = {0}; - info.channelId = channelId; - info.channelType = CHANNEL_TYPE_TCP_DIRECT; - info.isServer = conn.serverSide; - info.isEnabled = true; - info.fd = conn.appInfo.fd; - info.sessionKey = conn.appInfo.sessionKey; - info.myHandleId = conn.appInfo.myHandleId; - info.peerHandleId = conn.appInfo.peerHandleId; - info.peerSessionName = conn.appInfo.peerData.sessionName; - info.groupId = conn.appInfo.groupId; - info.isEncrypt = true; - info.keyLen = SESSION_KEY_LENGTH; - info.peerUid = conn.appInfo.peerData.uid; - info.peerPid = conn.appInfo.peerData.pid; - info.routeType = conn.appInfo.routeType; - info.businessType = conn.appInfo.businessType; - info.autoCloseTime = conn.appInfo.autoCloseTime; - info.peerIp = conn.appInfo.peerData.addr; - info.peerPort = conn.appInfo.peerData.port; - info.linkType = conn.appInfo.linkType; - info.dataConfig = conn.appInfo.myData.dataConfig; - char myIp[IP_LEN] = {0}; - if (conn.serverSide) { - if (conn.appInfo.routeType == WIFI_STA) { - if (LnnGetLocalStrInfo(STRING_KEY_WLAN_IP, myIp, sizeof(myIp)) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "NotifyChannelOpened get local ip fail"); - return SOFTBUS_TRANS_GET_LOCAL_IP_FAILED; - } - if (LnnSetLocalStrInfo(STRING_KEY_WLAN_IP, myIp) != SOFTBUS_OK) { - TRANS_LOGW(TRANS_CTRL, "ServerSide wifi set local ip fail"); - } - if (LnnSetDLP2pIp(conn.appInfo.peerData.deviceId, CATEGORY_UUID, conn.appInfo.peerData.addr) != SOFTBUS_OK) { - TRANS_LOGW(TRANS_CTRL, "ServerSide wifi set peer ip fail"); - } - } else if (conn.appInfo.routeType == WIFI_P2P) { - if (GetWifiDirectManager()->getLocalIpByUuid(conn.appInfo.peerData.deviceId, myIp, - sizeof(myIp)) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "NotifyChannelOpened get p2p ip fail"); - return SOFTBUS_TRANS_GET_P2P_INFO_FAILED; - } - if (LnnSetLocalStrInfo(STRING_KEY_P2P_IP, myIp) != SOFTBUS_OK) { - TRANS_LOGW(TRANS_CTRL, "ServerSide set local p2p ip fail"); - } - if (LnnSetDLP2pIp(conn.appInfo.peerData.deviceId, CATEGORY_UUID, conn.appInfo.peerData.addr) != SOFTBUS_OK) { - TRANS_LOGW(TRANS_CTRL, "ServerSide set peer p2p ip fail"); - } - } - info.myIp = myIp; - } else { - if (conn.appInfo.routeType == WIFI_STA) { - if (LnnGetLocalStrInfo(STRING_KEY_WLAN_IP, myIp, sizeof(myIp)) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "NotifyChannelOpened get local ip fail"); - return SOFTBUS_TRANS_GET_LOCAL_IP_FAILED; - } - if (LnnSetLocalStrInfo(STRING_KEY_WLAN_IP, myIp) != SOFTBUS_OK) { - TRANS_LOGW(TRANS_CTRL, "Client wifi set local ip fail"); - } - if (LnnSetDLP2pIp(conn.appInfo.peerData.deviceId, CATEGORY_UUID, conn.appInfo.peerData.addr) != SOFTBUS_OK) { - TRANS_LOGW(TRANS_CTRL, "Client wifi set peer ip fail"); - } - } else if (conn.appInfo.routeType == WIFI_P2P) { - if (GetWifiDirectManager()->getLocalIpByUuid(conn.appInfo.peerData.deviceId, myIp, - sizeof(myIp)) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "NotifyChannelOpened get p2p ip fail"); - return SOFTBUS_TRANS_GET_P2P_INFO_FAILED; - } - if (LnnSetLocalStrInfo(STRING_KEY_P2P_IP, myIp) != SOFTBUS_OK) { - TRANS_LOGW(TRANS_CTRL, "Client set local p2p ip fail"); - } - if (LnnSetDLP2pIp(conn.appInfo.peerData.deviceId, CATEGORY_UUID, conn.appInfo.peerData.addr) != SOFTBUS_OK) { - TRANS_LOGW(TRANS_CTRL, "Client set peer p2p ip fail"); - } - } - info.myIp = conn.appInfo.myData.addr; + ChannelInfo info = { 0 }; + GetChannelInfoFromConn(&info, &conn, channelId); + char myIp[IP_LEN] = { 0 }; + int32_t ret = conn.serverSide ? GetServerSideIpInfo(&conn, myIp, IP_LEN) : GetClientSideIpInfo(&conn, myIp, IP_LEN); + if (ret != SOFTBUS_OK) { + TRANS_LOGE(TRANS_CTRL, "get ip failed, ret = %d.", ret); + return ret; } + info.myIp = myIp; + char buf[NETWORK_ID_BUF_LEN] = {0}; - int32_t ret = LnnGetNetworkIdByUuid(conn.appInfo.peerData.deviceId, buf, NETWORK_ID_BUF_LEN); + ret = LnnGetNetworkIdByUuid(conn.appInfo.peerData.deviceId, buf, NETWORK_ID_BUF_LEN); if (ret != SOFTBUS_OK) { TRANS_LOGE(TRANS_CTRL, "get info networkId fail."); return SOFTBUS_ERR; @@ -433,7 +474,7 @@ int32_t NotifyChannelOpenFailed(int32_t channelId, int32_t errCode) .sessionName = conn.appInfo.myData.sessionName, }; TRANS_ALARM(OPEN_SESSION_FAIL_ALARM, CONTROL_ALARM_TYPE, extraAlarm); - + SoftbusRecordOpenSessionKpi(conn.appInfo.myData.pkgName, conn.appInfo.linkType, SOFTBUS_EVT_OPEN_SESSION_FAIL, timediff); char pkgName[PKG_NAME_SIZE_MAX] = {0}; @@ -442,8 +483,12 @@ int32_t NotifyChannelOpenFailed(int32_t channelId, int32_t errCode) return SOFTBUS_ERR; } - if (conn.serverSide == false) { + if (!(conn.serverSide)) { AppInfoData *myData = &conn.appInfo.myData; + if (myData == NULL) { + TRANS_LOGE(TRANS_CTRL, "myData is null"); + return SOFTBUS_INVALID_PARAM; + } int ret = TransTdcOnChannelOpenFailed(myData->pkgName, myData->pid, channelId, errCode); TRANS_LOGW(TRANS_CTRL, "channelId=%d, ret=%d", channelId, ret); return ret; @@ -454,7 +499,7 @@ int32_t NotifyChannelOpenFailed(int32_t channelId, int32_t errCode) static int TransTdcPostFisrtData(SessionConn *conn) { TRANS_LOGI(TRANS_CTRL, "enter."); - uint32_t outLen; + uint32_t outLen = 0; char *buf = TransTdcPackFastData(&(conn->appInfo), &outLen); if (buf == NULL) { TRANS_LOGE(TRANS_CTRL, "failed to pack bytes."); @@ -477,7 +522,6 @@ static int TransTdcPostFisrtData(SessionConn *conn) return SOFTBUS_ERR; } SoftBusFree(buf); - buf = NULL; return SOFTBUS_OK; } @@ -488,7 +532,8 @@ static const ConfigTypeMap g_configTypeMap[] = { static int32_t FindConfigType(int32_t channelType, int32_t businessType) { - for (uint32_t i = 0; i < sizeof(g_configTypeMap) / sizeof(ConfigTypeMap); i++) { + uint32_t size = (uint32_t)(sizeof(g_configTypeMap) / sizeof(ConfigTypeMap)); + for (uint32_t i = 0; i < size; i++) { if ((g_configTypeMap[i].channelType == channelType) && (g_configTypeMap[i].businessType == businessType)) { return g_configTypeMap[i].configType; @@ -505,12 +550,11 @@ static int32_t TransGetLocalConfig(int32_t channelType, int32_t businessType, ui channelType, businessType); return SOFTBUS_INVALID_PARAM; } - uint32_t maxLen; + uint32_t maxLen = 0; if (SoftbusGetConfig(configType, (unsigned char *)&maxLen, sizeof(maxLen)) != SOFTBUS_OK) { TRANS_LOGE(TRANS_CTRL, "get config failed, configType=%d.", configType); return SOFTBUS_GET_CONFIG_VAL_ERR; } - *len = maxLen; TRANS_LOGI(TRANS_CTRL, "get local config len=%d.", *len); return SOFTBUS_OK; @@ -547,11 +591,11 @@ static int32_t OpenDataBusReply(int32_t channelId, uint64_t seq, const cJSON *re (void)seq; TRANS_LOGI(TRANS_CTRL, "channelId=%d", channelId); SessionConn conn; + (void)memset_s(&conn, sizeof(SessionConn), 0, sizeof(SessionConn)); if (GetSessionConnById(channelId, &conn) == NULL) { TRANS_LOGE(TRANS_CTRL, "notify channel open failed, get tdcInfo is null"); return SOFTBUS_TRANS_GET_SESSION_CONN_FAILED; } - int errCode = SOFTBUS_OK; if (UnpackReplyErrCode(reply, &errCode) == SOFTBUS_OK) { TransEventExtra extra = { @@ -566,11 +610,11 @@ static int32_t OpenDataBusReply(int32_t channelId, uint64_t seq, const cJSON *re TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL, EVENT_STAGE_HANDSHAKE_REPLY, extra); TRANS_LOGE(TRANS_CTRL, "receive err reply msg"); if (NotifyChannelOpenFailed(channelId, errCode) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_CTRL, "channel open failed"); return SOFTBUS_ERR; } return errCode; } - uint16_t fastDataSize = 0; if (UnpackReply(reply, &conn.appInfo, &fastDataSize) != SOFTBUS_OK) { TRANS_LOGE(TRANS_CTRL, "UnpackReply failed"); @@ -590,6 +634,7 @@ static int32_t OpenDataBusReply(int32_t channelId, uint64_t seq, const cJSON *re if ((fastDataSize > 0 && (conn.appInfo.fastTransDataSize == fastDataSize)) || conn.appInfo.fastTransDataSize == 0) { ret = NotifyChannelOpened(channelId); if (ret != SOFTBUS_OK) { + TRANS_LOGE(TRANS_CTRL, "notify channel open failed"); return SOFTBUS_ERR; } } else { @@ -600,6 +645,7 @@ static int32_t OpenDataBusReply(int32_t channelId, uint64_t seq, const cJSON *re } ret = NotifyChannelOpened(channelId); if (ret != SOFTBUS_OK) { + TRANS_LOGE(TRANS_CTRL, "notify channel open failed"); return ret; } } @@ -616,7 +662,6 @@ static int32_t OpenDataBusReply(int32_t channelId, uint64_t seq, const cJSON *re } static inline int TransTdcPostReplyMsg(int32_t channelId, uint64_t seq, uint32_t flags, char *reply) - { TdcPacketHead packetHead = { .magicNumber = MAGIC_NUMBER, @@ -636,7 +681,6 @@ static int32_t OpenDataBusRequestReply(const AppInfo *appInfo, int32_t channelId TRANS_LOGE(TRANS_CTRL, "get pack reply err"); return SOFTBUS_ERR; } - int32_t ret = TransTdcPostReplyMsg(channelId, seq, flags, reply); cJSON_free(reply); return ret; @@ -650,7 +694,6 @@ static int32_t OpenDataBusRequestError(int32_t channelId, uint64_t seq, char *er TRANS_LOGE(TRANS_CTRL, "get pack reply err"); return SOFTBUS_ERR; } - int32_t ret = TransTdcPostReplyMsg(channelId, seq, flags, reply); cJSON_free(reply); return ret; @@ -682,10 +725,12 @@ static SessionConn* GetSessionConnFromDataBusRequest(int32_t channelId, const cJ { SessionConn *conn = (SessionConn *)SoftBusCalloc(sizeof(SessionConn)); if (conn == NULL) { + TRANS_LOGE(TRANS_CTRL, "conn calloc failed"); return NULL; } if (GetSessionConnById(channelId, conn) == NULL) { SoftBusFree(conn); + TRANS_LOGE(TRANS_CTRL, "get session conn failed"); return NULL; } if (UnpackRequest(request, &conn->appInfo) != SOFTBUS_OK) { @@ -714,7 +759,6 @@ static void NotifyFastDataRecv(SessionConn *conn, int32_t channelId) return; } TRANS_LOGD(TRANS_CTRL, "ok"); - return; } static int32_t TransTdcFillDataConfig(AppInfo *appInfo) @@ -760,6 +804,7 @@ static int32_t OpenDataBusRequest(int32_t channelId, uint32_t flags, uint64_t se TRANS_LOGI(TRANS_CTRL, "channelId=%d, seq=%d.", channelId, seq); SessionConn *conn = GetSessionConnFromDataBusRequest(channelId, request); if (conn == NULL) { + TRANS_LOGE(TRANS_CTRL, "conn is null"); return SOFTBUS_INVALID_PARAM; } @@ -771,7 +816,6 @@ static int32_t OpenDataBusRequest(int32_t channelId, uint32_t flags, uint64_t se AnonymizeFree(tmpName); return SOFTBUS_TRANS_NOT_META_SESSION; } - char *errDesc = NULL; int32_t errCode; int myHandleId; @@ -781,21 +825,18 @@ static int32_t OpenDataBusRequest(int32_t channelId, uint32_t flags, uint64_t se errDesc = (char *)"Peer Device Session Not Create"; goto ERR_EXIT; } - if (GetUuidByChanId(channelId, conn->appInfo.peerData.deviceId, DEVICE_ID_SIZE_MAX) != SOFTBUS_OK) { TRANS_LOGE(TRANS_CTRL, "Get Uuid By ChanId failed."); errCode = SOFTBUS_TRANS_TDC_CHANNEL_NOT_FOUND; errDesc = (char *)"Get Uuid By ChanId failed"; goto ERR_EXIT; } - if (TransTdcFillDataConfig(&conn->appInfo) != SOFTBUS_OK) { TRANS_LOGE(TRANS_CTRL, "fill data config failed."); errCode = SOFTBUS_INVALID_PARAM; errDesc = (char *)"fill data config failed"; goto ERR_EXIT; } - if (SetAppInfoById(channelId, &conn->appInfo) != SOFTBUS_OK) { TRANS_LOGE(TRANS_CTRL, "set app info by id failed."); errCode = SOFTBUS_TRANS_SESSION_INFO_NOT_FOUND; @@ -803,10 +844,10 @@ static int32_t OpenDataBusRequest(int32_t channelId, uint32_t flags, uint64_t se goto ERR_EXIT; } - OpenDataBusRequestOutSessionName(conn->appInfo.myData.sessionName, conn->appInfo.peerData.sessionName); + OpenDataBusRequestOutSessionName(conn->appInfo.myData.sessionName, + conn->appInfo.peerData.sessionName); TRANS_LOGI(TRANS_CTRL, "OpenDataBusRequest: myPid=%d, peerPid=%d", conn->appInfo.myData.pid, conn->appInfo.peerData.pid); - if (NotifyChannelOpened(channelId) != SOFTBUS_OK) { TRANS_LOGE(TRANS_CTRL, "Notify App Channel Opened Failed"); errCode = SOFTBUS_TRANS_UDP_SERVER_NOTIFY_APP_OPEN_FAILED; @@ -818,6 +859,7 @@ static int32_t OpenDataBusRequest(int32_t channelId, uint32_t flags, uint64_t se } myHandleId = NotifyNearByUpdateHandleId(channelId); if (myHandleId != SOFTBUS_ERR) { + TRANS_LOGE(TRANS_CTRL, "update handId notify failed"); conn->appInfo.myHandleId = myHandleId; } (void)SetAppInfoById(channelId, &conn->appInfo); @@ -832,6 +874,7 @@ static int32_t OpenDataBusRequest(int32_t channelId, uint32_t flags, uint64_t se if (conn->appInfo.routeType == WIFI_P2P) { if (LnnGetNetworkIdByUuid(conn->appInfo.peerData.deviceId, conn->appInfo.peerNetWorkId, DEVICE_ID_SIZE_MAX) == SOFTBUS_OK) { + TRANS_LOGI(TRANS_CTRL, "get networkId by uuid"); LaneUpdateP2pAddressByIp(conn->appInfo.peerData.addr, conn->appInfo.peerNetWorkId); } } @@ -869,9 +912,9 @@ static int32_t ProcessMessage(int32_t channelId, uint32_t flags, uint64_t seq, c static ServerDataBuf *TransSrvGetDataBufNodeById(int32_t channelId) { if (g_tcpSrvDataList == NULL) { + TRANS_LOGE(TRANS_CTRL, "g_tcpSrvDataList is null"); return NULL; } - ServerDataBuf *item = NULL; LIST_FOR_EACH_ENTRY(item, &(g_tcpSrvDataList->list), ServerDataBuf, node) { if (item->channelId == channelId) { @@ -886,15 +929,14 @@ static int64_t GetAuthIdByChannelInfo(int32_t channelId, uint64_t seq, uint32_t { int64_t authId = GetAuthIdByChanId(channelId); if (authId != AUTH_INVALID_ID) { + TRANS_LOGI(TRANS_CTRL, "authId is not AUTH_INVALID_ID"); return authId; } - AppInfo appInfo; if (GetAppInfoById(channelId, &appInfo) != SOFTBUS_OK) { TRANS_LOGE(TRANS_CTRL, "get appInfo fail"); return AUTH_INVALID_ID; } - bool fromAuthServer = ((seq & AUTH_CONN_SERVER_SIDE) != 0); char uuid[UUID_BUF_LEN] = {0}; if (GetWifiDirectManager()->getRemoteUuidByIp(appInfo.peerData.addr, uuid, sizeof(uuid)) != SOFTBUS_OK) { @@ -1003,7 +1045,6 @@ static int32_t TransTdcSrvProcData(ListenerModule module, int32_t channelId) TRANS_LOGE(TRANS_CTRL, "srv can not get buf node."); return SOFTBUS_TRANS_TCP_GET_SRV_DATA_FAILED; } - uint32_t bufLen = node->w - node->data; if (bufLen < DC_MSG_PACKET_HEAD_SIZE) { SoftBusMutexUnlock(&g_tcpSrvDataList->lock); @@ -1043,12 +1084,10 @@ static int32_t TransTdcGetDataBufInfoByChannelId(int32_t channelId, int32_t *fd, TRANS_LOGW(TRANS_CTRL, "invalid param."); return SOFTBUS_ERR; } - if (g_tcpSrvDataList == NULL) { TRANS_LOGE(TRANS_CTRL, "tcp srv data list empty."); return SOFTBUS_ERR; } - if (SoftBusMutexLock(&g_tcpSrvDataList->lock) != SOFTBUS_OK) { TRANS_LOGE(TRANS_CTRL, "lock failed."); return SOFTBUS_ERR; @@ -1081,7 +1120,6 @@ static int32_t TransTdcUpdateDataBufWInfo(int32_t channelId, char *recvBuf, int3 TRANS_LOGE(TRANS_CTRL, "lock failed."); return SOFTBUS_ERR; } - ServerDataBuf *item = NULL; ServerDataBuf *nextItem = NULL; LIST_FOR_EACH_ENTRY_SAFE(item, nextItem, &(g_tcpSrvDataList->list), ServerDataBuf, node) { @@ -1114,28 +1152,28 @@ int32_t TransTdcSrvRecvData(ListenerModule module, int32_t channelId) int32_t fd = -1; size_t len = 0; if (TransTdcGetDataBufInfoByChannelId(channelId, &fd, &len) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_CTRL, "get info failed"); return SOFTBUS_TRANS_TCP_GET_SRV_DATA_FAILED; } if (len == 0) { TRANS_LOGE(TRANS_CTRL, "trans channelId=%d free databuf less zero.", channelId); return SOFTBUS_TRANS_TCP_DATABUF_LESS_ZERO; } - char *recvBuf = (char*)SoftBusCalloc(len); if (recvBuf == NULL) { TRANS_LOGE(TRANS_CTRL, "trans channelId=%d malloc len%zu failed..", channelId, len); return SOFTBUS_MALLOC_ERR; } - int32_t recvLen = ConnRecvSocketData(fd, recvBuf, len, 0); if (recvLen < 0) { SoftBusFree(recvBuf); TRANS_LOGE(TRANS_CTRL, "channelId=%d recv tcp data fail,retLen=%d.", channelId, recvLen); return SOFTBUS_ERR; } else if (recvLen == 0) { + SoftBusFree(recvBuf); + TRANS_LOGE(TRANS_CTRL, "channelId=%d recv tcp data fail,retLen= 0.", channelId); return SOFTBUS_DATA_NOT_ENOUGH; } - if (TransTdcUpdateDataBufWInfo(channelId, recvBuf, recvLen) != SOFTBUS_OK) { SoftBusFree(recvBuf); TRANS_LOGE(TRANS_CTRL, "channelId=%d update channel data buf failed.", channelId); @@ -1144,4 +1182,4 @@ int32_t TransTdcSrvRecvData(ListenerModule module, int32_t channelId) SoftBusFree(recvBuf); return TransTdcSrvProcData(module, channelId); -} +} \ No newline at end of file diff --git a/core/transmission/trans_channel/tcp_direct/src/trans_tcp_direct_p2p.c b/core/transmission/trans_channel/tcp_direct/src/trans_tcp_direct_p2p.c index ec9c60c77..685f5cee8 100644 --- a/core/transmission/trans_channel/tcp_direct/src/trans_tcp_direct_p2p.c +++ b/core/transmission/trans_channel/tcp_direct/src/trans_tcp_direct_p2p.c @@ -50,7 +50,6 @@ static SoftBusList *g_hmlListenerList = NULL; static int32_t StartNewP2pListener(const char *ip, int32_t *port) { int32_t listenerPort; - LocalListenerInfo info; info.type = CONNECT_P2P; (void)memset_s(info.socketOption.addr, sizeof(info.socketOption.addr), 0, sizeof(info.socketOption.addr)); @@ -75,7 +74,7 @@ static int32_t StartNewP2pListener(const char *ip, int32_t *port) static int32_t StartNewHmlListener(const char *ip, int32_t *port, ListenerModule *moudleType) { - int32_t listenerPort; + int32_t listenerPort = 0; LocalListenerInfo info; info.type = CONNECT_P2P; (void)memset_s(info.socketOption.addr, sizeof(info.socketOption.addr), 0, sizeof(info.socketOption.addr)); @@ -85,7 +84,7 @@ static int32_t StartNewHmlListener(const char *ip, int32_t *port, ListenerModule TRANS_LOGE(TRANS_CTRL, "copy addr failed!"); return SOFTBUS_ERR; } - for (int i = DIRECT_CHANNEL_SERVER_HML_START; i <= DIRECT_CHANNEL_SERVER_HML_END; i++) { + for (int32_t i = DIRECT_CHANNEL_SERVER_HML_START; i <= DIRECT_CHANNEL_SERVER_HML_END; i++) { info.socketOption.moduleId = (ListenerModule)i; listenerPort = TransTdcStartSessionListener((ListenerModule)i, &info); if (listenerPort >= 0) { @@ -94,6 +93,7 @@ static int32_t StartNewHmlListener(const char *ip, int32_t *port, ListenerModule } } if (listenerPort < 0) { + TRANS_LOGE(TRANS_CTRL, "listenerPort is invalid!"); return SOFTBUS_ERR; } *port = listenerPort; @@ -128,7 +128,7 @@ void StopHmlListener(ListenerModule module) DelHmlListenerByMoudle(module); } -void StopP2pSessionListener(void) +void StopP2pSessionListener() { if (g_p2pSessionPort > 0) { if (StopBaseListener(DIRECT_CHANNEL_SERVER_P2P) != SOFTBUS_OK) { @@ -138,7 +138,6 @@ void StopP2pSessionListener(void) g_p2pSessionPort = -1; g_p2pSessionIp[0] = '\0'; - return; } static void NotifyP2pSessionConnClear(ListNode *sessionConnList) @@ -153,9 +152,9 @@ static void NotifyP2pSessionConnClear(ListNode *sessionConnList) LIST_FOR_EACH_ENTRY_SAFE(item, nextItem, sessionConnList, SessionConn, node) { (void)NotifyChannelOpenFailed(item->channelId, SOFTBUS_TRANS_NET_STATE_CHANGED); TransSrvDelDataBufNode(item->channelId); - SoftBusFree(item); } + TRANS_LOGI(TRANS_CTRL, "p2psession conn clear finished"); } static void ClearP2pSessionConn(void) @@ -164,10 +163,7 @@ static void ClearP2pSessionConn(void) SessionConn *nextItem = NULL; SoftBusList *sessionList = GetSessionConnList(); - if (sessionList == NULL) { - return; - } - if (GetSessionConnLock() != SOFTBUS_OK) { + if (sessionList == NULL || GetSessionConnLock() != SOFTBUS_OK) { return; } @@ -177,7 +173,6 @@ static void ClearP2pSessionConn(void) if (item->status < TCP_DIRECT_CHANNEL_STATUS_CONNECTED && item->appInfo.routeType == WIFI_P2P) { ListDelete(&item->node); sessionList->cnt--; - ListAdd(&tempSessionConnList, &item->node); } } @@ -273,8 +268,7 @@ static int32_t StartP2pListener(const char *ip, int32_t *port) return SOFTBUS_ERR; } if (strncmp(ip, HML_IP_PREFIX, NETWORK_ID_LEN) == 0) { - int32_t ret = StartHmlListener(ip, port); - return ret; + return StartHmlListener(ip, port); } TRANS_LOGI(TRANS_CTRL, "port=%d", *port); if (SoftBusMutexLock(&g_p2pLock) != SOFTBUS_OK) { @@ -282,6 +276,7 @@ static int32_t StartP2pListener(const char *ip, int32_t *port) return SOFTBUS_ERR; } if (g_p2pSessionPort > 0 && strcmp(ip, g_p2pSessionIp) != 0) { + TRANS_LOGE(TRANS_CTRL, "param invalid"); ClearP2pSessionConn(); StopP2pSessionListener(); } @@ -299,6 +294,7 @@ static int32_t StartP2pListener(const char *ip, int32_t *port) g_p2pSessionPort = *port; if (strcpy_s(g_p2pSessionIp, sizeof(g_p2pSessionIp), ip) != EOK) { + TRANS_LOGE(TRANS_CTRL, "strcpy_s fail"); StopP2pSessionListener(); (void)SoftBusMutexUnlock(&g_p2pLock); return SOFTBUS_MEM_ERR; @@ -342,6 +338,7 @@ static int32_t VerifyP2p(int64_t authId, const char *myIp, const char *peerIp, i int32_t ret; msg = VerifyP2pPack(myIp, myPort, peerIp); if (msg == NULL) { + TRANS_LOGE(TRANS_CTRL, "verifyp2p pack fail"); return SOFTBUS_PARSE_JSON_ERR; } ret = SendAuthData(authId, MODULE_P2P_LISTEN, MSG_FLAG_REQUEST, (int64_t)seq, msg); @@ -394,19 +391,20 @@ static void OnAuthConnOpenFailed(uint32_t requestId, int32_t reason) int32_t channelId; if (GetSessionConnLock() != SOFTBUS_OK) { + TRANS_LOGE(TRANS_CTRL, "get session conn lock fail"); return; } conn = GetSessionConnByRequestId(requestId); if (conn == NULL) { ReleaseSessonConnLock(); + TRANS_LOGE(TRANS_CTRL, "get session conn by requestid fail"); return; } channelId = conn->channelId; ReleaseSessonConnLock(); - OnChannelOpenFail(channelId, SOFTBUS_TRANS_OPEN_AUTH_CONN_FAILED); + (void)OnChannelOpenFail(channelId, SOFTBUS_TRANS_OPEN_AUTH_CONN_FAILED); TRANS_LOGW(TRANS_CTRL, "ok"); - return; } static int32_t OpenAuthConn(const char *uuid, uint32_t reqId, bool isMeta) @@ -437,6 +435,7 @@ static void SendVerifyP2pFailRsp(int64_t authId, int64_t seq, { char *reply = VerifyP2pPackError(code, errCode, errDesc); if (reply == NULL) { + TRANS_LOGE(TRANS_CTRL, "verify p2ppack error"); return; } if (isAuthLink) { @@ -447,6 +446,7 @@ static void SendVerifyP2pFailRsp(int64_t authId, int64_t seq, uint32_t strLen = strlen(reply) + 1; char *sendMsg = (char*)SoftBusCalloc(strLen + sizeof(int64_t) + sizeof(int64_t)); if (sendMsg == NULL) { + TRANS_LOGE(TRANS_CTRL, "softbuscalloc fail"); cJSON_free(reply); return; } @@ -462,7 +462,6 @@ static void SendVerifyP2pFailRsp(int64_t authId, int64_t seq, SoftBusFree(sendMsg); } cJSON_free(reply); - return; } static int32_t SendVerifyP2pRsp(int64_t authId, int32_t module, int32_t flag, int64_t seq, @@ -478,6 +477,7 @@ static int32_t SendVerifyP2pRsp(int64_t authId, int32_t module, int32_t flag, in uint32_t strLen = strlen(reply) + 1; char *sendMsg = (char*)SoftBusCalloc(strLen + sizeof(int64_t) + sizeof(int64_t)); if (sendMsg == NULL) { + TRANS_LOGE(TRANS_CTRL, "softbuscalloc fail"); return SOFTBUS_ERR; } *(int64_t*)sendMsg = P2P_VERIFY_REPLY; @@ -499,17 +499,27 @@ static int32_t SendVerifyP2pRsp(int64_t authId, int32_t module, int32_t flag, in static int32_t OnVerifyP2pRequest(int64_t authId, int64_t seq, const cJSON *json, bool isAuthLink) { TRANS_LOGI(TRANS_CTRL, "authId=%" PRId64 ", seq=%" PRId64, authId, seq); - int32_t peerPort; + int32_t peerPort = 0; char peerIp[IP_LEN] = {0}; int32_t myPort = 0; char myIp[IP_LEN] = {0}; + struct WifiDirectManager *pManager = NULL; int32_t ret = VerifyP2pUnPack(json, peerIp, IP_LEN, &peerPort); if (ret != SOFTBUS_OK) { SendVerifyP2pFailRsp(authId, seq, CODE_VERIFY_P2P, ret, "OnVerifyP2pRequest unpack fail", isAuthLink); return ret; } - if (GetWifiDirectManager()->getLocalIpByRemoteIp(peerIp, myIp, sizeof(myIp)) != SOFTBUS_OK) { + + pManager = GetWifiDirectManager(); + if (pManager == NULL || pManager->getLocalIpByRemoteIp == NULL) { + TRANS_LOGE(TRANS_CTRL, "get wifidirectmanager or get localipbyremoteip fail"); + SendVerifyP2pFailRsp(authId, seq, CODE_VERIFY_P2P, SOFTBUS_ERR, + "get wifidirectmanager or localip fail", isAuthLink); + return SOFTBUS_ERR; + } + + if (pManager->getLocalIpByRemoteIp(peerIp, myIp, sizeof(myIp)) != SOFTBUS_OK) { TRANS_LOGE(TRANS_CTRL, "OnVerifyP2pRequest get p2p ip fail"); SendVerifyP2pFailRsp(authId, seq, CODE_VERIFY_P2P, ret, "get p2p ip fail", isAuthLink); return SOFTBUS_TRANS_GET_P2P_INFO_FAILED; @@ -548,7 +558,7 @@ static int32_t ConnectTcpDirectPeer(const char *addr, int port) int32_t ret = strcpy_s(options.socketOption.addr, sizeof(options.socketOption.addr), addr); if (ret != SOFTBUS_OK) { TRANS_LOGE(TRANS_CTRL, "strcpy_s failed! ret=%" PRId32, ret); - return -1; + return SOFTBUS_ERR; } return ConnOpenClientSocket(&options, BIND_ADDR_ALL, true); @@ -617,6 +627,7 @@ static int32_t OnVerifyP2pReply(int64_t authId, int64_t seq, const cJSON *json) int32_t peerPort = -1; if (GetSessionConnLock() != SOFTBUS_OK) { + TRANS_LOGE(TRANS_CTRL, "getsessionconnlock fail"); return SOFTBUS_LOCK_ERR; } conn = GetSessionConnByReq(seq); @@ -694,22 +705,22 @@ static void OnAuthDataRecv(int64_t authId, const AuthTransData *data) TRANS_LOGI(TRANS_CTRL, "module=%d, seq=%" PRId64 ", len=%u.", data->module, data->seq, data->len); if (data->module != MODULE_P2P_LISTEN) { + TRANS_LOGE(TRANS_CTRL, "module is not MODULE_P2P_LISTEN"); return; } cJSON *json = cJSON_ParseWithLength((const char *)(data->data), data->len); if (json == NULL) { + TRANS_LOGE(TRANS_CTRL, "cjson parse with length failed"); return; } OnAuthMsgProc(authId, data->flag, data->seq, json); cJSON_Delete(json); - return; } static void OnAuthChannelClose(int64_t authId) { TRANS_LOGW(TRANS_CTRL, "authId=%" PRId64, authId); - return; } static int32_t OpenNewAuthConn(const AppInfo *appInfo, SessionConn *conn, @@ -754,6 +765,7 @@ static int32_t StartVerifyP2pInfo(const AppInfo *appInfo, SessionConn *conn) int32_t newChannelId = conn->channelId; int32_t pipeLineChannelId = TransProxyPipelineGetChannelIdByNetworkId(appInfo->peerNetWorkId); if (pipeLineChannelId == INVALID_CHANNEL_ID) { + TRANS_LOGI(TRANS_CTRL, "can not get channelid by networkid"); uint32_t requestId = AuthGenRequestId(); conn->status = TCP_DIRECT_CHANNEL_STATUS_AUTH_CHANNEL; conn->requestId = requestId; @@ -774,6 +786,7 @@ static int32_t StartVerifyP2pInfo(const AppInfo *appInfo, SessionConn *conn) conn->requestId = REQUEST_INVALID; char *msg = VerifyP2pPack(conn->appInfo.myData.addr, conn->appInfo.myData.port, NULL); if (msg == NULL) { + TRANS_LOGE(TRANS_CTRL, "verify p2p pack failed"); return SOFTBUS_ERR; } uint32_t strLen = strlen(msg) + 1; @@ -803,6 +816,7 @@ int32_t OpenP2pDirectChannel(const AppInfo *appInfo, const ConnectOption *connIn TRANS_LOGI(TRANS_CTRL, "enter."); if (appInfo == NULL || connInfo == NULL || channelId == NULL || (connInfo->type != CONNECT_P2P && connInfo->type != CONNECT_HML)) { + TRANS_LOGE(TRANS_CTRL, "invalid param"); return SOFTBUS_INVALID_PARAM; } SessionConn *conn = NULL; @@ -810,6 +824,7 @@ int32_t OpenP2pDirectChannel(const AppInfo *appInfo, const ConnectOption *connIn conn = CreateNewSessinConn(DIRECT_CHANNEL_SERVER_P2P, false); if (conn == NULL) { + TRANS_LOGE(TRANS_CTRL, "create new sessin conn fail"); return SOFTBUS_MEM_ERR; } SoftbusHitraceStart(SOFTBUS_HITRACE_ID_VALID, (uint64_t)(conn->channelId + ID_OFFSET)); diff --git a/core/transmission/trans_channel/udp_negotiation/src/trans_udp_negotiation.c b/core/transmission/trans_channel/udp_negotiation/src/trans_udp_negotiation.c index 089b71020..aacf2e0b6 100644 --- a/core/transmission/trans_channel/udp_negotiation/src/trans_udp_negotiation.c +++ b/core/transmission/trans_channel/udp_negotiation/src/trans_udp_negotiation.c @@ -999,6 +999,11 @@ void TransUdpChannelDeinit(void) void TransUdpDeathCallback(const char *pkgName, int32_t pid) { + if (pkgName == NULL) { + TRANS_LOGE(TRANS_CTRL, "param invalid"); + return; + } + TRANS_LOGW(TRANS_CTRL, "TransUdpDeathCallback: pkgName=%s, pid=%d", pkgName, pid); if (GetUdpChannelLock() != SOFTBUS_OK) { TRANS_LOGE(TRANS_CTRL, "lock failed"); return; diff --git a/interfaces/inner_kits/transport/inner_socket.h b/interfaces/inner_kits/transport/inner_socket.h new file mode 100644 index 000000000..0b3390ff0 --- /dev/null +++ b/interfaces/inner_kits/transport/inner_socket.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2023 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. + */ + +/** + * @addtogroup SoftBus + * @{ + * + * @brief Provides secure, high-speed communications between devices. + * + * This module implements unified distributed communication management of nearby devices and provides link-independent + * device discovery and transmission interfaces to support service publishing and data transmission. + * @since 1.0 + * @version 1.0 + */ + +/** + * @file inner_socket.h + * + * @brief Declare the function for getting the maximum transmission unit. + * + * @since 1.0 + * @version 1.0 + */ +#ifndef INNER_SOCKET_H +#define INNER_SOCKET_H + +#include "softbus_common.h" + +#ifdef __cplusplus +extern "C" { +#endif +/** + * @brief Get maximum transmission unit of socket + * + * @param socket Indicates the unique socket fd. + * @param size Indicates the maximum transmission unit. + * + * @return Returns SOFTBUS_INVALID_PARAM if invalid parameters are detected. + * @return Returns SOFTBUS_OK if the operation is successful; returns an error code otherwise. + * + * @since 1.0 + * @version 1.0 + */ +int32_t GetMtuSize(int32_t socket, uint32_t *mtuSize); +#ifdef __cplusplus +} +#endif +#endif // INNER_SOCKET_H \ No newline at end of file diff --git a/interfaces/kits/common/softbus_common.h b/interfaces/kits/common/softbus_common.h index fbed4178a..2ab5b0f7f 100644 --- a/interfaces/kits/common/softbus_common.h +++ b/interfaces/kits/common/softbus_common.h @@ -141,7 +141,7 @@ extern "C" { * @brief Indicates the maximum length of the custom data in IDiscoveryCallback. * */ -#define DISC_MAX_CUST_DATA_LEN 219 +#define DISC_MAX_CUST_DATA_LEN 513 /** * @brief Indicates the maximum number of capabilities contained in the bitmap in IDiscoveryCallback. @@ -230,12 +230,12 @@ typedef enum { */ typedef enum { PROXY_TRANSMISION = 0, /**< Proxy Transmision */ - PROXY_HEARTBEAT = 1, /**< Proxy Heartbeat */ - PROXY_HICAR, - PROXY_WEAR, - PROXY_SHARE, - PROXY_CASTPLUS, - CUSTOM_UNKNOWN, /**< Proxy Unknown*/ + PROXY_HEARTBEAT = 1, /**< Proxy Heartbeat */ + PROXY_HICAR = 2, + PROXY_SHARE = 4, + PROXY_CASTPLUS = 5, + PROXY_WEAR = 7, + CUSTOM_UNKNOWN = 8, /**< Proxy Unknown*/ } MetaNodeType; /** diff --git a/sdk/bus_center/ipc/mini/bus_center_server_proxy.c b/sdk/bus_center/ipc/mini/bus_center_server_proxy.c index 91e763f76..ce667eaa7 100644 --- a/sdk/bus_center/ipc/mini/bus_center_server_proxy.c +++ b/sdk/bus_center/ipc/mini/bus_center_server_proxy.c @@ -71,7 +71,7 @@ int32_t ServerIpcStartTimeSync(const char *pkgName, const char *targetNetworkId, int32_t ServerIpcStopTimeSync(const char *pkgName, const char *targetNetworkId) { - return LnnIpcStopTimeSync(pkgName, targetNetworkId); + return LnnIpcStopTimeSync(pkgName, targetNetworkId, 0); } int32_t ServerIpcPublishLNN(const char *pkgName, const PublishInfo *info) diff --git a/sdk/frame/common/src/softbus_client_frame_manager.c b/sdk/frame/common/src/softbus_client_frame_manager.c index 743d16473..e61e2e23c 100644 --- a/sdk/frame/common/src/softbus_client_frame_manager.c +++ b/sdk/frame/common/src/softbus_client_frame_manager.c @@ -170,7 +170,7 @@ static int32_t ConnClientInit(void) COMM_LOGE(COMM_EVENT, "InitBaseListener failed!ret=%" PRId32 " \r\n", ret); return ret; } - COMM_LOGI(COMM_EVENT, "init conn client success"); + COMM_LOGD(COMM_EVENT, "init conn client success"); return ret; } diff --git a/sdk/frame/standard/src/softbus_client_stub.cpp b/sdk/frame/standard/src/softbus_client_stub.cpp index e5b6fe4bf..f7cf74e76 100644 --- a/sdk/frame/standard/src/softbus_client_stub.cpp +++ b/sdk/frame/standard/src/softbus_client_stub.cpp @@ -401,6 +401,10 @@ int32_t SoftBusClientStub::OnChannelMsgReceivedInner(MessageParcel &data, Messag return SOFTBUS_ERR; } char *infoData = (char *)SoftBusMalloc(len); + if (infoData == NULL) { + COMM_LOGE(COMM_SDK, "malloc infoData failed!"); + return SOFTBUS_ERR; + } memcpy_s(infoData, len, dataInfo, len); int ret = OnChannelMsgReceived(channelId, channelType, infoData, len, type); SoftBusFree(infoData); diff --git a/sdk/frame/standard/src/softbus_server_proxy_frame.cpp b/sdk/frame/standard/src/softbus_server_proxy_frame.cpp index aefbfe11f..ee3a0243c 100644 --- a/sdk/frame/standard/src/softbus_server_proxy_frame.cpp +++ b/sdk/frame/standard/src/softbus_server_proxy_frame.cpp @@ -41,6 +41,8 @@ OHOS::sptr g_clientDeath = nullptr; std::mutex g_mutex; uint32_t g_waitServerInterval = 2; uint32_t g_getSystemAbilityId = 2; +uint32_t g_printRequestFailedCount = 0; +constexpr uint32_t g_printInterval = 200; const std::u16string SAMANAGER_INTERFACE_TOKEN = u"ohos.samgr.accessToken"; } @@ -80,8 +82,8 @@ static int InnerRegisterService(void) static OHOS::sptr GetSystemAbility() { OHOS::MessageParcel data; - if (!data.WriteInterfaceToken(SAMANAGER_INTERFACE_TOKEN)) { + COMM_LOGE(COMM_EVENT, "write interface token failed!"); return nullptr; } @@ -95,7 +97,9 @@ static OHOS::sptr GetSystemAbility() } int32_t err = samgr->SendRequest(g_getSystemAbilityId, data, reply, option); if (err != 0) { - COMM_LOGE(COMM_EVENT, "Get GetSystemAbility failed!"); + if ((++g_printRequestFailedCount) % g_printInterval == 0) { + COMM_LOGE(COMM_EVENT, "Get GetSystemAbility failed!"); + } return nullptr; } return reply.ReadRemoteObject(); @@ -107,7 +111,6 @@ static int32_t ServerProxyInit(void) if (g_serverProxy == nullptr) { g_serverProxy = GetSystemAbility(); if (g_serverProxy == nullptr) { - COMM_LOGE(COMM_SDK, "Get remote softbus object failed!\n"); return SOFTBUS_ERR; } g_clientDeath = diff --git a/sdk/libsoftbus_client_map b/sdk/libsoftbus_client_map index 867befb7f..810f0d13c 100644 --- a/sdk/libsoftbus_client_map +++ b/sdk/libsoftbus_client_map @@ -382,6 +382,7 @@ "ClientGetPeerSocketInfoById"; "TransSetSocketFileListener"; "EvaluateQos"; + "GetMtuSize"; extern "C++" { OHOS::StreamAdaptor*; Communication::SoftBus*; diff --git a/sdk/transmission/session/include/client_trans_session_adapter.h b/sdk/transmission/session/include/client_trans_session_adapter.h index 4a204fd39..d87595faf 100644 --- a/sdk/transmission/session/include/client_trans_session_adapter.h +++ b/sdk/transmission/session/include/client_trans_session_adapter.h @@ -27,6 +27,7 @@ int32_t ClientAddSocket(const SocketInfo *info, int32_t *sessionId); int32_t ClientListen(int32_t socket, const QosTV qos[], uint32_t qosCount, const ISocketListener *listener); int32_t ClientBind(int32_t socket, const QosTV qos[], uint32_t qosCount, const ISocketListener *listener); void ClientShutdown(int32_t socket); +int32_t GetSocketMtuSize(int32_t socket, uint32_t *mtuSize); #ifdef __cplusplus } #endif diff --git a/sdk/transmission/session/include/client_trans_session_manager.h b/sdk/transmission/session/include/client_trans_session_manager.h index baf5326ec..80d22b2d5 100644 --- a/sdk/transmission/session/include/client_trans_session_manager.h +++ b/sdk/transmission/session/include/client_trans_session_manager.h @@ -34,6 +34,7 @@ typedef struct { char peerDeviceId[DEVICE_ID_SIZE_MAX]; char groupId[GROUP_ID_SIZE_MAX]; int flag; // TYPE_MESSAGE & TYPE_BYTES & TYPE_FILE + int streamType; } SessionTag; typedef enum { diff --git a/sdk/transmission/session/src/client_trans_message_service.c b/sdk/transmission/session/src/client_trans_message_service.c index 6f4b08541..c361a9d29 100644 --- a/sdk/transmission/session/src/client_trans_message_service.c +++ b/sdk/transmission/session/src/client_trans_message_service.c @@ -57,7 +57,7 @@ int CheckSendLen(int32_t channelId, int32_t channelType, unsigned int len, int32 int SendBytes(int sessionId, const void *data, unsigned int len) { - TRANS_LOGI(TRANS_BYTES, "SendBytes: sessionId=%d", sessionId); + TRANS_LOGI(TRANS_BYTES, "sessionId=%d, len=%d", sessionId, len); if (data == NULL || len == 0) { TRANS_LOGW(TRANS_BYTES, "Invalid param"); return SOFTBUS_INVALID_PARAM; @@ -98,7 +98,7 @@ int SendBytes(int sessionId, const void *data, unsigned int len) int SendMessage(int sessionId, const void *data, unsigned int len) { - TRANS_LOGE(TRANS_MSG, "SendMessage: sessionId=%d", sessionId); + TRANS_LOGI(TRANS_MSG, "sessionId=%d, len=%d", sessionId, len); if (data == NULL || len == 0) { TRANS_LOGW(TRANS_MSG, "Invalid param"); return SOFTBUS_INVALID_PARAM; diff --git a/sdk/transmission/session/src/client_trans_session_manager.c b/sdk/transmission/session/src/client_trans_session_manager.c index c5faa586f..91c0d3a1d 100644 --- a/sdk/transmission/session/src/client_trans_session_manager.c +++ b/sdk/transmission/session/src/client_trans_session_manager.c @@ -184,7 +184,7 @@ NO_SANITIZE("cfi") static DestroySessionInfo *CreateDestroySessionNode(SessionIn NO_SANITIZE("cfi") static void ClientDestroySession(const ListNode *destroyList, ShutdownReason reason) { if (IsListEmpty(destroyList)) { - TRANS_LOGE(TRANS_SDK, "destroyList is empty fail."); + TRANS_LOGD(TRANS_SDK, "destroyList is empty fail."); return; } DestroySessionInfo *destroyNode = NULL; @@ -1242,7 +1242,7 @@ static INodeStateCb g_transLnnCb = { int32_t ReCreateSessionServerToServer(void) { - TRANS_LOGI(TRANS_SDK, "enter."); + TRANS_LOGD(TRANS_SDK, "enter."); if (g_clientSessionServerList == NULL) { TRANS_LOGE(TRANS_INIT, "entry list not init"); return SOFTBUS_ERR; @@ -1282,7 +1282,10 @@ void ClientTransOnLinkDown(const char *networkId, int32_t routeType) if (networkId == NULL || g_clientSessionServerList == NULL) { return; } - TRANS_LOGI(TRANS_SDK, "routeType=%d", routeType); + char *anonyNetworkId = NULL; + Anonymize(networkId, &anonyNetworkId); + TRANS_LOGI(TRANS_SDK, "routeType=%d, networkId=%s", routeType, anonyNetworkId); + AnonymizeFree(anonyNetworkId); if (SoftBusMutexLock(&(g_clientSessionServerList->lock)) != 0) { TRANS_LOGE(TRANS_CTRL, "lock failed"); @@ -1563,6 +1566,7 @@ static SessionInfo *CreateNewSocketSession(const SessionParam *param) session->role = SESSION_ROLE_INIT; session->isEnable = false; session->info.flag = param->attr->dataType; + session->info.streamType = param->attr->attr.streamAttr.streamType; session->isEncrypt = true; return session; } @@ -1725,6 +1729,7 @@ int32_t ClientIpcOpenSession(int32_t sessionId, const QosTV *qos, uint32_t qosCo tmpAttr.fastTransData = NULL; tmpAttr.fastTransDataSize = 0; tmpAttr.dataType = sessionNode->info.flag; + tmpAttr.attr.streamAttr.streamType = sessionNode->info.streamType; tmpAttr.linkTypeNum = 0; SessionParam param = { .sessionName = serverNode->sessionName, diff --git a/sdk/transmission/session/src/client_trans_session_service.c b/sdk/transmission/session/src/client_trans_session_service.c index 419a636db..aaf191573 100644 --- a/sdk/transmission/session/src/client_trans_session_service.c +++ b/sdk/transmission/session/src/client_trans_session_service.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 @@ -31,7 +31,6 @@ #include "inner_session.h" #include "securec.h" #include "softbus_adapter_mem.h" -#include "softbus_adapter_timer.h" #include "softbus_client_frame_manager.h" #include "softbus_def.h" #include "softbus_errcode.h" @@ -174,16 +173,37 @@ int RemoveSessionServer(const char *pkgName, const char *sessionName) static int32_t CheckParamIsValid(const char *mySessionName, const char *peerSessionName, const char *peerNetworkId, const char *groupId, const SessionAttribute *attr) { - if (!IsValidString(mySessionName, SESSION_NAME_SIZE_MAX) || - !IsValidString(peerSessionName, SESSION_NAME_SIZE_MAX) || - !IsValidString(peerNetworkId, DEVICE_ID_SIZE_MAX) || - (attr == NULL) || - (attr->dataType >= TYPE_BUTT)) { - TRANS_LOGW(TRANS_SDK, "invalid param"); + if (!IsValidString(mySessionName, SESSION_NAME_SIZE_MAX)) { + char *tmpMyName = NULL; + Anonymize(mySessionName, &tmpMyName); + TRANS_LOGE(TRANS_SDK, "invalid mySessionName: %s", tmpMyName); + AnonymizeFree(tmpMyName); return SOFTBUS_INVALID_PARAM; } - - if (groupId == NULL || strlen(groupId) >= GROUP_ID_SIZE_MAX) { + if (!IsValidString(peerSessionName, SESSION_NAME_SIZE_MAX)) { + char *tmpPeerName = NULL; + Anonymize(peerSessionName, &tmpPeerName); + TRANS_LOGE(TRANS_SDK, "invalid peerSessionName: %s", tmpPeerName); + AnonymizeFree(tmpPeerName); + return SOFTBUS_INVALID_PARAM; + } + if (!IsValidString(peerNetworkId, DEVICE_ID_SIZE_MAX)) { + char *tmpPeerNetworkId = NULL; + Anonymize(peerNetworkId, &tmpPeerNetworkId); + TRANS_LOGE(TRANS_SDK, "invalid peerNetworkId: %s", tmpPeerNetworkId); + AnonymizeFree(tmpPeerNetworkId); + return SOFTBUS_INVALID_PARAM; + } + if (attr == NULL) { + TRANS_LOGE(TRANS_SDK, "attr is NULL"); + return SOFTBUS_INVALID_PARAM; + } + if (groupId == NULL) { + TRANS_LOGE(TRANS_SDK, "groupId is NULL"); + return SOFTBUS_INVALID_PARAM; + } + if (strlen(groupId) >= GROUP_ID_SIZE_MAX) { + TRANS_LOGE(TRANS_SDK, "groupId length is invalid"); return SOFTBUS_INVALID_PARAM; } @@ -207,11 +227,9 @@ int OpenSession(const char *mySessionName, const char *peerSessionName, const ch { int ret = CheckParamIsValid(mySessionName, peerSessionName, peerNetworkId, groupId, attr); if (ret != SOFTBUS_OK) { - TRANS_LOGW(TRANS_SDK, "invalid param, CheckParamIsValid ret=%d.", ret); - return SOFTBUS_INVALID_PARAM; + return ret; } PrintSessionName(mySessionName, peerSessionName); - TransInfo transInfo; SessionAttribute *tmpAttr = (SessionAttribute *)SoftBusCalloc(sizeof(SessionAttribute)); if (tmpAttr == NULL) { TRANS_LOGE(TRANS_SDK, "SoftBusCalloc SessionAttribute failed"); @@ -249,6 +267,8 @@ int OpenSession(const char *mySessionName, const char *peerSessionName, const ch return ret; } + TransInfo transInfo; + (void)memset_s(&transInfo, sizeof(TransInfo), 0, sizeof(TransInfo)); ret = ServerIpcOpenSession(¶m, &transInfo); if (ret != SOFTBUS_OK) { TRANS_LOGE(TRANS_SDK, "open session ipc err: ret=%d", ret); @@ -273,15 +293,18 @@ int OpenSession(const char *mySessionName, const char *peerSessionName, const ch static int32_t ConvertAddrStr(const char *addrStr, ConnectionAddr *addrInfo) { if (addrStr == NULL || addrInfo == NULL) { + TRANS_LOGE(TRANS_SDK, "param invalid"); return SOFTBUS_INVALID_PARAM; } cJSON *obj = cJSON_Parse(addrStr); if (obj == NULL) { + TRANS_LOGE(TRANS_SDK, "cJSON_Parse fail"); return SOFTBUS_PARSE_JSON_ERR; } if (memset_s(addrInfo, sizeof(ConnectionAddr), 0x0, sizeof(ConnectionAddr)) != EOK) { cJSON_Delete(obj); + TRANS_LOGE(TRANS_SDK, "memset_s info fail"); return SOFTBUS_MEM_ERR; } int port; @@ -314,6 +337,7 @@ static int32_t ConvertAddrStr(const char *addrStr, ConnectionAddr *addrInfo) return SOFTBUS_OK; } cJSON_Delete(obj); + TRANS_LOGE(TRANS_SDK, "addr convert fail"); return SOFTBUS_ERR; } @@ -448,12 +472,10 @@ int OpenSessionSync(const char *mySessionName, const char *peerSessionName, cons { int ret = CheckParamIsValid(mySessionName, peerSessionName, peerNetworkId, groupId, attr); if (ret != SOFTBUS_OK) { - TRANS_LOGW(TRANS_SDK, "invalid param"); - return INVALID_SESSION_ID; + return ret; } PrintSessionName(mySessionName, peerSessionName); - TransInfo transInfo; SessionParam param = { .sessionName = mySessionName, .peerSessionName = peerSessionName, @@ -479,6 +501,8 @@ int OpenSessionSync(const char *mySessionName, const char *peerSessionName, cons return ret; } + TransInfo transInfo; + (void)memset_s(&transInfo, sizeof(TransInfo), 0, sizeof(TransInfo)); ret = ServerIpcOpenSession(¶m, &transInfo); if (ret != SOFTBUS_OK) { TRANS_LOGE(TRANS_SDK, "open session ipc err: ret=%d", ret); @@ -743,6 +767,10 @@ int ReadMaxSendBytesSize(int32_t channelId, int32_t type, void* value, uint32_t int ReadMaxSendMessageSize(int32_t channelId, int32_t type, void* value, uint32_t valueSize) { + if (value == NULL) { + TRANS_LOGE(TRANS_SDK, "param invalid"); + return SOFTBUS_INVALID_PARAM; + } if (valueSize != sizeof(uint32_t)) { TRANS_LOGE(TRANS_SDK, "valueSize=%d, not match", valueSize); return SOFTBUS_INVALID_PARAM; @@ -760,6 +788,10 @@ int ReadMaxSendMessageSize(int32_t channelId, int32_t type, void* value, uint32_ int ReadSessionLinkType(int32_t channelId, int32_t type, void* value, uint32_t valueSize) { + if (value == NULL) { + TRANS_LOGE(TRANS_SDK, "param invalid"); + return SOFTBUS_INVALID_PARAM; + } if (valueSize != sizeof(uint32_t)) { TRANS_LOGE(TRANS_SDK, "valueSize=%d, not match", valueSize); return SOFTBUS_INVALID_PARAM; @@ -1032,3 +1064,35 @@ void ClientShutdown(int32_t socket) } TRANS_LOGI(TRANS_SDK, "Shutdown ok: socket=%d", socket); } + +int32_t GetSocketMtuSize(int32_t socket, uint32_t *mtuSize) +{ + if (!IsValidSessionId(socket) || mtuSize == NULL) { + TRANS_LOGE(TRANS_SDK, "invalid param"); + return SOFTBUS_INVALID_PARAM; + } + + int32_t channelId = INVALID_CHANNEL_ID; + int32_t type = CHANNEL_TYPE_BUTT; + bool isEnable = false; + int32_t ret = ClientGetChannelBySessionId(socket, &channelId, &type, &isEnable); + if (ret != SOFTBUS_OK) { + TRANS_LOGE(TRANS_SDK, "get channel err, ret=%d.", ret); + return ret; + } + + if (!isEnable) { + TRANS_LOGI(TRANS_SDK, "socket not enable"); + return SOFTBUS_TRANS_SESSION_NO_ENABLE; + } + + uint32_t dataConfig = INVALID_DATA_CONFIG; + if (ClientGetDataConfigByChannelId(channelId, type, &dataConfig) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_SDK, "get config failed."); + return SOFTBUS_GET_CONFIG_VAL_ERR; + } + + *mtuSize = dataConfig; + TRANS_LOGI(TRANS_SDK, "get mtuSize success, socket=%d, mtu=%" PRIu32, socket, *mtuSize); + return SOFTBUS_OK; +} \ No newline at end of file diff --git a/sdk/transmission/session/src/client_trans_socket_service.c b/sdk/transmission/session/src/client_trans_socket_service.c index ba3255de5..218cdb411 100644 --- a/sdk/transmission/session/src/client_trans_socket_service.c +++ b/sdk/transmission/session/src/client_trans_socket_service.c @@ -16,6 +16,7 @@ #include "anonymizer.h" #include "client_trans_session_adapter.h" #include "socket.h" +#include "inner_socket.h" #include "softbus_adapter_mem.h" #include "softbus_def.h" #include "softbus_error_code.h" @@ -110,4 +111,10 @@ int32_t EvaluateQos(const char *peerNetworkId, TransDataType dataType, const Qos } return ServerIpcEvaluateQos(peerNetworkId, dataType, qos, qosCount); +} + +int32_t GetMtuSize(int32_t socket, uint32_t *mtuSize) +{ + TRANS_LOGI(TRANS_SDK, "GetMtuSize: socket=%d", socket); + return GetSocketMtuSize(socket, mtuSize); } \ No newline at end of file diff --git a/sdk/transmission/trans_channel/auth/include/client_trans_auth_manager.h b/sdk/transmission/trans_channel/auth/include/client_trans_auth_manager.h index 292b11983..40290bc2d 100644 --- a/sdk/transmission/trans_channel/auth/include/client_trans_auth_manager.h +++ b/sdk/transmission/trans_channel/auth/include/client_trans_auth_manager.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 @@ -43,5 +43,4 @@ int32_t TransAuthChannelSendMessage(int32_t channelId, const void *data, uint32_ #ifdef __cplusplus } #endif - -#endif \ No newline at end of file +#endif // CLIENT_TRANS_AUTH_MANAGER_H diff --git a/sdk/transmission/trans_channel/auth/src/client_trans_auth_manager.c b/sdk/transmission/trans_channel/auth/src/client_trans_auth_manager.c index 133f30252..0a8c437cf 100644 --- a/sdk/transmission/trans_channel/auth/src/client_trans_auth_manager.c +++ b/sdk/transmission/trans_channel/auth/src/client_trans_auth_manager.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 @@ -73,6 +73,7 @@ int32_t ClientTransAuthOnDataReceived(int32_t channelId, const void *data, uint32_t len, SessionPktType type) { if (data == NULL) { + TRANS_LOGE(TRANS_SDK, "param invalid"); return SOFTBUS_INVALID_PARAM; } int ret = g_sessionCb.OnDataReceived(channelId, CHANNEL_TYPE_AUTH, data, len, type); diff --git a/sdk/transmission/trans_channel/manager/src/client_trans_channel_callback.c b/sdk/transmission/trans_channel/manager/src/client_trans_channel_callback.c index 5ef5376ff..062f2f16c 100644 --- a/sdk/transmission/trans_channel/manager/src/client_trans_channel_callback.c +++ b/sdk/transmission/trans_channel/manager/src/client_trans_channel_callback.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 @@ -17,7 +17,6 @@ #include "client_trans_auth_manager.h" #include "client_trans_proxy_manager.h" -#include "client_trans_session_callback.h" #include "client_trans_session_manager.h" #include "client_trans_tcp_direct_manager.h" #include "client_trans_tcp_direct_callback.h" @@ -111,6 +110,10 @@ int32_t TransOnChannelClosed(int32_t channelId, int32_t channelType, ShutdownRea int32_t TransOnChannelMsgReceived(int32_t channelId, int32_t channelType, const void *data, unsigned int len, SessionPktType type) { + if (data == NULL) { + TRANS_LOGE(TRANS_MSG, "param invalid"); + return SOFTBUS_INVALID_PARAM; + } TRANS_LOGI(TRANS_MSG, "[client]: channelId=%d, channelType=%d.", channelId, channelType); switch (channelType) { @@ -128,6 +131,10 @@ int32_t TransOnChannelMsgReceived(int32_t channelId, int32_t channelType, int32_t TransOnChannelQosEvent(int32_t channelId, int32_t channelType, int32_t eventId, int32_t tvCount, const QosTv *tvList) { + if (tvList == NULL) { + TRANS_LOGE(TRANS_MSG, "param invalid"); + return SOFTBUS_INVALID_PARAM; + } TRANS_LOGI(TRANS_QOS, "[client] TransOnQosEvent: channelId=%d, channelType=%d eventId=%d.", channelId, channelType, eventId); switch (channelType) { diff --git a/sdk/transmission/trans_channel/manager/src/client_trans_channel_manager.c b/sdk/transmission/trans_channel/manager/src/client_trans_channel_manager.c index 173f37ab7..7b6ddd4cf 100644 --- a/sdk/transmission/trans_channel/manager/src/client_trans_channel_manager.c +++ b/sdk/transmission/trans_channel/manager/src/client_trans_channel_manager.c @@ -28,19 +28,23 @@ int32_t ClientTransChannelInit(void) { IClientSessionCallBack *cb = GetClientSessionCb(); if (cb == NULL) { + TRANS_LOGE(TRANS_SDK, "get client session Cb failed."); return SOFTBUS_ERR; } if (TransTdcManagerInit(cb) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_SDK, "trans tcp direct manager init failed."); + TRANS_LOGE(TRANS_SDK, "trans tcp manager init failed."); return SOFTBUS_ERR; } if (ClientTransAuthInit(cb) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_SDK, "client trans auth init failed."); return SOFTBUS_ERR; } if (ClientTransProxyInit(cb) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_SDK, "client trans proxy init failed."); return SOFTBUS_ERR; } if (ClientTransUdpMgrInit(cb) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_SDK, "client trans udp mgr init failed."); return SOFTBUS_ERR; } return SOFTBUS_OK; diff --git a/sdk/transmission/trans_channel/proxy/include/client_trans_pending.h b/sdk/transmission/trans_channel/proxy/include/client_trans_pending.h index 42ec50119..a8727c497 100644 --- a/sdk/transmission/trans_channel/proxy/include/client_trans_pending.h +++ b/sdk/transmission/trans_channel/proxy/include/client_trans_pending.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 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 @@ -37,4 +37,4 @@ int32_t SetPendingPacketData(uint32_t id, uint64_t seq, const TransPendData *dat #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif // CLIENT_TRANS_PENDING_H diff --git a/sdk/transmission/trans_channel/proxy/include/client_trans_proxy_file_common.h b/sdk/transmission/trans_channel/proxy/include/client_trans_proxy_file_common.h index 2d7265047..f985abe84 100644 --- a/sdk/transmission/trans_channel/proxy/include/client_trans_proxy_file_common.h +++ b/sdk/transmission/trans_channel/proxy/include/client_trans_proxy_file_common.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 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 @@ -62,5 +62,4 @@ int32_t FileUnLock(int32_t fd); #ifdef __cplusplus } #endif - -#endif \ No newline at end of file +#endif // CLIENT_TRANS_PROXY_FILE_COMMON_H diff --git a/sdk/transmission/trans_channel/proxy/include/client_trans_proxy_file_manager.h b/sdk/transmission/trans_channel/proxy/include/client_trans_proxy_file_manager.h index 60ae2c252..5a64d9e5c 100644 --- a/sdk/transmission/trans_channel/proxy/include/client_trans_proxy_file_manager.h +++ b/sdk/transmission/trans_channel/proxy/include/client_trans_proxy_file_manager.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 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 @@ -105,4 +105,4 @@ int32_t ProcessRecvFileFrameData(int32_t sessionId, int32_t channelId, const Fil #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif // CLIENT_TRANS_PROXY_FILE_MANAGER_H diff --git a/sdk/transmission/trans_channel/proxy/include/client_trans_proxy_manager.h b/sdk/transmission/trans_channel/proxy/include/client_trans_proxy_manager.h index f92dfbd2d..033c3c8e3 100644 --- a/sdk/transmission/trans_channel/proxy/include/client_trans_proxy_manager.h +++ b/sdk/transmission/trans_channel/proxy/include/client_trans_proxy_manager.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 @@ -95,4 +95,4 @@ int32_t ProcessFileFrameData(int32_t sessionId, int32_t channelId, const char *d #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif // CLIENT_TRANS_PROXY_CHANNEL_H diff --git a/sdk/transmission/trans_channel/proxy/src/client_trans_pending.c b/sdk/transmission/trans_channel/proxy/src/client_trans_pending.c index e08ae956f..4fa237348 100644 --- a/sdk/transmission/trans_channel/proxy/src/client_trans_pending.c +++ b/sdk/transmission/trans_channel/proxy/src/client_trans_pending.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 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 @@ -15,17 +15,13 @@ #include #include -#include -#include #include "client_trans_pending.h" #include "common_list.h" -#include "securec.h" #include "softbus_adapter_mem.h" #include "softbus_def.h" #include "softbus_errcode.h" -#include "softbus_type_def.h" #include "trans_log.h" typedef struct { @@ -40,13 +36,12 @@ typedef struct { static SoftBusMutex g_pendingLock; static LIST_HEAD(g_pendingList); -static bool g_Init = false; #define USECTONSEC 1000LL int32_t InitPendingPacket(void) { - if (!g_Init && SoftBusMutexInit(&g_pendingLock, NULL) != 0) { + if (SoftBusMutexInit(&g_pendingLock, NULL) != 0) { return SOFTBUS_LOCK_ERR; } return SOFTBUS_OK; @@ -119,6 +114,7 @@ EXIT: void DeletePendingPacket(uint32_t id, uint64_t seq) { if (SoftBusMutexLock(&g_pendingLock) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_SDK, "mutex lock fail"); return; } PendingPacket *pending = NULL; @@ -209,24 +205,27 @@ EXIT: int32_t SetPendingPacketData(uint32_t id, uint64_t seq, const TransPendData *data) { if (SoftBusMutexLock(&g_pendingLock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_SDK, "SetBrPendingPacket lock fail"); + TRANS_LOGE(TRANS_SDK, "mutex lock fail"); return SOFTBUS_LOCK_ERR; } PendingPacket *item = NULL; LIST_FOR_EACH_ENTRY(item, &g_pendingList, PendingPacket, node) { if (item->seq == seq && item->id == id) { - (void)SoftBusMutexLock(&item->lock); + if (SoftBusMutexLock(&item->lock) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_SDK, "mutex lock fail"); + return SOFTBUS_LOCK_ERR; + } item->finded = true; if (data != NULL) { item->data.data = data->data; item->data.len = data->len; } SoftBusCondSignal(&item->cond); - SoftBusMutexUnlock(&item->lock); - SoftBusMutexUnlock(&g_pendingLock); + (void)SoftBusMutexUnlock(&item->lock); + (void)SoftBusMutexUnlock(&g_pendingLock); return SOFTBUS_OK; } } - SoftBusMutexUnlock(&g_pendingLock); + (void)SoftBusMutexUnlock(&g_pendingLock); return SOFTBUS_ERR; } \ No newline at end of file diff --git a/sdk/transmission/trans_channel/proxy/src/client_trans_proxy_file_common.c b/sdk/transmission/trans_channel/proxy/src/client_trans_proxy_file_common.c index 75f0ffde8..ebbea5d21 100644 --- a/sdk/transmission/trans_channel/proxy/src/client_trans_proxy_file_common.c +++ b/sdk/transmission/trans_channel/proxy/src/client_trans_proxy_file_common.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 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 @@ -13,8 +13,6 @@ * limitations under the License. */ -#include -#include #include #include #include @@ -28,7 +26,6 @@ #include "softbus_adapter_timer.h" #include "softbus_def.h" #include "softbus_errcode.h" -#include "softbus_type_def.h" #include "trans_log.h" #pragma pack(push, 1) @@ -69,7 +66,7 @@ int32_t GetAndCheckRealPath(const char *filePath, char *absPath) return SOFTBUS_ERR; } - int32_t pathLength = strlen(absPath); + int32_t pathLength = (int32_t)(strlen(absPath)); if (pathLength > (MAX_FILE_PATH_NAME_LEN - 1)) { TRANS_LOGE(TRANS_FILE, "pathLength=%d is too large", pathLength); return SOFTBUS_ERR; @@ -83,7 +80,7 @@ bool CheckDestFilePathValid(const char *destFile) TRANS_LOGE(TRANS_FILE, "destFile is null"); return false; } - int32_t len = strlen(destFile); + int32_t len = (int32_t)(strlen(destFile)); if ((len == 0) || (len > MAX_FILE_PATH_NAME_LEN) || (destFile[0] == PATH_SEPARATOR)) { TRANS_LOGE(TRANS_FILE, "destFile first char is '/'"); return false; @@ -183,7 +180,7 @@ const char *TransGetFileName(const char *path) } int i; - for (i = pathLength - 1; i >= 0; i--) { + for (i = (int)(pathLength - 1); i >= 0; i--) { if (path[i] == SOFTBUS_PATH_SEPRATOR) { i++; break; @@ -294,7 +291,7 @@ int32_t FileLock(int32_t fd, int32_t type, bool isBlock) return SOFTBUS_ERR; } struct flock fl = {0}; - fl.l_type = (type == SOFTBUS_F_RDLCK ? F_RDLCK : F_WRLCK); + fl.l_type = (short)(type == SOFTBUS_F_RDLCK ? F_RDLCK : F_WRLCK); fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; diff --git a/sdk/transmission/trans_channel/proxy/src/client_trans_proxy_file_manager.c b/sdk/transmission/trans_channel/proxy/src/client_trans_proxy_file_manager.c index 5df6da454..5b19a1830 100644 --- a/sdk/transmission/trans_channel/proxy/src/client_trans_proxy_file_manager.c +++ b/sdk/transmission/trans_channel/proxy/src/client_trans_proxy_file_manager.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 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 @@ -16,7 +16,6 @@ #include #include #include -#include #include #include @@ -26,20 +25,15 @@ #include "client_trans_proxy_file_common.h" #include "client_trans_proxy_manager.h" #include "client_trans_session_manager.h" -#include "client_trans_tcp_direct_message.h" #include "securec.h" #include "softbus_adapter_errcode.h" #include "softbus_adapter_file.h" #include "softbus_adapter_mem.h" -#include "softbus_adapter_timer.h" #include "softbus_app_info.h" -#include "softbus_conn_interface.h" #include "softbus_def.h" #include "softbus_errcode.h" -#include "softbus_type_def.h" #include "softbus_utils.h" #include "trans_log.h" -#include "trans_server_proxy.h" typedef struct { const char **files; @@ -63,6 +57,7 @@ typedef struct { uint64_t checkSumCRC; char filePath[MAX_FILE_PATH_NAME_LEN]; } SingleFileInfo; + typedef struct { ListNode node; int32_t sessionId; @@ -112,6 +107,7 @@ static int32_t ProxyChannelSendFileStream(int32_t channelId, const char *data, u { ProxyChannelInfoDetail info; if (ClientTransProxyGetInfoByChannelId(channelId, &info) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_FILE, "client trans proxy get info by ChannelId fail"); return SOFTBUS_ERR; } return TransProxyPackAndSendData(channelId, data, len, &info, (SessionPktType)type); @@ -139,10 +135,12 @@ static int32_t SendFileTransResult(int32_t channelId, uint32_t seq, int32_t resu SoftBusFree(data); return ret; } + static int32_t UnpackFileTransResultFrame(const uint8_t *data, uint32_t len, uint32_t *seq, int32_t *result, uint32_t *side) { if (seq == NULL || result == NULL || side == NULL) { + TRANS_LOGE(TRANS_FILE, "param invalid"); return SOFTBUS_ERR; } if (data == NULL || len < FRAME_HEAD_LEN + FRAME_DATA_SEQ_OFFSET + FRAME_DATA_SEQ_OFFSET) { @@ -254,6 +252,7 @@ int32_t ClinetTransProxyFileManagerInit(void) } return SOFTBUS_OK; } + void ClinetTransProxyFileManagerDeinit(void) { (void)RegisterTimeoutCallback(SOFTBUS_PROXY_SENDFILE_TIMER_FUN, NULL); @@ -286,6 +285,7 @@ static int32_t SendFileAckReqAndResData(int32_t channelId, uint32_t startSeq, ui SoftBusFree(data); return ret; } + static int32_t UnpackAckReqAndResData(FileFrame *frame, uint32_t *startSeq, uint32_t *value) { if (frame == NULL || startSeq == NULL || value == NULL || frame->data == NULL) { @@ -320,6 +320,7 @@ static int64_t PackReadFileData(FileFrame *fileFrame, uint64_t readLength, uint6 uint64_t dataLen = len + FRAME_DATA_SEQ_OFFSET; fileFrame->frameLength = FRAME_HEAD_LEN + dataLen + FRAME_CRC_LEN; if (fileFrame->frameLength > PROXY_MAX_PACKET_SIZE) { + TRANS_LOGE(TRANS_FILE, "frameLength invalid. frameLength=%u", fileFrame->frameLength); return SOFTBUS_ERR; } uint16_t crc = RTU_CRC(fileFrame->fileData + FRAME_DATA_SEQ_OFFSET, len); @@ -332,12 +333,14 @@ static int64_t PackReadFileData(FileFrame *fileFrame, uint64_t readLength, uint6 } else { fileFrame->frameLength = FRAME_DATA_SEQ_OFFSET + len; if (fileFrame->frameLength > PROXY_MAX_PACKET_SIZE) { + TRANS_LOGE(TRANS_FILE, "frameLength invalid. frameLength=%u", fileFrame->frameLength); return SOFTBUS_ERR; } (*(int32_t *)(fileFrame->fileData)) = info->channelId; } return len; } + static int64_t PackReadFileRetransData(FileFrame *fileFrame, uint32_t seq, uint64_t readLength, uint64_t fileOffset, const SendListenerInfo *info) { @@ -349,6 +352,7 @@ static int64_t PackReadFileRetransData(FileFrame *fileFrame, uint32_t seq, uint6 uint64_t dataLen = len + FRAME_DATA_SEQ_OFFSET; fileFrame->frameLength = FRAME_HEAD_LEN + dataLen + FRAME_CRC_LEN; if (fileFrame->frameLength > PROXY_MAX_PACKET_SIZE) { + TRANS_LOGE(TRANS_FILE, "frameLength invalid. frameLength=%u", fileFrame->frameLength); return SOFTBUS_ERR; } uint16_t crc = RTU_CRC(fileFrame->fileData + FRAME_DATA_SEQ_OFFSET, len); @@ -365,10 +369,12 @@ static int64_t PackReadFileRetransData(FileFrame *fileFrame, uint32_t seq, uint6 } return len; } + static int32_t UnpackFileDataFrame(FileRecipientInfo *info, FileFrame *fileFrame, uint32_t *fileDataLen) { if (info->crc == APP_INFO_FILE_FEATURES_SUPPORT) { if (fileFrame->frameLength <= FRAME_HEAD_LEN + FRAME_DATA_SEQ_OFFSET + FRAME_CRC_LEN) { + TRANS_LOGE(TRANS_FILE, "frameLength invalid. frameLength=%u", fileFrame->frameLength); return SOFTBUS_TRANS_INVALID_DATA_LENGTH; } fileFrame->magic = (*(uint32_t *)(fileFrame->data)); @@ -393,6 +399,7 @@ static int32_t UnpackFileDataFrame(FileRecipientInfo *info, FileFrame *fileFrame } else { fileFrame->fileData = fileFrame->data; if (fileFrame->frameLength <= FRAME_DATA_SEQ_OFFSET) { + TRANS_LOGE(TRANS_FILE, "frameLength invalid. frameLength=%u", fileFrame->frameLength); return SOFTBUS_TRANS_INVALID_DATA_LENGTH; } fileFrame->seq = (*(uint32_t *)(fileFrame->fileData)); @@ -407,11 +414,13 @@ static int32_t RetransFileFrameBySeq(const SendListenerInfo *info, int32_t seq) return SOFTBUS_OK; } if ((info == NULL) || (seq <= 0)) { + TRANS_LOGE(TRANS_FILE, "param invalid"); return SOFTBUS_INVALID_PARAM; } FileFrame fileFrame = {0}; fileFrame.data = (uint8_t *)SoftBusCalloc(PROXY_MAX_PACKET_SIZE); if (fileFrame.data == NULL) { + TRANS_LOGE(TRANS_FILE, "data calloc fail"); return SOFTBUS_MALLOC_ERR; } fileFrame.magic = FILE_MAGIC_NUMBER; @@ -438,6 +447,7 @@ static int32_t RetransFileFrameBySeq(const SendListenerInfo *info, int32_t seq) static int32_t AckResponseDataHandle(const SendListenerInfo *info, const char *data, uint32_t len) { if (data == NULL || len != sizeof(AckResponseData)) { + TRANS_LOGE(TRANS_FILE, "data or len invalid"); return SOFTBUS_OK; } AckResponseData *resData = (AckResponseData *)data; @@ -450,7 +460,7 @@ static int32_t AckResponseDataHandle(const SendListenerInfo *info, const char *d continue; } failSeq = startSeq + i; - if (RetransFileFrameBySeq(info, failSeq) != SOFTBUS_OK) { + if (RetransFileFrameBySeq(info, (int32_t)failSeq) != SOFTBUS_OK) { return SOFTBUS_ERR; } } @@ -464,15 +474,15 @@ static char *GetFullRecvPath(const char *filePath, const char *recvRootDir) TRANS_LOGE(TRANS_FILE, "filePath or rootDir is null"); return NULL; } - int32_t rootDirLength = strlen(recvRootDir); - int32_t filePathLength = strlen(filePath); + int32_t rootDirLength = (int32_t)strlen(recvRootDir); + int32_t filePathLength = (int32_t)strlen(filePath); bool isNeedAddSep = true; if (((filePathLength > 0) && (filePath[0] == PATH_SEPARATOR)) || ((rootDirLength > 0) && (recvRootDir[rootDirLength - 1] == PATH_SEPARATOR))) { isNeedAddSep = false; } - int32_t destFullPathLength = (isNeedAddSep) ? (rootDirLength + sizeof('/') + filePathLength) : - (rootDirLength + filePathLength); + int32_t destFullPathLength = (int32_t)((isNeedAddSep) ? (rootDirLength + sizeof('/') + filePathLength) : + (rootDirLength + filePathLength)); char *recvFullPath = (char *)SoftBusCalloc(destFullPathLength + 1); if (recvFullPath == NULL) { TRANS_LOGE(TRANS_FILE, "recvFullPath is null"); @@ -550,8 +560,8 @@ static int32_t GetAbsFullPath(const char *fullPath, char *recvAbsPath, int32_t p goto EXIT_ERR; } TRANS_LOGI(TRANS_FILE, "dirPath=%s, absFullDir=%s", dirPath, absFullDir); - fileNameLength = strlen(fileName); - dirPathLength = strlen(absFullDir); + fileNameLength = (int32_t)strlen(fileName); + dirPathLength = (int32_t)strlen(absFullDir); if (pathSize < (fileNameLength + dirPathLength + 1)) { TRANS_LOGE(TRANS_FILE, "copy name is too large, dirLen=%d, fileNameLen=%d", dirPathLength, fileNameLength); @@ -652,7 +662,7 @@ static void DelSessionFileLock(ProxyFileMutexLock *sessionLock) return; } - if (SoftBusMutexLock(&g_sendFileInfoLock.lock) != 0) { + if (SoftBusMutexLock(&g_sendFileInfoLock.lock) != SOFTBUS_OK) { TRANS_LOGE(TRANS_FILE, "lock mutex failed"); return; } @@ -678,7 +688,7 @@ static int32_t AddSendListenerInfo(SendListenerInfo *info) SendListenerInfo *item = NULL; LIST_FOR_EACH_ENTRY(item, &g_sendListenerInfoList, SendListenerInfo, node) { if (item->sessionId == info->sessionId) { - SoftBusMutexUnlock(&g_sendFileInfoLock.lock); + (void)SoftBusMutexUnlock(&g_sendFileInfoLock.lock); return SOFTBUS_ALREADY_EXISTED; } } @@ -693,7 +703,10 @@ static void DelSendListenerInfo(SendListenerInfo *info) TRANS_LOGW(TRANS_FILE, "invalid param."); return; } - (void)SoftBusMutexLock(&g_sendFileInfoLock.lock); + if (SoftBusMutexLock(&g_sendFileInfoLock.lock) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_FILE, "mutex lock error."); + return; + } ListDelete(&info->node); (void)SoftBusMutexUnlock(&g_sendFileInfoLock.lock); } @@ -705,11 +718,12 @@ static int32_t PackFileTransStartInfo(FileFrame *fileFrame, const char *destFile TRANS_LOGW(TRANS_FILE, "invalid param."); return SOFTBUS_INVALID_PARAM; } - int32_t len = strlen(destFile); + int32_t len = (int32_t)strlen(destFile); if (info->crc == APP_INFO_FILE_FEATURES_SUPPORT) { uint64_t dataLen = len + FRAME_DATA_SEQ_OFFSET + sizeof(uint64_t); fileFrame->frameLength = FRAME_HEAD_LEN + dataLen; if (fileFrame->frameLength > PROXY_MAX_PACKET_SIZE) { + TRANS_LOGE(TRANS_FILE, "frameLength overSize"); return SOFTBUS_ERR; } // magic(4 byte) + dataLen(8 byte) + oneFrameLen(4 byte) + fileSize + fileName @@ -745,6 +759,7 @@ static int32_t UnpackFileTransStartInfo(FileFrame *fileFrame, const FileRecipien uint64_t fileNameLen = 0; if (info->crc == APP_INFO_FILE_FEATURES_SUPPORT) { if (fileFrame->frameLength < FRAME_HEAD_LEN + FRAME_DATA_SEQ_OFFSET) { + TRANS_LOGE(TRANS_FILE, "frameLength invalid"); return SOFTBUS_INVALID_PARAM; } // magic(4 byte) + dataLen(8 byte) + oneFrameLen(4 byte) + fileSize(8 byte) + fileName @@ -783,10 +798,8 @@ static int32_t UnpackFileTransStartInfo(FileFrame *fileFrame, const FileRecipien TRANS_LOGE(TRANS_FILE, "start info fail fileNameLen=%" PRIu64, fileNameLen); return SOFTBUS_INVALID_PARAM; } - if (fileNameData != NULL) { - if (memcpy_s(file->filePath, MAX_FILE_PATH_NAME_LEN, fileNameData, fileNameLen) != EOK) { - return SOFTBUS_MEM_ERR; - } + if (fileNameData != NULL && memcpy_s(file->filePath, MAX_FILE_PATH_NAME_LEN, fileNameData, fileNameLen) != EOK) { + return SOFTBUS_MEM_ERR; } return SOFTBUS_OK; } @@ -808,10 +821,6 @@ static int32_t GetAndCheckFileSize(const char *sourceFile, uint64_t *fileSize, u return SOFTBUS_FILE_ERR; } - if (PROXY_MAX_PACKET_SIZE <= FRAME_DATA_SEQ_OFFSET) { - TRANS_LOGE(TRANS_FILE, "size error"); - return SOFTBUS_ERR; - } uint64_t oneFrameSize = PROXY_MAX_PACKET_SIZE - FRAME_DATA_SEQ_OFFSET; if (crc == APP_INFO_FILE_FEATURES_SUPPORT) { oneFrameSize -= (FRAME_HEAD_LEN + FRAME_CRC_LEN); @@ -862,7 +871,7 @@ static int32_t SendOneFrameMiddle(SendListenerInfo *info, int32_t frameType) if (CreatePendingPacket((uint32_t)info->sessionId, (uint64_t)info->seq) != SOFTBUS_OK) { return SOFTBUS_ERR; } - info->waitSeq = info->seq; + info->waitSeq = (int32_t)(info->seq); info->waitTimeoutCount = 0; if (SendFileAckReqAndResData(info->channelId, info->seq - FILE_SEND_ACK_INTERVAL + 1, info->seq, TRANS_SESSION_FILE_ACK_REQUEST_SENT) != SOFTBUS_OK) { @@ -881,10 +890,7 @@ static int32_t SendOneFrameRear(SendListenerInfo *info, int32_t frameType) if (info == NULL) { return SOFTBUS_INVALID_PARAM; } - if (info->crc != APP_INFO_FILE_FEATURES_SUPPORT) { - return SOFTBUS_OK; - } - if (frameType == TRANS_SESSION_FILE_ONLYONE_FRAME) { + if (info->crc != APP_INFO_FILE_FEATURES_SUPPORT || frameType == TRANS_SESSION_FILE_ONLYONE_FRAME) { return SOFTBUS_OK; } int32_t ret; @@ -934,9 +940,6 @@ static int32_t SendOneFrame(const SendListenerInfo *sendInfo, const FileFrame *f TRANS_LOGW(TRANS_FILE, "invalid param."); return SOFTBUS_INVALID_PARAM; } - if (fileFrame->data == NULL) { - return SOFTBUS_ERR; - } if (SendOneFrameFront((SendListenerInfo *)sendInfo, fileFrame->frameType) != SOFTBUS_OK) { return SOFTBUS_ERR; } @@ -974,7 +977,7 @@ static int32_t SendFileCrcCheckSum(const SendListenerInfo *info) if (data == NULL) { return SOFTBUS_MALLOC_ERR; } - uint32_t seq = info->seq + 1; + uint32_t seq = info->seq + 1; //magic(4 byte) + dataLen(8 byte) + seq(4 byte) + crc(8 byte) (*(uint32_t *)data) = FILE_MAGIC_NUMBER; (*(uint64_t *)(data + FRAME_MAGIC_OFFSET)) = (FRAME_DATA_SEQ_OFFSET + sizeof(info->checkSumCRC)); (*(uint32_t *)(data + FRAME_HEAD_LEN)) = seq; @@ -1203,14 +1206,17 @@ static int32_t SendFileList(int32_t channelId, const char **destFile, uint32_t f static bool IsValidFileString(const char *str[], uint32_t fileNum, uint32_t maxLen) { if (str == NULL || fileNum == 0) { + TRANS_LOGE(TRANS_FILE, "param invalid"); return false; } for (uint32_t i = 0; i < fileNum; i++) { if (str[i] == NULL) { + TRANS_LOGE(TRANS_FILE, "file string invalid"); return false; } uint32_t len = strlen(str[i]); if (len == 0 || len >= maxLen) { + TRANS_LOGE(TRANS_FILE, "len invalid"); return false; } } @@ -1601,6 +1607,7 @@ static FileRecipientInfo *CreateNewRecipient(int32_t sessionId, int32_t channelI } info = (FileRecipientInfo *)SoftBusCalloc(sizeof(FileRecipientInfo)); if (info == NULL) { + TRANS_LOGE(TRANS_FILE, "info calloc failed"); return NULL; } char sessionName[SESSION_NAME_SIZE_MAX] = {0}; @@ -1674,6 +1681,7 @@ static int32_t GetFileInfoByStartFrame(const FileFrame *fileFrame, const FileRec static FileRecipientInfo *GetRecipientInCreateFileRef(int32_t sessionId, int32_t channelId) { if (SoftBusMutexLock(&g_recvFileInfoLock.lock) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_FILE, "mutex lock fail"); return NULL; } FileRecipientInfo *recipient = GetRecipientNoLock(sessionId); @@ -1700,11 +1708,13 @@ static FileRecipientInfo *GetRecipientInCreateFileRef(int32_t sessionId, int32_t static FileRecipientInfo *GetRecipientInProcessRef(int32_t sessionId) { if (SoftBusMutexLock(&g_recvFileInfoLock.lock) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_FILE, "mutex lock fail"); return NULL; } FileRecipientInfo *recipient = GetRecipientNoLock(sessionId); if (recipient == NULL || recipient->recvState == TRANS_FILE_RECV_IDLE_STATE) { - SoftBusMutexUnlock(&g_recvFileInfoLock.lock); + TRANS_LOGE(TRANS_FILE, "get recipient no lock fail"); + (void)SoftBusMutexUnlock(&g_recvFileInfoLock.lock); return NULL; } if (recipient->recvState == TRANS_FILE_RECV_START_STATE) { @@ -1718,11 +1728,13 @@ static FileRecipientInfo *GetRecipientInProcessRef(int32_t sessionId) static FileRecipientInfo *GetRecipientInfo(int32_t sessionId) { if (SoftBusMutexLock(&g_recvFileInfoLock.lock) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_FILE, "mutex lock fail"); return NULL; } FileRecipientInfo *recipient = GetRecipientNoLock(sessionId); if (recipient == NULL) { - SoftBusMutexUnlock(&g_recvFileInfoLock.lock); + TRANS_LOGE(TRANS_FILE, "get recipient no lock fail"); + (void)SoftBusMutexUnlock(&g_recvFileInfoLock.lock); return NULL; } if (recipient->recvState == TRANS_FILE_RECV_START_STATE) { @@ -1743,9 +1755,11 @@ static int32_t CreateFileFromFrame(int32_t sessionId, int32_t channelId, const F int32_t result = SOFTBUS_ERR; SingleFileInfo *file = (SingleFileInfo *)SoftBusCalloc(sizeof(SingleFileInfo)); if (file == NULL) { + TRANS_LOGE(TRANS_FILE, "file calloc fail"); goto EXIT_ERR; } if (GetFileInfoByStartFrame(fileFrame, recipient, file) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_FILE, "get file info by start frame fail"); goto EXIT_ERR; } TRANS_LOGI(TRANS_FILE, "null filePath%s, seq=%u", file->filePath, file->seq); @@ -1831,9 +1845,9 @@ static int32_t ProcessOneFrameCRC(const FileFrame *frame, uint32_t dataLen, Sing uint32_t bit = seq % FILE_SEND_ACK_INTERVAL; bit = ((bit == 0) ? (FILE_SEND_ACK_INTERVAL - 1) : (bit - 1)); if (seq >= fileInfo->startSeq) { - int32_t seqDiff = seq - fileInfo->seq - 1; + int32_t seqDiff = (int32_t)(seq - fileInfo->seq - 1); - int64_t bytesToWrite = seqDiff * fileInfo->oneFrameLen; + int64_t bytesToWrite = (int64_t)(seqDiff * fileInfo->oneFrameLen); if (MAX_FILE_SIZE < bytesToWrite) { TRANS_LOGE(TRANS_FILE, "WriteEmptyFrame bytesToWrite is too large, bytesToWrite=%" PRIu64, bytesToWrite); @@ -1938,6 +1952,7 @@ static int32_t WriteFrameToFile(int32_t sessionId, const FileFrame *fileFrame) { FileRecipientInfo *recipient = GetRecipientInProcessRef(sessionId); if (recipient == NULL) { + TRANS_LOGE(TRANS_FILE, "get recipient in process ref fail"); return SOFTBUS_NOT_FIND; } int32_t result = SOFTBUS_ERR; @@ -1972,7 +1987,10 @@ static int32_t WriteFrameToFile(int32_t sessionId, const FileFrame *fileFrame) (fileFrame->frameType == TRANS_SESSION_FILE_ONLYONE_FRAME)) { TRANS_LOGI(TRANS_FILE, "process last frame, seq=%u", fileFrame->seq); SetRecipientRecvState(recipient, TRANS_FILE_RECV_IDLE_STATE); - (void)SoftBusMutexLock(&g_recvFileInfoLock.lock); + if (SoftBusMutexLock(&g_recvFileInfoLock.lock) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_FILE, "mutex lock fail"); + return SOFTBUS_LOCK_ERR; + } (void)FileUnLock(fileInfo->fileFd); SoftBusCloseFile(fileInfo->fileFd); fileInfo->fileFd = INVALID_FD; @@ -2001,6 +2019,7 @@ static int32_t ProcessFileListData(int32_t sessionId, const FileFrame *frame) { FileRecipientInfo *recipient = GetRecipientInfo(sessionId); if (recipient == NULL) { + TRANS_LOGE(TRANS_FILE, "get recipient info fail"); return SOFTBUS_NOT_FIND; } int32_t ret = SOFTBUS_ERR; @@ -2112,7 +2131,7 @@ static int32_t ProcessFileSendResult(int32_t sessionId, uint32_t seq, int32_t re static int32_t ProcessFileTransResult(int32_t sessionId, const FileFrame *frame) { if (frame == NULL) { - TRANS_LOGW(TRANS_FILE, "invalid param."); + TRANS_LOGE(TRANS_FILE, "invalid param."); return SOFTBUS_INVALID_PARAM; } TRANS_LOGI(TRANS_FILE, "proxy channel send file result. sessionId=%d", sessionId); @@ -2120,6 +2139,7 @@ static int32_t ProcessFileTransResult(int32_t sessionId, const FileFrame *frame) int32_t result; uint32_t side; if (UnpackFileTransResultFrame(frame->data, frame->frameLength, &seq, &result, &side) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_FILE, "file trans fail"); return SOFTBUS_ERR; } if (side == IS_RECV_RESULT) { @@ -2133,13 +2153,14 @@ static int32_t ProcessFileTransResult(int32_t sessionId, const FileFrame *frame) static int32_t ProcessCrcCheckSumData(int32_t sessionId, const FileFrame *frame) { if (frame == NULL) { - TRANS_LOGW(TRANS_FILE, "invalid param."); + TRANS_LOGE(TRANS_FILE, "invalid param."); return SOFTBUS_INVALID_PARAM; } TRANS_LOGI(TRANS_FILE, "proxy channel recv file crc data. sessionId=%d, frameLen=%d", sessionId, frame->frameLength); FileRecipientInfo *recipient = GetRecipientInProcessRef(sessionId); if (recipient == NULL) { + TRANS_LOGE(TRANS_FILE, "recipient invalid"); return SOFTBUS_NOT_FIND; } int32_t result = UnpackFileCrcCheckSum(recipient, (FileFrame *)frame); @@ -2158,7 +2179,7 @@ static int32_t ProcessCrcCheckSumData(int32_t sessionId, const FileFrame *frame) static int32_t ProcessFileAckRequest(int32_t sessionId, const FileFrame *frame) { if (frame == NULL) { - TRANS_LOGW(TRANS_FILE, "invalid param."); + TRANS_LOGE(TRANS_FILE, "invalid param."); return SOFTBUS_INVALID_PARAM; } TRANS_LOGI(TRANS_FILE, "proxy channel recv file ack request. sessionId=%d, len=%u", @@ -2196,7 +2217,7 @@ static int32_t ProcessFileAckRequest(int32_t sessionId, const FileFrame *frame) static int32_t ProcessFileAckResponse(int32_t sessionId, const FileFrame *frame) { if ((frame == NULL) || (frame->data == NULL) || (frame->frameLength == 0)) { - TRANS_LOGW(TRANS_FILE, "invalid param."); + TRANS_LOGE(TRANS_FILE, "invalid param."); return SOFTBUS_INVALID_PARAM; } AckResponseData *data = (AckResponseData *)SoftBusCalloc(sizeof(AckResponseData)); @@ -2242,7 +2263,7 @@ static int32_t ProcessFileAckResponse(int32_t sessionId, const FileFrame *frame) int32_t ProcessRecvFileFrameData(int32_t sessionId, int32_t channelId, const FileFrame *oneFrame) { if (oneFrame == NULL) { - TRANS_LOGW(TRANS_FILE, "invalid param."); + TRANS_LOGE(TRANS_FILE, "invalid param."); return SOFTBUS_INVALID_PARAM; } if (oneFrame->frameLength > PROXY_MAX_PACKET_SIZE) { diff --git a/sdk/transmission/trans_channel/proxy/src/client_trans_proxy_manager.c b/sdk/transmission/trans_channel/proxy/src/client_trans_proxy_manager.c index 543ec57e3..156b1b451 100644 --- a/sdk/transmission/trans_channel/proxy/src/client_trans_proxy_manager.c +++ b/sdk/transmission/trans_channel/proxy/src/client_trans_proxy_manager.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 @@ -15,21 +15,13 @@ #include "client_trans_proxy_manager.h" -#include #include #include #include "anonymizer.h" -#include "client_trans_pending.h" #include "client_trans_proxy_file_manager.h" -#include "client_trans_session_manager.h" #include "client_trans_tcp_direct_message.h" -#include "softbus_adapter_errcode.h" -#include "softbus_adapter_file.h" #include "softbus_adapter_mem.h" -#include "softbus_adapter_timer.h" -#include "softbus_app_info.h" -#include "softbus_conn_interface.h" #include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_feature_config.h" @@ -117,6 +109,7 @@ static int32_t ClientTransProxyListInit() return SOFTBUS_ERR; } if (RegisterTimeoutCallback(SOFTBUS_PROXYSLICE_TIMER_FUN, ClientTransProxySliceTimerProc) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_INIT, "register timeout fail"); DestroySoftBusList(g_proxyChannelInfoList); DestroySoftBusList(g_channelSliceProcessorList); return SOFTBUS_ERR; @@ -256,10 +249,12 @@ static ClientProxyChannelInfo* ClientTransProxyCreateChannelInfo(const ChannelIn { ClientProxyChannelInfo *info = (ClientProxyChannelInfo*)SoftBusMalloc(sizeof(ClientProxyChannelInfo)); if (info == NULL) { + TRANS_LOGE(TRANS_SDK, "info is null"); return NULL; } if (memcpy_s(info->detail.sessionKey, SESSION_KEY_LENGTH, channel->sessionKey, SESSION_KEY_LENGTH) != EOK) { SoftBusFree(info); + TRANS_LOGE(TRANS_SDK, "sessionKey memcpy fail"); return NULL; } info->channelId = channel->channelId; @@ -344,7 +339,6 @@ int32_t ClientTransProxySessionDataLenCheck(uint32_t dataLen, SessionPktType typ static int32_t ClientTransProxyDecryptPacketData(int32_t channelId, int32_t seq, ClientProxyDataInfo *dataInfo) { - int32_t ret = SOFTBUS_ERR; ProxyChannelInfoDetail info; if (ClientTransProxyGetInfoByChannelId(channelId, &info) != SOFTBUS_OK) { return SOFTBUS_ERR; @@ -355,6 +349,7 @@ static int32_t ClientTransProxyDecryptPacketData(int32_t channelId, int32_t seq, TRANS_LOGE(TRANS_SDK, "memcpy key error."); return SOFTBUS_ERR; } + int32_t ret = SOFTBUS_ERR; ret = SoftBusDecryptDataWithSeq(&cipherKey, dataInfo->inData, dataInfo->inLen, dataInfo->outData, &(dataInfo->outLen), seq); (void)memset_s(&cipherKey, sizeof(AesGcmCipherKey), 0, sizeof(AesGcmCipherKey)); @@ -429,7 +424,7 @@ int32_t ClientTransProxyNotifySession(int32_t channelId, ClientTransProxySendSessionAck(channelId, seq); return g_sessionCb.OnDataReceived(channelId, CHANNEL_TYPE_PROXY, data, len, flags); case TRANS_SESSION_ACK: - return ClientTransProxyProcSendMsgAck(channelId, data, len); + return (int32_t)(ClientTransProxyProcSendMsgAck(channelId, data, len)); case TRANS_SESSION_BYTES: case TRANS_SESSION_FILE_FIRST_FRAME: case TRANS_SESSION_FILE_ONGOINE_FRAME: @@ -483,7 +478,7 @@ static int32_t ClientTransProxyProcessSessionData(int32_t channelId, const Packe return SOFTBUS_ERR; } - TRANS_LOGI(TRANS_SDK, "ProcessData debug: outlen=%d", dataInfo.outLen); + TRANS_LOGD(TRANS_SDK, "ProcessData debug: outlen=%d", dataInfo.outLen); if (ClientTransProxyNotifySession(channelId, (SessionPktType)dataHead->flags, dataHead->seq, (const char *)dataInfo.outData, dataInfo.outLen) != SOFTBUS_OK) { TRANS_LOGE(TRANS_SDK, "process data err"); @@ -510,8 +505,9 @@ static int32_t ClientTransProxyNoSubPacketProc(int32_t channelId, const char *da TRANS_LOGE(TRANS_SDK, "invalid dataLen=%d", head->dataLen); return SOFTBUS_ERR; } - TRANS_LOGI(TRANS_SDK, "NoSubPacketProc dataLen=%d inputLen=%d", head->dataLen, len); + TRANS_LOGD(TRANS_SDK, "NoSubPacketProc dataLen=%d inputLen=%d", head->dataLen, len); if (head->dataLen + sizeof(PacketHead) != len) { + TRANS_LOGE(TRANS_SDK, "dataLen error"); return SOFTBUS_ERR; } int32_t ret = ClientTransProxyProcessSessionData(channelId, head, data + sizeof(PacketHead)); @@ -735,7 +731,7 @@ static int32_t ClientTransProxySliceProc(int32_t channelId, const char *data, ui uint32_t dataLen = len - sizeof(SliceHead); if (headSlice.sliceNum == 1) { // no sub packets - TRANS_LOGI(TRANS_SDK, "no sub packets proc"); + TRANS_LOGI(TRANS_SDK, "no sub packets proc, channelId=%d", channelId); return ClientTransProxyNoSubPacketProc(channelId, data + sizeof(SliceHead), dataLen); } else { TRANS_LOGI(TRANS_SDK, "sub packets proc sliceNum=%d", headSlice.sliceNum); @@ -762,6 +758,7 @@ static void ClientTransProxySliceTimerProc(void) if (removeNode->processor[i].active == true) { removeNode->processor[i].timeout++; if (removeNode->processor[i].timeout >= SLICE_PACKET_TIMEOUT) { + TRANS_LOGE(TRANS_SDK, "timeout = %d", removeNode->processor[i].timeout); ClientTransProxyClearProcessor(&removeNode->processor[i]); } } @@ -847,7 +844,7 @@ static int32_t ClientTransProxyPackBytes(int32_t channelId, ClientProxyDataInfo pktHead->magicNumber = MAGIC_NUMBER; pktHead->seq = seq; pktHead->flags = flag; - pktHead->dataLen = (int32_t)dataInfo->outLen - sizeof(PacketHead); + pktHead->dataLen = (int32_t)((int32_t)dataInfo->outLen - sizeof(PacketHead)); ClientPackPacketHead(pktHead); return SOFTBUS_OK; @@ -870,16 +867,19 @@ static int32_t SessionPktTypeToProxyIndex(SessionPktType packetType) int32_t TransProxyPackAndSendData(int32_t channelId, const void *data, uint32_t len, ProxyChannelInfoDetail* info, SessionPktType pktType) { + if (data == NULL || info == NULL) { + return SOFTBUS_INVALID_PARAM; + } ClientProxyDataInfo dataInfo = {(uint8_t*)data, len, (uint8_t*)data, len}; if (ClientTransProxyPackBytes(channelId, &dataInfo, info->sequence, info->sessionKey, pktType) != SOFTBUS_OK) { TRANS_LOGE(TRANS_SDK, "ClientTransProxyPackBytes error, channelId=%d", channelId); return SOFTBUS_ERR; } - int32_t sliceNum = (dataInfo.outLen + SLICE_LEN - 1) / SLICE_LEN; + int32_t sliceNum = (int32_t)((dataInfo.outLen + SLICE_LEN - 1) / SLICE_LEN); for (int i = 0; i < sliceNum; i++) { - int32_t dataLen = (i == (sliceNum - 1)) ? (dataInfo.outLen - i * SLICE_LEN) : SLICE_LEN; - int32_t offset = i * SLICE_LEN; + int32_t dataLen = (int32_t)((i == (sliceNum - 1)) ? (dataInfo.outLen - i * SLICE_LEN) : SLICE_LEN); + int32_t offset = (int32_t)(i * SLICE_LEN); uint8_t* sliceData = SoftBusMalloc(dataLen + sizeof(SliceHead)); if (sliceData == NULL) { @@ -945,6 +945,5 @@ int32_t TransProxyChannelSendMessage(int32_t channelId, const void *data, uint32 if (ret != SOFTBUS_OK) { return SOFTBUS_ERR; } - return ProcPendingPacket(channelId, info.sequence, PENDING_TYPE_PROXY); } diff --git a/sdk/transmission/trans_channel/qos/include/client_qos_manager.h b/sdk/transmission/trans_channel/qos/include/client_qos_manager.h index ef1ec9bc6..be9e4a961 100644 --- a/sdk/transmission/trans_channel/qos/include/client_qos_manager.h +++ b/sdk/transmission/trans_channel/qos/include/client_qos_manager.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 @@ -24,5 +24,5 @@ extern "C" { int32_t ClientQosReport(int32_t channelId, int32_t chanType, int32_t appType, int32_t quality); #ifdef __cplusplus } -#endif -#endif \ No newline at end of file +#endif /* __cplusplus */ +#endif //SOFTBUS_CLIENT_QOS_MANAGER_H \ No newline at end of file diff --git a/sdk/transmission/trans_channel/tcp_direct/include/client_trans_tcp_direct_callback.h b/sdk/transmission/trans_channel/tcp_direct/include/client_trans_tcp_direct_callback.h index bceebdb2d..15c4be32c 100644 --- a/sdk/transmission/trans_channel/tcp_direct/include/client_trans_tcp_direct_callback.h +++ b/sdk/transmission/trans_channel/tcp_direct/include/client_trans_tcp_direct_callback.h @@ -44,4 +44,4 @@ int32_t ClientTransTdcOnDataReceived(int32_t channelId, } #endif /* __cplusplus */ #endif /* __cplusplus */ -#endif +#endif //SOFTBUS_TCP_DIRECT_CALLBACK_H diff --git a/sdk/transmission/trans_channel/tcp_direct/include/client_trans_tcp_direct_manager.h b/sdk/transmission/trans_channel/tcp_direct/include/client_trans_tcp_direct_manager.h index 4d7e148fe..3ab7fad2a 100644 --- a/sdk/transmission/trans_channel/tcp_direct/include/client_trans_tcp_direct_manager.h +++ b/sdk/transmission/trans_channel/tcp_direct/include/client_trans_tcp_direct_manager.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 diff --git a/sdk/transmission/trans_channel/tcp_direct/src/client_trans_tcp_direct_callback.c b/sdk/transmission/trans_channel/tcp_direct/src/client_trans_tcp_direct_callback.c index 5a235a901..e36ae5032 100644 --- a/sdk/transmission/trans_channel/tcp_direct/src/client_trans_tcp_direct_callback.c +++ b/sdk/transmission/trans_channel/tcp_direct/src/client_trans_tcp_direct_callback.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 @@ -17,7 +17,6 @@ #include -#include "session.h" #include "softbus_def.h" #include "softbus_errcode.h" #include "client_trans_tcp_direct_manager.h" diff --git a/sdk/transmission/trans_channel/tcp_direct/src/client_trans_tcp_direct_listener.c b/sdk/transmission/trans_channel/tcp_direct/src/client_trans_tcp_direct_listener.c index 4e7bba303..f63edd028 100644 --- a/sdk/transmission/trans_channel/tcp_direct/src/client_trans_tcp_direct_listener.c +++ b/sdk/transmission/trans_channel/tcp_direct/src/client_trans_tcp_direct_listener.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 @@ -17,18 +17,16 @@ #include #include +#include #include "client_trans_tcp_direct_callback.h" #include "client_trans_tcp_direct_manager.h" #include "client_trans_tcp_direct_message.h" #include "softbus_adapter_thread.h" #include "softbus_base_listener.h" -#include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_socket.h" -#include "softbus_type_def.h" #include "trans_log.h" -#include "trans_pending_pkt.h" typedef struct { SoftBusMutex lock; @@ -49,7 +47,6 @@ static void TdcLockInit(void) } g_lock.lockInit = true; } - return; } static int32_t ClientTdcOnConnectEvent(ListenerModule module, int cfd, const ConnectOption *clientAddr) @@ -64,6 +61,7 @@ static int32_t ClientTdcOnDataEvent(ListenerModule module, int events, int32_t f { (void)module; TcpDirectChannelInfo channel; + (void)memset_s(&channel, sizeof(TcpDirectChannelInfo), 0, sizeof(TcpDirectChannelInfo)); if (TransTdcGetInfoByFd(fd, &channel) == NULL) { TRANS_LOGE(TRANS_SDK, "can not match fd. fd=%d", fd); return SOFTBUS_ERR; @@ -73,6 +71,7 @@ static int32_t ClientTdcOnDataEvent(ListenerModule module, int events, int32_t f int32_t channelId = channel.channelId; int32_t ret = TransTdcRecvData(channelId); if (ret == SOFTBUS_DATA_NOT_ENOUGH) { + TRANS_LOGE(TRANS_SDK, "client channelId=%d process data fail, SOFTBUS_DATA_NOT_ENOUGH,", channelId); return SOFTBUS_OK; } if (ret != SOFTBUS_OK) { @@ -117,6 +116,7 @@ int32_t TransTdcCreateListener(int32_t fd) void TransTdcReleaseFd(int32_t fd) { if (fd < 0) { + TRANS_LOGI(TRANS_SDK, "fd less than zero"); return; } DelTrigger(DIRECT_CHANNEL_CLIENT, fd, READ_TRIGGER); @@ -126,6 +126,7 @@ void TransTdcReleaseFd(int32_t fd) int32_t TransTdcStopRead(int32_t fd) { if (fd < 0) { + TRANS_LOGI(TRANS_SDK, "fd less than zero"); return SOFTBUS_OK; } return DelTrigger(DIRECT_CHANNEL_CLIENT, fd, READ_TRIGGER); diff --git a/sdk/transmission/trans_channel/tcp_direct/src/client_trans_tcp_direct_manager.c b/sdk/transmission/trans_channel/tcp_direct/src/client_trans_tcp_direct_manager.c index e053d0bdb..b469d34aa 100644 --- a/sdk/transmission/trans_channel/tcp_direct/src/client_trans_tcp_direct_manager.c +++ b/sdk/transmission/trans_channel/tcp_direct/src/client_trans_tcp_direct_manager.c @@ -20,7 +20,6 @@ #include "client_trans_tcp_direct_callback.h" #include "client_trans_tcp_direct_listener.h" #include "softbus_adapter_mem.h" -#include "softbus_base_listener.h" #include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_socket.h" @@ -34,14 +33,22 @@ static SoftBusList *g_tcpDirectChannelInfoList = NULL; -TcpDirectChannelInfo *TransTdcGetInfoById(int32_t channelId, TcpDirectChannelInfo *info) +static bool CheckInfoAndMutexLock(TcpDirectChannelInfo *info) { if (info == NULL) { TRANS_LOGE(TRANS_SDK, "param invalid."); - return NULL; + return false; } if (SoftBusMutexLock(&g_tcpDirectChannelInfoList->lock) != SOFTBUS_OK) { TRANS_LOGE(TRANS_SDK, "lock failed"); + return false; + } + return true; +} + +TcpDirectChannelInfo *TransTdcGetInfoById(int32_t channelId, TcpDirectChannelInfo *info) +{ + if (!CheckInfoAndMutexLock(info)) { return NULL; } @@ -60,12 +67,7 @@ TcpDirectChannelInfo *TransTdcGetInfoById(int32_t channelId, TcpDirectChannelInf TcpDirectChannelInfo *TransTdcGetInfoByIdWithIncSeq(int32_t channelId, TcpDirectChannelInfo *info) { - if (info == NULL) { - TRANS_LOGE(TRANS_SDK, "param invalid."); - return NULL; - } - if (SoftBusMutexLock(&g_tcpDirectChannelInfoList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_SDK, "lock failed"); + if (!CheckInfoAndMutexLock(info)) { return NULL; } @@ -85,12 +87,7 @@ TcpDirectChannelInfo *TransTdcGetInfoByIdWithIncSeq(int32_t channelId, TcpDirect TcpDirectChannelInfo *TransTdcGetInfoByFd(int32_t fd, TcpDirectChannelInfo *info) { - if (info == NULL) { - TRANS_LOGE(TRANS_SDK, "param invalid."); - return NULL; - } - if (SoftBusMutexLock(&g_tcpDirectChannelInfoList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_SDK, "lock failed"); + if (!CheckInfoAndMutexLock(info)) { return NULL; } @@ -153,6 +150,7 @@ static TcpDirectChannelInfo *TransGetNewTcpChannel(const ChannelInfo *channel) item->detail.channelType = channel->channelType; if (memcpy_s(item->detail.sessionKey, SESSION_KEY_LENGTH, channel->sessionKey, SESSION_KEY_LENGTH) != EOK) { SoftBusFree(item); + TRANS_LOGE(TRANS_SDK, "sessionKey copy failed"); return NULL; } return item; diff --git a/sdk/transmission/trans_channel/tcp_direct/src/client_trans_tcp_direct_message.c b/sdk/transmission/trans_channel/tcp_direct/src/client_trans_tcp_direct_message.c index b152e9610..67b757af7 100644 --- a/sdk/transmission/trans_channel/tcp_direct/src/client_trans_tcp_direct_message.c +++ b/sdk/transmission/trans_channel/tcp_direct/src/client_trans_tcp_direct_message.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 @@ -15,7 +15,6 @@ #include "client_trans_tcp_direct_message.h" -#include #include #include "client_trans_tcp_direct_callback.h" @@ -95,7 +94,10 @@ static int32_t TransTdcEncryptWithSeq(const char *sessionKey, int32_t seqNum, co return SOFTBUS_ERR; } int ret = SoftBusEncryptDataWithSeq(&cipherKey, (unsigned char*)in, inLen, (unsigned char*)out, outLen, seqNum); - (void)memset_s(&cipherKey, sizeof(AesGcmCipherKey), 0, sizeof(AesGcmCipherKey)); + if (memset_s(&cipherKey, sizeof(AesGcmCipherKey), 0, sizeof(AesGcmCipherKey)) != EOK) { + TRANS_LOGE(TRANS_SDK, "memset cipherKey failed."); + return SOFTBUS_MEM_ERR; + } if (ret != SOFTBUS_OK || *outLen != inLen + OVERHEAD_LEN) { TRANS_LOGE(TRANS_SDK, "encrypt error."); return SOFTBUS_ENCRYPT_ERR; @@ -161,7 +163,7 @@ static char *TransTdcPackData(const TcpDirectChannelInfo *channel, const char *d static int32_t TransTdcProcessPostData(const TcpDirectChannelInfo *channel, const char *data, uint32_t len, int32_t flags) { - uint32_t outLen; + uint32_t outLen = 0; char *buf = TransTdcPackData(channel, data, len, flags, &outLen); if (buf == NULL) { TRANS_LOGE(TRANS_SDK, "failed to pack bytes."); @@ -248,7 +250,7 @@ static uint32_t TransGetDataBufSize(void) #define SLICE_HEAD_LEN 16 static int32_t TransGetDataBufMaxSize(void) { - uint32_t maxLen; + uint32_t maxLen = 0; if (SoftbusGetConfig(SOFTBUS_INT_MAX_BYTES_NEW_LENGTH, (unsigned char *)&maxLen, sizeof(maxLen)) != SOFTBUS_OK) { TRANS_LOGE(TRANS_SDK, "get config err"); return SOFTBUS_ERR; @@ -260,6 +262,7 @@ static int32_t TransGetDataBufMaxSize(void) int32_t TransAddDataBufNode(int32_t channelId, int32_t fd) { if (g_tcpDataList == NULL) { + TRANS_LOGE(TRANS_SDK, "g_tcpDataList is null."); return SOFTBUS_ERR; } ClientDataBuf *node = (ClientDataBuf *)SoftBusCalloc(sizeof(ClientDataBuf)); @@ -512,7 +515,7 @@ static int32_t TransTdcProcAllData(int32_t channelId) static int32_t TransClientGetTdcDataBufByChannel(int32_t channelId, int32_t *fd, size_t *len) { if (fd == NULL || len == NULL) { - TRANS_LOGW(TRANS_SDK, "invalid param."); + TRANS_LOGE(TRANS_SDK, "invalid param."); return SOFTBUS_ERR; } @@ -542,7 +545,7 @@ static int32_t TransClientGetTdcDataBufByChannel(int32_t channelId, int32_t *fd, static int32_t TransClientUpdateTdcDataBufWInfo(int32_t channelId, char *recvBuf, int32_t recvLen) { if (recvBuf == NULL) { - TRANS_LOGW(TRANS_SDK, "invalid param."); + TRANS_LOGE(TRANS_SDK, "invalid param."); return SOFTBUS_ERR; } if (g_tcpDataList == NULL) { @@ -573,6 +576,7 @@ static int32_t TransClientUpdateTdcDataBufWInfo(int32_t channelId, char *recvBuf } item->w += recvLen; (void)SoftBusMutexUnlock(&g_tcpDataList->lock); + TRANS_LOGI(TRANS_SDK, "client updata tdc data success", channelId); return SOFTBUS_OK; } (void)SoftBusMutexUnlock(&g_tcpDataList->lock); @@ -605,6 +609,7 @@ int32_t TransTdcRecvData(int32_t channelId) TRANS_LOGE(TRANS_SDK, "client channelId=%d recv data failed,recvLen=%d.", channelId, recvLen); return SOFTBUS_ERR; } else if (recvLen == 0) { + SoftBusFree(recvBuf); return SOFTBUS_DATA_NOT_ENOUGH; } @@ -621,13 +626,16 @@ int32_t TransTdcRecvData(int32_t channelId) int32_t TransDataListInit(void) { if (g_tcpDataList != NULL) { + TRANS_LOGI(TRANS_SDK, "g_tcpDataList already init"); return SOFTBUS_OK; } if (TransGetDataBufMaxSize() != SOFTBUS_OK) { + TRANS_LOGE(TRANS_SDK, "TransGetDataBufMaxSize failed"); return SOFTBUS_ERR; } g_tcpDataList = CreateSoftBusList(); if (g_tcpDataList == NULL) { + TRANS_LOGE(TRANS_SDK, "g_tcpDataList creat list failed"); return SOFTBUS_ERR; } return SOFTBUS_OK; diff --git a/sdk/transmission/trans_channel/udp/common/src/client_trans_udp_manager.c b/sdk/transmission/trans_channel/udp/common/src/client_trans_udp_manager.c index 02d47ffff..3c820e01c 100644 --- a/sdk/transmission/trans_channel/udp/common/src/client_trans_udp_manager.c +++ b/sdk/transmission/trans_channel/udp/common/src/client_trans_udp_manager.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 @@ -18,14 +18,12 @@ #include #include "client_trans_file.h" #include "client_trans_file_listener.h" -#include "client_trans_session_manager.h" #include "client_trans_stream.h" #include "nstackx_dfile.h" #include "securec.h" #include "softbus_adapter_mem.h" #include "softbus_def.h" #include "softbus_errcode.h" -#include "softbus_log_old.h" #include "softbus_utils.h" #include "trans_log.h" #include "trans_server_proxy.h" @@ -99,7 +97,10 @@ int32_t TransGetUdpChannel(int32_t channelId, UdpChannel *channel) TRANS_LOGE(TRANS_INIT, "udp channel manager hasn't init."); return SOFTBUS_ERR; } - + if (channel == NULL) { + TRANS_LOGE(TRANS_INIT, "param invalid"); + return SOFTBUS_INVALID_PARAM; + } if (SoftBusMutexLock(&(g_udpChannelMgr->lock)) != 0) { TRANS_LOGE(TRANS_SDK, "lock failed"); return SOFTBUS_LOCK_ERR; diff --git a/sdk/transmission/trans_channel/udp/file/src/client_trans_file.c b/sdk/transmission/trans_channel/udp/file/src/client_trans_file.c index eb87b2065..658188450 100644 --- a/sdk/transmission/trans_channel/udp/file/src/client_trans_file.c +++ b/sdk/transmission/trans_channel/udp/file/src/client_trans_file.c @@ -23,7 +23,6 @@ #include "softbus_adapter_thread.h" #include "softbus_def.h" #include "softbus_errcode.h" -#include "softbus_utils.h" #include "trans_log.h" #define DEFAULT_KEY_LENGTH 32 @@ -91,15 +90,18 @@ static void FileSendListener(int32_t dfileId, DFileMsgType msgType, const DFileM TRANS_LOGI(TRANS_FILE, "send dfileId=%d type=%d", dfileId, msgType); if (msgData == NULL || msgType == DFILE_ON_BIND || msgType == DFILE_ON_SESSION_IN_PROGRESS || msgType == DFILE_ON_SESSION_TRANSFER_RATE) { + TRANS_LOGE(TRANS_SDK, "param invalid"); return; } UdpChannel udpChannel; (void)memset_s(&udpChannel, sizeof(UdpChannel), 0, sizeof(UdpChannel)); if (TransGetUdpChannelByFileId(dfileId, &udpChannel) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_SDK, "trans get udp channel failed"); return; } if (msgType == DFILE_ON_CONNECT_SUCCESS) { g_udpChannelMgrCb->OnUdpChannelOpened(udpChannel.channelId); + TRANS_LOGE(TRANS_SDK, "msgType failed"); return; } @@ -111,6 +113,7 @@ static void FileSendListener(int32_t dfileId, DFileMsgType msgType, const DFileM int32_t sessionId = -1; if (g_udpChannelMgrCb->OnFileGetSessionId(udpChannel.channelId, &sessionId) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_SDK, "get sessionId failed"); return; } @@ -132,13 +135,13 @@ static void FileSendListener(int32_t dfileId, DFileMsgType msgType, const DFileM } else { NotifySendResult(sessionId, msgType, msgData, &fileListener); } - return; } static void NotifyRecvResult(int32_t sessionId, DFileMsgType msgType, const DFileMsg *msgData, FileListener *listener) { if (msgData == NULL || listener == NULL) { + TRANS_LOGE(TRANS_SDK, "param invalid"); return; } @@ -206,21 +209,25 @@ static void FileReceiveListener(int32_t dfileId, DFileMsgType msgType, const DFi TRANS_LOGI(TRANS_FILE, "recv dfileId=%d type=%d", dfileId, msgType); if (msgData == NULL || msgType == DFILE_ON_BIND || msgType == DFILE_ON_SESSION_IN_PROGRESS || msgType == DFILE_ON_SESSION_TRANSFER_RATE) { + TRANS_LOGE(TRANS_SDK, "param invalid"); return; } UdpChannel udpChannel; (void)memset_s(&udpChannel, sizeof(UdpChannel), 0, sizeof(UdpChannel)); if (TransGetUdpChannelByFileId(dfileId, &udpChannel) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_SDK, "get udp channel failed"); return; } FileListener fileListener; (void)memset_s(&fileListener, sizeof(FileListener), 0, sizeof(FileListener)); if (TransGetFileListener(udpChannel.info.mySessionName, &fileListener) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_SDK, "get listener failed"); return; } int32_t sessionId = -1; if (g_udpChannelMgrCb->OnFileGetSessionId(udpChannel.channelId, &sessionId) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_SDK, "get sessionId failed"); return; } if (msgType == DFILE_ON_CONNECT_FAIL || msgType == DFILE_ON_FATAL_ERROR) { @@ -360,10 +367,12 @@ void TransCloseFileChannel(int32_t dfileId) void RegisterFileCb(const UdpChannelMgrCb *fileCb) { if (fileCb == NULL) { + TRANS_LOGE(TRANS_FILE, "param invalid"); g_udpChannelMgrCb = NULL; return; } if (g_udpChannelMgrCb != NULL) { + TRANS_LOGE(TRANS_FILE, "g_udpChannelMgrCb is null"); return; } g_udpChannelMgrCb = fileCb; diff --git a/sdk/transmission/trans_channel/udp/file/src/client_trans_file_schema_virtual.c b/sdk/transmission/trans_channel/udp/file/src/client_trans_file_schema_virtual.c index 7ab0b5e3d..5436ed732 100755 --- a/sdk/transmission/trans_channel/udp/file/src/client_trans_file_schema_virtual.c +++ b/sdk/transmission/trans_channel/udp/file/src/client_trans_file_schema_virtual.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 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 @@ -13,14 +13,8 @@ * limitations under the License. */ -#include - #include "client_trans_file.h" -#include "client_trans_file_listener.h" -#include "file_adapter.h" -#include "nstackx_dfile.h" #include "softbus_errcode.h" -#include "softbus_utils.h" int32_t TransFileSchemaInit(void) { diff --git a/sdk/transmission/trans_channel/udp/file/src/file_adapter.c b/sdk/transmission/trans_channel/udp/file/src/file_adapter.c index c23b48c06..503e78392 100644 --- a/sdk/transmission/trans_channel/udp/file/src/file_adapter.c +++ b/sdk/transmission/trans_channel/udp/file/src/file_adapter.c @@ -20,7 +20,6 @@ #include "softbus_adapter_errcode.h" #include "softbus_adapter_socket.h" -#include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_socket.h" #include "trans_log.h" @@ -38,7 +37,7 @@ static int SetReuseAddr(int fd, int on) static int SetReusePort(int fd, int on) { int rc = SoftBusSocketSetOpt(fd, SOFTBUS_SOL_SOCKET, SOFTBUS_SO_REUSEPORT, &on, sizeof(on)); - if (rc != 0) { + if (rc != SOFTBUS_OK) { TRANS_LOGE(TRANS_FILE, "fd=%d set SO_REUSEPORT error", fd); return SOFTBUS_ERR; } diff --git a/sdk/transmission/trans_channel/udp/stream/adaptor/src/client_trans_udp_stream_interface.cpp b/sdk/transmission/trans_channel/udp/stream/adaptor/src/client_trans_udp_stream_interface.cpp index 749f575ab..9861b4baa 100644 --- a/sdk/transmission/trans_channel/udp/stream/adaptor/src/client_trans_udp_stream_interface.cpp +++ b/sdk/transmission/trans_channel/udp/stream/adaptor/src/client_trans_udp_stream_interface.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 @@ -18,10 +18,8 @@ #include #include #include -#include #include "securec.h" -#include "softbus_adapter_crypto.h" #include "softbus_errcode.h" #include "stream_adaptor.h" #include "stream_adaptor_listener.h" @@ -125,7 +123,6 @@ int32_t StartVtpStreamChannelServer(int32_t channelId, const VtpStreamOpenParam return SOFTBUS_ERR; } TRANS_LOGI(TRANS_STREAM, "channelId=%d Start Channel Server.", channelId); - int32_t ret = SOFTBUS_ERR; auto it = g_adaptorMap.find(channelId); if (it != g_adaptorMap.end()) { TRANS_LOGE(TRANS_STREAM, "adaptor already existed!"); @@ -152,6 +149,7 @@ int32_t StartVtpStreamChannelServer(int32_t channelId, const VtpStreamOpenParam ipPort.ip = param->myIp; ipPort.port = 0; + int32_t ret = SOFTBUS_ERR; ret = newAdaptor->GetStreamManager()->CreateStreamServerChannel(ipPort, Communication::SoftBus::VTP, param->type, newAdaptor->GetSessionKey()); if (ret > 0) { diff --git a/sdk/transmission/trans_channel/udp/stream/adaptor/src/stream_adaptor.cpp b/sdk/transmission/trans_channel/udp/stream/adaptor/src/stream_adaptor.cpp index 5ac10a95f..3e4c3cbc0 100644 --- a/sdk/transmission/trans_channel/udp/stream/adaptor/src/stream_adaptor.cpp +++ b/sdk/transmission/trans_channel/udp/stream/adaptor/src/stream_adaptor.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 @@ -18,7 +18,6 @@ #include #include #include -#include #include "client_trans_udp_stream_interface.h" #include "securec.h" @@ -26,7 +25,6 @@ #include "softbus_def.h" #include "softbus_errcode.h" #include "stream_adaptor_listener.h" -#include "stream_common.h" #include "trans_log.h" using namespace OHOS; @@ -76,6 +74,10 @@ void StreamAdaptor::SetAliveState(bool state) void StreamAdaptor::InitAdaptor(int32_t channelId, const VtpStreamOpenParam *param, bool isServerSide, const IStreamListener *callback) { + if (param == nullptr) { + TRANS_LOGE(TRANS_STREAM, "param invalid"); + return; + } auto adaptor = shared_from_this(); auto adaptorListener = std::make_shared(adaptor); streamManager_ = Communication::SoftBus::IStreamManager::GetInstance(nullptr, adaptorListener); @@ -123,7 +125,8 @@ ssize_t StreamAdaptor::Encrypt(const void *in, ssize_t inLen, void *out, ssize_t return SOFTBUS_ERR; } - int ret = SoftBusEncryptData(&cipherKey, (unsigned char *)in, inLen, (unsigned char *)out, (unsigned int *)&outLen); + int ret = SoftBusEncryptData(&cipherKey, reinterpret_cast(in), inLen, + reinterpret_cast(out), reinterpret_cast(&outLen)); (void)memset_s(&cipherKey, sizeof(AesGcmCipherKey), 0, sizeof(AesGcmCipherKey)); if (ret != SOFTBUS_OK || outLen != inLen + OVERHEAD_LEN) { TRANS_LOGE(TRANS_STREAM, "Encrypt Data fail. ret=%d", ret); @@ -148,7 +151,8 @@ ssize_t StreamAdaptor::Decrypt(const void *in, ssize_t inLen, void *out, ssize_t TRANS_LOGE(TRANS_STREAM, "memcpy key error."); return SOFTBUS_ERR; } - int ret = SoftBusDecryptData(&cipherKey, (unsigned char *)in, inLen, (unsigned char *)out, (unsigned int *)&outLen); + int ret = SoftBusDecryptData(&cipherKey, reinterpret_cast(in), inLen, + reinterpret_cast(out), reinterpret_cast(&outLen)); (void)memset_s(&cipherKey, sizeof(AesGcmCipherKey), 0, sizeof(AesGcmCipherKey)); if (ret != SOFTBUS_OK) { TRANS_LOGE(TRANS_STREAM, "Decrypt Data fail. ret=%d ", ret); diff --git a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/i_stream_socket.h b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/i_stream_socket.h index ecb0655d3..556216ce9 100644 --- a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/i_stream_socket.h +++ b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/i_stream_socket.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 @@ -149,4 +149,4 @@ protected: } // namespace SoftBus } // namespace Communication -#endif \ No newline at end of file +#endif //STREAM_SOCKET_H \ No newline at end of file diff --git a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/include/i_stream.h b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/include/i_stream.h index 41183c389..400a8f8b2 100644 --- a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/include/i_stream.h +++ b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/include/i_stream.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 @@ -69,4 +69,4 @@ public: }; // namespace SoftBus }; // namespace Communication -#endif \ No newline at end of file +#endif //I_STREAM_DATA_H \ No newline at end of file diff --git a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/include/stream_common.h b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/include/stream_common.h index bf389e59b..eb4f1ecdf 100644 --- a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/include/stream_common.h +++ b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/include/stream_common.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 @@ -168,4 +168,4 @@ static constexpr int MAX_STREAM_LEN = 2 * 1024 * 1024; } // namespace SoftBus } // namespace Communication -#endif +#endif //STREAM_COMMON_H diff --git a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/raw_stream_data.cpp b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/raw_stream_data.cpp index e5acddaeb..62bfb6305 100644 --- a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/raw_stream_data.cpp +++ b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/raw_stream_data.cpp @@ -19,6 +19,7 @@ #include "securec.h" #include "stream_common.h" +#include "trans_log.h" namespace Communication { namespace SoftBus { @@ -34,10 +35,12 @@ std::unique_ptr IStream::MakeRawStream(StreamData &data, const StreamFr std::unique_ptr IStream::MakeRawStream(const char *buf, ssize_t bufLen, const StreamFrameInfo &info, int scene) { if (scene != COMPATIBLE_SCENE && scene != SOFTBUS_SCENE) { + TRANS_LOGE(TRANS_STREAM, "scene invalid"); return nullptr; } if (bufLen <= 0 || bufLen > MAX_STREAM_LEN) { + TRANS_LOGE(TRANS_STREAM, "bufLen invalid"); return nullptr; } @@ -47,6 +50,7 @@ std::unique_ptr IStream::MakeRawStream(const char *buf, ssize_t bufLen, auto buffer = std::make_unique(bufLen); auto ret = memcpy_s(buffer.get(), bufLen, buf, bufLen); if (ret != 0) { + TRANS_LOGE(TRANS_STREAM, "memcpy failed"); return nullptr; } raw->InitStreamData(std::move(buffer), bufLen, nullptr, 0); @@ -57,6 +61,7 @@ std::unique_ptr IStream::MakeRawStream(const char *buf, ssize_t bufLen, auto buffer = std::make_unique(bufLen + RawStreamData::FRAME_HEADER_LEN); auto ret = memcpy_s(buffer.get() + RawStreamData::FRAME_HEADER_LEN, bufLen, buf, bufLen); if (ret != 0) { + TRANS_LOGE(TRANS_STREAM, "memcpy failed"); return nullptr; } RawStreamData::InsertBufferLength(bufLen, RawStreamData::FRAME_HEADER_LEN, @@ -89,6 +94,10 @@ ssize_t RawStreamData::GetBufferLen() const void RawStreamData::InsertBufferLength(int num, int length, uint8_t *output) { + if (output == nullptr || length < 0) { + TRANS_LOGE(TRANS_STREAM, "param invalid"); + return; + } for (int i = 0; i < length; i++) { output[length - 1 - i] = static_cast( ((static_cast(num) >> static_cast(BYTE_TO_BIT * i))) & INT_TO_BYTE); diff --git a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_common_data.h b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_common_data.h index aa105478f..adf4187e1 100644 --- a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_common_data.h +++ b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_common_data.h @@ -82,7 +82,7 @@ public: { return &streamFrameInfo_; } - + protected: std::unique_ptr streamData_ = nullptr; ssize_t streamLen_ = 0; diff --git a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_manager.cpp b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_manager.cpp index 40e57462d..07e55b6bc 100644 --- a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_manager.cpp +++ b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_manager.cpp @@ -15,8 +15,10 @@ #include "stream_manager.h" -#include "session.h" #include "vtp_stream_socket.h" +#include "softbus_error_code.h" + +#define INVALID_FD (-1) namespace Communication { namespace SoftBus { @@ -51,7 +53,7 @@ int StreamManager::CreateStreamClientChannel(IpAndPort &local, IpAndPort remote, streamSocket = std::make_shared(); } else { TRANS_LOGE(TRANS_STREAM, "do not support protocol=%d", protocol); - return -1; + return INVALID_FD; } curProtocol_ = protocol; @@ -61,13 +63,13 @@ int StreamManager::CreateStreamClientChannel(IpAndPort &local, IpAndPort remote, int scene = SOFTBUS_SCENE; if (!streamSocket->SetOption(SCENE, StreamAttr(scene))) { TRANS_LOGE(TRANS_STREAM, "set stream scene failed"); - return -1; + return INVALID_FD; } TRANS_LOGI(TRANS_STREAM, "streamSocket CreateClient success, localPort=%d", local.port); return local.port; } - return 0; + return SOFTBUS_OK; } int StreamManager::CreateStreamServerChannel(IpAndPort &local, Proto protocol, @@ -81,13 +83,13 @@ int StreamManager::CreateStreamServerChannel(IpAndPort &local, Proto protocol, streamSocket = std::make_shared(); } else { TRANS_LOGE(TRANS_STREAM, "do not support protocol=%d", protocol); - return -1; + return INVALID_FD; } curProtocol_ = protocol; if (!streamSocket->CreateServer(local, streamType, sessionKey)) { TRANS_LOGE(TRANS_STREAM, "create protocol=%d server error", protocol); - return -1; + return INVALID_FD; } socketMap_.insert(std::pair>(curProtocol_, streamSocket)); @@ -96,7 +98,7 @@ int StreamManager::CreateStreamServerChannel(IpAndPort &local, Proto protocol, int scene = SOFTBUS_SCENE; if (!streamSocket->SetOption(SCENE, StreamAttr(scene))) { TRANS_LOGE(TRANS_STREAM, "set stream scene failed"); - return -1; + return INVALID_FD; } return local.port; } diff --git a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_packetizer.cpp b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_packetizer.cpp index ccce3c5f5..41f7c7af2 100644 --- a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_packetizer.cpp +++ b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_packetizer.cpp @@ -17,7 +17,6 @@ #include "common_inner.h" #include "securec.h" -#include "stream_common.h" #include "stream_packet_header.h" namespace Communication { diff --git a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/vtp_instance.cpp b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/vtp_instance.cpp index aad8f45fb..3e020e0e4 100644 --- a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/vtp_instance.cpp +++ b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/vtp_instance.cpp @@ -25,7 +25,6 @@ #include "securec.h" #include "softbus_adapter_crypto.h" #include "stream_common.h" -#include "softbus_hisysevt_nstack.h" namespace Communication { namespace SoftBus { diff --git a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/vtp_stream_socket.cpp b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/vtp_stream_socket.cpp index 35c8d1b04..6c0336ae3 100644 --- a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/vtp_stream_socket.cpp +++ b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/vtp_stream_socket.cpp @@ -115,7 +115,6 @@ void VtpStreamSocket::RemoveStreamSocketLock(int fd) TRANS_LOGE(TRANS_STREAM, "Streamsocketlock for fd=%d not exist in the map", fd); } - return; } void VtpStreamSocket::RemoveStreamSocketListener(int fd) @@ -127,7 +126,6 @@ void VtpStreamSocket::RemoveStreamSocketListener(int fd) } else { TRANS_LOGE(TRANS_STREAM, "Streamreceiver for fd=%d not exist in the map", fd); } - return; } void VtpStreamSocket::InsertElementToFuncMap(int type, ValueType valueType, MySetFunc set, MyGetFunc get) @@ -196,6 +194,10 @@ std::shared_ptr VtpStreamSocket::GetSelf() int VtpStreamSocket::HandleFillpFrameStats(int fd, const FtEventCbkInfo *info) { + if (info == nullptr) { + TRANS_LOGE(TRANS_STREAM, "stats info is nullptr"); + return SOFTBUS_INVALID_PARAM; + } StreamSendStats stats = {}; if (memcpy_s(&stats, sizeof(StreamSendStats), &info->info.frameSendStats, sizeof(info->info.frameSendStats)) != EOK) { @@ -220,6 +222,10 @@ int VtpStreamSocket::HandleFillpFrameStats(int fd, const FtEventCbkInfo *info) int VtpStreamSocket::HandleRipplePolicy(int fd, const FtEventCbkInfo *info) { + if (info == nullptr) { + TRANS_LOGE(TRANS_STREAM, "policy info is nullptr"); + return SOFTBUS_INVALID_PARAM; + } TrafficStats stats; (void)memset_s(&stats, sizeof(TrafficStats), 0, sizeof(TrafficStats)); if (memcpy_s(&stats.stats, sizeof(stats.stats), info->info.trafficData.stats, @@ -246,8 +252,8 @@ int VtpStreamSocket::HandleRipplePolicy(int fd, const FtEventCbkInfo *info) #ifdef FILLP_SUPPORT_BW_DET void VtpStreamSocket::FillSupportDet(int fd, const FtEventCbkInfo *info, QosTv *metricList) { - if (info == nullptr) { - TRANS_LOGE(TRANS_STREAM, "stats info is nullptr"); + if (info == nullptr || metricList == nullptr) { + TRANS_LOGE(TRANS_STREAM, "info or metricList is nullptr"); return; } if (info->evt == FT_EVT_BW_DET) { @@ -278,8 +284,8 @@ void VtpStreamSocket::FillSupportDet(int fd, const FtEventCbkInfo *info, QosTv * /* This function is used to prompt the metrics returned by FtApiRegEventCallbackFunc() function */ int VtpStreamSocket::FillpStatistics(int fd, const FtEventCbkInfo *info) { - if (info == nullptr) { - TRANS_LOGE(TRANS_STREAM, "stats info is nullptr"); + if (info == nullptr || fd <= 0) { + TRANS_LOGE(TRANS_STREAM, "param invalid"); return -1; } if (info->evt == FT_EVT_FRAME_STATS) { @@ -437,7 +443,7 @@ bool VtpStreamSocket::CreateServer(IpAndPort &local, int streamType, std::pair(&remoteSockAddr), sizeof(remoteSockAddr)); - if (ret != 0) { + if (ret != SOFTBUS_OK) { TRANS_LOGE(TRANS_STREAM, "FtConnect failed, ret=%d, errno=%d", ret, FtGetErrno()); DestroyStreamSocket(); return false; @@ -554,6 +560,7 @@ bool VtpStreamSocket::Send(std::unique_ptr stream) if (!isBlocked_) { isBlocked_ = true; if (!SetNonBlockMode(streamFd_, StreamAttr(false))) { + TRANS_LOGE(TRANS_STREAM, "set non block mode fail"); return false; } } @@ -561,7 +568,7 @@ bool VtpStreamSocket::Send(std::unique_ptr stream) int ret = -1; std::unique_ptr data = nullptr; ssize_t len = 0; - + if (streamType_ == RAW_STREAM) { data = stream->GetBuffer(); len = stream->GetBufferLen(); @@ -597,7 +604,7 @@ bool VtpStreamSocket::Send(std::unique_ptr stream) ConvertStreamFrameInfo2FrameInfo(&frameInfo, streamFrameInfo); ret = FtSendFrame(streamFd_, data.get(), len, 0, &frameInfo); } - + if (ret == -1) { TRANS_LOGE(TRANS_STREAM, "send failed, errno=%d", FtGetErrno()); return false; @@ -707,10 +714,15 @@ int VtpStreamSocket::CreateAndBindSocket(IpAndPort &local) } // bind - sockaddr_in localSockAddr = {0}; + sockaddr_in localSockAddr = { 0 }; + char host[ADDR_MAX_SIZE]; localSockAddr.sin_family = AF_INET; localSockAddr.sin_port = htons((short)local.port); localSockAddr.sin_addr.s_addr = inet_addr(local.ip.c_str()); + localIpPort_.ip = SoftBusInetNtoP(AF_INET, &(localSockAddr.sin_addr), host, ADDR_MAX_SIZE); + if (!SetSocketBoundInner(sockFd, localIpPort_.ip)) { + TRANS_LOGE(TRANS_STREAM, "SetSocketBoundInner failed, errno= %d", FtGetErrno()); + } socklen_t localAddrLen = sizeof(localSockAddr); int ret = FtBind(sockFd, reinterpret_cast(&localSockAddr), localAddrLen); @@ -728,14 +740,9 @@ int VtpStreamSocket::CreateAndBindSocket(IpAndPort &local) return -1; } - char host[ADDR_MAX_SIZE]; localIpPort_.port = static_cast(ntohs(localSockAddr.sin_port)); - localIpPort_.ip = SoftBusInetNtoP(AF_INET, &(localSockAddr.sin_addr), host, ADDR_MAX_SIZE); local.port = localIpPort_.port; - if (!SetSocketBoundInner(sockFd, localIpPort_.ip)) { - TRANS_LOGE(TRANS_STREAM, "SetSocketBoundInner failed, errno= %d", FtGetErrno()); - } return sockFd; } @@ -861,6 +868,7 @@ bool VtpStreamSocket::Accept() socklen_t remoteAddrLen = sizeof(remoteAddr); auto ret = FtGetPeerName(fd, &remoteAddr, &remoteAddrLen); if (ret != ERR_OK) { + TRANS_LOGE(TRANS_STREAM, "get name failed, fd=%d", fd); FtClose(fd); return false; } @@ -1016,6 +1024,7 @@ int VtpStreamSocket::RecvStreamLen() TRANS_LOGD(TRANS_STREAM, "recv frame header, len=%d, scene=%d", len, scene_); if (len <= 0) { + TRANS_LOGE(TRANS_STREAM, "len invalid,len=%d", len); return -1; } @@ -1214,7 +1223,7 @@ StreamAttr VtpStreamSocket::GetListenSocketFd(int type) const bool VtpStreamSocket::SetSocketBoundInner(int fd, std::string ip) const { - auto boundIp = (ip == "") ? localIpPort_.ip : ip; + auto boundIp = (ip.empty()) ? localIpPort_.ip : ip; struct ifaddrs *ifList = nullptr; if (getifaddrs(&ifList) < 0) { TRANS_LOGE(TRANS_STREAM, @@ -1254,7 +1263,7 @@ bool VtpStreamSocket::SetSocketBindToDevices(int type, const StreamAttr &ip) { static_cast(type); auto tmp = ip.GetStrValue(); - auto boundIp = (tmp == "") ? localIpPort_.ip : tmp; + auto boundIp = (tmp.empty()) ? localIpPort_.ip : tmp; return SetSocketBoundInner(streamFd_, boundIp); } @@ -1284,7 +1293,7 @@ bool VtpStreamSocket::SetVtpStackConfig(int type, const StreamAttr &value) if (value.GetType() == INT_TYPE) { int intVal = value.GetIntValue(); int ret = FtConfigSet(type, &intVal, &streamFd_); - if (ret != 0) { + if (ret != SOFTBUS_OK) { TRANS_LOGE(TRANS_STREAM, "FtConfigSet failed, type=%d, errno=%d", type, FtGetErrno()); return false; @@ -1298,7 +1307,7 @@ bool VtpStreamSocket::SetVtpStackConfig(int type, const StreamAttr &value) if (value.GetType() == BOOL_TYPE) { bool flag = value.GetBoolValue(); int ret = FtConfigSet(type, &flag, &streamFd_); - if (ret != 0) { + if (ret != SOFTBUS_OK) { TRANS_LOGE(TRANS_STREAM, "FtConfigSet failed, type=%d, errno=%d", type, FtGetErrno()); return false; @@ -1318,7 +1327,7 @@ StreamAttr VtpStreamSocket::GetVtpStackConfig(int type) const int intVal = -1; int configFd = (streamFd_ == -1) ? FILLP_CONFIG_ALL_SOCKET : streamFd_; int ret = FtConfigGet(type, &intVal, &configFd); - if (ret != 0) { + if (ret != SOFTBUS_OK) { TRANS_LOGE(TRANS_STREAM, "FtConfigGet failed, type=%d, errno=%d", type, FtGetErrno()); return std::move(StreamAttr()); @@ -1424,6 +1433,7 @@ bool VtpStreamSocket::SetStreamScene(int type, const StreamAttr &value) { static_cast(type); if (value.GetType() != INT_TYPE) { + TRANS_LOGE(TRANS_STREAM, "value.GetType=%d", value.GetType()); return false; } scene_ = value.GetIntValue(); @@ -1435,6 +1445,7 @@ bool VtpStreamSocket::SetStreamHeaderSize(int type, const StreamAttr &value) { static_cast(type); if (value.GetType() != INT_TYPE) { + TRANS_LOGE(TRANS_STREAM, "value.GetType=%d", value.GetType()); return false; } streamHdrSize_ = value.GetIntValue(); @@ -1473,6 +1484,10 @@ ssize_t VtpStreamSocket::GetEncryptOverhead() const ssize_t VtpStreamSocket::Encrypt(const void *in, ssize_t inLen, void *out, ssize_t outLen) const { + if (in == nullptr || out == nullptr) { + TRANS_LOGE(TRANS_STREAM, "param invalid"); + return SOFTBUS_INVALID_PARAM; + } AesGcmCipherKey cipherKey = {0}; if (inLen - OVERHEAD_LEN > outLen) { @@ -1497,6 +1512,10 @@ ssize_t VtpStreamSocket::Encrypt(const void *in, ssize_t inLen, void *out, ssize ssize_t VtpStreamSocket::Decrypt(const void *in, ssize_t inLen, void *out, ssize_t outLen) const { + if (in == nullptr || out == nullptr) { + TRANS_LOGE(TRANS_STREAM, "param invalid"); + return SOFTBUS_INVALID_PARAM; + } AesGcmCipherKey cipherKey = {0}; if (inLen - OVERHEAD_LEN > outLen) { diff --git a/sdk/transmission/trans_channel/udp/stream/src/client_trans_stream.c b/sdk/transmission/trans_channel/udp/stream/src/client_trans_stream.c index 86283371f..1adecb923 100644 --- a/sdk/transmission/trans_channel/udp/stream/src/client_trans_stream.c +++ b/sdk/transmission/trans_channel/udp/stream/src/client_trans_stream.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 @@ -182,6 +182,10 @@ int32_t TransOnstreamChannelOpened(const ChannelInfo *channel, int32_t *streamPo int32_t TransSendStream(int32_t channelId, const StreamData *data, const StreamData *ext, const StreamFrameInfo *param) { + if (channelId < 0) { + TRANS_LOGE(TRANS_STREAM, "param faild"); + return SOFTBUS_INVALID_PARAM; + } return SendVtpStream(channelId, data, ext, param); } diff --git a/sdk/transmission/trans_channel/udp/stream/src/client_trans_stream_virtual.c b/sdk/transmission/trans_channel/udp/stream/src/client_trans_stream_virtual.c index 097346d4e..cd9b9ad6f 100644 --- a/sdk/transmission/trans_channel/udp/stream/src/client_trans_stream_virtual.c +++ b/sdk/transmission/trans_channel/udp/stream/src/client_trans_stream_virtual.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2023 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 diff --git a/tests/adapter/bluetooth/BUILD.gn b/tests/adapter/bluetooth/BUILD.gn index a05af33cd..5d257ebb0 100644 --- a/tests/adapter/bluetooth/BUILD.gn +++ b/tests/adapter/bluetooth/BUILD.gn @@ -101,11 +101,11 @@ if (!defined(ohos_lite)) { if (support_bluetooth && (dsoftbus_feature_conn_ble || dsoftbus_feature_conn_br)) { deps += [ - ":AdapterBleGattClientTest", - ":AdapterBleGattServerTest", - ":AdapterBleGattTest", - ":AdapterBtCommonTest", - ":AdapterBtUtilsTest", + # ":AdapterBleGattClientTest", + # ":AdapterBleGattServerTest", + # ":AdapterBleGattTest", + # ":AdapterBtCommonTest", + # ":AdapterBtUtilsTest", ] } } diff --git a/tests/adapter/bluetooth/assert_helper.h b/tests/adapter/bluetooth/assert_helper.h index 267a9812f..a026da7e5 100644 --- a/tests/adapter/bluetooth/assert_helper.h +++ b/tests/adapter/bluetooth/assert_helper.h @@ -25,7 +25,6 @@ #include "softbus_adapter_bt_common.h" #include "softbus_adapter_mem.h" #include "softbus_common.h" -#include "softbus_log_old.h" #include "softbus_utils.h" class RecordCtx { diff --git a/tests/adapter/bluetooth/bluetooth_mock.cpp b/tests/adapter/bluetooth/bluetooth_mock.cpp index befe7f738..d386bb100 100644 --- a/tests/adapter/bluetooth/bluetooth_mock.cpp +++ b/tests/adapter/bluetooth/bluetooth_mock.cpp @@ -19,7 +19,6 @@ #include "softbus_common.h" #include "softbus_errcode.h" -#include "softbus_log_old.h" #include "softbus_utils.h" MockBluetooth *MockBluetooth::targetMocker = nullptr; diff --git a/tests/adapter/fuzztest/BUILD.gn b/tests/adapter/fuzztest/BUILD.gn index 5b84953cd..fc82dba76 100644 --- a/tests/adapter/fuzztest/BUILD.gn +++ b/tests/adapter/fuzztest/BUILD.gn @@ -16,6 +16,7 @@ group("fuzztest") { deps = [ "softbusadapterhisysevent_fuzzer:fuzztest", "softbusadapterrange_fuzzer:fuzztest", + "softbusaescrypto_fuzzer:fuzztest", "softbusdecryptdata_fuzzer:SoftBusDecryptDataFuzzTest", "softbussocketrecv_fuzzer:fuzztest", ] diff --git a/tests/adapter/fuzztest/softbusaescrypto_fuzzer/BUILD.gn b/tests/adapter/fuzztest/softbusaescrypto_fuzzer/BUILD.gn new file mode 100755 index 000000000..37dcc7a52 --- /dev/null +++ b/tests/adapter/fuzztest/softbusaescrypto_fuzzer/BUILD.gn @@ -0,0 +1,54 @@ +# Copyright (c) 2023 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. + +#####################hydra-fuzz################### +import("//build/test.gni") +import("../../../../dsoftbus.gni") + +##############################fuzztest########################################## + +dsoftbus_root_path = "../../../.." + +ohos_fuzztest("SoftBusAesCryptoFuzzTest") { + module_out_path = dsoftbus_fuzz_out_path + fuzz_config_file = + "$dsoftbus_root_path/tests/adapter/fuzztest/softbusaescrypto_fuzzer" + include_dirs = [ "$dsoftbus_root_path/adapter/common/include" ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-fstack-protector-strong", + ] + + sources = [ "softbusaescrypto_fuzzer.cpp" ] + + deps = [ "$dsoftbus_root_path/adapter:softbus_adapter" ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [ + # deps file + ":SoftBusAesCryptoFuzzTest", + ] +} +############################################################################### diff --git a/tests/core/common/log/fuzztest/softbuslog_fuzzer/corpus/init b/tests/adapter/fuzztest/softbusaescrypto_fuzzer/corpus/init old mode 100644 new mode 100755 similarity index 91% rename from tests/core/common/log/fuzztest/softbuslog_fuzzer/corpus/init rename to tests/adapter/fuzztest/softbusaescrypto_fuzzer/corpus/init index 8eb5a7d6e..2b595da0c --- a/tests/core/common/log/fuzztest/softbuslog_fuzzer/corpus/init +++ b/tests/adapter/fuzztest/softbusaescrypto_fuzzer/corpus/init @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2023 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 diff --git a/tests/core/common/log/fuzztest/softbuslog_fuzzer/project.xml b/tests/adapter/fuzztest/softbusaescrypto_fuzzer/project.xml old mode 100644 new mode 100755 similarity index 95% rename from tests/core/common/log/fuzztest/softbuslog_fuzzer/project.xml rename to tests/adapter/fuzztest/softbusaescrypto_fuzzer/project.xml index 6e8ad2cfd..4fdbc407f --- a/tests/core/common/log/fuzztest/softbuslog_fuzzer/project.xml +++ b/tests/adapter/fuzztest/softbusaescrypto_fuzzer/project.xml @@ -1,5 +1,5 @@ - + + + + 1000 + + 300 + + 4096 + + diff --git a/tests/core/adapter/fuzztest/softbusrsacrypto_fuzzer/softbusrsacrypto_fuzzer.cpp b/tests/core/adapter/fuzztest/softbusrsacrypto_fuzzer/softbusrsacrypto_fuzzer.cpp new file mode 100755 index 000000000..0bb0250f9 --- /dev/null +++ b/tests/core/adapter/fuzztest/softbusrsacrypto_fuzzer/softbusrsacrypto_fuzzer.cpp @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2023 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 "softbus_rsa_encrypt.h" + +#include +#include +#include +#include + +#include "comm_log.h" +#include "softbus_adapter_mem.h" +#include "softbus_errcode.h" + +namespace OHOS { +bool SoftBusRsaEncryptFuzzTest(const uint8_t *data, size_t size) +{ + uint32_t encryptedDataLen = 0; + uint8_t *encryptedData = nullptr; + PublicKey peerPublicKey = { data, size }; + + if (SoftBusRsaEncrypt(data, size, &peerPublicKey, &encryptedData, &encryptedDataLen) != SOFTBUS_OK) { + COMM_LOGE(COMM_TEST, "SoftBusRsaEncrypt failed!"); + return false; + } + SoftBusFree(encryptedData); + return true; +} + +bool SoftBusRsaDecryptFuzzTest(const uint8_t *data, size_t size) +{ + uint32_t decryptedDataLen = 0; + uint8_t *decryptedData = nullptr; + + if (SoftBusRsaDecrypt(data, size, &decryptedData, &decryptedDataLen) != SOFTBUS_OK) { + COMM_LOGE(COMM_TEST, "SoftBusRsaDecrypt failed!"); + return false; + } + SoftBusFree(decryptedData); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + if (data == nullptr || size == 0) { + return 0; + } + + OHOS::SoftBusRsaEncryptFuzzTest(data, size); + OHOS::SoftBusRsaDecryptFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/tests/core/adapter/fuzztest/softbusrsacrypto_fuzzer/softbusrsacrypto_fuzzer.h b/tests/core/adapter/fuzztest/softbusrsacrypto_fuzzer/softbusrsacrypto_fuzzer.h new file mode 100755 index 000000000..28db2305d --- /dev/null +++ b/tests/core/adapter/fuzztest/softbusrsacrypto_fuzzer/softbusrsacrypto_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2023 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 TEST_FUZZTEST_SOFTBUSRSACRYPTO_FUZZER_H +#define TEST_FUZZTEST_SOFTBUSRSACRYPTO_FUZZER_H + +#define FUZZ_PROJECT_NAME "softbusrsacrypto_fuzzer" + +#endif // TEST_FUZZTEST_SOFTBUSRSACRYPTO_FUZZER_H \ No newline at end of file diff --git a/tests/core/adapter/unittest/bus_center_adapter_test.cpp b/tests/core/adapter/unittest/bus_center_adapter_test.cpp index 1c599cf64..dd77485fd 100755 --- a/tests/core/adapter/unittest/bus_center_adapter_test.cpp +++ b/tests/core/adapter/unittest/bus_center_adapter_test.cpp @@ -22,7 +22,6 @@ #include "softbus_adapter_file.h" #include "softbus_adapter_mem.h" #include "softbus_errcode.h" -#include "softbus_adapter_log.h" using namespace std; using namespace testing::ext; diff --git a/tests/core/adapter/unittest/dsoftbus_rsa_crypto_test.cpp b/tests/core/adapter/unittest/dsoftbus_rsa_crypto_test.cpp index 6cab49419..9e4a6c1ec 100644 --- a/tests/core/adapter/unittest/dsoftbus_rsa_crypto_test.cpp +++ b/tests/core/adapter/unittest/dsoftbus_rsa_crypto_test.cpp @@ -22,7 +22,6 @@ #include "comm_log.h" #include "softbus_adapter_crypto.h" -#include "softbus_adapter_log.h" #include "softbus_adapter_mem.h" #include "softbus_errcode.h" #include "gtest/gtest.h" diff --git a/tests/core/authentication/BUILD.gn b/tests/core/authentication/BUILD.gn index 8391be5aa..eca491209 100644 --- a/tests/core/authentication/BUILD.gn +++ b/tests/core/authentication/BUILD.gn @@ -466,6 +466,45 @@ ohos_unittest("AuthHichainTest") { } } +ohos_unittest("DsoftbusAppBindTest") { + module_out_path = module_output_path + sources = [ "unittest/dsoftbus_app_bind_test.cpp" ] + + include_dirs = [ + "//base/security/device_auth/interfaces/inner_api", + "$dsoftbus_root_path/interfaces/kits", + "$dsoftbus_root_path/core/authentication/interface", + "$dsoftbus_root_path/core/authentication/include", + "//commonlibrary/c_utils/base/include", + "//third_party/cJSON", + "unittest/common/", + "//third_party/bounds_checking_function/include", + ] + + deps = [ + "$dsoftbus_root_path/core/common:softbus_utils", + "$dsoftbus_root_path/core/frame:softbus_server", + "//third_party/bounds_checking_function:libsec_shared", + "//third_party/googletest:gmock", + "//third_party/googletest:gtest_main", + ] + + if (!defined(global_parts_info) || + defined(global_parts_info.deviceprofile_device_info_manager)) { + external_deps = [ + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", + "hilog:libhilog", + "ipc:ipc_core", + ] + } else { + external_deps = [ + "hilog:libhilog", + "ipc:ipc_core", + ] + } +} + group("unittest") { testonly = true deps = [ @@ -475,6 +514,7 @@ group("unittest") { ":AuthTcpConnectionTest", ":AuthTest", ":AuthTestCallBackTest", + ":DsoftbusAppBindTest", ] } diff --git a/tests/core/authentication/unittest/auth_other_test.cpp b/tests/core/authentication/unittest/auth_other_test.cpp index ea8be67a3..1cef09d23 100644 --- a/tests/core/authentication/unittest/auth_other_test.cpp +++ b/tests/core/authentication/unittest/auth_other_test.cpp @@ -22,6 +22,7 @@ #include "auth_connection.c" #include "auth_interface.h" #include "auth_interface.c" +#include "auth_log.h" #include "auth_manager.h" #include "auth_manager.c" #include "auth_session_fsm.h" @@ -63,7 +64,6 @@ void AuthOtherTest::TearDownTestCase() void AuthOtherTest::SetUp() { - LOG_INFO("AuthOtherTest start."); } void AuthOtherTest::TearDown() {} @@ -1034,7 +1034,7 @@ HWTEST_F(AuthOtherTest, AUTH_RESTORE_MANAGER_TEST_001, TestSize.Level1) return; } connInfo->type = AUTH_LINK_TYPE_BLE; - int32_t requestId = 1; + uint32_t requestId = 1; NodeInfo *nodeInfo = (NodeInfo*)SoftBusCalloc(sizeof(NodeInfo)); ASSERT_TRUE(nodeInfo != nullptr); int64_t *authId = (int64_t *)malloc(sizeof(int64_t)); diff --git a/tests/core/authentication/unittest/dsoftbus_app_bind_test.cpp b/tests/core/authentication/unittest/dsoftbus_app_bind_test.cpp new file mode 100644 index 000000000..f01d7c402 --- /dev/null +++ b/tests/core/authentication/unittest/dsoftbus_app_bind_test.cpp @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2023 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 "auth_device_profile_listener.h" +#include "auth_deviceprofile.h" +#include + +#include "device_profile_listener.h" +#include "lnn_app_bind_interface.h" +#include "auth_log.h" +#include "softbus_errcode.h" +#include "trust_device_profile.h" + +namespace OHOS { +using namespace testing; +using namespace testing::ext; + +class DsoftbusAppBindTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void DsoftbusAppBindTest::SetUpTestCase() { } + +void DsoftbusAppBindTest::TearDownTestCase() { } + +void DsoftbusAppBindTest::SetUp() { } + +void DsoftbusAppBindTest::TearDown() { } + +static void OnDeviceBound(const char *udid, const char *groupInfo) +{ + (void)udid; + (void)groupInfo; + AUTH_LOGI(AUTH_TEST, "deviceBound success!"); +} + +static void OnDeviceNotTrusted(const char *udid) +{ + (void)udid; + AUTH_LOGI(AUTH_TEST, "device is not trusted!"); +} + +static DeviceProfileChangeListener g_deviceProfilePara = { + .onDeviceProfileAdd = OnDeviceBound, + .onDeviceProfileDeleted = OnDeviceNotTrusted, +}; + +/* + * @tc.name: TRUST_DEVICE_PROFILE_ADD_TEST_001 + * @tc.desc: + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(DsoftbusAppBindTest, TRUST_DEVICE_PROFILE_ADD_TEST_001, TestSize.Level1) +{ + RegisterToDp(&g_deviceProfilePara); + std::unique_ptr myFunc_ = + std::make_unique(); + AuthToDeviceProfile::TrustDeviceProfile profile; + int32_t ret = myFunc_->OnTrustDeviceProfileAdd(profile); + EXPECT_EQ(ret, SOFTBUS_OK); +} + +/* + * @tc.name: TRUST_DEVICE_PROFILE_DELETE_TEST_002 + * @tc.desc: + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(DsoftbusAppBindTest, TRUST_DEVICE_PROFILE_DELETE_TEST_002, TestSize.Level1) +{ + RegisterToDp(&g_deviceProfilePara); + std::unique_ptr myFunc_ = + std::make_unique(); + AuthToDeviceProfile::TrustDeviceProfile profile; + int32_t ret = myFunc_->OnTrustDeviceProfileDelete(profile); + EXPECT_EQ(ret, SOFTBUS_OK); +} + +/* + * @tc.name: IS_POTENTIAL_TRUSTED_DEVCIE_TEST_003 + * @tc.desc: + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(DsoftbusAppBindTest, IS_POTENTIAL_DEVCIE_TEST_003, TestSize.Level1) +{ + const char *deviceIdHash = nullptr; + bool ret = IsPotentialTrustedDeviceDp(deviceIdHash); + EXPECT_TRUE(!ret); + deviceIdHash = "dev/ice%Id()Hash()"; + ret = IsPotentialTrustedDeviceDp(deviceIdHash); + EXPECT_TRUE(!ret); +} +} // namespace OHOS diff --git a/tests/core/bus_center/lnn/BUILD.gn b/tests/core/bus_center/lnn/BUILD.gn index 03c72f144..7b48209c6 100644 --- a/tests/core/bus_center/lnn/BUILD.gn +++ b/tests/core/bus_center/lnn/BUILD.gn @@ -1394,7 +1394,6 @@ ohos_unittest("LNNLaneLinkTest") { "$dsoftbus_root_path/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_score_virtual.c", "$dsoftbus_root_path/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_select.c", "$dsoftbus_root_path/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_select_rule.c", - "$dsoftbus_root_path/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_trans_lane.c", "$dsoftbus_root_path/core/connection/wifi_direct/channel/default_negotiate_channel_virtual.c", "$dsoftbus_root_path/core/connection/wifi_direct/channel/fast_connect_negotiate_channel_virtual.c", "$dsoftbus_root_path/core/connection/wifi_direct/utils/wifi_direct_utils_virtual.c", @@ -1402,6 +1401,7 @@ ohos_unittest("LNNLaneLinkTest") { "$dsoftbus_root_path/core/transmission/trans_channel/proxy/src/softbus_proxychannel_listener.c", "$dsoftbus_root_path/core/transmission/trans_channel/proxy/src/softbus_proxychannel_pipeline.c", "$dsoftbus_root_path/tests/core/bus_center/lnn/lane/src/lnn_lane_deps_mock.cpp", + "$dsoftbus_root_path/tests/core/bus_center/lnn/lane_link/lnn_lane_link_deps_mock.cpp", "$dsoftbus_root_path/tests/core/bus_center/lnn/lane_link/lnn_lane_link_test.cpp", ] diff --git a/tests/core/bus_center/lnn/disc_mgr/lnn_discovery_interface_test.cpp b/tests/core/bus_center/lnn/disc_mgr/lnn_discovery_interface_test.cpp index 9be4b6d90..729a704e3 100644 --- a/tests/core/bus_center/lnn/disc_mgr/lnn_discovery_interface_test.cpp +++ b/tests/core/bus_center/lnn/disc_mgr/lnn_discovery_interface_test.cpp @@ -24,7 +24,6 @@ #include "lnn_discovery_manager.c" #include "lnn_hichain_mock.h" #include "softbus_errcode.h" -#include "softbus_log_old.h" namespace OHOS { using namespace testing; diff --git a/tests/core/bus_center/lnn/lane_link/lnn_lane_link_deps_mock.cpp b/tests/core/bus_center/lnn/lane_link/lnn_lane_link_deps_mock.cpp new file mode 100644 index 000000000..747a2ee9a --- /dev/null +++ b/tests/core/bus_center/lnn/lane_link/lnn_lane_link_deps_mock.cpp @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2023 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_lane_link_deps_mock.h" + +using namespace testing::ext; +using namespace testing; + +namespace OHOS { +void *g_laneLinkDepsInterface; +LaneLinkDepsInterfaceMock::LaneLinkDepsInterfaceMock() +{ + g_laneLinkDepsInterface = reinterpret_cast(this); +} + +LaneLinkDepsInterfaceMock::~LaneLinkDepsInterfaceMock() +{ + g_laneLinkDepsInterface = nullptr; +} + +static LaneLinkDepsInterface *GetLaneLinkDepsInterface() +{ + return reinterpret_cast(g_laneLinkDepsInterface); +} + +extern "C" { +int32_t GetTransOptionByLaneId(uint32_t laneId, TransOption *reqInfo) +{ + return GetLaneLinkDepsInterface()->GetTransOptionByLaneId(laneId, reqInfo); +} +} +} // namespace OHOS diff --git a/tests/core/bus_center/lnn/lane_link/lnn_lane_link_deps_mock.h b/tests/core/bus_center/lnn/lane_link/lnn_lane_link_deps_mock.h new file mode 100644 index 000000000..4dd56b0a8 --- /dev/null +++ b/tests/core/bus_center/lnn/lane_link/lnn_lane_link_deps_mock.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2023 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 LNN_LANE_LINK_DEPS_MOCK_H +#define LNN_LANE_LINK_DEPS_MOCK_H + +#include + +#include "lnn_lane_assign.h" + +namespace OHOS { +class LaneLinkDepsInterface { +public: + LaneLinkDepsInterface() {}; + virtual ~LaneLinkDepsInterface() {}; + + virtual int32_t GetTransOptionByLaneId(uint32_t laneId, TransOption *reqInfo) = 0; +}; + +class LaneLinkDepsInterfaceMock : public LaneLinkDepsInterface { +public: + LaneLinkDepsInterfaceMock(); + ~LaneLinkDepsInterfaceMock() override; + + MOCK_METHOD2(GetTransOptionByLaneId, int32_t (uint32_t laneId, TransOption *reqInfo)); +}; +} // namespace OHOS +#endif // LNN_LANE_LINK_DEPS_MOCK_H diff --git a/tests/core/bus_center/lnn/lane_link/lnn_lane_link_test.cpp b/tests/core/bus_center/lnn/lane_link/lnn_lane_link_test.cpp index d8ebea769..75c844044 100644 --- a/tests/core/bus_center/lnn/lane_link/lnn_lane_link_test.cpp +++ b/tests/core/bus_center/lnn/lane_link/lnn_lane_link_test.cpp @@ -22,6 +22,7 @@ #include "softbus_error_code.h" #include "softbus_adapter_mem.h" #include "lnn_select_rule.h" +#include "lnn_lane_link_deps_mock.h" #include "lnn_lane_link_p2p.h" #include "bus_center_manager.h" @@ -94,9 +95,6 @@ HWTEST_F(LNNLaneLinkTest, LNN_LANE_LINK_001, TestSize.Level1) .OnLaneLinkException = OnLaneLinkException, }; LaneDepsInterfaceMock linkMock; - EXPECT_CALL(linkMock, AuthGetPreferConnInfo) - .WillOnce(Return(SOFTBUS_ERR)) - .WillRepeatedly(Return(SOFTBUS_OK)); EXPECT_CALL(linkMock, LnnGetRemoteStrInfo) .WillOnce(Return(SOFTBUS_ERR)) .WillRepeatedly(Return(SOFTBUS_OK)); @@ -106,9 +104,6 @@ HWTEST_F(LNNLaneLinkTest, LNN_LANE_LINK_001, TestSize.Level1) EXPECT_CALL(linkMock, LnnGetLocalNumU64Info).WillRepeatedly(Return(SOFTBUS_OK)); EXPECT_CALL(linkMock, LnnGetRemoteNumU64Info).WillRepeatedly(Return(SOFTBUS_ERR)); EXPECT_CALL(linkMock, CheckActiveConnection).WillRepeatedly(Return(true)); - EXPECT_CALL(linkMock, AuthDeviceCheckConnInfo) - .WillOnce(Return(SOFTBUS_ERR)) - .WillRepeatedly(Return(SOFTBUS_OK)); LinkRequest *request = (LinkRequest *)SoftBusCalloc(sizeof(LinkRequest)); if (request == NULL) { return; @@ -183,6 +178,9 @@ HWTEST_F(LNNLaneLinkTest, LNN_LANE_LINK_002, TestSize.Level1) .OnLaneLinkException = OnLaneLinkException, }; + LaneLinkDepsInterfaceMock laneLinkMock; + EXPECT_CALL(laneLinkMock, GetTransOptionByLaneId).WillRepeatedly(Return(SOFTBUS_OK)); + ret = LnnConnectP2p(request, laneLinkReqId, &cb); EXPECT_TRUE(ret == SOFTBUS_OK); ret = LnnConnectP2p(request, laneLinkReqId, &cb); @@ -230,6 +228,9 @@ HWTEST_F(LNNLaneLinkTest, LNN_LANE_LINK_003, TestSize.Level1) .OnLaneLinkException = OnLaneLinkException, }; + LaneLinkDepsInterfaceMock laneLinkMock; + EXPECT_CALL(laneLinkMock, GetTransOptionByLaneId).WillRepeatedly(Return(SOFTBUS_OK)); + ret = LnnConnectP2p(request, laneLinkReqId, &cb); EXPECT_TRUE(ret == SOFTBUS_OK); SoftBusFree(request); @@ -270,6 +271,9 @@ HWTEST_F(LNNLaneLinkTest, LNN_LANE_LINK_004, TestSize.Level1) .OnLaneLinkException = OnLaneLinkException, }; + LaneLinkDepsInterfaceMock laneLinkMock; + EXPECT_CALL(laneLinkMock, GetTransOptionByLaneId).WillRepeatedly(Return(SOFTBUS_OK)); + ret = LnnConnectP2p(request, laneLinkReqId, &cb); EXPECT_TRUE(ret != SOFTBUS_OK); SoftBusFree(request); @@ -329,6 +333,10 @@ HWTEST_F(LNNLaneLinkTest, LNN_LANE_LINK_006, TestSize.Level1) EXPECT_CALL(linkMock, GetAuthIdByConnInfo).WillRepeatedly(Return(5)); EXPECT_CALL(linkMock, AuthGenRequestId).WillRepeatedly(Return(5)); EXPECT_CALL(linkMock, CheckActiveConnection).WillRepeatedly(Return(true)); + + LaneLinkDepsInterfaceMock laneLinkMock; + EXPECT_CALL(laneLinkMock, GetTransOptionByLaneId).WillRepeatedly(Return(SOFTBUS_OK)); + uint32_t ret = LnnConnectP2p(request, laneLinkReqId, &cb); EXPECT_TRUE(ret == SOFTBUS_OK); LnnDisconnectP2p(network, request->pid, laneLinkReqId); diff --git a/tests/core/bus_center/lnn/unittest/lane_test.cpp b/tests/core/bus_center/lnn/unittest/lane_test.cpp index 82d1cefb6..4ae882d7f 100644 --- a/tests/core/bus_center/lnn/unittest/lane_test.cpp +++ b/tests/core/bus_center/lnn/unittest/lane_test.cpp @@ -21,6 +21,7 @@ #include "lnn_distributed_net_ledger.h" #include "lnn_lane.h" #include "lnn_lane_link.h" +#include "lnn_lane_reliability.h" #include "lnn_lane_select.h" #include "lnn_local_net_ledger.h" #include "message_handler.h" @@ -31,6 +32,7 @@ namespace OHOS { using namespace testing::ext; +using namespace testing; constexpr char NODE_NETWORK_ID[] = "111122223333abcdef"; constexpr char NODE_UDID[] = "123456ABCDEF"; constexpr char NODE_BT_MAC[] = "b1:ab:cd:ef:aa:d7"; @@ -337,6 +339,8 @@ HWTEST_F(LaneTest, EXPECT_LANE_SELECT_BY_QOS_Test_002, TestSize.Level1) */ HWTEST_F(LaneTest, LANE_LINK_Test_001, TestSize.Level1) { + ConnServerInit(); + InitLaneReliability(); LinkRequest reqInfo; (void)memset_s(&reqInfo, sizeof(LinkRequest), 0, sizeof(LinkRequest)); int32_t ret = memcpy_s(reqInfo.peerNetworkId, NETWORK_ID_BUF_LEN, NODE_NETWORK_ID, strlen(NODE_NETWORK_ID)); @@ -352,6 +356,7 @@ HWTEST_F(LaneTest, LANE_LINK_Test_001, TestSize.Level1) uint32_t requestId = 0x5A5A; ret = BuildLink(&reqInfo, requestId, &linkCb); EXPECT_TRUE(ret == SOFTBUS_OK); + ConnServerDeinit(); } /* diff --git a/tests/core/bus_center/mock_common/src/lnn_hichain_mock.cpp b/tests/core/bus_center/mock_common/src/lnn_hichain_mock.cpp index 1565bc8a1..4d33b47a2 100644 --- a/tests/core/bus_center/mock_common/src/lnn_hichain_mock.cpp +++ b/tests/core/bus_center/mock_common/src/lnn_hichain_mock.cpp @@ -17,9 +17,7 @@ #include "auth_interface.h" #include "auth_log.h" -#include "softbus_adapter_log.h" #include "softbus_adapter_mem.h" -#include "softbus_log_old.h" #include "softbus_adapter_json.h" using namespace testing; diff --git a/tests/core/bus_center/test/ipc/client_proxy_test.cpp b/tests/core/bus_center/test/ipc/client_proxy_test.cpp index c2f60e397..92853d58b 100644 --- a/tests/core/bus_center/test/ipc/client_proxy_test.cpp +++ b/tests/core/bus_center/test/ipc/client_proxy_test.cpp @@ -21,7 +21,6 @@ #include "if_system_ability_manager.h" #include "iremote_object.h" #include "iservice_registry.h" -#include "softbus_adapter_log.h" #include "softbus_bus_center.h" #include "softbus_error_code.h" diff --git a/tests/core/bus_center/test/mock/include/bus_center_ipc_mock.h b/tests/core/bus_center/test/mock/include/bus_center_ipc_mock.h index 96d2b3368..606af8d0c 100644 --- a/tests/core/bus_center/test/mock/include/bus_center_ipc_mock.h +++ b/tests/core/bus_center/test/mock/include/bus_center_ipc_mock.h @@ -38,7 +38,7 @@ public: virtual int32_t LnnSetNodeDataChangeFlag(const char *networkId, uint16_t dataChangeFlag) = 0; virtual int32_t LnnStartTimeSync(const char *pkgName, int32_t callingPid, const char *targetNetworkId, TimeSyncAccuracy accuracy, TimeSyncPeriod period) = 0; - virtual int32_t LnnStopTimeSync(const char *pkgName, const char *targetNetworkId) = 0; + virtual int32_t LnnStopTimeSync(const char *pkgName, const char *targetNetworkId, int32_t callingPid) = 0; virtual int32_t LnnPublishService(const char *pkgName, const PublishInfo *info, bool isInnerRequest) = 0; virtual int32_t LnnUnPublishService(const char *pkgName, int32_t publishId, bool isInnerRequest) = 0; virtual int32_t LnnStartDiscDevice( @@ -76,7 +76,7 @@ public: MOCK_METHOD4(LnnGetNodeKeyInfo, int32_t(const char *, int, uint8_t *, uint32_t)); MOCK_METHOD2(LnnSetNodeDataChangeFlag, int32_t(const char *, uint16_t)); MOCK_METHOD5(LnnStartTimeSync, int32_t(const char *, int32_t, const char *, TimeSyncAccuracy, TimeSyncPeriod)); - MOCK_METHOD2(LnnStopTimeSync, int32_t(const char *, const char *)); + MOCK_METHOD3(LnnStopTimeSync, int32_t(const char *, const char *, int32_t)); MOCK_METHOD3(LnnPublishService, int32_t(const char *, const PublishInfo *, bool)); MOCK_METHOD3(LnnUnPublishService, int32_t(const char *, int32_t, bool)); MOCK_METHOD4(LnnStartDiscDevice, int32_t(const char *, const SubscribeInfo *, const InnerCallback *, bool)); diff --git a/tests/core/bus_center/test/mock/src/bus_center_ipc_mock.cpp b/tests/core/bus_center/test/mock/src/bus_center_ipc_mock.cpp index 30143c76a..4b20a0246 100644 --- a/tests/core/bus_center/test/mock/src/bus_center_ipc_mock.cpp +++ b/tests/core/bus_center/test/mock/src/bus_center_ipc_mock.cpp @@ -78,9 +78,9 @@ int32_t LnnStartTimeSync(const char *pkgName, return BusCenterIpcInterfaceInstance()->LnnStartTimeSync(pkgName, callingPid, targetNetworkId, accuracy, period); } -int32_t LnnStopTimeSync(const char *pkgName, const char *targetNetworkId) +int32_t LnnStopTimeSync(const char *pkgName, const char *targetNetworkId, int32_t callingPid) { - return BusCenterIpcInterfaceInstance()->LnnStopTimeSync(pkgName, targetNetworkId); + return BusCenterIpcInterfaceInstance()->LnnStopTimeSync(pkgName, targetNetworkId, callingPid); } int32_t LnnPublishService(const char *pkgName, const PublishInfo *info, bool isInnerRequest) diff --git a/tests/core/common/BUILD.gn b/tests/core/common/BUILD.gn index 5ab4f7473..260afa983 100644 --- a/tests/core/common/BUILD.gn +++ b/tests/core/common/BUILD.gn @@ -17,14 +17,12 @@ import("../../../dsoftbus.gni") group("unittest") { testonly = true deps = [ - "anonymize:unittest", "bitmap:unittest", "dfx/anonymize:unittest", "dfx/event:unittest", "dfx/hidumper_adapter/unittest:unittest", "dfx/hisysevent_adapter/unittest:unittest", "dfx/log:unittest", - "log:unittest", "network:unittest", "security/permission/common:unittest", "security/permission/standard:unittest", @@ -39,7 +37,6 @@ group("fuzztest") { "dfx/hidumper_adapter/fuzztest:fuzztest", "dfx/hisysevent_adapter/fuzztest:fuzztest", "json_utils:fuzztest", - "log:fuzztest", "message_handler:fuzztest", "utils/fuzztest:fuzztest", ] diff --git a/tests/core/common/anonymize/BUILD.gn b/tests/core/common/anonymize/BUILD.gn deleted file mode 100644 index fc70b0135..000000000 --- a/tests/core/common/anonymize/BUILD.gn +++ /dev/null @@ -1,52 +0,0 @@ -# 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. - -import("../../../../core/common/dfx/dsoftbus_dfx.gni") -import("../../../../dsoftbus.gni") - -dsoftbus_root_path = "../../../.." - -if (defined(ohos_lite)) { - import("//build/lite/config/component/lite_component.gni") - import("//build/lite/config/test.gni") - - if (ohos_build_type == "debug") { - unittest("AnonymizePacketTest") { - output_extension = "bin" - output_dir = "$root_out_dir/test/unittest/dsoftbus" - sources = [ "anonymize_packet_test.cpp" ] - include_dirs = [ "$dsoftbus_root_path/core/common/include" ] - deps = [ "$dsoftbus_root_path/core/common:softbus_utils" ] - deps += [ "$hilog_lite_deps_path" ] - } - } -} else { - import("//build/test.gni") - - module_output_path = "dsoftbus/common" - ohos_unittest("AnonymizePacketTest") { - module_out_path = module_output_path - sources = [ "anonymize_packet_test.cpp" ] - include_dirs = [ "$dsoftbus_root_path/core/common/include" ] - deps = [ "$dsoftbus_root_path/core/common:softbus_utils" ] - if (is_standard_system) { - external_deps = [ "hilog:libhilog" ] - } else { - external_deps = [ "hilog:libhilog" ] - } - } - group("unittest") { - testonly = true - deps = [ ":AnonymizePacketTest" ] - } -} diff --git a/tests/core/common/anonymize/anonymize_packet_test.cpp b/tests/core/common/anonymize/anonymize_packet_test.cpp deleted file mode 100644 index a41581a61..000000000 --- a/tests/core/common/anonymize/anonymize_packet_test.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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 -#include - -#include "softbus_adapter_mem.h" -#include "softbus_log_old.h" - -using namespace std; -using namespace testing::ext; - -namespace OHOS { -const char *g_originPacket = "\"DEVICE_ID\":\"18f3b221c8661b51eaf6520c223f48afe211111113ab9c6a4f03b7c719eb60d1\""; -const char *g_anonymizedPacket = "\"DEVICE_ID\":\"18f3******60d1\""; -const char *g_shortPacket = "\"DEVICE_ID\":\"18f3b221c8661b5111111111111111b7c719eb60d1\""; -const char *g_testSessionName = "test.ohos.abc60272D6C226F0E08021F07AAAAAAAAAABBBBBBBB9A0111111111169A5342784D2EB\ -123456789ABCCCCCCCCCCCCCD57A4Cam_Cam123"; -const char *g_testAnonySessionName = "test.ohos.abc6027******57A4Cam_Cam123"; - -class AnonymizePacketTest : public testing::Test { -public: - static void SetUpTestCase(); - static void TearDownTestCase(); - void SetUp(); - void TearDown(); -}; - -void AnonymizePacketTest::SetUpTestCase(void) {} - -void AnonymizePacketTest::TearDownTestCase(void) {} - -void AnonymizePacketTest::SetUp(void) {} - -void AnonymizePacketTest::TearDown(void) {} - -/** - * @tc.name: AnonySessionNameNormalTest001 - * @tc.desc: Verify AnonyDevId function, use the normal parameter. - * @tc.type: FUNC - * @tc.require: - */ -HWTEST_F(AnonymizePacketTest, AnonySessionNameNormalTest001, TestSize.Level0) -{ - char *anonymizedOut = nullptr; - const char *res = AnonyDevId(&anonymizedOut, g_testSessionName); - EXPECT_STREQ(g_testAnonySessionName, res); - - SoftBusFree(anonymizedOut); -} -}; // namespace OHOS diff --git a/tests/core/common/dfx/anonymize/unittest/src/anonymizer_test.cpp b/tests/core/common/dfx/anonymize/unittest/src/anonymizer_test.cpp index 0d6a0641e..6af2a7a32 100644 --- a/tests/core/common/dfx/anonymize/unittest/src/anonymizer_test.cpp +++ b/tests/core/common/dfx/anonymize/unittest/src/anonymizer_test.cpp @@ -54,7 +54,7 @@ class AnonymizerTest : public testing::Test { }; HWTEST_F(AnonymizerTest, AnonymizeTest001, TestSize.Level0) { const char *plainStr = nullptr; - char *anonymizedStr; + char *anonymizedStr = NULL; Anonymize(plainStr, &anonymizedStr); EXPECT_STREQ("NULL", anonymizedStr); AnonymizeFree(anonymizedStr); @@ -69,7 +69,7 @@ HWTEST_F(AnonymizerTest, AnonymizeTest001, TestSize.Level0) HWTEST_F(AnonymizerTest, AnonymizeTest002, TestSize.Level0) { const char *plainStr = "a"; - char *anonymizedStr; + char *anonymizedStr = NULL; Anonymize(plainStr, &anonymizedStr); EXPECT_STREQ("*", anonymizedStr); AnonymizeFree(anonymizedStr); @@ -84,7 +84,7 @@ HWTEST_F(AnonymizerTest, AnonymizeTest002, TestSize.Level0) HWTEST_F(AnonymizerTest, AnonymizeTest003, TestSize.Level0) { const char *plainStr = "ab"; - char *anonymizedStr; + char *anonymizedStr = NULL; Anonymize(plainStr, &anonymizedStr); EXPECT_STREQ("*b", anonymizedStr); AnonymizeFree(anonymizedStr); @@ -99,7 +99,7 @@ HWTEST_F(AnonymizerTest, AnonymizeTest003, TestSize.Level0) HWTEST_F(AnonymizerTest, AnonymizeTest004, TestSize.Level0) { const char *plainStr = "abc"; - char *anonymizedStr; + char *anonymizedStr = NULL; Anonymize(plainStr, &anonymizedStr); EXPECT_STREQ("*c", anonymizedStr); AnonymizeFree(anonymizedStr); @@ -127,7 +127,7 @@ HWTEST_F(AnonymizerTest, AnonymizeTest005, TestSize.Level0) HWTEST_F(AnonymizerTest, AnonymizeTest006, TestSize.Level0) { const char *plainStr = ""; - char *anonymizedStr; + char *anonymizedStr = NULL; Anonymize(plainStr, &anonymizedStr); EXPECT_STREQ("EMPTY", anonymizedStr); AnonymizeFree(anonymizedStr); @@ -141,9 +141,10 @@ HWTEST_F(AnonymizerTest, AnonymizeTest006, TestSize.Level0) */ HWTEST_F(AnonymizerTest, AnonymizeTest007, TestSize.Level0) { - char *anonymizedStr; + char *anonymizedStr = NULL; Anonymize(TEST_PLAIN_UDID, &anonymizedStr); EXPECT_STREQ(TEST_ANONYMIZED_UDID, anonymizedStr); + AnonymizeFree(anonymizedStr); Anonymize(TEST_PLAIN_UDID_CAPS, &anonymizedStr); EXPECT_STREQ(TEST_ANONYMIZED_UDID_CAPS, anonymizedStr); @@ -158,15 +159,18 @@ HWTEST_F(AnonymizerTest, AnonymizeTest007, TestSize.Level0) */ HWTEST_F(AnonymizerTest, AnonymizeTest008, TestSize.Level0) { - char *anonymizedStr; + char *anonymizedStr = NULL; Anonymize(TEST_PLAIN_MAC, &anonymizedStr); EXPECT_STREQ(TEST_ANONYMIZED_MAC, anonymizedStr); + AnonymizeFree(anonymizedStr); Anonymize(TEST_PLAIN_MAC_CAPS, &anonymizedStr); EXPECT_STREQ(TEST_ANONYMIZED_MAC_CAPS, anonymizedStr); + AnonymizeFree(anonymizedStr); Anonymize(TEST_PLAIN_MAC_COLON, &anonymizedStr); EXPECT_STREQ(TEST_ANONYMIZED_MAC_COLON, anonymizedStr); + AnonymizeFree(anonymizedStr); Anonymize(TEST_PLAIN_MAC_CAPS_COLON, &anonymizedStr); EXPECT_STREQ(TEST_ANONYMIZED_MAC_CAPS_COLON, anonymizedStr); @@ -181,12 +185,14 @@ HWTEST_F(AnonymizerTest, AnonymizeTest008, TestSize.Level0) */ HWTEST_F(AnonymizerTest, AnonymizeTest009, TestSize.Level0) { - char *anonymizedStr; + char *anonymizedStr = NULL; Anonymize(TEST_PLAIN_IP_ONE, &anonymizedStr); EXPECT_STREQ(TEST_ANONYMIZED_IP_ONE, anonymizedStr); + AnonymizeFree(anonymizedStr); Anonymize(TEST_PLAIN_IP_TWO, &anonymizedStr); EXPECT_STREQ(TEST_ANONYMIZED_IP_TWO, anonymizedStr); + AnonymizeFree(anonymizedStr); Anonymize(TEST_PLAIN_IP_THREE, &anonymizedStr); EXPECT_STREQ(TEST_ANONYMIZED_IP_THREE, anonymizedStr); diff --git a/tests/core/common/dfx/event/unittest/BUILD.gn b/tests/core/common/dfx/event/unittest/BUILD.gn index 1d6095ed2..00c6231d4 100644 --- a/tests/core/common/dfx/event/unittest/BUILD.gn +++ b/tests/core/common/dfx/event/unittest/BUILD.gn @@ -35,6 +35,7 @@ ohos_unittest("SoftBusDfxEventTest") { "//third_party/bounds_checking_function/include", ] deps = [ + "$dsoftbus_dfx_path/anonymize:softbus_dfx_anonymizer", "$dsoftbus_dfx_path/event:softbus_dfx_event", "$dsoftbus_dfx_path/log:softbus_dfx_log", "//third_party/bounds_checking_function:libsec_shared", diff --git a/tests/core/common/dfx/event/unittest/mock/conn_hisysevent_matcher.h b/tests/core/common/dfx/event/unittest/mock/conn_hisysevent_matcher.h index e5c07108a..14f074aef 100644 --- a/tests/core/common/dfx/event/unittest/mock/conn_hisysevent_matcher.h +++ b/tests/core/common/dfx/event/unittest/mock/conn_hisysevent_matcher.h @@ -82,19 +82,28 @@ MATCHER_P2(ConnValidParamArrayMatcher, inExtra, validSize, "conn valid param arr ++index; EXPECT_STREQ(params[index].name, g_connAssigners[index].name); EXPECT_EQ(params[index].t, g_connAssigners[index].type); - EXPECT_STREQ(params[index].v.s, extra.peerIp); + char *anonyStr = NULL; + Anonymize(extra.peerIp, &anonyStr); + EXPECT_STREQ(params[index].v.s, anonyStr); + AnonymizeFree(anonyStr); ++index; EXPECT_STREQ(params[index].name, g_connAssigners[index].name); EXPECT_EQ(params[index].t, g_connAssigners[index].type); - EXPECT_STREQ(params[index].v.s, extra.peerBrMac); + Anonymize(extra.peerBrMac, &anonyStr); + EXPECT_STREQ(params[index].v.s, anonyStr); + AnonymizeFree(anonyStr); ++index; EXPECT_STREQ(params[index].name, g_connAssigners[index].name); EXPECT_EQ(params[index].t, g_connAssigners[index].type); - EXPECT_STREQ(params[index].v.s, extra.peerBleMac); + Anonymize(extra.peerBleMac, &anonyStr); + EXPECT_STREQ(params[index].v.s, anonyStr); + AnonymizeFree(anonyStr); ++index; EXPECT_STREQ(params[index].name, g_connAssigners[index].name); EXPECT_EQ(params[index].t, g_connAssigners[index].type); - EXPECT_STREQ(params[index].v.s, extra.peerWifiMac); + Anonymize(extra.peerWifiMac, &anonyStr); + EXPECT_STREQ(params[index].v.s, anonyStr); + AnonymizeFree(anonyStr); ++index; EXPECT_STREQ(params[index].name, g_connAssigners[index].name); EXPECT_EQ(params[index].t, g_connAssigners[index].type); diff --git a/tests/core/common/dfx/event/unittest/mock/disc_hisysevent_matcher.h b/tests/core/common/dfx/event/unittest/mock/disc_hisysevent_matcher.h index a6545f28a..141b04d36 100644 --- a/tests/core/common/dfx/event/unittest/mock/disc_hisysevent_matcher.h +++ b/tests/core/common/dfx/event/unittest/mock/disc_hisysevent_matcher.h @@ -66,11 +66,16 @@ MATCHER_P2(DiscValidParamArrayMatcher, inExtra, validSize, "disc valid param arr ++index; EXPECT_STREQ(params[index].name, g_discAssigners[index].name); EXPECT_EQ(params[index].t, g_discAssigners[index].type); - EXPECT_STREQ(params[index].v.s, extra.localNetworkId); + char *anonyStr = NULL; + Anonymize(extra.localNetworkId, &anonyStr); + EXPECT_STREQ(params[index].v.s, anonyStr); + AnonymizeFree(anonyStr); ++index; EXPECT_STREQ(params[index].name, g_discAssigners[index].name); EXPECT_EQ(params[index].t, g_discAssigners[index].type); - EXPECT_STREQ(params[index].v.s, extra.localUdid); + Anonymize(extra.localUdid, &anonyStr); + EXPECT_STREQ(params[index].v.s, anonyStr); + AnonymizeFree(anonyStr); ++index; EXPECT_STREQ(params[index].name, g_discAssigners[index].name); EXPECT_EQ(params[index].t, g_discAssigners[index].type); @@ -78,19 +83,27 @@ MATCHER_P2(DiscValidParamArrayMatcher, inExtra, validSize, "disc valid param arr ++index; EXPECT_STREQ(params[index].name, g_discAssigners[index].name); EXPECT_EQ(params[index].t, g_discAssigners[index].type); - EXPECT_STREQ(params[index].v.s, extra.peerIp); + Anonymize(extra.peerIp, &anonyStr); + EXPECT_STREQ(params[index].v.s, anonyStr); + AnonymizeFree(anonyStr); ++index; EXPECT_STREQ(params[index].name, g_discAssigners[index].name); EXPECT_EQ(params[index].t, g_discAssigners[index].type); - EXPECT_STREQ(params[index].v.s, extra.peerBrMac); + Anonymize(extra.peerBrMac, &anonyStr); + EXPECT_STREQ(params[index].v.s, anonyStr); + AnonymizeFree(anonyStr); ++index; EXPECT_STREQ(params[index].name, g_discAssigners[index].name); EXPECT_EQ(params[index].t, g_discAssigners[index].type); - EXPECT_STREQ(params[index].v.s, extra.peerBleMac); + Anonymize(extra.peerBleMac, &anonyStr); + EXPECT_STREQ(params[index].v.s, anonyStr); + AnonymizeFree(anonyStr); ++index; EXPECT_STREQ(params[index].name, g_discAssigners[index].name); EXPECT_EQ(params[index].t, g_discAssigners[index].type); - EXPECT_STREQ(params[index].v.s, extra.peerWifiMac); + Anonymize(extra.peerWifiMac, &anonyStr); + EXPECT_STREQ(params[index].v.s, anonyStr); + AnonymizeFree(anonyStr); ++index; EXPECT_STREQ(params[index].name, g_discAssigners[index].name); EXPECT_EQ(params[index].t, g_discAssigners[index].type); @@ -98,11 +111,15 @@ MATCHER_P2(DiscValidParamArrayMatcher, inExtra, validSize, "disc valid param arr ++index; EXPECT_STREQ(params[index].name, g_discAssigners[index].name); EXPECT_EQ(params[index].t, g_discAssigners[index].type); - EXPECT_STREQ(params[index].v.s, extra.peerUdid); + Anonymize(extra.peerUdid, &anonyStr); + EXPECT_STREQ(params[index].v.s, anonyStr); + AnonymizeFree(anonyStr); ++index; EXPECT_STREQ(params[index].name, g_discAssigners[index].name); EXPECT_EQ(params[index].t, g_discAssigners[index].type); - EXPECT_STREQ(params[index].v.s, extra.peerNetworkId); + Anonymize(extra.peerNetworkId, &anonyStr); + EXPECT_STREQ(params[index].v.s, anonyStr); + AnonymizeFree(anonyStr); ++index; EXPECT_STREQ(params[index].name, g_discAssigners[index].name); EXPECT_EQ(params[index].t, g_discAssigners[index].type); diff --git a/tests/core/common/dfx/event/unittest/mock/lnn_hisysevent_matcher.h b/tests/core/common/dfx/event/unittest/mock/lnn_hisysevent_matcher.h index be1fabdfe..11efa948d 100644 --- a/tests/core/common/dfx/event/unittest/mock/lnn_hisysevent_matcher.h +++ b/tests/core/common/dfx/event/unittest/mock/lnn_hisysevent_matcher.h @@ -67,19 +67,28 @@ MATCHER_P2(LnnValidParamArrayMatcher, inExtra, validSize, "lnn valid param array ++index; EXPECT_STREQ(params[index].name, g_lnnAssigners[index].name); EXPECT_EQ(params[index].t, g_lnnAssigners[index].type); - EXPECT_STREQ(params[index].v.s, extra.peerIp); + char *anonyStr = NULL; + Anonymize(extra.peerIp, &anonyStr); + EXPECT_STREQ(params[index].v.s, anonyStr); + AnonymizeFree(anonyStr); ++index; EXPECT_STREQ(params[index].name, g_lnnAssigners[index].name); EXPECT_EQ(params[index].t, g_lnnAssigners[index].type); - EXPECT_STREQ(params[index].v.s, extra.peerBrMac); + Anonymize(extra.peerBrMac, &anonyStr); + EXPECT_STREQ(params[index].v.s, anonyStr); + AnonymizeFree(anonyStr); ++index; EXPECT_STREQ(params[index].name, g_lnnAssigners[index].name); EXPECT_EQ(params[index].t, g_lnnAssigners[index].type); - EXPECT_STREQ(params[index].v.s, extra.peerBleMac); + Anonymize(extra.peerBleMac, &anonyStr); + EXPECT_STREQ(params[index].v.s, anonyStr); + AnonymizeFree(anonyStr); ++index; EXPECT_STREQ(params[index].name, g_lnnAssigners[index].name); EXPECT_EQ(params[index].t, g_lnnAssigners[index].type); - EXPECT_STREQ(params[index].v.s, extra.peerWifiMac); + Anonymize(extra.peerWifiMac, &anonyStr); + EXPECT_STREQ(params[index].v.s, anonyStr); + AnonymizeFree(anonyStr); ++index; EXPECT_STREQ(params[index].name, g_lnnAssigners[index].name); EXPECT_EQ(params[index].t, g_lnnAssigners[index].type); @@ -87,11 +96,15 @@ MATCHER_P2(LnnValidParamArrayMatcher, inExtra, validSize, "lnn valid param array ++index; EXPECT_STREQ(params[index].name, g_lnnAssigners[index].name); EXPECT_EQ(params[index].t, g_lnnAssigners[index].type); - EXPECT_STREQ(params[index].v.s, extra.peerUdid); + Anonymize(extra.peerUdid, &anonyStr); + EXPECT_STREQ(params[index].v.s, anonyStr); + AnonymizeFree(anonyStr); ++index; EXPECT_STREQ(params[index].name, g_lnnAssigners[index].name); EXPECT_EQ(params[index].t, g_lnnAssigners[index].type); - EXPECT_STREQ(params[index].v.s, extra.peerNetworkId); + Anonymize(extra.peerNetworkId, &anonyStr); + EXPECT_STREQ(params[index].v.s, anonyStr); + AnonymizeFree(anonyStr); ++index; EXPECT_STREQ(params[index].name, g_lnnAssigners[index].name); EXPECT_EQ(params[index].t, g_lnnAssigners[index].type); diff --git a/tests/core/common/dfx/event/unittest/mock/trans_hisysevent_matcher.h b/tests/core/common/dfx/event/unittest/mock/trans_hisysevent_matcher.h index 3a8ae24e5..f017f5b12 100644 --- a/tests/core/common/dfx/event/unittest/mock/trans_hisysevent_matcher.h +++ b/tests/core/common/dfx/event/unittest/mock/trans_hisysevent_matcher.h @@ -103,7 +103,10 @@ MATCHER_P2(TransValidParamArrayMatcher, inExtra, validSize, "trans valid param a ++index; EXPECT_STREQ(params[index].name, g_transAssigners[index].name); EXPECT_EQ(params[index].t, g_transAssigners[index].type); - EXPECT_STREQ(params[index].v.s, extra.peerNetworkId); + char *anonyStr = NULL; + Anonymize(extra.peerNetworkId, &anonyStr); + EXPECT_STREQ(params[index].v.s, anonyStr); + AnonymizeFree(anonyStr); ++index; EXPECT_STREQ(params[index].name, g_transAssigners[index].name); EXPECT_EQ(params[index].t, g_transAssigners[index].type); diff --git a/tests/core/common/dfx/event/unittest/src/conn_event_test.cpp b/tests/core/common/dfx/event/unittest/src/conn_event_test.cpp index 4b43e768b..120e3f632 100644 --- a/tests/core/common/dfx/event/unittest/src/conn_event_test.cpp +++ b/tests/core/common/dfx/event/unittest/src/conn_event_test.cpp @@ -72,10 +72,10 @@ HWTEST_F(ConnEventTest, ConnEventTest002, TestSize.Level0) .rssi = 10, .load = 11, .frequency = 12, - .peerIp = "testPeerIp", - .peerBrMac = "testPeerBrMac", - .peerBleMac = "testPeerBleMac", - .peerWifiMac = "testPeerWifiMac", + .peerIp = "10.11.12.1", + .peerBrMac = "dd-15-bc-b9-f2-04", + .peerBleMac = "dd-15-bc-b9-f2-04", + .peerWifiMac = "dd-15-bc-b9-f2-04", .peerPort = "testPeerPort", .callerPkg = "testCallerPkg", .calleePkg = "testCalleePkg", diff --git a/tests/core/common/dfx/event/unittest/src/disc_event_test.cpp b/tests/core/common/dfx/event/unittest/src/disc_event_test.cpp index e883f6b2c..e03474f47 100644 --- a/tests/core/common/dfx/event/unittest/src/disc_event_test.cpp +++ b/tests/core/common/dfx/event/unittest/src/disc_event_test.cpp @@ -68,17 +68,17 @@ HWTEST_F(DiscEventTest, DiscEventTest002, TestSize.Level0) .discType = 7, .discMode = 8, .costTime = 9, - .localNetworkId = "testLocalNetworkId", - .localUdid = "testLocalUdid", + .localNetworkId = "a8ynvpdaihw1f6nknjd2hkfhxljxypkr6kvjsbhnhpp16974uo4fvsrpfa6t50fm", + .localUdid = "a8ynvpdaihw1f6nknjd2hkfhxljxypkr6kvjsbhnhpp16974uo4fvsrpfa6t50fm", .localDeviceType = "testLocalDeviceType", - .peerIp = "testPeerIp", - .peerBrMac = "testPeerBrMac", - .peerBleMac = "testPeerBleMac", - .peerWifiMac = "testPeerWifiMac", + .peerIp = "10.11.12.1", + .peerBrMac = "dd:15:bc:b9:f2:05", + .peerBleMac = "dd:15:bc:b9:f2:04", + .peerWifiMac = "dd:15:bc:b9:f2:04", .peerPort = "testPeerPort", .peerUdid = "testPeerUdid", - .peerNetworkId = "testPeerNetworkId", - .peerDeviceType = "testPeerDeviceType", + .peerNetworkId = "a8ynvpdaihw1f6nknjd2hkfhxljxypkr6kvjsbhnhpp16974uo4fvsrpfa6t50fm", + .peerDeviceType = "a8ynvpdaihw1f6nknjd2hkfhxljxypkr6kvjsbhnhpp16974uo4fvsrpfa6t50fm", .callerPkg = "testCallerPkg", }; constexpr int32_t VALID_EXTRA_SIZE = DISC_ASSIGNER_SIZE; diff --git a/tests/core/common/dfx/event/unittest/src/lnn_event_test.cpp b/tests/core/common/dfx/event/unittest/src/lnn_event_test.cpp index db0593733..9b21ea4e3 100644 --- a/tests/core/common/dfx/event/unittest/src/lnn_event_test.cpp +++ b/tests/core/common/dfx/event/unittest/src/lnn_event_test.cpp @@ -68,13 +68,13 @@ HWTEST_F(LnnEventTest, LnnEventTest002, TestSize.Level0) .onlineNum = 7, .peerDeviceAbility = 8, .peerDeviceInfo = "testPeerDeviceInfo", - .peerIp = "testPeerIp", - .peerBrMac = "testPeerBrMac", - .peerBleMac = "testPeerBleMac", - .peerWifiMac = "testPeerWifiMac", + .peerIp = "10.11.12.1", + .peerBrMac = "dd:15:bc:b9:f2:04", + .peerBleMac = "dd:15:bc:b9:f2:04", + .peerWifiMac = "dd:15:bc:b9:f2:04", .peerPort = "testPeerPort", - .peerUdid = "testPeerUdid", - .peerNetworkId = "testPeerNetworkId", + .peerUdid = "a8ynvpdaihw1f6nknjd2hkfhxljxypkr6kvjsbhnhpp16974uo4fvsrpfa6t50fm", + .peerNetworkId = "a8ynvpdaihw1f6nknjd2hkfhxljxypkr6kvjsbhnhpp16974uo4fvsrpfa6t50fm", .peerDeviceType = "testPeerDeviceType", .callerPkg = "testCallerPkg", .calleePkg = "testCalleePkg", diff --git a/tests/core/common/dfx/event/unittest/src/trans_event_test.cpp b/tests/core/common/dfx/event/unittest/src/trans_event_test.cpp index 79af3d5e9..be0e822b8 100644 --- a/tests/core/common/dfx/event/unittest/src/trans_event_test.cpp +++ b/tests/core/common/dfx/event/unittest/src/trans_event_test.cpp @@ -77,7 +77,7 @@ HWTEST_F(TransEventTest, TransEventTest002, TestSize.Level0) .channelScore = 15, .peerChannelId = 16, .btFlow = 17, - .peerNetworkId = "testNetworkId", + .peerNetworkId = "a8ynvpdaihw1f6nknjd2hkfhxljxypkr6kvjsbhnhpp16974uo4fvsrpfa6t50fm", .callerPkg = "testCallerPkg", .calleePkg = "testCalleePkg", }; diff --git a/tests/core/common/dfx/hisysevent_adapter/unittest/disc_conn_dfx_test.cpp b/tests/core/common/dfx/hisysevent_adapter/unittest/disc_conn_dfx_test.cpp index 931511d01..a2b66a077 100644 --- a/tests/core/common/dfx/hisysevent_adapter/unittest/disc_conn_dfx_test.cpp +++ b/tests/core/common/dfx/hisysevent_adapter/unittest/disc_conn_dfx_test.cpp @@ -18,7 +18,6 @@ #include "softbus_error_code.h" #include "softbus_adapter_mem.h" -#include "softbus_log_old.h" #include "softbus_common.h" #include "softbus_hisysevt_bus_center.h" #include "securec.h" diff --git a/tests/core/common/dfx/hisysevent_adapter/unittest/lnn_dfx_test.cpp b/tests/core/common/dfx/hisysevent_adapter/unittest/lnn_dfx_test.cpp index 256ad0ab9..ab035c0bf 100644 --- a/tests/core/common/dfx/hisysevent_adapter/unittest/lnn_dfx_test.cpp +++ b/tests/core/common/dfx/hisysevent_adapter/unittest/lnn_dfx_test.cpp @@ -18,7 +18,6 @@ #include "softbus_error_code.h" #include "softbus_adapter_mem.h" -#include "softbus_log_old.h" #include "softbus_common.h" #include "softbus_hisysevt_bus_center.h" #include "securec.h" diff --git a/tests/core/common/dfx/log/unittest/src/softbus_log_test.cpp b/tests/core/common/dfx/log/unittest/src/softbus_log_test.cpp index 95829230b..514092137 100644 --- a/tests/core/common/dfx/log/unittest/src/softbus_log_test.cpp +++ b/tests/core/common/dfx/log/unittest/src/softbus_log_test.cpp @@ -48,11 +48,11 @@ class SoftBusLogTest : public testing::Test { }; */ HWTEST_F(SoftBusLogTest, SoftBusLogTest001, TestSize.Level0) { - EXPECT_EQ(static_cast(LOG_DEBUG), static_cast(SOFTBUS_DFX_LOG_DEBUG)); - EXPECT_EQ(static_cast(LOG_INFO), static_cast(SOFTBUS_DFX_LOG_INFO)); - EXPECT_EQ(static_cast(LOG_WARN), static_cast(SOFTBUS_DFX_LOG_WARN)); - EXPECT_EQ(static_cast(LOG_ERROR), static_cast(SOFTBUS_DFX_LOG_ERROR)); - EXPECT_EQ(static_cast(LOG_FATAL), static_cast(SOFTBUS_DFX_LOG_FATAL)); + EXPECT_EQ(static_cast(LOG_DEBUG), static_cast(SOFTBUS_LOG_DEBUG)); + EXPECT_EQ(static_cast(LOG_INFO), static_cast(SOFTBUS_LOG_INFO)); + EXPECT_EQ(static_cast(LOG_WARN), static_cast(SOFTBUS_LOG_WARN)); + EXPECT_EQ(static_cast(LOG_ERROR), static_cast(SOFTBUS_LOG_ERROR)); + EXPECT_EQ(static_cast(LOG_FATAL), static_cast(SOFTBUS_LOG_FATAL)); } /** @@ -63,7 +63,7 @@ HWTEST_F(SoftBusLogTest, SoftBusLogTest001, TestSize.Level0) */ HWTEST_F(SoftBusLogTest, SoftBusLogTest002, TestSize.Level0) { - SoftBusDfxLogLevel level = SOFTBUS_DFX_LOG_INFO; + SoftBusLogLevel level = SOFTBUS_LOG_INFO; SoftBusLogLabel label = { .domain = DOMAIN_ID_TEST, .tag = "SoftBusTest", @@ -89,7 +89,7 @@ HWTEST_F(SoftBusLogTest, SoftBusLogTest003, TestSize.Level0) // Test for debug level uint32_t logLevel = NSTACKX_LOG_LEVEL_DEBUG; - SoftBusDfxLogLevel expectLevel = SOFTBUS_DFX_LOG_DEBUG; + SoftBusLogLevel expectLevel = SOFTBUS_LOG_DEBUG; HilogMock mock; EXPECT_CALL(mock, HiLogPrint(Eq(LOG_CORE), Eq(static_cast(expectLevel)), Eq(NSTACKX_LOG_DOMAIN), StrEq(moduleName), @@ -99,7 +99,7 @@ HWTEST_F(SoftBusLogTest, SoftBusLogTest003, TestSize.Level0) // Test for info level logLevel = NSTACKX_LOG_LEVEL_INFO; - expectLevel = SOFTBUS_DFX_LOG_INFO; + expectLevel = SOFTBUS_LOG_INFO; EXPECT_CALL(mock, HiLogPrint(Eq(LOG_CORE), Eq(static_cast(expectLevel)), Eq(NSTACKX_LOG_DOMAIN), StrEq(moduleName), StrEq("%{public}s"), EndsWith(TEST_LOG_DETAIL))) @@ -108,7 +108,7 @@ HWTEST_F(SoftBusLogTest, SoftBusLogTest003, TestSize.Level0) // Test for warn level logLevel = NSTACKX_LOG_LEVEL_WARNING; - expectLevel = SOFTBUS_DFX_LOG_WARN; + expectLevel = SOFTBUS_LOG_WARN; EXPECT_CALL(mock, HiLogPrint(Eq(LOG_CORE), Eq(static_cast(expectLevel)), Eq(NSTACKX_LOG_DOMAIN), StrEq(moduleName), StrEq("%{public}s"), EndsWith(TEST_LOG_DETAIL))) @@ -117,7 +117,7 @@ HWTEST_F(SoftBusLogTest, SoftBusLogTest003, TestSize.Level0) // Test for error level logLevel = NSTACKX_LOG_LEVEL_ERROR; - expectLevel = SOFTBUS_DFX_LOG_ERROR; + expectLevel = SOFTBUS_LOG_ERROR; EXPECT_CALL(mock, HiLogPrint(Eq(LOG_CORE), Eq(static_cast(expectLevel)), Eq(NSTACKX_LOG_DOMAIN), StrEq(moduleName), StrEq("%{public}s"), EndsWith(TEST_LOG_DETAIL))) @@ -126,7 +126,7 @@ HWTEST_F(SoftBusLogTest, SoftBusLogTest003, TestSize.Level0) // Test for fatal level logLevel = NSTACKX_LOG_LEVEL_FATAL; - expectLevel = SOFTBUS_DFX_LOG_FATAL; + expectLevel = SOFTBUS_LOG_FATAL; EXPECT_CALL(mock, HiLogPrint(Eq(LOG_CORE), Eq(static_cast(expectLevel)), Eq(NSTACKX_LOG_DOMAIN), StrEq(moduleName), StrEq("%{public}s"), EndsWith(TEST_LOG_DETAIL))) diff --git a/tests/core/common/log/fuzztest/softbuslog_fuzzer/softbuslog_fuzzer.cpp b/tests/core/common/log/fuzztest/softbuslog_fuzzer/softbuslog_fuzzer.cpp deleted file mode 100644 index f10fed074..000000000 --- a/tests/core/common/log/fuzztest/softbuslog_fuzzer/softbuslog_fuzzer.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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 "softbuslog_fuzzer.h" - -#include - -#include "softbus_log_old.h" - -namespace OHOS { -static constexpr size_t MAX_BUFFER_LEN = 100; - -static void AnonymizesTest(const char *buffer) -{ - Anonymizes(buffer, 10); -} - -static void AnonyPacketPrintoutTest(const char *buffer, size_t size) -{ - AnonyPacketPrintout(SOFTBUS_LOG_DISC, buffer, buffer, size); -} - -static void AnonyDevIdTest(const char *buffer) -{ - char *outName = nullptr; - AnonyDevId(&outName, buffer); -} -} // namespace OHOS - -/* Fuzzer entry point */ -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) -{ - if (data == nullptr || size < OHOS::MAX_BUFFER_LEN) { - return 0; - } - - char buffer[OHOS::MAX_BUFFER_LEN] = { 0 }; - if (memcpy_s(buffer, sizeof(buffer) - 1, data, size) != EOK) { - return 0; - } - - OHOS::AnonymizesTest(buffer); - OHOS::AnonyPacketPrintoutTest(buffer, OHOS::MAX_BUFFER_LEN - 1); - OHOS::AnonyDevIdTest(buffer); - return 0; -} \ No newline at end of file diff --git a/tests/core/common/log/unittest/BUILD.gn b/tests/core/common/log/unittest/BUILD.gn deleted file mode 100644 index a986e06d9..000000000 --- a/tests/core/common/log/unittest/BUILD.gn +++ /dev/null @@ -1,30 +0,0 @@ -# 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. - -import("//build/test.gni") -import("../../../../../dsoftbus.gni") - -module_output_path = "dsoftbus/common" -dsoftbus_root_path = "../../../../.." - -ohos_unittest("SoftBusLogTest") { - module_out_path = module_output_path - sources = [ "softbus_log_test.cpp" ] - include_dirs = [ "$dsoftbus_root_path/core/common/include" ] - deps = [ "$dsoftbus_root_path/core/common:softbus_utils" ] - if (is_standard_system) { - external_deps = [ "hilog:libhilog" ] - } else { - external_deps = [ "hilog:libhilog" ] - } -} diff --git a/tests/core/common/log/unittest/softbus_log_test.cpp b/tests/core/common/log/unittest/softbus_log_test.cpp deleted file mode 100644 index 9fdf40159..000000000 --- a/tests/core/common/log/unittest/softbus_log_test.cpp +++ /dev/null @@ -1,102 +0,0 @@ -/* - * 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 -#include - -#include "softbus_adapter_mem.h" -#include "softbus_error_code.h" -#include "softbus_log_old.h" -#include "softbus_utils.h" - -using namespace std; -using namespace testing::ext; - -namespace OHOS { -class SoftBusLogTest : public testing::Test { -public: - static void SetUpTestCase(); - static void TearDownTestCase(); - void SetUp(); - void TearDown(); -}; - -void SoftBusLogTest::SetUpTestCase(void) -{ -} - -void SoftBusLogTest::TearDownTestCase(void) -{ -} - -void SoftBusLogTest::SetUp(void) -{ -} - -void SoftBusLogTest::TearDown(void) -{ -} - -/** - * @tc.name: AnonymizesTest001 - * @tc.desc: Anonymize. - * @tc.type: FUNC - * @tc.require: I60DWN - */ -HWTEST_F(SoftBusLogTest, AnonymizesTest001, TestSize.Level1) -{ - const char *target = nullptr; - uint8_t expectAnonymizedLength = 0; - const char *expected = "NULL"; - const char *actual = Anonymizes(target, expectAnonymizedLength); - EXPECT_STREQ(expected, actual); - - const char *target1 = "target"; - uint8_t expectAnonymizedLength1 = 0; - const char *expected1 = "BADLENGTH"; - const char *actual1 = Anonymizes(target1, expectAnonymizedLength1); - EXPECT_STREQ(expected1, actual1); - - const char *target2 = "target"; - uint8_t expectAnonymizedLength2 = 6; - const char *expected2 = "TOOSHORT"; - const char *actual2 = Anonymizes(target2, expectAnonymizedLength2); - EXPECT_STREQ(expected2, actual2); -} - -/** - * @tc.name: AnonyDevIdTest001 - * @tc.desc: Anonymize devid. - * @tc.type: FUNC - * @tc.require: I60DWN - */ -HWTEST_F(SoftBusLogTest, AnonyDevIdTest001, TestSize.Level1) -{ - char *outName = nullptr; - const char *inName = nullptr; - const char *expected = "null"; - const char *actual = AnonyDevId(&outName, inName); - EXPECT_STREQ(expected, actual); - SoftBusFree(outName); - - char *outName2 = nullptr; - const char *inName2 = "abcdeg"; - const char *expected2 = "abcdeg"; - const char *actual2 = AnonyDevId(&outName2, inName2); - EXPECT_STREQ(expected2, actual2); - SoftBusFree(outName2); -} - -} // namespace OHOS \ No newline at end of file diff --git a/tests/core/common/message_handler/unittest/message_handler_test.c b/tests/core/common/message_handler/unittest/message_handler_test.c index b7e6c11b4..51c1361c1 100644 --- a/tests/core/common/message_handler/unittest/message_handler_test.c +++ b/tests/core/common/message_handler/unittest/message_handler_test.c @@ -15,7 +15,7 @@ #include "message_handler.h" #include "softbus_adapter_mem.h" -#include "softbus_log_old.h" +#include "comm_log.h" #define CASE_ONE_WHAT 1 #define CASE_TWO_WHAT 2 @@ -30,7 +30,7 @@ static void NetworkingHandleMessage(const SoftBusMessage* msg) { - LOG_INFO("NetworkingHandleMessage msg what=%d", msg->what); + COMM_LOGI(COMM_TEST, "NetworkingHandleMessage msg what=%d", msg->what); } static SoftBusHandler g_networkingHandler = { @@ -39,7 +39,7 @@ static SoftBusHandler g_networkingHandler = { static void CustomfreeMessage(SoftBusMessage* msg) { - LOG_INFO("CustomfreeMessage msg=%d", msg->what); + COMM_LOGI(COMM_TEST, "CustomfreeMessage msg=%d", msg->what); if (msg->what == CASE_FOUR_POST_DELAY) { SoftBusFree(msg->obj); SoftBusFree(msg); @@ -50,20 +50,20 @@ void TestMessageHandler(void) { g_networkingHandler.looper = GetLooper(LOOP_TYPE_DEFAULT); g_networkingHandler.HandleMessage = NetworkingHandleMessage; - LOG_INFO("testHandler msg1"); + COMM_LOGI(COMM_TEST, "testHandler msg1"); SoftBusMessage* msg = SoftBusCalloc(sizeof(SoftBusMessage)); if (msg == NULL) { - LOG_INFO("msg malloc fail"); + COMM_LOGI(COMM_TEST, "msg malloc fail"); return; } msg->what = CASE_ONE_WHAT; msg->arg1 = CASE_ARG; msg->handler = &g_networkingHandler; g_networkingHandler.looper->PostMessage(g_networkingHandler.looper, msg); - LOG_INFO("testHandler msg4"); + COMM_LOGI(COMM_TEST, "testHandler msg4"); SoftBusMessage* msg4 = SoftBusCalloc(sizeof(SoftBusMessage)); if (msg4 == NULL) { - LOG_INFO("msg4 malloc fail"); + COMM_LOGI(COMM_TEST, "msg4 malloc fail"); return; } msg4->what = CASE_FOUR_WHAT; @@ -72,14 +72,14 @@ void TestMessageHandler(void) msg4->FreeMessage = CustomfreeMessage; msg4->obj = SoftBusMalloc(CASE_FOUR_OBJ_SIZE); if (msg4->obj == NULL) { - LOG_INFO("msg4_obj malloc fail"); + COMM_LOGI(COMM_TEST, "msg4_obj malloc fail"); return; } g_networkingHandler.looper->PostMessageDelay(g_networkingHandler.looper, msg4, CASE_FOUR_POST_DELAY); - LOG_INFO("testHandler msg3"); + COMM_LOGI(COMM_TEST, "testHandler msg3"); SoftBusMessage* msg3 = SoftBusCalloc(sizeof(SoftBusMessage)); if (msg3 == NULL) { - LOG_INFO("msg3 malloc fail"); + COMM_LOGI(COMM_TEST, "msg3 malloc fail"); return; } msg3->what = CASE_THREE_WHAT; @@ -87,10 +87,10 @@ void TestMessageHandler(void) msg3->handler = &g_networkingHandler; g_networkingHandler.looper->PostMessageDelay(g_networkingHandler.looper, msg3, CASE_THREE_POST_DELAY); g_networkingHandler.looper->RemoveMessage(g_networkingHandler.looper, &g_networkingHandler, CASE_THREE_WHAT); - LOG_INFO("testHandler msg2"); + COMM_LOGI(COMM_TEST, "testHandler msg2"); SoftBusMessage* msg2 = SoftBusCalloc(sizeof(SoftBusMessage)); if (msg2 == NULL) { - LOG_INFO("msg2 malloc fail"); + COMM_LOGI(COMM_TEST, "msg2 malloc fail"); return; } msg2->what = CASE_TWO_WHAT; diff --git a/tests/core/common/utils/fuzztest/encrypteddb_fuzzer/encrypteddb_fuzzer.cpp b/tests/core/common/utils/fuzztest/encrypteddb_fuzzer/encrypteddb_fuzzer.cpp index fab62cef5..4f3533a68 100755 --- a/tests/core/common/utils/fuzztest/encrypteddb_fuzzer/encrypteddb_fuzzer.cpp +++ b/tests/core/common/utils/fuzztest/encrypteddb_fuzzer/encrypteddb_fuzzer.cpp @@ -21,7 +21,6 @@ #include #include "softbus_adapter_mem.h" #include "softbus_errcode.h" -#include "softbus_log_old.h" namespace OHOS { bool DoSomethingInterestingWithMyAPI(const uint8_t *data, size_t size) diff --git a/tests/core/common/utils/fuzztest/insertrecord_fuzzer/insertrecord_fuzzer.cpp b/tests/core/common/utils/fuzztest/insertrecord_fuzzer/insertrecord_fuzzer.cpp index a3157fc16..29ff2690c 100755 --- a/tests/core/common/utils/fuzztest/insertrecord_fuzzer/insertrecord_fuzzer.cpp +++ b/tests/core/common/utils/fuzztest/insertrecord_fuzzer/insertrecord_fuzzer.cpp @@ -21,7 +21,6 @@ #include #include "softbus_adapter_mem.h" #include "softbus_errcode.h" -#include "softbus_log_old.h" namespace OHOS { static constexpr size_t MAX_BUFFER_LEN = 100; diff --git a/tests/core/connection/br/connection_br_connection_test.cpp b/tests/core/connection/br/connection_br_connection_test.cpp index a5e0b258e..9c6a5bb96 100644 --- a/tests/core/connection/br/connection_br_connection_test.cpp +++ b/tests/core/connection/br/connection_br_connection_test.cpp @@ -29,7 +29,6 @@ #include "softbus_conn_manager.h" #include "softbus_errcode.h" #include "softbus_feature_config.h" -#include "softbus_log_old.h" #include "softbus_conn_br_send_queue.h" #include "softbus_feature_config.c" diff --git a/tests/core/connection/br/connection_br_test.cpp b/tests/core/connection/br/connection_br_test.cpp index 8ba7b0a47..03b0c3d6e 100644 --- a/tests/core/connection/br/connection_br_test.cpp +++ b/tests/core/connection/br/connection_br_test.cpp @@ -30,7 +30,6 @@ #include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_feature_config.h" -#include "softbus_log_old.h" #include "softbus_conn_br_send_queue.h" static const uint32_t CONN_HEAD_SIZE = 24; diff --git a/tests/core/connection/common/unittest/softbus_conn_common_test.cpp b/tests/core/connection/common/unittest/softbus_conn_common_test.cpp index 43965b75f..306727082 100644 --- a/tests/core/connection/common/unittest/softbus_conn_common_test.cpp +++ b/tests/core/connection/common/unittest/softbus_conn_common_test.cpp @@ -21,7 +21,6 @@ #include "softbus_base_listener.h" #include "softbus_def.h" #include "softbus_errcode.h" -#include "softbus_log_old.h" #include "softbus_tcp_socket.h" #include "softbus_utils.h" #include "softbus_conn_manager.h" diff --git a/tests/core/connection/manager/connection_manager_test.cpp b/tests/core/connection/manager/connection_manager_test.cpp index 1051998e8..98f38b655 100644 --- a/tests/core/connection/manager/connection_manager_test.cpp +++ b/tests/core/connection/manager/connection_manager_test.cpp @@ -25,7 +25,6 @@ #include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_feature_config.h" -#include "softbus_log_old.h" static const uint32_t CONN_HEAD_SIZE = 24; static const uint32_t SHIFT_BITS = 16; diff --git a/tests/core/connection/tcp/tcp_manager_test.cpp b/tests/core/connection/tcp/tcp_manager_test.cpp index 12ea86109..3771b18f2 100644 --- a/tests/core/connection/tcp/tcp_manager_test.cpp +++ b/tests/core/connection/tcp/tcp_manager_test.cpp @@ -27,6 +27,7 @@ #include #include "common_list.h" +#include "conn_log.h" #include "softbus_adapter_mem.h" #include "softbus_base_listener.h" #include "softbus_conn_interface.h" @@ -34,7 +35,6 @@ #include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_feature_config.h" -#include "softbus_log_old.h" #include "softbus_tcp_connect_manager.h" #include "softbus_tcp_socket.h" #include "softbus_utils.h" @@ -371,7 +371,7 @@ HWTEST_F(TcpManagerTest, testTcpManager008, TestSize.Level1) int32_t i = 0; if (SoftbusGetConfig(SOFTBUS_INT_CONN_TCP_MAX_CONN_NUM, (unsigned char*)&maxConnNum, sizeof(maxConnNum)) != SOFTBUS_OK) { - LOG_ERR("get maxConnNum fail"); + CONN_LOGE(CONN_TEST, "get maxConnNum fail"); } printf("maxConnNum: %d\n", maxConnNum); EXPECT_EQ(port, TcpStartListening(&info)); @@ -414,7 +414,7 @@ HWTEST_F(TcpManagerTest, testTcpManager009, TestSize.Level1) int maxDataLen; if (SoftbusGetConfig(SOFTBUS_INT_CONN_TCP_MAX_LENGTH, (unsigned char*)&maxDataLen, sizeof(maxDataLen)) != SOFTBUS_OK) { - LOG_ERR("get maxDataLen fail"); + CONN_LOGE(CONN_TEST, "get maxDataLen fail"); } printf("maxDataLen: %d\n", maxDataLen); ConnPktHead head = {0}; diff --git a/tests/core/connection/wifi_direct/adapter/single/broadcast_receiver_test.cpp b/tests/core/connection/wifi_direct/adapter/single/broadcast_receiver_test.cpp index 20044de84..afadf18c9 100644 --- a/tests/core/connection/wifi_direct/adapter/single/broadcast_receiver_test.cpp +++ b/tests/core/connection/wifi_direct/adapter/single/broadcast_receiver_test.cpp @@ -22,7 +22,6 @@ #include "common_list.h" #include "softbus_adapter_mem.h" #include "softbus_error_code.h" -#include "softbus_log_old.h" #include "utils/wifi_direct_work_queue.h" #include "wifi_direct_p2p_adapter.h" #include "wifi_direct_p2p_adapter_mock.h" diff --git a/tests/core/connection/wifi_direct/adapter/single/link_manager_broadcast_handler_test.cpp b/tests/core/connection/wifi_direct/adapter/single/link_manager_broadcast_handler_test.cpp index 4e76461dd..30999df54 100644 --- a/tests/core/connection/wifi_direct/adapter/single/link_manager_broadcast_handler_test.cpp +++ b/tests/core/connection/wifi_direct/adapter/single/link_manager_broadcast_handler_test.cpp @@ -22,7 +22,6 @@ #include "link_manager_broadcast_handler.h" #include "link_manager_broadcast_handler.c" #include "softbus_error_code.h" -#include "softbus_log_old.h" #include "utils/wifi_direct_anonymous.h" #include "utils/wifi_direct_ipv4_info.h" #include "utils/wifi_direct_network_utils.h" diff --git a/tests/core/connection/wifi_direct/adapter/single/resource_manager_broadcast_handler_test.cpp b/tests/core/connection/wifi_direct/adapter/single/resource_manager_broadcast_handler_test.cpp index e615b3136..ed2cdcb02 100644 --- a/tests/core/connection/wifi_direct/adapter/single/resource_manager_broadcast_handler_test.cpp +++ b/tests/core/connection/wifi_direct/adapter/single/resource_manager_broadcast_handler_test.cpp @@ -23,7 +23,6 @@ #include "resource_manager_broadcast_handler.c" #include "softbus_adapter_mem.h" #include "softbus_error_code.h" -#include "softbus_log_old.h" #include "wifi_direct_p2p_adapter.h" #include "wifi_p2p.h" #include "wifi_p2p_config.h" diff --git a/tests/core/connection/wifi_direct/adapter/single/wifi_direct_p2p_adapter_mock.h b/tests/core/connection/wifi_direct/adapter/single/wifi_direct_p2p_adapter_mock.h index c4d4e89c4..64eac66be 100644 --- a/tests/core/connection/wifi_direct/adapter/single/wifi_direct_p2p_adapter_mock.h +++ b/tests/core/connection/wifi_direct/adapter/single/wifi_direct_p2p_adapter_mock.h @@ -23,7 +23,6 @@ #include "softbus_adapter_crypto.h" #include "softbus_adapter_mem.h" #include "softbus_error_code.h" -#include "softbus_log_old.h" #include "utils/wifi_direct_anonymous.h" #include "utils/wifi_direct_network_utils.h" #include "wifi_device.h" diff --git a/tests/core/connection/wifi_direct/adapter/single/wifi_direct_p2p_adapter_test.cpp b/tests/core/connection/wifi_direct/adapter/single/wifi_direct_p2p_adapter_test.cpp index 37901d5ad..a6c48909c 100644 --- a/tests/core/connection/wifi_direct/adapter/single/wifi_direct_p2p_adapter_test.cpp +++ b/tests/core/connection/wifi_direct/adapter/single/wifi_direct_p2p_adapter_test.cpp @@ -21,7 +21,6 @@ #include "data/resource_manager.h" #include "softbus_adapter_mem.h" #include "softbus_error_code.h" -#include "softbus_log_old.h" #include "wifi_direct_p2p_adapter.h" #include "wifi_direct_p2p_adapter.c" #include "wifi_direct_p2p_adapter_mock.h" diff --git a/tests/core/connection/wifi_direct/channel/channel/BUILD.gn b/tests/core/connection/wifi_direct/channel/BUILD.gn similarity index 100% rename from tests/core/connection/wifi_direct/channel/channel/BUILD.gn rename to tests/core/connection/wifi_direct/channel/BUILD.gn diff --git a/tests/core/connection/wifi_direct/channel/channel/default_negotiate_channel_test.cpp b/tests/core/connection/wifi_direct/channel/default_negotiate_channel_test.cpp similarity index 91% rename from tests/core/connection/wifi_direct/channel/channel/default_negotiate_channel_test.cpp rename to tests/core/connection/wifi_direct/channel/default_negotiate_channel_test.cpp index dde534402..549d7968c 100644 --- a/tests/core/connection/wifi_direct/channel/channel/default_negotiate_channel_test.cpp +++ b/tests/core/connection/wifi_direct/channel/default_negotiate_channel_test.cpp @@ -1,304 +1,288 @@ -/* - * Copyright (c) 2023 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 -#include -#include - -#include "link_manager.h" -#include "interface_info.h" -#include "resource_manager.h" -#include "p2p_v1_processor.h" -#include "negotiate_message.h" -#include "softbus_error_code.h" -#include "softbus_adapter_mem.h" -#include "wifi_direct_command.h" -#include "default_negotiate_channel.h" -#include "wifi_direct_negotiate_channel.h" -#include "fast_connect_negotiate_channel.h" - - -namespace OHOS { -using namespace testing::ext; -using namespace testing; -using namespace std; -extern "C"{ -class WifiDirectChannelTest : public testing::Test { -public: - WifiDirectChannelTest() - {} - ~WifiDirectChannelTest() - {} - static void SetUpTestCase(void); - static void TearDownTestCase(void); - void SetUp(); - void TearDown(); -}; - -void OnConnectSuccess(uint32_t requestId, int64_t authId) -{ - (void)requestId; - (void)authId; -} - -void OnConnectFailure(uint32_t requestId, int32_t reason) -{ - (void)requestId; - (void)reason; -} - -int32_t PostData(struct WifiDirectNegotiateChannel *base, const uint8_t *data, size_t size) -{ - base = nullptr; - data = nullptr; - (void)size; - return SOFTBUS_OK; -} - -int32_t GetDeviceId(struct WifiDirectNegotiateChannel *base, char *deviceId, size_t deviceIdSize) -{ - base = nullptr; - (void)deviceId; - (void)deviceIdSize; - return SOFTBUS_OK; -} - -int32_t GetP2pMac(struct WifiDirectNegotiateChannel *base, char *p2pMac, size_t p2pMacSize) -{ - base = nullptr; - (void)p2pMac; - (void)p2pMacSize; - return SOFTBUS_OK; -} - -void SetP2pMac(struct WifiDirectNegotiateChannel *base, const char *p2pMac) -{ - base = nullptr; -} - -bool IsP2pChannel(struct WifiDirectNegotiateChannel *base) -{ - base = nullptr; - return true; -} - -bool IsMetaChannel(struct WifiDirectNegotiateChannel *base) -{ - base = nullptr; - return false; -} - -struct WifiDirectNegotiateChannel* Duplicate(struct WifiDirectNegotiateChannel *base) -{ - base = nullptr; - return base; -} - -void Destructor(struct WifiDirectNegotiateChannel *base) -{ - SoftBusFree(base); -} - -void WifiDirectNegotiateChannelConstructorTest(struct WifiDirectNegotiateChannel *self) -{ - (void)memset_s(self, sizeof(*self), 0, sizeof(*self)); - self->postData = PostData; - self->getDeviceId = GetDeviceId; - self->getP2pMac = GetP2pMac; - self->setP2pMac = SetP2pMac; - self->isP2pChannel = IsP2pChannel; - self->isMetaChannel = IsMetaChannel; - self->duplicate = Duplicate; - self->destructor = Destructor; -} - -struct WifiDirectNegotiateChannel *WifiDirectNegotiateChannelNew(void) -{ - struct WifiDirectNegotiateChannel *self - = static_cast(SoftBusCalloc(sizeof(*self))); - WifiDirectNegotiateChannelConstructorTest(self); - return self; -} -void WifiDirectChannelTest::SetUpTestCase(void) {} -void WifiDirectChannelTest::TearDownTestCase(void) {} -void WifiDirectChannelTest::SetUp(void) {} -void WifiDirectChannelTest::TearDown(void) {} - -/* default_negotiate_channel.c */ -/* -* @tc.name: testDirectChannelTest001 -* @tc.desc: test OpenDefaultNegotiateChannel -* @tc.type: FUNC -* @tc.require: AR000I9Q40 -*/ -HWTEST_F(WifiDirectChannelTest, testDirectChannelTest001, TestSize.Level0) -{ - struct DefaultNegoChannelOpenCallback callback; - struct P2pV1Processor *self = GetP2pV1Processor(); - struct NegotiateMessage *msg = NegotiateMessageNew(); - EXPECT_NE(msg, nullptr); - - struct WifiDirectNegotiateChannel *channel = WifiDirectNegotiateChannelNew(); - EXPECT_NE(channel, nullptr); - const char *remoteMac = "1a:2b:3c:4d:5e:6f:7g"; - const char *remoteIp = "192.168.1.1"; - channel->setP2pMac(channel, remoteMac); - callback.onConnectFailure = OnConnectFailure; - callback.onConnectSuccess = OnConnectSuccess; - int ret = OpenDefaultNegotiateChannel(remoteIp, self->goPort, channel, &callback); - EXPECT_EQ(SOFTBUS_ERR, ret); -}; - -/* -* @tc.name: testDirectChannelTest002 -* @tc.desc: test PostData -* @tc.type: FUNC -* @tc.require: AR000I9Q40 -*/ -HWTEST_F(WifiDirectChannelTest, testDirectChannelTest002, TestSize.Level0) -{ - WifiDirectNegotiateChannel channel; - uint8_t arr[] = {0x01, 0x02, 0x03, 0x04, 0x05}; - const uint8_t *data = arr; - size_t size = 10; - int32_t ret = DefaultNegotiateChannelNew(1)->postData(&channel, data, size); - EXPECT_EQ(SOFTBUS_ERR, ret); -}; - -/* -* @tc.name: testDirectChannelTest003 -* @tc.desc: test getDeviceId -* @tc.type: FUNC -* @tc.require: AR000I9Q40 -*/ -HWTEST_F(WifiDirectChannelTest, testDirectChannelTest003, TestSize.Level0) -{ - WifiDirectNegotiateChannel channel; - char deviceId[] = {'d', 'e', 'v', 'i', 'c', 'e', 'I', 'd'}; - size_t size = sizeof(deviceId) / sizeof(deviceId[0]); - int32_t ret = DefaultNegotiateChannelNew(1)->getDeviceId(&channel, deviceId, size); - EXPECT_EQ(SOFTBUS_NOT_IMPLEMENT, ret); -}; - -/* -* @tc.name: testDirectChannelTest004 -* @tc.desc: test getP2pMac -* @tc.type: FUNC -* @tc.require: AR000I9Q40 -*/ -HWTEST_F(WifiDirectChannelTest, testDirectChannelTest004, TestSize.Level0) -{ - DefaultNegotiateChannel *base = DefaultNegotiateChannelNew(1); - EXPECT_NE(base, nullptr); - char p2pMac[] = {'p', '2', 'p', 'M', 'a', 'c'}; - size_t p2pMacSize = sizeof(p2pMac) / sizeof(p2pMac[0]); - int32_t ret = base->getP2pMac((WifiDirectNegotiateChannel*)base, p2pMac, p2pMacSize); - EXPECT_EQ(SOFTBUS_NOT_IMPLEMENT, ret); -}; - -/* -* @tc.name: testDirectChannelTest005 -* @tc.desc: test isMetaChannel isP2pChannel SetP2pMac -* @tc.type: FUNC -* @tc.require: AR000I9Q40 -*/ -HWTEST_F(WifiDirectChannelTest, testDirectChannelTest005, TestSize.Level0) -{ - DefaultNegotiateChannel *base = DefaultNegotiateChannelNew(1); - EXPECT_NE(base, nullptr); - const char *p2pMac = "test345"; - base->setP2pMac((WifiDirectNegotiateChannel*)base, p2pMac); - bool ret = base->isP2pChannel((WifiDirectNegotiateChannel*)base); - EXPECT_EQ(false, ret); - ret = base->isMetaChannel((WifiDirectNegotiateChannel*)base); - EXPECT_EQ(true, ret); - - base->authId = 0; - base->setP2pMac((WifiDirectNegotiateChannel*)base, p2pMac); - ret = base->isP2pChannel((WifiDirectNegotiateChannel*)base); - EXPECT_EQ(false, ret); - ret = base->isMetaChannel((WifiDirectNegotiateChannel*)base); - EXPECT_EQ(true, ret); -}; - -/* -* @tc.name: testDirectChannelTest006 -* @tc.desc: test Duplicate -* @tc.type: FUNC -* @tc.require: AR000I9Q40 -*/ -HWTEST_F(WifiDirectChannelTest, testDirectChannelTest006, TestSize.Level0) -{ - DefaultNegotiateChannel *base = DefaultNegotiateChannelNew(1); - EXPECT_NE(base, nullptr); - WifiDirectNegotiateChannel *ret = base->duplicate((WifiDirectNegotiateChannel*)base); - EXPECT_NE(ret, nullptr); -}; - -/* -* @tc.name: testDirectChannelTest007 -* @tc.desc: test StartListeningForDefaultChannel -* @tc.type: FUNC -* @tc.require: AR000I9Q40 -*/ -HWTEST_F(WifiDirectChannelTest, testDirectChannelTest007, TestSize.Level0) -{ - const char *localIp = "0A:2B:3C:4D:5E6"; - int32_t ret = StartListeningForDefaultChannel(localIp); - EXPECT_EQ(SOFTBUS_CONN_MANAGER_TYPE_NOT_SUPPORT, ret); -}; - -/* fast_connect_negotiate_channel.c */ -/* -* @tc.name: testDirectChannelTest008 -* @tc.desc: test FastConnectNegotiateChannelInit -* @tc.type: FUNC -* @tc.require: AR000I9Q40 -*/ -HWTEST_F(WifiDirectChannelTest, testDirectChannelTest008, TestSize.Level0) -{ - int ret = FastConnectNegotiateChannelInit(); - EXPECT_EQ(SOFTBUS_LOCK_ERR, ret); -}; - -/* -* @tc.name: testDirectChannelTest009 -* @tc.desc: test FastConnectNegotiateChannelNew -* @tc.type: FUNC -* @tc.require: AR000I9Q40 -*/ -HWTEST_F(WifiDirectChannelTest, testDirectChannelTest009, TestSize.Level0) -{ - int32_t channelId = 1; - FastConnectNegotiateChannel *channel = FastConnectNegotiateChannelNew(channelId); - EXPECT_NE(nullptr, channel); -}; - -/* -* @tc.name: testDirectChannelTest010 -* @tc.desc: test Duplicate -* @tc.type: FUNC -* @tc.require: AR000I9Q40 -*/ -HWTEST_F(WifiDirectChannelTest, testDirectChannelTest010, TestSize.Level0) -{ - DefaultNegotiateChannel *base = DefaultNegotiateChannelNew(1); - EXPECT_NE(base, nullptr); - WifiDirectNegotiateChannel *ret = base->duplicate((WifiDirectNegotiateChannel*)base); - EXPECT_NE(nullptr, ret); -}; -} -} //namespace OHOS +/* + * Copyright (c) 2023 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 +#include +#include + +#include "link_manager.h" +#include "interface_info.h" +#include "resource_manager.h" +#include "p2p_v1_processor.h" +#include "negotiate_message.h" +#include "softbus_error_code.h" +#include "softbus_adapter_mem.h" +#include "wifi_direct_command.h" +#include "default_negotiate_channel.h" +#include "wifi_direct_negotiate_channel.h" +#include "fast_connect_negotiate_channel.h" + + +namespace OHOS { +using namespace testing::ext; +using namespace testing; +using namespace std; +extern "C"{ +class WifiDirectChannelTest : public testing::Test { +public: + WifiDirectChannelTest() + {} + ~WifiDirectChannelTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void OnConnectSuccess(uint32_t requestId, int64_t authId) +{ + (void)requestId; + (void)authId; +} + +void OnConnectFailure(uint32_t requestId, int32_t reason) +{ + (void)requestId; + (void)reason; +} + +int32_t PostData(struct WifiDirectNegotiateChannel *base, const uint8_t *data, size_t size) +{ + base = nullptr; + data = nullptr; + (void)size; + return SOFTBUS_OK; +} + +int32_t GetDeviceId(struct WifiDirectNegotiateChannel *base, char *deviceId, size_t deviceIdSize) +{ + base = nullptr; + (void)deviceId; + (void)deviceIdSize; + return SOFTBUS_OK; +} + +int32_t GetP2pMac(struct WifiDirectNegotiateChannel *base, char *p2pMac, size_t p2pMacSize) +{ + base = nullptr; + (void)p2pMac; + (void)p2pMacSize; + return SOFTBUS_OK; +} + +void SetP2pMac(struct WifiDirectNegotiateChannel *base, const char *p2pMac) +{ + base = nullptr; +} + +bool IsP2pChannel(struct WifiDirectNegotiateChannel *base) +{ + base = nullptr; + return true; +} + +bool IsMetaChannel(struct WifiDirectNegotiateChannel *base) +{ + base = nullptr; + return false; +} + +struct WifiDirectNegotiateChannel* Duplicate(struct WifiDirectNegotiateChannel *base) +{ + base = nullptr; + return base; +} + +void Destructor(struct WifiDirectNegotiateChannel *base) +{ + SoftBusFree(base); +} + +void WifiDirectNegotiateChannelConstructorTest(struct WifiDirectNegotiateChannel *self) +{ + (void)memset_s(self, sizeof(*self), 0, sizeof(*self)); + self->postData = PostData; + self->getDeviceId = GetDeviceId; + self->getP2pMac = GetP2pMac; + self->setP2pMac = SetP2pMac; + self->isP2pChannel = IsP2pChannel; + self->isMetaChannel = IsMetaChannel; + self->duplicate = Duplicate; + self->destructor = Destructor; +} + +struct WifiDirectNegotiateChannel *WifiDirectNegotiateChannelNew(void) +{ + struct WifiDirectNegotiateChannel *self + = static_cast(SoftBusCalloc(sizeof(*self))); + WifiDirectNegotiateChannelConstructorTest(self); + return self; +} +void WifiDirectChannelTest::SetUpTestCase(void) {} +void WifiDirectChannelTest::TearDownTestCase(void) {} +void WifiDirectChannelTest::SetUp(void) {} +void WifiDirectChannelTest::TearDown(void) {} + +/* default_negotiate_channel.c */ +/* +* @tc.name: testDirectChannelTest001 +* @tc.desc: test OpenDefaultNegotiateChannel +* @tc.type: FUNC +* @tc.require: AR000I9Q40 +*/ +HWTEST_F(WifiDirectChannelTest, testDirectChannelTest001, TestSize.Level0) +{ + struct DefaultNegoChannelOpenCallback callback; + struct P2pV1Processor *self = GetP2pV1Processor(); + struct NegotiateMessage *msg = NegotiateMessageNew(); + EXPECT_NE(msg, nullptr); + + struct WifiDirectNegotiateChannel *channel = WifiDirectNegotiateChannelNew(); + EXPECT_NE(channel, nullptr); + const char *remoteMac = "1a:2b:3c:4d:5e:6f:7g"; + const char *remoteIp = "192.168.1.1"; + channel->setP2pMac(channel, remoteMac); + callback.onConnectFailure = OnConnectFailure; + callback.onConnectSuccess = OnConnectSuccess; + int ret = OpenDefaultNegotiateChannel(remoteIp, self->goPort, channel, &callback); + EXPECT_EQ(SOFTBUS_ERR, ret); +}; + +/* +* @tc.name: testDirectChannelTest002 +* @tc.desc: test getDeviceId +* @tc.type: FUNC +* @tc.require: AR000I9Q40 +*/ +HWTEST_F(WifiDirectChannelTest, testDirectChannelTest003, TestSize.Level0) +{ + WifiDirectNegotiateChannel channel; + char deviceId[] = {'d', 'e', 'v', 'i', 'c', 'e', 'I', 'd'}; + size_t size = sizeof(deviceId) / sizeof(deviceId[0]); + int32_t ret = DefaultNegotiateChannelNew(1)->getDeviceId(&channel, deviceId, size); + EXPECT_EQ(SOFTBUS_NOT_IMPLEMENT, ret); +}; + +/* +* @tc.name: testDirectChannelTest003 +* @tc.desc: test getP2pMac +* @tc.type: FUNC +* @tc.require: AR000I9Q40 +*/ +HWTEST_F(WifiDirectChannelTest, testDirectChannelTest004, TestSize.Level0) +{ + DefaultNegotiateChannel *base = DefaultNegotiateChannelNew(1); + EXPECT_NE(base, nullptr); + char p2pMac[] = {'p', '2', 'p', 'M', 'a', 'c'}; + size_t p2pMacSize = sizeof(p2pMac) / sizeof(p2pMac[0]); + int32_t ret = base->getP2pMac((WifiDirectNegotiateChannel*)base, p2pMac, p2pMacSize); + EXPECT_EQ(SOFTBUS_NOT_IMPLEMENT, ret); +}; + +/* +* @tc.name: testDirectChannelTest004 +* @tc.desc: test isMetaChannel isP2pChannel SetP2pMac +* @tc.type: FUNC +* @tc.require: AR000I9Q40 +*/ +HWTEST_F(WifiDirectChannelTest, testDirectChannelTest005, TestSize.Level0) +{ + DefaultNegotiateChannel *base = DefaultNegotiateChannelNew(1); + EXPECT_NE(base, nullptr); + const char *p2pMac = "test345"; + base->setP2pMac((WifiDirectNegotiateChannel*)base, p2pMac); + bool ret = base->isP2pChannel((WifiDirectNegotiateChannel*)base); + EXPECT_EQ(false, ret); + ret = base->isMetaChannel((WifiDirectNegotiateChannel*)base); + EXPECT_EQ(true, ret); + + base->authId = 0; + base->setP2pMac((WifiDirectNegotiateChannel*)base, p2pMac); + ret = base->isP2pChannel((WifiDirectNegotiateChannel*)base); + EXPECT_EQ(false, ret); + ret = base->isMetaChannel((WifiDirectNegotiateChannel*)base); + EXPECT_EQ(true, ret); +}; + +/* +* @tc.name: testDirectChannelTest005 +* @tc.desc: test Duplicate +* @tc.type: FUNC +* @tc.require: AR000I9Q40 +*/ +HWTEST_F(WifiDirectChannelTest, testDirectChannelTest006, TestSize.Level0) +{ + DefaultNegotiateChannel *base = DefaultNegotiateChannelNew(1); + EXPECT_NE(base, nullptr); + WifiDirectNegotiateChannel *ret = base->duplicate((WifiDirectNegotiateChannel*)base); + EXPECT_NE(ret, nullptr); +}; + +/* +* @tc.name: testDirectChannelTest006 +* @tc.desc: test StartListeningForDefaultChannel +* @tc.type: FUNC +* @tc.require: AR000I9Q40 +*/ +HWTEST_F(WifiDirectChannelTest, testDirectChannelTest007, TestSize.Level0) +{ + const char *localIp = "0A:2B:3C:4D:5E6"; + int32_t ret = StartListeningForDefaultChannel(localIp); + EXPECT_EQ(SOFTBUS_CONN_MANAGER_TYPE_NOT_SUPPORT, ret); +}; + +/* fast_connect_negotiate_channel.c */ +/* +* @tc.name: testDirectChannelTest007 +* @tc.desc: test FastConnectNegotiateChannelInit +* @tc.type: FUNC +* @tc.require: AR000I9Q40 +*/ +HWTEST_F(WifiDirectChannelTest, testDirectChannelTest008, TestSize.Level0) +{ + int ret = FastConnectNegotiateChannelInit(); + EXPECT_EQ(SOFTBUS_LOCK_ERR, ret); +}; + +/* +* @tc.name: testDirectChannelTest008 +* @tc.desc: test FastConnectNegotiateChannelNew +* @tc.type: FUNC +* @tc.require: AR000I9Q40 +*/ +HWTEST_F(WifiDirectChannelTest, testDirectChannelTest009, TestSize.Level0) +{ + int32_t channelId = 1; + FastConnectNegotiateChannel *channel = FastConnectNegotiateChannelNew(channelId); + EXPECT_NE(nullptr, channel); +}; + +/* +* @tc.name: testDirectChannelTest009 +* @tc.desc: test Duplicate +* @tc.type: FUNC +* @tc.require: AR000I9Q40 +*/ +HWTEST_F(WifiDirectChannelTest, testDirectChannelTest010, TestSize.Level0) +{ + DefaultNegotiateChannel *base = DefaultNegotiateChannelNew(1); + EXPECT_NE(base, nullptr); + WifiDirectNegotiateChannel *ret = base->duplicate((WifiDirectNegotiateChannel*)base); + EXPECT_NE(nullptr, ret); +}; +} +} //namespace OHOS diff --git a/tests/core/connection/wifi_direct/data/wifi_direct_data_test.cpp b/tests/core/connection/wifi_direct/data/wifi_direct_data_test.cpp index d3177a14a..e91f26038 100644 --- a/tests/core/connection/wifi_direct/data/wifi_direct_data_test.cpp +++ b/tests/core/connection/wifi_direct/data/wifi_direct_data_test.cpp @@ -34,7 +34,6 @@ #include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_feature_config.h" -#include "softbus_log_old.h" #define ZERO_NUM 0 #define ONE_NUM 1 diff --git a/tests/core/connection/wifi_direct/processor/p2p_v1_processor_mock_test.cpp b/tests/core/connection/wifi_direct/processor/p2p_v1_processor_mock_test.cpp index 6b706f793..627bcc65e 100644 --- a/tests/core/connection/wifi_direct/processor/p2p_v1_processor_mock_test.cpp +++ b/tests/core/connection/wifi_direct/processor/p2p_v1_processor_mock_test.cpp @@ -25,7 +25,6 @@ #include "default_negotiate_channel_mock.h" #include "wifi_direct_negotiator_mock.h" #include "wifi_direct_p2p_adapter_mock.h" -#include "softbus_log_old.h" #include "softbus_errcode.h" #include "resource_manager.h" #include "negotiate_message.h" diff --git a/tests/core/connection/wifi_direct/processor/p2p_v2_processor_mock_test.cpp b/tests/core/connection/wifi_direct/processor/p2p_v2_processor_mock_test.cpp index 1fa6c4b28..067b590a1 100644 --- a/tests/core/connection/wifi_direct/processor/p2p_v2_processor_mock_test.cpp +++ b/tests/core/connection/wifi_direct/processor/p2p_v2_processor_mock_test.cpp @@ -26,7 +26,6 @@ #include "default_negotiate_channel_mock.h" #include "wifi_direct_negotiator_mock.h" #include "wifi_direct_p2p_adapter_mock.h" -#include "softbus_log_old.h" #include "softbus_errcode.h" #include "wifi_direct_p2p_adapter.h" #include "resource_manager.h" diff --git a/tests/core/connection/wifi_direct/processor/wifi_direct_processor_test.cpp b/tests/core/connection/wifi_direct/processor/wifi_direct_processor_test.cpp index d6705f1a1..98e09a121 100644 --- a/tests/core/connection/wifi_direct/processor/wifi_direct_processor_test.cpp +++ b/tests/core/connection/wifi_direct/processor/wifi_direct_processor_test.cpp @@ -32,7 +32,6 @@ #include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_feature_config.h" -#include "softbus_log_old.h" #include "channel/default_negotiate_channel.h" #include "resource_manager.h" #include "wifi_direct_ipv4_info.h" diff --git a/tests/core/connection/wifi_direct/protocol/json_mock.cpp b/tests/core/connection/wifi_direct/protocol/json_mock.cpp index 7a158e952..f99b5fcbc 100644 --- a/tests/core/connection/wifi_direct/protocol/json_mock.cpp +++ b/tests/core/connection/wifi_direct/protocol/json_mock.cpp @@ -20,7 +20,6 @@ #include "softbus_adapter_mem.h" #include "softbus_errcode.h" -#include "softbus_log_old.h" using namespace testing; using namespace testing::ext; diff --git a/tests/core/connection/wifi_direct/wifi_direct_coexist_rule_test.cpp b/tests/core/connection/wifi_direct/wifi_direct_coexist_rule_test.cpp index ebb5b509c..80df687b0 100644 --- a/tests/core/connection/wifi_direct/wifi_direct_coexist_rule_test.cpp +++ b/tests/core/connection/wifi_direct/wifi_direct_coexist_rule_test.cpp @@ -34,7 +34,6 @@ #include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_feature_config.h" -#include "softbus_log_old.h" #include "softbus_utils.h" #include "wifi_direct_command_manager.h" #include "wifi_direct_fast_connect.h" diff --git a/tests/core/connection/wifi_direct/wifi_direct_command_manage_test.cpp b/tests/core/connection/wifi_direct/wifi_direct_command_manage_test.cpp index b38867331..f57e27a6b 100644 --- a/tests/core/connection/wifi_direct/wifi_direct_command_manage_test.cpp +++ b/tests/core/connection/wifi_direct/wifi_direct_command_manage_test.cpp @@ -34,7 +34,6 @@ #include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_feature_config.h" -#include "softbus_log_old.h" #include "softbus_utils.h" #include "wifi_direct_command_manager.h" #include "wifi_direct_fast_connect.h" diff --git a/tests/core/connection/wifi_direct/wifi_direct_initiator_test.cpp b/tests/core/connection/wifi_direct/wifi_direct_initiator_test.cpp index 54865b5e2..9ee17abbe 100644 --- a/tests/core/connection/wifi_direct/wifi_direct_initiator_test.cpp +++ b/tests/core/connection/wifi_direct/wifi_direct_initiator_test.cpp @@ -34,7 +34,6 @@ #include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_feature_config.h" -#include "softbus_log_old.h" #include "softbus_utils.h" #include "wifi_direct_fast_connect.h" #include "wifi_direct_initiator.h" diff --git a/tests/core/connection/wifi_direct/wifi_direct_ip_manager_test.cpp b/tests/core/connection/wifi_direct/wifi_direct_ip_manager_test.cpp index 018a7d304..c9397c961 100644 --- a/tests/core/connection/wifi_direct/wifi_direct_ip_manager_test.cpp +++ b/tests/core/connection/wifi_direct/wifi_direct_ip_manager_test.cpp @@ -34,7 +34,6 @@ #include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_feature_config.h" -#include "softbus_log_old.h" #include "softbus_utils.h" #include "wifi_direct_fast_connect.h" #include "wifi_direct_initiator.h" diff --git a/tests/core/connection/wifi_direct/wifi_direct_negotiator_test.cpp b/tests/core/connection/wifi_direct/wifi_direct_negotiator_test.cpp index cde1bb30c..6fc923256 100644 --- a/tests/core/connection/wifi_direct/wifi_direct_negotiator_test.cpp +++ b/tests/core/connection/wifi_direct/wifi_direct_negotiator_test.cpp @@ -34,7 +34,6 @@ #include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_feature_config.h" -#include "softbus_log_old.h" #include "softbus_utils.h" #include "wifi_direct_command_manager.h" #include "wifi_direct_fast_connect.h" diff --git a/tests/core/connection/wifi_direct/wifi_direct_role_negotiator_test.cpp b/tests/core/connection/wifi_direct/wifi_direct_role_negotiator_test.cpp index aa27f41f8..ec9e684aa 100644 --- a/tests/core/connection/wifi_direct/wifi_direct_role_negotiator_test.cpp +++ b/tests/core/connection/wifi_direct/wifi_direct_role_negotiator_test.cpp @@ -29,7 +29,6 @@ #include "wifi_direct_role_negotiator.h" #include #include "softbus_error_code.h" -#include "softbus_log_old.h" #include "utils/wifi_direct_utils.h" #include "utils/wifi_direct_anonymous.h" diff --git a/tests/core/connection/wifi_direct/wifi_direct_role_option_test.cpp b/tests/core/connection/wifi_direct/wifi_direct_role_option_test.cpp index 298ee7ced..4cd63ee64 100644 --- a/tests/core/connection/wifi_direct/wifi_direct_role_option_test.cpp +++ b/tests/core/connection/wifi_direct/wifi_direct_role_option_test.cpp @@ -34,7 +34,6 @@ #include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_feature_config.h" -#include "softbus_log_old.h" #include "softbus_utils.h" #include "wifi_direct_role_option.h" diff --git a/tests/core/connection/wifi_direct/wifi_direct_test.cpp b/tests/core/connection/wifi_direct/wifi_direct_test.cpp index e8e0ee00d..159fdbd41 100644 --- a/tests/core/connection/wifi_direct/wifi_direct_test.cpp +++ b/tests/core/connection/wifi_direct/wifi_direct_test.cpp @@ -34,7 +34,6 @@ #include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_feature_config.h" -#include "softbus_log_old.h" #include "softbus_utils.h" #include "wifi_direct_fast_connect.h" #include "wifi_direct_initiator.h" diff --git a/tests/core/discovery/BUILD.gn b/tests/core/discovery/BUILD.gn index c7f670a50..e493485fa 100644 --- a/tests/core/discovery/BUILD.gn +++ b/tests/core/discovery/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2021-2024 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 diff --git a/tests/core/discovery/ble/softbus_ble/BUILD.gn b/tests/core/discovery/ble/softbus_ble/BUILD.gn index dfa274330..10388cdc6 100644 --- a/tests/core/discovery/ble/softbus_ble/BUILD.gn +++ b/tests/core/discovery/ble/softbus_ble/BUILD.gn @@ -35,6 +35,7 @@ ohos_unittest("DiscDistributedBleTest") { "$dsoftbus_root_path/interfaces/kits/bus_center", "$softbus_adapter_common/include", "$softbus_adapter_common/net/bluetooth/include", + "$softbus_adapter_common/net/bluetooth/broadcast/interface", "$dsoftbus_root_path/core/common/include", "$dsoftbus_root_path/core/connection/interface", "$dsoftbus_root_path/core/connection/manager", diff --git a/tests/core/discovery/ble/softbus_ble/disc_ble_distributed_test.cpp b/tests/core/discovery/ble/softbus_ble/disc_ble_distributed_test.cpp index d0d8829e0..82b251882 100755 --- a/tests/core/discovery/ble/softbus_ble/disc_ble_distributed_test.cpp +++ b/tests/core/discovery/ble/softbus_ble/disc_ble_distributed_test.cpp @@ -126,12 +126,7 @@ HWTEST_F(DiscDistributedBleTest, TestCheckScanner001, TestSize.Level1) /* * @tc.name: TestScanFilter001 - * @tc.desc: Test ScanFilter should return SOFTBUS_ERR - * when given not SOFTBUS_BLE_DATA_COMPLETE testScanResultData.dataStatus - * should return SOFTBUS_ERR when don't suit the appointed lenth testScanResultData.advLen - * should return SOFTBUS_ERR when don't suit the appointed value testScanResultData.advData - * should return SOFTBUS_OK when given 0x1 one of g_bleInfoManager[0],[1],[2].capBitMap[0] - * and have correct testScanResultData + * @tc.desc: Test ScanFilter should return SOFTBUS_ERR when given invalid reportInfo * @tc.type: FUNC * @tc.require: */ @@ -141,58 +136,140 @@ HWTEST_F(DiscDistributedBleTest, TestScanFilter001, TestSize.Level1) g_testDiscBleDispatcherInterface = DiscSoftBusBleInit(&g_testDiscInnerCallBack); ASSERT_NE(g_testDiscBleDispatcherInterface, nullptr); - uint8_t advDataTest[INT32_MAX_BIT_NUM]; - uint32_t advLenTest = sizeof(advDataTest); - SoftBusBleScanResult testScanResultData{ - .dataStatus = SOFTBUS_BLE_DATA_INCOMPLETE_MORE_TO_COME, - .advLen = POS_TLV, - .advData = advDataTest, - }; - int32_t ret = ScanFilter(&testScanResultData); + BroadcastReportInfo reportInfo = {0}; + + // when not reportInfo->dataStatus == SOFTBUS_BLE_DATA_COMPLETE + reportInfo.dataStatus = SOFTBUS_BLE_DATA_INCOMPLETE_MORE_TO_COME; + int32_t ret = ScanFilter(&reportInfo); EXPECT_NE(ret, SOFTBUS_OK); - testScanResultData.dataStatus = SOFTBUS_BLE_DATA_COMPLETE; - ret = ScanFilter(&testScanResultData); + // when not advData != NULL + reportInfo.dataStatus = SOFTBUS_BLE_DATA_COMPLETE; + ret = ScanFilter(&reportInfo); EXPECT_NE(ret, SOFTBUS_OK); - testScanResultData.advLen = POS_TLV + ADV_HEAD_LEN; - testScanResultData.advData[POS_PACKET_LENGTH] = ADV_HEAD_LEN; - ret = ScanFilter(&testScanResultData); + // when not advLen >= POS_TLV + uint8_t payload[POS_TLV] = {0}; + reportInfo.packet.bcData.payload = &payload[0]; + reportInfo.packet.bcData.payloadLen = POS_TLV - 1; + ret = ScanFilter(&reportInfo); EXPECT_NE(ret, SOFTBUS_OK); - testScanResultData.advData[POS_PACKET_LENGTH] = ADV_HEAD_LEN + RSP_HEAD_LEN - 1; - ret = ScanFilter(&testScanResultData); + // when not rspData != NULL + reportInfo.packet.bcData.payloadLen = POS_TLV; + ret = ScanFilter(&reportInfo); EXPECT_NE(ret, SOFTBUS_OK); - testScanResultData.advLen = POS_PACKET_LENGTH + ADV_HEAD_LEN + RSP_HEAD_LEN + 1; - testScanResultData.advData[POS_PACKET_LENGTH + ADV_HEAD_LEN + RSP_HEAD_LEN] = 1; - ret = ScanFilter(&testScanResultData); + // when not rspLen > 0 + reportInfo.packet.rspData.payload = &payload[0]; + reportInfo.packet.rspData.payloadLen = -1; + ret = ScanFilter(&reportInfo); EXPECT_NE(ret, SOFTBUS_OK); - testScanResultData.advLen = advLenTest; - ret = ScanFilter(&testScanResultData); - EXPECT_NE(ret, SOFTBUS_OK); - - testScanResultData.advData[POS_UUID] = (uint8_t)(BLE_UUID & BYTE_MASK); - ret = ScanFilter(&testScanResultData); - EXPECT_NE(ret, SOFTBUS_OK); - - testScanResultData.advData[POS_UUID + 1] = (uint8_t)((BLE_UUID >> BYTE_SHIFT_BIT) & BYTE_MASK); - ret = ScanFilter(&testScanResultData); - EXPECT_NE(ret, SOFTBUS_OK); - - testScanResultData.advData[POS_VERSION + ADV_HEAD_LEN] = BLE_VERSION; - ret = ScanFilter(&testScanResultData); - EXPECT_NE(ret, SOFTBUS_OK); - - g_bleInfoManager[BLE_SUBSCRIBE | BLE_ACTIVE].capBitMap[0] = 0x1; - ret = ScanFilter(&testScanResultData); - EXPECT_EQ(ret, SOFTBUS_OK); - DiscSoftBusBleDeinit(); DISC_LOGI(DISC_TEST, "DiscDistributedBleTest, TestScanFilter001, End"); } +/* + * @tc.name: TestScanFilter002 + * @tc.desc: Test ScanFilter should return SOFTBUS_ERR when given invalid reportInfo + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(DiscDistributedBleTest, TestScanFilter002, TestSize.Level1) +{ + DISC_LOGI(DISC_TEST, "DiscDistributedBleTest, TestScanFilter002, Start"); + g_testDiscBleDispatcherInterface = DiscSoftBusBleInit(&g_testDiscInnerCallBack); + ASSERT_NE(g_testDiscBleDispatcherInterface, nullptr); + + uint8_t payload[POS_TLV] = {0}; + BroadcastReportInfo reportInfo = { + .dataStatus = SOFTBUS_BLE_DATA_COMPLETE, + .packet = { + .bcData = { + .payload = &payload[0], + .payloadLen = POS_TLV, + }, + .rspData = { + .payload = &payload[0], + .payloadLen = POS_TLV, + }, + }, + }; + + // when not reportInfo->packet.bcData.type == BC_DATA_TYPE_SERVICE + reportInfo.packet.bcData.type = BC_DATA_TYPE_MANUFACTURER; + int32_t ret = ScanFilter(&reportInfo); + EXPECT_NE(ret, SOFTBUS_OK); + + // when not reportInfo->packet.bcData.id == BLE_UUID + reportInfo.packet.bcData.type = BC_DATA_TYPE_SERVICE; + reportInfo.packet.bcData.id = BLE_UUID + 1; + ret = ScanFilter(&reportInfo); + EXPECT_NE(ret, SOFTBUS_OK); + + // when not advData[POS_VERSION] == BLE_VERSION + reportInfo.packet.bcData.id = BLE_UUID; + reportInfo.packet.bcData.payload[POS_VERSION] = BLE_VERSION + 1; + ret = ScanFilter(&reportInfo); + EXPECT_NE(ret, SOFTBUS_OK); + + // when not reportInfo->packet.rspData.type == BC_DATA_TYPE_SERVICE + reportInfo.packet.bcData.payload[POS_VERSION] = BLE_VERSION; + reportInfo.packet.rspData.type = BC_DATA_TYPE_MANUFACTURER; + ret = ScanFilter(&reportInfo); + EXPECT_NE(ret, SOFTBUS_OK); + + // when not reportInfo->packet.rspData.id == COMPANY_ID + reportInfo.packet.rspData.type = BC_DATA_TYPE_SERVICE; + reportInfo.packet.rspData.id = COMPANY_ID + 1; + ret = ScanFilter(&reportInfo); + EXPECT_NE(ret, SOFTBUS_OK); + + DiscSoftBusBleDeinit(); + DISC_LOGI(DISC_TEST, "DiscDistributedBleTest, TestScanFilter002, End"); +} + +/* + * @tc.name: TestScanFilter003 + * @tc.desc: Test ScanFilter should return SOFTBUS_OK when given valid reportInfo + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(DiscDistributedBleTest, TestScanFilter003, TestSize.Level1) +{ + DISC_LOGI(DISC_TEST, "DiscDistributedBleTest, TestScanFilter003, Start"); + g_testDiscBleDispatcherInterface = DiscSoftBusBleInit(&g_testDiscInnerCallBack); + ASSERT_NE(g_testDiscBleDispatcherInterface, nullptr); + + uint8_t payload[POS_TLV] = {0}; + BroadcastReportInfo reportInfo = { + .dataStatus = SOFTBUS_BLE_DATA_COMPLETE, + .packet = { + .bcData = { + .payload = &payload[0], + .payloadLen = POS_TLV, + .type = BC_DATA_TYPE_SERVICE, + .id = BLE_UUID, + }, + .rspData = { + .payload = &payload[0], + .payloadLen = POS_TLV, + .type = BC_DATA_TYPE_SERVICE, + .id = COMPANY_ID, + }, + }, + }; + reportInfo.packet.bcData.payload[POS_VERSION] = BLE_VERSION; + g_bleInfoManager[BLE_SUBSCRIBE | BLE_ACTIVE].capBitMap[0] = 0x1; + + int32_t ret = ScanFilter(&reportInfo); + EXPECT_EQ(ret, SOFTBUS_OK); + + DiscSoftBusBleDeinit(); + DISC_LOGI(DISC_TEST, "DiscDistributedBleTest, TestScanFilter003, End"); +} + /* * @tc.name: TestProcessHwHashAccout001 * @tc.desc: Test ProcessHwHashAccout should return true when given 0x1 testFoundInfo.capabilityBitmap[0] and @@ -310,16 +387,19 @@ HWTEST_F(DiscDistributedBleTest, TestBuildBleConfigAdvData001, TestSize.Level1) g_testDiscBleDispatcherInterface = DiscSoftBusBleInit(&g_testDiscInnerCallBack); ASSERT_NE(g_testDiscBleDispatcherInterface, nullptr); - SoftBusBleAdvData advDataTest; - BroadcastData broadcastDataTest; - int32_t ret = BuildBleConfigAdvData(nullptr, &broadcastDataTest); - EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); - ret = BuildBleConfigAdvData(&advDataTest, nullptr); - EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); + BroadcastPacket broadcastPacket = {}; + BroadcastData broadcastData = {}; - broadcastDataTest.dataLen = ADV_DATA_MAX_LEN; - ret = BuildBleConfigAdvData(&advDataTest, &broadcastDataTest); - EXPECT_EQ(advDataTest.scanRspData[POS_RSP_TYPE], RSP_TYPE); + broadcastData.dataLen = ADV_DATA_MAX_LEN; + int32_t ret = BuildBleConfigAdvData(&broadcastPacket, &broadcastData); + EXPECT_EQ(broadcastPacket.rspData.type, 0); + EXPECT_EQ(broadcastPacket.rspData.id, 0); + EXPECT_EQ(ret, SOFTBUS_OK); + + broadcastData.dataLen = ADV_DATA_MAX_LEN + 1; + ret = BuildBleConfigAdvData(&broadcastPacket, &broadcastData); + EXPECT_EQ(broadcastPacket.rspData.type, BC_DATA_TYPE_MANUFACTURER); + EXPECT_EQ(broadcastPacket.rspData.id, COMPANY_ID); EXPECT_EQ(ret, SOFTBUS_OK); DiscSoftBusBleDeinit(); @@ -352,103 +432,6 @@ HWTEST_F(DiscDistributedBleTest, TestGetBroadcastData001, TestSize.Level1) DISC_LOGI(DISC_TEST, "DiscDistributedBleTest, TestGetBroadcastData001, End"); } -/* - * @tc.name: TestStartAdvertiser001 - * @tc.desc: Test StartAdvertiser should return SOFTBUS_OK when given true/false g_bleAdvertiser[adv].isAdvertising - * @tc.type: FUNC - * @tc.require: - */ -HWTEST_F(DiscDistributedBleTest, TestStartAdvertiser001, TestSize.Level1) -{ - DISC_LOGI(DISC_TEST, "DiscDistributedBleTest, TestStartAdvertiser001, Start"); - g_testDiscBleDispatcherInterface = DiscSoftBusBleInit(&g_testDiscInnerCallBack); - ASSERT_NE(g_testDiscBleDispatcherInterface, nullptr); - - int32_t adv = CON_ADV_ID; - g_bleAdvertiser[adv].isAdvertising = true; - g_bleInfoManager[BLE_SUBSCRIBE | BLE_ACTIVE].needUpdate = true; - g_bleInfoManager[BLE_SUBSCRIBE | BLE_PASSIVE].needUpdate = true; - int32_t ret = StartAdvertiser(adv); - EXPECT_EQ(ret, SOFTBUS_OK); - - g_bleAdvertiser[adv].isAdvertising = true; - g_bleInfoManager[BLE_SUBSCRIBE | BLE_ACTIVE].needUpdate = false; - g_bleInfoManager[BLE_SUBSCRIBE | BLE_PASSIVE].needUpdate = false; - ret = StartAdvertiser(adv); - EXPECT_EQ(ret, SOFTBUS_OK); - - g_bleAdvertiser[adv].isAdvertising = false; - g_bleInfoManager[BLE_SUBSCRIBE | BLE_ACTIVE].capBitMap[0] = 0x1; - ret = StartAdvertiser(adv); - EXPECT_EQ(ret, SOFTBUS_OK); - - g_bleInfoManager[BLE_SUBSCRIBE | BLE_ACTIVE].capBitMap[0] = 0x0; - ret = StartAdvertiser(adv); - EXPECT_EQ(ret, SOFTBUS_OK); - - DiscSoftBusBleDeinit(); - DISC_LOGI(DISC_TEST, "DiscDistributedBleTest, TestStartAdvertiser001, End"); -} - -/* - * @tc.name: TestStopAdvertiser001 - * @tc.desc: Test StopAdvertiser should return SOFTBUS_OK when given CON_ADV_ID/NON_ADV_ID adv - * @tc.type: FUNC - * @tc.require: - */ -HWTEST_F(DiscDistributedBleTest, TestStopAdvertiser001, TestSize.Level1) -{ - DISC_LOGI(DISC_TEST, "DiscDistributedBleTest, TestStopAdvertiser001, Start"); - g_testDiscBleDispatcherInterface = DiscSoftBusBleInit(&g_testDiscInnerCallBack); - ASSERT_NE(g_testDiscBleDispatcherInterface, nullptr); - - int32_t adv = CON_ADV_ID; - g_bleAdvertiser[adv].isAdvertising = true; - int32_t ret = StopAdvertiser(adv); - EXPECT_EQ(ret, SOFTBUS_OK); - - g_bleAdvertiser[adv].isAdvertising = false; - ret = StopAdvertiser(adv); - EXPECT_EQ(ret, SOFTBUS_OK); - - adv = NON_ADV_ID; - g_bleAdvertiser[adv].isAdvertising = true; - ret = StopAdvertiser(adv); - EXPECT_EQ(ret, SOFTBUS_OK); - - g_bleAdvertiser[adv].isAdvertising = false; - ret = StopAdvertiser(adv); - EXPECT_EQ(ret, SOFTBUS_OK); - - DiscSoftBusBleDeinit(); - DISC_LOGI(DISC_TEST, "DiscDistributedBleTest, TestStopAdvertiser001, End"); -} - -/* - * @tc.name: TestUpdateAdvertiser001 - * @tc.desc: Test UpdateAdvertiser should return SOFTBUS_OK when given 1/0 g_bleInfoManager[2].capBitMap[0] - * @tc.type: FUNC - * @tc.require: - */ -HWTEST_F(DiscDistributedBleTest, TestUpdateAdvertiser001, TestSize.Level1) -{ - DISC_LOGI(DISC_TEST, "DiscDistributedBleTest, TestUpdateAdvertiser001, Start"); - g_testDiscBleDispatcherInterface = DiscSoftBusBleInit(&g_testDiscInnerCallBack); - ASSERT_NE(g_testDiscBleDispatcherInterface, nullptr); - - int32_t adv = CON_ADV_ID; - g_bleInfoManager[BLE_SUBSCRIBE | BLE_ACTIVE].capBitMap[0] = 0x1; - int32_t ret = UpdateAdvertiser(adv); - EXPECT_EQ(ret, SOFTBUS_OK); - - g_bleInfoManager[BLE_SUBSCRIBE | BLE_ACTIVE].capBitMap[0] = 0x0; - ret = UpdateAdvertiser(adv); - EXPECT_EQ(ret, SOFTBUS_OK); - - DiscSoftBusBleDeinit(); - DISC_LOGI(DISC_TEST, "DiscDistributedBleTest, TestUpdateAdvertiser001, End"); -} - /* * @tc.name: TestGetScannerParam001 * @tc.desc: Test GetScannerParam should return SOFTBUS_OK when given valid param @@ -461,9 +444,9 @@ HWTEST_F(DiscDistributedBleTest, TestGetScannerParam001, TestSize.Level1) g_testDiscBleDispatcherInterface = DiscSoftBusBleInit(&g_testDiscInnerCallBack); ASSERT_NE(g_testDiscBleDispatcherInterface, nullptr); - int32_t freqTest = 0; - SoftBusBleScanParams scanParamTest; - int32_t ret = GetScannerParam(freqTest, &scanParamTest); + int32_t freq = LOW; + BcScanParams scanParam; + int32_t ret = GetScannerParam(freq, &scanParam); EXPECT_EQ(ret, SOFTBUS_OK); DiscSoftBusBleDeinit(); diff --git a/tests/core/discovery/ble/softbus_ble_mock/BUILD.gn b/tests/core/discovery/ble/softbus_ble_mock/BUILD.gn index 8afbd0c64..35b25581c 100644 --- a/tests/core/discovery/ble/softbus_ble_mock/BUILD.gn +++ b/tests/core/discovery/ble/softbus_ble_mock/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021-2023 Huawei Device Co., Ltd. +# Copyright (c) 2021-2024 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 @@ -23,7 +23,6 @@ module_output_path = "dsoftbus/discovery" ohos_unittest("DiscBleTest") { module_out_path = module_output_path sources = [ - "$dsoftbus_root_path/core/discovery/ble/approach_ble/src/disc_approach_ble_virtual.c", "$dsoftbus_root_path/core/discovery/ble/softbus_ble/src/disc_ble.c", "$dsoftbus_root_path/core/discovery/ble/softbus_ble/src/disc_ble_utils.c", "ble_mock.cpp", @@ -33,31 +32,22 @@ ohos_unittest("DiscBleTest") { sources += test_utils_src include_dirs = [ + "$dsoftbus_root_path/core/adapter/bus_center/include", + "$dsoftbus_root_path/core/bus_center/lnn/lane_hub/lane_manager/include", + "$dsoftbus_root_path/core/bus_center/lnn/net_ledger/common/include", + "$dsoftbus_root_path/core/bus_center/interface", "$dsoftbus_root_path/core/common/include", "$dsoftbus_root_path/core/discovery/ble/dispatcher/include", - "$dsoftbus_root_path/core/discovery/manager/include", - "$dsoftbus_root_path/core/discovery/interface", - "$dsoftbus_root_path/core/discovery/ble/approach_ble/include", - "$dsoftbus_root_path/core/discovery/ble/softbus_ble/include", - "$dsoftbus_root_path/interfaces/kits/common", - "$dsoftbus_root_path/interfaces/kits/discovery", - "$dsoftbus_root_path/interfaces/kits/bus_center", - "$softbus_adapter_common/include", - "$softbus_adapter_common/net/bluetooth/include", - "$dsoftbus_root_path/core/common/include", - "$dsoftbus_root_path/core/connection/interface", - "$dsoftbus_root_path/core/connection/manager", - "$dsoftbus_root_path/core/connection/tcp/include", - "$dsoftbus_root_path/core/connection/ble/include", - "$dsoftbus_root_path/core/connection/ble/src", - "$dsoftbus_root_path/core/bus_center/interface", - "$dsoftbus_root_path/core/bus_center/lnn/lane_hub/lane_manager/include", - "$dsoftbus_root_path/core/discovery/interface", - "$dsoftbus_root_path/core/discovery/manager/include", "$dsoftbus_root_path/core/discovery/ble/softbus_ble/include", "$dsoftbus_root_path/core/discovery/ble/softbus_ble/src", - "$dsoftbus_root_path/core/bus_center/lnn/net_ledger/common/include", - "$dsoftbus_root_path/core/adapter/bus_center/include", + "$dsoftbus_root_path/core/discovery/interface", + "$dsoftbus_root_path/core/discovery/manager/include", + "$dsoftbus_root_path/interfaces/kits/common", + "$dsoftbus_root_path/interfaces/kits/bus_center", + "$dsoftbus_root_path/interfaces/kits/discovery", + "$softbus_adapter_common/include", + "$softbus_adapter_common/net/bluetooth/broadcast/interface", + "$softbus_adapter_common/net/bluetooth/include", "//base/security/huks/interfaces/inner_api/huks_standard/main/include", ] include_dirs += test_utils_inc diff --git a/tests/core/discovery/ble/softbus_ble_mock/ble_mock.cpp b/tests/core/discovery/ble/softbus_ble_mock/ble_mock.cpp index 9a694ed7e..9e8659291 100644 --- a/tests/core/discovery/ble/softbus_ble_mock/ble_mock.cpp +++ b/tests/core/discovery/ble/softbus_ble_mock/ble_mock.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 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 @@ -12,11 +12,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #include "ble_mock.h" -#include #include +#include #include +#include "disc_ble_constant.h" #include "disc_log.h" #include "securec.h" #include "softbus_error_code.h" @@ -35,34 +35,39 @@ int SoftBusAddBtStateListener(const SoftBusBtStateListener *listener) return BleMock::GetMock()->SoftBusAddBtStateListener(listener); } -int SoftBusAddScanListener(const SoftBusScanListener *listener, int *scannerId, bool isLpDeviceScan) +int32_t InitBroadcastMgr() { - return BleMock::GetMock()->SoftBusAddScanListener(listener, scannerId, isLpDeviceScan); + return BleMock::GetMock()->InitBroadcastMgr(); } -int SoftBusSetScanFilter(int listenerId, SoftBusBleScanFilter *filter, uint8_t filterSize) +int32_t DeInitBroadcastMgr() { - return BleMock::GetMock()->SoftBusSetScanFilter(listenerId, filter, filterSize); + return BleMock::GetMock()->DeInitBroadcastMgr(); } -int SoftBusGetAdvChannel(const SoftBusAdvCallback *callback, int *scannerId, bool isLpDeviceScan) +int32_t RegisterScanListener(BaseServiceType type, int32_t *listenerId, const ScanCallback *cb) { - return BleMock::GetMock()->SoftBusGetAdvChannel(callback, scannerId, isLpDeviceScan); + return BleMock::GetMock()->RegisterScanListener(type, listenerId, cb); } -int SoftBusReleaseAdvChannel(int channel) +int32_t SetScanFilter(int32_t listenerId, const BcScanFilter *scanFilter, uint8_t filterNum) { - return BleMock::GetMock()->SoftBusReleaseAdvChannel(channel); + return BleMock::GetMock()->SetScanFilter(listenerId, scanFilter, filterNum); } -int SoftBusStopScan(int listenerId, int scannerId) +int32_t RegisterBroadcaster(BaseServiceType type, int32_t *bcId, const BroadcastCallback *cb) { - return BleMock::GetMock()->SoftBusStopScan(listenerId, scannerId); + return BleMock::GetMock()->RegisterBroadcaster(type, bcId, cb); } -int SoftBusStopScanImmediately(int listenerId, int scannerId) +int32_t UnRegisterBroadcaster(int32_t bcId) { - return BleMock::GetMock()->SoftBusStopScanImmediately(listenerId, scannerId); + return BleMock::GetMock()->UnRegisterBroadcaster(bcId); +} + +int32_t StopScan(int32_t listenerId) +{ + return BleMock::GetMock()->StopScan(listenerId); } int SoftBusRemoveBtStateListener(int listenerId) @@ -70,39 +75,34 @@ int SoftBusRemoveBtStateListener(int listenerId) return BleMock::GetMock()->SoftBusRemoveBtStateListener(listenerId); } -int SoftBusRemoveScanListener(int listenerId) +int32_t UnRegisterScanListener(int32_t listenerId) { - return BleMock::GetMock()->SoftBusRemoveScanListener(listenerId); + return BleMock::GetMock()->UnRegisterScanListener(listenerId); } -int32_t SoftBusDeregisterScanCallbacks(int32_t scannerId) +int32_t StopBroadcasting(int32_t bcId) { - return BleMock::GetMock()->SoftBusDeregisterScanCallbacks(scannerId); + return BleMock::GetMock()->StopBroadcasting(bcId); } -int SoftBusStopAdv(int channel) +int32_t UpdateBroadcasting(int32_t bcId, const BroadcastParam *param, const BroadcastPacket *packet) { - return BleMock::GetMock()->SoftBusStopAdv(channel); + return BleMock::GetMock()->UpdateBroadcasting(bcId, param, packet); } -int SoftBusUpdateAdv(int channel, const SoftBusBleAdvData *data, const SoftBusBleAdvParams *param) +int32_t StartScan(int32_t listenerId, const BcScanParams *param) { - return BleMock::GetMock()->SoftBusUpdateAdv(channel, data, param); + return BleMock::GetMock()->StartScan(listenerId, param); } -int SoftBusStartScan(int listenerId, int scannerId, const SoftBusBleScanParams *param) +int32_t SetBroadcastingData(int32_t bcId, const BroadcastPacket *packet) { - return BleMock::GetMock()->SoftBusStartScan(listenerId, scannerId, param); + return BleMock::GetMock()->SetBroadcastingData(bcId, packet); } -int SoftBusSetAdvData(int channel, const SoftBusBleAdvData *data) +int32_t StartBroadcasting(int32_t bcId, const BroadcastParam *param, const BroadcastPacket *packet) { - return BleMock::GetMock()->SoftBusSetAdvData(channel, data); -} - -int SoftBusStartAdv(int channel, const SoftBusBleAdvParams *param) -{ - return BleMock::GetMock()->SoftBusStartAdv(channel, param); + return BleMock::GetMock()->StartBroadcasting(bcId, param, packet); } int SoftBusGetBtMacAddr(SoftBusBtAddr *mac) @@ -132,6 +132,16 @@ int32_t BleMock::ActionOfBleGattLockInit() return SOFTBUS_OK; } +int32_t BleMock::ActionOfInitBroadcastMgr() +{ + return SOFTBUS_OK; +} + +int32_t BleMock::ActionOfDeInitBroadcastMgr() +{ + return SOFTBUS_OK; +} + int32_t BleMock::ActionOfAddBtStateListener(const SoftBusBtStateListener *listener) { btStateListener = listener; @@ -144,107 +154,96 @@ int32_t BleMock::ActionOfRemoveBtStateListener(int listenerId) return SOFTBUS_OK; } -int32_t BleMock::ActionOfAddScanListener(const SoftBusScanListener *listener, int *scannerId, bool isLpDeviceScan) +int32_t BleMock::ActionOfRegisterScanListener(BaseServiceType type, int32_t *listenerId, const ScanCallback *cb) { - scanListener = listener; - return SCAN_LISTENER_ID; + *listenerId = SCAN_LISTENER_ID; + scanListener = cb; + return SOFTBUS_OK; } -int32_t BleMock::ActionOfRemoveScanListener(int listenerId) +int32_t BleMock::ActionOfUnRegisterScanListener(int32_t listenerId) { scanListener = nullptr; return SOFTBUS_OK; } -int32_t BleMock::ActionOfDeregisterScanCallbacks(int scannerId) +int32_t BleMock::ActionOfSetScanFilter(int32_t listenerId, const BcScanFilter *scanFilter, uint8_t filterNum) { + DISC_LOGI(DISC_TEST, "listenerId=%d filterSize=%d", listenerId, filterNum); return SOFTBUS_OK; } -int32_t BleMock::ActionOfSetScanFilter(int listenerId, const SoftBusBleScanFilter *filter, uint8_t filterSize) -{ - DISC_LOGI(DISC_TEST, "listenerId=%d filterSize=%d", listenerId, filterSize); - return SOFTBUS_OK; -} - -int32_t BleMock::ActionOfGetAdvChannel(const SoftBusAdvCallback *callback, int *scannerId, bool isLpDeviceScan) +int32_t BleMock::ActionOfRegisterBroadcaster(BaseServiceType type, int32_t *bcId, const BroadcastCallback *cb) { static int32_t advChannel = 0; - advCallback = callback; - return advChannel++; + *bcId = advChannel; + advChannel++; + advCallback = cb; + return SOFTBUS_OK; } -int32_t BleMock::ActionOfReleaseAdvChannel(int channel) +int32_t BleMock::ActionOfUnRegisterBroadcaster(int32_t bcId) { advCallback = nullptr; return SOFTBUS_OK; } -int32_t BleMock::ActionOfStartScan(int listenerId, int scannerId, const SoftBusBleScanParams *param) +int32_t BleMock::ActionOfStartScan(int32_t listenerId, const BcScanParams *param) { if (listenerId != SCAN_LISTENER_ID) { return SOFTBUS_ERR; } isScanning = true; - if (scanListener && scanListener->OnScanStart) { - scanListener->OnScanStart(SCAN_LISTENER_ID, SOFTBUS_BT_STATUS_SUCCESS); + if (scanListener && scanListener->OnStartScanCallback) { + scanListener->OnStartScanCallback(SCAN_LISTENER_ID, SOFTBUS_BT_STATUS_SUCCESS); } GetMock()->UpdateScanStateDone(); return SOFTBUS_OK; } -int32_t BleMock::ActionOfStopScan(int listenerId, int scannerId) +int32_t BleMock::ActionOfStopScan(int32_t listenerId) { if (listenerId != SCAN_LISTENER_ID) { return SOFTBUS_ERR; } isScanning = false; - if (scanListener && scanListener->OnScanStop) { - scanListener->OnScanStop(SCAN_LISTENER_ID, SOFTBUS_BT_STATUS_SUCCESS); + if (scanListener && scanListener->OnStopScanCallback) { + scanListener->OnStopScanCallback(SCAN_LISTENER_ID, SOFTBUS_BT_STATUS_SUCCESS); } GetMock()->UpdateScanStateDone(); return SOFTBUS_OK; } -int32_t BleMock::ActionOfStopScanImmediately(int listenerId, int scannerId) -{ - if (listenerId != SCAN_LISTENER_ID) { - return SOFTBUS_ERR; - } - - isScanning = false; - if (scanListener && scanListener->OnScanStop) { - scanListener->OnScanStop(SCAN_LISTENER_ID, SOFTBUS_BT_STATUS_SUCCESS); - } - GetMock()->UpdateScanStateDone(); - return SOFTBUS_OK; -} - -int32_t BleMock::ActionOfStartAdv(int channel, const SoftBusBleAdvParams *param) +int32_t BleMock::ActionOfStartBroadcasting(int32_t bcId, const BroadcastParam *param, const BroadcastPacket *packet) { + ShowAdvData(bcId, packet); if (isAdvertising) { DISC_LOGE(DISC_TEST, "already in advertising"); + GetMock()->AsyncAdvertiseDone(); return SOFTBUS_ERR; } isAdvertising = !isAdvertising; if (advCallback) { - advCallback->AdvEnableCallback(channel, SOFTBUS_BT_STATUS_SUCCESS); + advCallback->OnStartBroadcastingCallback(bcId, SOFTBUS_BT_STATUS_SUCCESS); } + GetMock()->AsyncAdvertiseDone(); return SOFTBUS_OK; } -int32_t BleMock::ActionOfStopAdv(int channel) +int32_t BleMock::ActionOfStopBroadcasting(int32_t bcId) { if (!isAdvertising) { DISC_LOGE(DISC_TEST, "already has stopped"); + GetMock()->AsyncAdvertiseDone(); return SOFTBUS_ERR; } if (advCallback) { - advCallback->AdvDisableCallback(channel, SOFTBUS_BT_STATUS_SUCCESS); + advCallback->OnStopBroadcastingCallback(bcId, SOFTBUS_BT_STATUS_SUCCESS); } isAdvertising = !isAdvertising; + GetMock()->AsyncAdvertiseDone(); return SOFTBUS_OK; } @@ -258,114 +257,114 @@ void BleMock::HexDump(const uint8_t *data, uint32_t len) DISC_LOGI(DISC_TEST, "%s", ss.str().c_str()); } -void BleMock::ShowAdvData(int channel, const SoftBusBleAdvData *data) +void BleMock::ShowAdvData(int32_t bcId, const BroadcastPacket *packet) { - DISC_LOGI(DISC_TEST, "channel=%d advLen=%d rspLen=%d", channel, data->advLength, data->scanRspLength); + DISC_LOGI(DISC_TEST, "bcId=%d advLen=%d rspLen=%d", bcId, packet->bcData.payloadLen, packet->rspData.payloadLen); DISC_LOGI(DISC_TEST, "adv data:"); - HexDump(reinterpret_cast(data->advData), data->advLength); + HexDump(reinterpret_cast(packet->bcData.payload), packet->bcData.payloadLen); DISC_LOGI(DISC_TEST, "rsp data:"); - HexDump(reinterpret_cast(data->scanRspData), data->scanRspLength); + HexDump(reinterpret_cast(packet->rspData.payload), packet->rspData.payloadLen); } -int32_t BleMock::ActionOfSetAdvDataForActiveDiscovery(int channel, const SoftBusBleAdvData *data) +int32_t BleMock::ActionOfSetAdvDataForActiveDiscovery(int32_t bcId, const BroadcastPacket *packet) { - ShowAdvData(channel, data); + ShowAdvData(bcId, packet); - if (data->advLength != sizeof(activeDiscoveryAdvData) || - data->scanRspLength != sizeof(activeDiscoveryRspData) || - memcmp(data->advData, activeDiscoveryAdvData, data->advLength) != 0 || - memcmp(data->scanRspData, activeDiscoveryRspData, data->scanRspLength) != 0) { + if (packet->bcData.payloadLen != sizeof(activeDiscoveryAdvData) || + packet->rspData.payloadLen != sizeof(activeDiscoveryRspData) || + memcmp(packet->bcData.payload, activeDiscoveryAdvData, packet->bcData.payloadLen) != 0 || + memcmp(packet->rspData.payload, activeDiscoveryRspData, packet->rspData.payloadLen) != 0) { isAsyncAdvertiseSuccess = false; GetMock()->AsyncAdvertiseDone(); return SOFTBUS_ERR; } if (advCallback) { - advCallback->AdvDataCallback(channel, SOFTBUS_BT_STATUS_SUCCESS); + advCallback->OnSetBroadcastingCallback(bcId, SOFTBUS_BT_STATUS_SUCCESS); } GetMock()->AsyncAdvertiseDone(); return SOFTBUS_OK; } -int32_t BleMock::ActionOfSetAdvDataForActivePublish(int channel, const SoftBusBleAdvData *data) +int32_t BleMock::ActionOfSetAdvDataForActivePublish(int32_t bcId, const BroadcastPacket *packet) { - ShowAdvData(channel, data); + ShowAdvData(bcId, packet); - if (data->advLength != sizeof(activePublishAdvData) || - data->scanRspLength != sizeof(activePublishRspData) || - memcmp(data->advData, activePublishAdvData, data->advLength) != 0 || - memcmp(data->scanRspData, activePublishRspData, data->scanRspLength) != 0) { + if (packet->bcData.payloadLen != sizeof(activePublishAdvData) || + packet->rspData.payloadLen != sizeof(activePublishRspData) || + memcmp(packet->bcData.payload, activePublishAdvData, packet->bcData.payloadLen) != 0 || + memcmp(packet->rspData.payload, activePublishRspData, packet->rspData.payloadLen) != 0) { isAsyncAdvertiseSuccess = false; GetMock()->AsyncAdvertiseDone(); return SOFTBUS_ERR; } if (advCallback) { - advCallback->AdvDataCallback(channel, SOFTBUS_BT_STATUS_SUCCESS); + advCallback->OnSetBroadcastingCallback(bcId, SOFTBUS_BT_STATUS_SUCCESS); } GetMock()->AsyncAdvertiseDone(); return SOFTBUS_OK; } -int32_t BleMock::ActionOfSetAdvDataForPassivePublish(int channel, const SoftBusBleAdvData *data) +int32_t BleMock::ActionOfSetAdvDataForPassivePublish(int32_t bcId, const BroadcastPacket *packet) { - ShowAdvData(channel, data); + ShowAdvData(bcId, packet); - if (data->advLength != sizeof(passivePublishAdvData) || - data->scanRspLength != sizeof(passivePublishRspData) || - memcmp(data->advData, passivePublishAdvData, data->advLength) != 0 || - memcmp(data->scanRspData, passivePublishRspData, data->scanRspLength) != 0) { + if (packet->bcData.payloadLen != sizeof(passivePublishAdvData) || + packet->rspData.payloadLen != sizeof(passivePublishRspData) || + memcmp(packet->bcData.payload, passivePublishAdvData, packet->bcData.payloadLen) != 0 || + memcmp(packet->rspData.payload, passivePublishRspData, packet->rspData.payloadLen) != 0) { isAsyncAdvertiseSuccess = false; GetMock()->AsyncAdvertiseDone(); return SOFTBUS_ERR; } if (advCallback) { - advCallback->AdvDataCallback(channel, SOFTBUS_BT_STATUS_SUCCESS); + advCallback->OnSetBroadcastingCallback(bcId, SOFTBUS_BT_STATUS_SUCCESS); } GetMock()->AsyncAdvertiseDone(); return SOFTBUS_OK; } -int32_t BleMock::ActionOfUpdateAdvForActiveDiscovery(int channel, const SoftBusBleAdvData *data, - const SoftBusBleAdvParams *param) +int32_t BleMock::ActionOfUpdateAdvForActiveDiscovery( + int32_t bcId, const BroadcastParam *param, const BroadcastPacket *packet) { - ShowAdvData(channel, data); + ShowAdvData(bcId, packet); - if (data->advLength != sizeof(activeDiscoveryAdvData2) || - data->scanRspLength != sizeof(activeDiscoveryRspData) || - memcmp(data->advData, activeDiscoveryAdvData2, data->advLength) != 0 || - memcmp(data->scanRspData, activeDiscoveryRspData, data->scanRspLength) != 0) { + if (packet->bcData.payloadLen != sizeof(activeDiscoveryAdvData2) || + packet->rspData.payloadLen != sizeof(activeDiscoveryRspData) || + memcmp(packet->bcData.payload, activeDiscoveryAdvData2, packet->bcData.payloadLen) != 0 || + memcmp(packet->rspData.payload, activeDiscoveryRspData, packet->rspData.payloadLen) != 0) { isAsyncAdvertiseSuccess = false; GetMock()->AsyncAdvertiseDone(); return SOFTBUS_ERR; } if (advCallback) { - advCallback->AdvUpdateCallback(channel, SOFTBUS_BT_STATUS_SUCCESS); + advCallback->OnUpdateBroadcastingCallback(bcId, SOFTBUS_BT_STATUS_SUCCESS); } GetMock()->AsyncAdvertiseDone(); return SOFTBUS_OK; } -int32_t BleMock::ActionOfUpdateAdvForPassivePublish(int channel, const SoftBusBleAdvData *data, - const SoftBusBleAdvParams *param) +int32_t BleMock::ActionOfUpdateAdvForPassivePublish( + int32_t bcId, const BroadcastParam *param, const BroadcastPacket *packet) { - ShowAdvData(channel, data); + ShowAdvData(bcId, packet); - if (data->advLength != sizeof(passivePublishAdvData) || - data->scanRspLength != sizeof(passivePublishRspData) || - memcmp(data->advData, passivePublishAdvData, data->advLength) != 0 || - memcmp(data->scanRspData, passivePublishRspData, data->scanRspLength) != 0) { + if (packet->bcData.payloadLen != sizeof(passivePublishAdvData) || + packet->rspData.payloadLen != sizeof(passivePublishRspData) || + memcmp(packet->bcData.payload, passivePublishAdvData, packet->bcData.payloadLen) != 0 || + memcmp(packet->rspData.payload, passivePublishRspData, packet->rspData.payloadLen) != 0) { isAsyncAdvertiseSuccess = false; GetMock()->AsyncAdvertiseDone(); return SOFTBUS_ERR; } if (advCallback) { - advCallback->AdvUpdateCallback(channel, SOFTBUS_BT_STATUS_SUCCESS); + advCallback->OnUpdateBroadcastingCallback(bcId, SOFTBUS_BT_STATUS_SUCCESS); } GetMock()->AsyncAdvertiseDone(); @@ -387,67 +386,60 @@ int32_t BleMock::ActionOfGetBtState() void BleMock::InjectPassiveNonPacket() { - if (scanListener && scanListener->OnScanResult) { + if (scanListener && scanListener->OnReportScanDataCallback) { constexpr uint32_t advLen = sizeof(passivePublishAdvData); constexpr uint32_t rspLen = sizeof(passivePublishRspData); - uint8_t data[advLen + rspLen]; - if (memcpy_s(data, sizeof(data), passivePublishAdvData, advLen) != EOK) { - return; - } - if (memcpy_s(data + advLen, sizeof(data) - advLen, passivePublishRspData, rspLen) != EOK) { - return; - } - - SoftBusBleScanResult result; - result.advData = data; - result.advLen = sizeof(data); - scanListener->OnScanResult(SCAN_LISTENER_ID, &result); + BroadcastReportInfo reportInfo = {}; + reportInfo.packet.bcData.id = BLE_UUID; + reportInfo.packet.bcData.type = BC_DATA_TYPE_SERVICE; + reportInfo.packet.rspData.id = COMPANY_ID; + reportInfo.packet.rspData.type = BC_DATA_TYPE_MANUFACTURER; + reportInfo.packet.bcData.payload = &passivePublishAdvData[0]; + reportInfo.packet.bcData.payloadLen = advLen; + reportInfo.packet.rspData.payload = &passivePublishRspData[0]; + reportInfo.packet.rspData.payloadLen = rspLen; + scanListener->OnReportScanDataCallback(SCAN_LISTENER_ID, &reportInfo); } } void BleMock::InjectActiveNonPacket() { - if (scanListener && scanListener->OnScanResult) { + if (scanListener && scanListener->OnReportScanDataCallback) { constexpr uint32_t advLen = sizeof(activePublishAdvData); constexpr uint32_t rspLen = sizeof(activePublishRspData); - uint8_t data[advLen + rspLen]; - if (memcpy_s(data, sizeof(data), activePublishAdvData, advLen) != EOK) { - return; - } - if (memcpy_s(data + advLen, sizeof(data) - advLen, activePublishRspData, rspLen) != EOK) { - return; - } - - SoftBusBleScanResult result; - result.advData = data; - result.advLen = sizeof(data); - scanListener->OnScanResult(SCAN_LISTENER_ID, &result); + BroadcastReportInfo reportInfo = {}; + reportInfo.packet.bcData.id = BLE_UUID; + reportInfo.packet.bcData.type = BC_DATA_TYPE_SERVICE; + reportInfo.packet.rspData.id = COMPANY_ID; + reportInfo.packet.rspData.type = BC_DATA_TYPE_MANUFACTURER; + reportInfo.packet.bcData.payload = &activePublishAdvData[0]; + reportInfo.packet.bcData.payloadLen = advLen; + reportInfo.packet.rspData.payload = &activePublishRspData[0]; + reportInfo.packet.rspData.payloadLen = rspLen; + scanListener->OnReportScanDataCallback(SCAN_LISTENER_ID, &reportInfo); } } void BleMock::InjectActiveConPacket() { - if (scanListener && scanListener->OnScanResult) { + if (scanListener && scanListener->OnReportScanDataCallback) { constexpr uint32_t advLen = sizeof(activeDiscoveryAdvData); constexpr uint32_t rspLen = sizeof(activeDiscoveryRspData); - uint8_t data[advLen + rspLen]; - if (memcpy_s(data, sizeof(data), activeDiscoveryAdvData, advLen) != EOK) { - return; - } - if (memcpy_s(data + advLen, sizeof(data) - advLen, activeDiscoveryRspData, rspLen) != EOK) { - return; - } - - SoftBusBleScanResult result; - result.advData = data; - result.advLen = sizeof(data); - scanListener->OnScanResult(SCAN_LISTENER_ID, &result); + BroadcastReportInfo reportInfo = {}; + reportInfo.packet.bcData.id = BLE_UUID; + reportInfo.packet.bcData.type = BC_DATA_TYPE_SERVICE; + reportInfo.packet.rspData.id = COMPANY_ID; + reportInfo.packet.rspData.type = BC_DATA_TYPE_MANUFACTURER; + reportInfo.packet.bcData.payload = &activeDiscoveryAdvData[0]; + reportInfo.packet.bcData.payloadLen = advLen; + reportInfo.packet.rspData.payload = &activeDiscoveryRspData[0]; + reportInfo.packet.rspData.payloadLen = rspLen; + scanListener->OnReportScanDataCallback(SCAN_LISTENER_ID, &reportInfo); } } void BleMock::TurnOnBt() { - DISC_LOGI(DISC_TEST, "enter"); btState = true; if (btStateListener) { btStateListener->OnBtStateChanged(BT_STATE_LISTENER_ID, SOFTBUS_BT_STATE_TURN_ON); @@ -456,7 +448,6 @@ void BleMock::TurnOnBt() void BleMock::TurnOffBt() { - DISC_LOGI(DISC_TEST, "enter"); btState = false; if (btStateListener) { btStateListener->OnBtStateChanged(BT_STATE_LISTENER_ID, SOFTBUS_BT_STATE_TURN_OFF); @@ -484,22 +475,22 @@ bool BleMock::IsDeInitSuccess() void BleMock::SetupSuccessStub() { - EXPECT_CALL(*this, SoftBusGetBtState).WillRepeatedly(BleMock::ActionOfGetBtState); - EXPECT_CALL(*this, SoftBusStartAdv).WillRepeatedly(BleMock::ActionOfStartAdv); - EXPECT_CALL(*this, SoftBusStopAdv).WillRepeatedly(BleMock::ActionOfStopAdv); - EXPECT_CALL(*this, SoftBusStartScan).WillRepeatedly(BleMock::ActionOfStartScan); - EXPECT_CALL(*this, SoftBusStopScan).WillRepeatedly(BleMock::ActionOfStopScan); - EXPECT_CALL(*this, SoftBusStopScanImmediately).WillRepeatedly(BleMock::ActionOfStopScanImmediately); - EXPECT_CALL(*this, SoftBusGetBtMacAddr(NotNull())).WillRepeatedly(BleMock::ActionOfGetBtMacAddr); - EXPECT_CALL(*this, SoftBusRemoveBtStateListener).WillRepeatedly(BleMock::ActionOfRemoveBtStateListener); EXPECT_CALL(*this, BleGattLockInit).WillRepeatedly(BleMock::ActionOfBleGattLockInit); + EXPECT_CALL(*this, InitBroadcastMgr).WillRepeatedly(BleMock::ActionOfInitBroadcastMgr); + EXPECT_CALL(*this, DeInitBroadcastMgr).WillRepeatedly(BleMock::ActionOfDeInitBroadcastMgr); + EXPECT_CALL(*this, SoftBusGetBtState).WillRepeatedly(BleMock::ActionOfGetBtState); EXPECT_CALL(*this, SoftBusAddBtStateListener(NotNull())).WillRepeatedly(BleMock::ActionOfAddBtStateListener); - EXPECT_CALL(*this, SoftBusAddScanListener).WillRepeatedly(BleMock::ActionOfAddScanListener); - EXPECT_CALL(*this, SoftBusGetAdvChannel).WillRepeatedly(BleMock::ActionOfGetAdvChannel); - EXPECT_CALL(*this, SoftBusSetScanFilter).WillRepeatedly(BleMock::ActionOfSetScanFilter); - EXPECT_CALL(*this, SoftBusRemoveScanListener).WillRepeatedly(BleMock::ActionOfRemoveScanListener); - EXPECT_CALL(*this, SoftBusReleaseAdvChannel).WillRepeatedly(BleMock::ActionOfReleaseAdvChannel); - EXPECT_CALL(*this, SoftBusDeregisterScanCallbacks).WillRepeatedly(BleMock::ActionOfDeregisterScanCallbacks); + EXPECT_CALL(*this, SoftBusRemoveBtStateListener).WillRepeatedly(BleMock::ActionOfRemoveBtStateListener); + EXPECT_CALL(*this, StartBroadcasting).WillRepeatedly(BleMock::ActionOfStartBroadcasting); + EXPECT_CALL(*this, StopBroadcasting).WillRepeatedly(BleMock::ActionOfStopBroadcasting); + EXPECT_CALL(*this, StartScan).WillRepeatedly(BleMock::ActionOfStartScan); + EXPECT_CALL(*this, StopScan).WillRepeatedly(BleMock::ActionOfStopScan); + EXPECT_CALL(*this, SetScanFilter).WillRepeatedly(BleMock::ActionOfSetScanFilter); + EXPECT_CALL(*this, SoftBusGetBtMacAddr(NotNull())).WillRepeatedly(BleMock::ActionOfGetBtMacAddr); + EXPECT_CALL(*this, RegisterScanListener).WillRepeatedly(BleMock::ActionOfRegisterScanListener); + EXPECT_CALL(*this, UnRegisterScanListener).WillRepeatedly(BleMock::ActionOfUnRegisterScanListener); + EXPECT_CALL(*this, RegisterBroadcaster).WillRepeatedly(BleMock::ActionOfRegisterBroadcaster); + EXPECT_CALL(*this, UnRegisterBroadcaster).WillRepeatedly(BleMock::ActionOfUnRegisterBroadcaster); } void BleMock::AsyncAdvertiseDone() diff --git a/tests/core/discovery/ble/softbus_ble_mock/ble_mock.h b/tests/core/discovery/ble/softbus_ble_mock/ble_mock.h index 7ff082358..21fa05fd3 100644 --- a/tests/core/discovery/ble/softbus_ble_mock/ble_mock.h +++ b/tests/core/discovery/ble/softbus_ble_mock/ble_mock.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 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 @@ -17,14 +17,16 @@ #define BLE_MOCK_H #include -#include #include #include +#include -#include "softbus_adapter_bt_common.h" #include "softbus_adapter_ble_gatt.h" #include "softbus_adapter_ble_gatt_client.h" #include "softbus_adapter_ble_gatt_server.h" +#include "softbus_adapter_bt_common.h" +#include "softbus_broadcast_manager.h" +#include "softbus_broadcast_utils.h" class BleInterface { public: @@ -32,28 +34,28 @@ public: virtual int SoftBusAddBtStateListener(const SoftBusBtStateListener *listener) = 0; virtual int SoftBusRemoveBtStateListener(int listenerId) = 0; - virtual int SoftBusAddScanListener(const SoftBusScanListener *listener, int *scannerId, bool isLpDeviceScan) = 0; - virtual int SoftBusRemoveScanListener(int listenerId) = 0; + virtual int32_t InitBroadcastMgr() = 0; + virtual int32_t DeInitBroadcastMgr() = 0; - virtual int SoftBusSetScanFilter(int listenerId, SoftBusBleScanFilter *filter, uint8_t filterSize) = 0; + virtual int32_t RegisterScanListener(BaseServiceType type, int32_t *listenerId, const ScanCallback *cb) = 0; + virtual int32_t UnRegisterScanListener(int32_t listenerId) = 0; - virtual int SoftBusGetAdvChannel(const SoftBusAdvCallback *callback, int *scannerId, bool isLpDeviceScan) = 0; - virtual int SoftBusReleaseAdvChannel(int channel) = 0; + virtual int32_t SetScanFilter(int32_t listenerId, const BcScanFilter *scanFilter, uint8_t filterNum) = 0; - virtual int SoftBusStartScan(int listenerId, int scannerId, const SoftBusBleScanParams *param) = 0; - virtual int SoftBusStopScan(int listenerId, int scannerId) = 0; - virtual int SoftBusStopScanImmediately(int listenerId, int scannerId) = 0; + virtual int32_t RegisterBroadcaster(BaseServiceType type, int32_t *bcId, const BroadcastCallback *cb) = 0; + virtual int32_t UnRegisterBroadcaster(int32_t bcId) = 0; - virtual int SoftBusStartAdv(int channel, const SoftBusBleAdvParams *param) = 0; - virtual int SoftBusStopAdv(int channel) = 0; + virtual int32_t StartScan(int32_t listenerId, const BcScanParams *param) = 0; + virtual int32_t StopScan(int32_t listenerId) = 0; - virtual int SoftBusUpdateAdv(int channel, const SoftBusBleAdvData *data, const SoftBusBleAdvParams *param) = 0; - virtual int SoftBusSetAdvData(int channel, const SoftBusBleAdvData *data) = 0; + virtual int32_t StartBroadcasting(int32_t bcId, const BroadcastParam *param, const BroadcastPacket *packet) = 0; + virtual int32_t StopBroadcasting(int32_t bcId) = 0; + + virtual int32_t UpdateBroadcasting(int32_t bcId, const BroadcastParam *param, const BroadcastPacket *packet) = 0; + virtual int32_t SetBroadcastingData(int32_t bcId, const BroadcastPacket *packet) = 0; virtual int SoftBusGetBtMacAddr(SoftBusBtAddr *mac) = 0; virtual int SoftBusGetBtState() = 0; - - virtual int32_t SoftBusDeregisterScanCallbacks(int32_t scannerId) = 0; }; class BleMock : public BleInterface { @@ -67,35 +69,27 @@ public: ~BleMock(); MOCK_METHOD(int, BleGattLockInit, (), (override)); - MOCK_METHOD(int, SoftBusAddBtStateListener, (const SoftBusBtStateListener *listener), (override)); MOCK_METHOD(int, SoftBusRemoveBtStateListener, (int listenerId), (override)); - - MOCK_METHOD(int, SoftBusAddScanListener, - (const SoftBusScanListener *listener, int *scannerId, bool isLpDeviceScan), (override)); - MOCK_METHOD(int, SoftBusRemoveScanListener, (int listenerId), (override)); - - MOCK_METHOD(int, SoftBusDeregisterScanCallbacks, (int32_t scannerId), (override)); - - MOCK_METHOD(int, SoftBusSetScanFilter, (int listenerId, SoftBusBleScanFilter *filter, uint8_t filterSize), - (override)); - - MOCK_METHOD(int, SoftBusGetAdvChannel, (const SoftBusAdvCallback *callback, int *scannerId, bool isLpDeviceScan), + MOCK_METHOD(int32_t, InitBroadcastMgr, (), (override)); + MOCK_METHOD(int32_t, DeInitBroadcastMgr, (), (override)); + MOCK_METHOD( + int32_t, RegisterScanListener, (BaseServiceType type, int32_t *listenerId, const ScanCallback *cb), (override)); + MOCK_METHOD(int32_t, UnRegisterScanListener, (int32_t listenerId), (override)); + MOCK_METHOD( + int32_t, SetScanFilter, (int32_t listenerId, const BcScanFilter *scanFilter, uint8_t filterNum), (override)); + MOCK_METHOD( + int32_t, RegisterBroadcaster, (BaseServiceType type, int32_t *bcId, const BroadcastCallback *cb), (override)); + MOCK_METHOD(int32_t, UnRegisterBroadcaster, (int32_t bcId), (override)); + MOCK_METHOD(int32_t, StartScan, (int32_t listenerId, const BcScanParams *param), (override)); + MOCK_METHOD(int32_t, StopScan, (int32_t listenerId), (override)); + MOCK_METHOD(int32_t, StartBroadcasting, (int32_t bcId, const BroadcastParam *param, const BroadcastPacket *packet), (override)); - MOCK_METHOD(int, SoftBusReleaseAdvChannel, (int channel), (override)); - - MOCK_METHOD(int, SoftBusStartScan, (int listenerId, int scannerId, const SoftBusBleScanParams *param), (override)); - MOCK_METHOD(int, SoftBusStopScan, (int listenerId, int scannerId), (override)); - MOCK_METHOD(int, SoftBusStopScanImmediately, (int listenerId, int scannerId), (override)); - - MOCK_METHOD(int, SoftBusStartAdv, (int channel, const SoftBusBleAdvParams *param), (override)); - MOCK_METHOD(int, SoftBusStopAdv, (int channel), (override)); - - MOCK_METHOD(int, SoftBusSetAdvData, (int channel, const SoftBusBleAdvData *data), (override)); - MOCK_METHOD(int, SoftBusUpdateAdv, (int channel, const SoftBusBleAdvData *data, const SoftBusBleAdvParams *param), - (override)); - - MOCK_METHOD(int, SoftBusGetBtMacAddr, (SoftBusBtAddr *mac), (override)); + MOCK_METHOD(int32_t, StopBroadcasting, (int32_t bcId), (override)); + MOCK_METHOD(int32_t, SetBroadcastingData, (int32_t bcId, const BroadcastPacket *packet), (override)); + MOCK_METHOD(int32_t, UpdateBroadcasting, (int32_t bcId, const BroadcastParam *param, const BroadcastPacket *packet), + (override)); + MOCK_METHOD(int, SoftBusGetBtMacAddr, (SoftBusBtAddr * mac), (override)); MOCK_METHOD(int, SoftBusGetBtState, (), (override)); void SetupSuccessStub(); @@ -107,24 +101,24 @@ public: static int32_t ActionOfBleGattLockInit(); static int32_t ActionOfAddBtStateListener(const SoftBusBtStateListener *listener); static int32_t ActionOfRemoveBtStateListener(int listenerId); - static int32_t ActionOfAddScanListener(const SoftBusScanListener *listener, int *scannerId, bool isLpDeviceScan); - static int32_t ActionOfRemoveScanListener(int listenerId); - static int32_t ActionOfDeregisterScanCallbacks(int scannerId); - static int32_t ActionOfSetScanFilter(int listenerId, const SoftBusBleScanFilter *filter, uint8_t filterSize); - static int32_t ActionOfGetAdvChannel(const SoftBusAdvCallback *callback, int *scannerId, bool isLpDeviceScan); - static int32_t ActionOfReleaseAdvChannel(int channel); - static int32_t ActionOfStartScan(int listenerId, int scannerId, const SoftBusBleScanParams *param); - static int32_t ActionOfStopScan(int listenerId, int scannerId); - static int32_t ActionOfStopScanImmediately(int listenerId, int scannerId); - static int32_t ActionOfStartAdv(int channel, const SoftBusBleAdvParams *param); - static int32_t ActionOfStopAdv(int channel); - static int32_t ActionOfSetAdvDataForActiveDiscovery(int channel, const SoftBusBleAdvData *data); - static int32_t ActionOfUpdateAdvForActiveDiscovery(int channel, const SoftBusBleAdvData *data, - const SoftBusBleAdvParams *param); - static int32_t ActionOfSetAdvDataForActivePublish(int channel, const SoftBusBleAdvData *data); - static int32_t ActionOfSetAdvDataForPassivePublish(int channel, const SoftBusBleAdvData *data); - static int32_t ActionOfUpdateAdvForPassivePublish(int channel, const SoftBusBleAdvData *data, - const SoftBusBleAdvParams *param); + static int32_t ActionOfInitBroadcastMgr(); + static int32_t ActionOfDeInitBroadcastMgr(); + static int32_t ActionOfRegisterScanListener(BaseServiceType type, int32_t *listenerId, const ScanCallback *cb); + static int32_t ActionOfUnRegisterScanListener(int32_t listenerId); + static int32_t ActionOfSetScanFilter(int32_t listenerId, const BcScanFilter *scanFilter, uint8_t filterNum); + static int32_t ActionOfRegisterBroadcaster(BaseServiceType type, int32_t *bcId, const BroadcastCallback *cb); + static int32_t ActionOfUnRegisterBroadcaster(int32_t bcId); + static int32_t ActionOfStartScan(int32_t listenerId, const BcScanParams *param); + static int32_t ActionOfStopScan(int32_t listenerId); + static int32_t ActionOfStartBroadcasting(int32_t bcId, const BroadcastParam *param, const BroadcastPacket *packet); + static int32_t ActionOfStopBroadcasting(int32_t bcId); + static int32_t ActionOfSetAdvDataForActiveDiscovery(int32_t bcId, const BroadcastPacket *packet); + static int32_t ActionOfUpdateAdvForActiveDiscovery( + int32_t bcId, const BroadcastParam *param, const BroadcastPacket *packet); + static int32_t ActionOfSetAdvDataForActivePublish(int32_t bcId, const BroadcastPacket *packet); + static int32_t ActionOfSetAdvDataForPassivePublish(int32_t bcId, const BroadcastPacket *packet); + static int32_t ActionOfUpdateAdvForPassivePublish( + int32_t bcId, const BroadcastParam *param, const BroadcastPacket *packet); static int32_t ActionOfGetBtMacAddr(SoftBusBtAddr *mac); static int32_t ActionOfGetBtState(); @@ -142,56 +136,32 @@ public: static constexpr int SCAN_LISTENER_ID = 2; static constexpr int BLE_MSG_TIME_OUT_MS = 6000; - static inline const SoftBusScanListener *scanListener {}; + static inline const ScanCallback *scanListener {}; static inline const SoftBusBtStateListener *btStateListener {}; - static inline const SoftBusAdvCallback *advCallback {}; + static inline const BroadcastCallback *advCallback {}; static inline bool isAdvertising {}; static inline bool isScanning {}; static inline bool btState {}; - static inline uint8_t btMacAddr[] = {0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; + static inline uint8_t btMacAddr[] = { 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; - static inline uint8_t activeDiscoveryAdvData[] = { - 0x02, 0x01, 0x02, 0x1B, 0x16, 0xEE, 0xFD, 0x04, - 0x05, 0x90, 0x00, 0x01, 0x02, 0x00, 0x18, 0xE8, - 0x31, 0xF7, 0x63, 0x0B, 0x76, 0x19, 0xAE, 0x21, - 0x0E, 0x3A, 0x4D, 0x79, 0x20, 0x44, 0x65 - }; - static inline uint8_t activeDiscoveryAdvData2[] = { - 0x02, 0x01, 0x02, 0x1B, 0x16, 0xEE, 0xFD, 0x04, - 0x05, 0x90, 0x00, 0x01, 0x12, 0x00, 0x18, 0xE8, - 0x31, 0xF7, 0x63, 0x0B, 0x76, 0x19, 0xAE, 0x21, - 0x0E, 0x3A, 0x4D, 0x79, 0x20, 0x44, 0x65 - }; - static inline uint8_t activeDiscoveryRspData[] = { - 0x08, 0xFF, 0x7D, 0x02, 0x76, 0x69, 0x63, 0x65, - 0x00 - }; + static inline uint8_t activeDiscoveryAdvData[] = { 0x04, 0x05, 0x90, 0x00, 0x01, 0x02, 0x00, 0x18, 0xE8, 0x31, 0xF7, + 0x63, 0x0B, 0x76, 0x19, 0xAE, 0x21, 0x0E, 0x3A, 0x4D, 0x79, 0x20, 0x44, 0x65 }; + static inline uint8_t activeDiscoveryAdvData2[] = { 0x04, 0x05, 0x90, 0x00, 0x01, 0x12, 0x00, 0x18, 0xE8, 0x31, + 0xF7, 0x63, 0x0B, 0x76, 0x19, 0xAE, 0x21, 0x0E, 0x3A, 0x4D, 0x79, 0x20, 0x44, 0x65 }; + static inline uint8_t activeDiscoveryRspData[] = { 0x76, 0x69, 0x63, 0x65, 0x00 }; - static inline uint8_t activePublishAdvData[] = { - 0x02, 0x01, 0x02, 0x1B, 0x16, 0xEE, 0xFD, 0x04, - 0x05, 0x10, 0x00, 0x01, 0x02, 0x00, 0x18, 0xE8, - 0x31, 0xF7, 0x63, 0x0B, 0x76, 0x19, 0xAE, 0x21, - 0x0E, 0x3A, 0x4D, 0x79, 0x20, 0x44, 0x65 - }; - static inline uint8_t activePublishRspData[] = { - 0x08, 0xFF, 0x7D, 0x02, 0x76, 0x69, 0x63, 0x65, - 0x00 - }; + static inline uint8_t activePublishAdvData[] = { 0x04, 0x05, 0x10, 0x00, 0x01, 0x02, 0x00, 0x18, 0xE8, 0x31, 0xF7, + 0x63, 0x0B, 0x76, 0x19, 0xAE, 0x21, 0x0E, 0x3A, 0x4D, 0x79, 0x20, 0x44, 0x65 }; + static inline uint8_t activePublishRspData[] = { 0x76, 0x69, 0x63, 0x65, 0x00 }; - static inline uint8_t passivePublishAdvData[] = { - 0x02, 0x01, 0x02, 0x1B, 0x16, 0xEE, 0xFD, 0x04, - 0x05, 0x10, 0x00, 0x01, 0x02, 0x00, 0x18, 0xE8, - 0x31, 0xF7, 0x63, 0x0B, 0x76, 0x19, 0xAE, 0x21, - 0x0E, 0x56, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E - }; - static inline uint8_t passivePublishRspData[] = { - 0x0F, 0xFF, 0x7D, 0x02, 0x0F, 0x3A, 0x4D, 0x79, - 0x20, 0x44, 0x65, 0x76, 0x69, 0x63, 0x65, 0x00 - }; + static inline uint8_t passivePublishAdvData[] = { 0x04, 0x05, 0x10, 0x00, 0x01, 0x02, 0x00, 0x18, 0xE8, 0x31, 0xF7, + 0x63, 0x0B, 0x76, 0x19, 0xAE, 0x21, 0x0E, 0x56, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E }; + static inline uint8_t passivePublishRspData[] = { 0x0F, 0x3A, 0x4D, 0x79, 0x20, 0x44, 0x65, + 0x76, 0x69, 0x63, 0x65, 0x00 }; private: static void HexDump(const uint8_t *data, uint32_t len); - static void ShowAdvData(int channel, const SoftBusBleAdvData *data); + static void ShowAdvData(int32_t bcId, const BroadcastPacket *packet); static inline std::atomic mock = nullptr; static inline std::atomic_bool isAsyncAdvertiseSuccess; diff --git a/tests/core/discovery/ble/softbus_ble_mock/disc_ble_test.cpp b/tests/core/discovery/ble/softbus_ble_mock/disc_ble_test.cpp index 17f6b35cb..e8ab413ef 100644 --- a/tests/core/discovery/ble/softbus_ble_mock/disc_ble_test.cpp +++ b/tests/core/discovery/ble/softbus_ble_mock/disc_ble_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 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 @@ -14,25 +14,25 @@ */ #include -#include -#include #include +#include +#include +#include "ble_mock.h" +#include "bus_center_mock.h" #include "disc_ble.h" #include "disc_ble_utils.h" #include "disc_log.h" -#include "bus_center_mock.h" -#include "ble_mock.h" -#include "message_handler.h" -#include "softbus_error_code.h" -#include "securec.h" #include "exception_branch_checker.h" +#include "message_handler.h" +#include "securec.h" +#include "softbus_error_code.h" using namespace testing::ext; -using testing::Return; using testing::_; -using testing::NotNull; using testing::NiceMock; +using testing::NotNull; +using testing::Return; namespace OHOS { class DiscBleTest : public testing::Test { @@ -105,11 +105,11 @@ static SubscribeOption GetSubscribeOptionForOsd() } /* -* @tc.name: DiscBleInit001 -* @tc.desc: invalid input parameter -* @tc.type: FUNC -* @tc.require: -*/ + * @tc.name: DiscBleInit001 + * @tc.desc: invalid input parameter + * @tc.type: FUNC + * @tc.require: + */ HWTEST_F(DiscBleTest, DiscBleInit001, TestSize.Level1) { DISC_LOGI(DISC_TEST, "DiscBleInit001 begin ----"); @@ -127,58 +127,63 @@ HWTEST_F(DiscBleTest, DiscBleInit001, TestSize.Level1) } /* -* @tc.name: DiscBleInit002 -* @tc.desc: scan listener init failed -* @tc.type: FUNC -* @tc.require: -*/ + * @tc.name: DiscBleInit002 + * @tc.desc: scan listener init failed + * @tc.type: FUNC + * @tc.require: + */ HWTEST_F(DiscBleTest, DiscBleInit002, TestSize.Level1) { DISC_LOGI(DISC_TEST, "DiscBleInit002 begin ----"); { BleMock bleMock; bleMock.SetupSuccessStub(); - EXPECT_CALL(bleMock, SoftBusAddScanListener).WillRepeatedly(Return(SOFTBUS_ERR)); - + EXPECT_CALL(bleMock, InitBroadcastMgr).WillRepeatedly(Return(SOFTBUS_ERR)); EXPECT_EQ(DiscSoftBusBleInit(&g_discInnerCallback), nullptr); } { BleMock bleMock; bleMock.SetupSuccessStub(); + EXPECT_CALL(bleMock, InitBroadcastMgr).WillRepeatedly(Return(SOFTBUS_OK)); + EXPECT_CALL(bleMock, RegisterScanListener).WillRepeatedly(Return(SOFTBUS_ERR)); + EXPECT_EQ(DiscSoftBusBleInit(&g_discInnerCallback), nullptr); + } + { + BleMock bleMock; + bleMock.SetupSuccessStub(); + EXPECT_CALL(bleMock, InitBroadcastMgr).WillRepeatedly(Return(SOFTBUS_OK)); + EXPECT_CALL(bleMock, RegisterScanListener).WillRepeatedly(Return(SOFTBUS_OK)); EXPECT_CALL(bleMock, SoftBusAddBtStateListener).WillRepeatedly(Return(SOFTBUS_ERR)); - EXPECT_EQ(DiscSoftBusBleInit(&g_discInnerCallback), nullptr); } { BleMock bleMock; bleMock.SetupSuccessStub(); - EXPECT_CALL(bleMock, SoftBusGetAdvChannel).WillOnce(Return(SOFTBUS_OK)).WillOnce(Return(SOFTBUS_ERR)); - + EXPECT_CALL(bleMock, InitBroadcastMgr).WillRepeatedly(Return(SOFTBUS_OK)); + EXPECT_CALL(bleMock, RegisterScanListener).WillRepeatedly(Return(SOFTBUS_OK)); + EXPECT_CALL(bleMock, SoftBusAddBtStateListener).WillRepeatedly(Return(SOFTBUS_OK)); + EXPECT_CALL(bleMock, SetScanFilter).WillRepeatedly(Return(SOFTBUS_ERR)); EXPECT_EQ(DiscSoftBusBleInit(&g_discInnerCallback), nullptr); } { BleMock bleMock; bleMock.SetupSuccessStub(); - EXPECT_CALL(bleMock, SoftBusGetAdvChannel).WillOnce(Return(SOFTBUS_ERR)).WillOnce(Return(SOFTBUS_OK)); - + EXPECT_CALL(bleMock, InitBroadcastMgr).WillRepeatedly(Return(SOFTBUS_OK)); + EXPECT_CALL(bleMock, RegisterScanListener).WillRepeatedly(Return(SOFTBUS_OK)); + EXPECT_CALL(bleMock, SoftBusAddBtStateListener).WillRepeatedly(Return(SOFTBUS_OK)); + EXPECT_CALL(bleMock, SetScanFilter).WillRepeatedly(Return(SOFTBUS_OK)); + EXPECT_CALL(bleMock, RegisterBroadcaster).WillRepeatedly(Return(SOFTBUS_ERR)); EXPECT_EQ(DiscSoftBusBleInit(&g_discInnerCallback), nullptr); } - { - BleMock bleMock; - bleMock.SetupSuccessStub(); - EXPECT_CALL(bleMock, SoftBusSetScanFilter).WillOnce(Return(SOFTBUS_ERR)); - - EXPECT_NE(DiscSoftBusBleInit(&g_discInnerCallback), nullptr); - } DISC_LOGI(DISC_TEST, "DiscBleInit002 end ----"); } /* -* @tc.name: DiscBleInit003 -* @tc.desc: valid parameter, init successful -* @tc.type: FUNC -* @tc.require: -*/ + * @tc.name: DiscBleInit003 + * @tc.desc: valid parameter, init successful + * @tc.type: FUNC + * @tc.require: + */ HWTEST_F(DiscBleTest, DiscBleInit003, TestSize.Level1) { DISC_LOGI(DISC_TEST, "DiscBleInit003 begin ----"); @@ -191,17 +196,16 @@ HWTEST_F(DiscBleTest, DiscBleInit003, TestSize.Level1) } /* -* @tc.name: StartActiveDiscovery001 -* @tc.desc: start active discovery successfully -* @tc.type: FUNC -* @tc.require: -*/ + * @tc.name: StartActiveDiscovery001 + * @tc.desc: start active discovery successfully + * @tc.type: FUNC + * @tc.require: + */ HWTEST_F(DiscBleTest, StartActiveDiscovery001, TestSize.Level1) { DISC_LOGI(DISC_TEST, "StartActiveDiscovery001 begin ----"); NiceMock bleMock; bleMock.SetupSuccessStub(); - EXPECT_CALL(bleMock, SoftBusSetAdvData(_, NotNull())).WillRepeatedly(BleMock::ActionOfSetAdvDataForActiveDiscovery); BusCenterMock busMock; busMock.SetupSuccessStub(); @@ -221,17 +225,17 @@ HWTEST_F(DiscBleTest, StartActiveDiscovery001, TestSize.Level1) } /* -* @tc.name: StartActiveDiscovery002 -* @tc.desc: start the second capability to update advertiser -* @tc.type: FUNC -* @tc.require: -*/ + * @tc.name: StartActiveDiscovery002 + * @tc.desc: start the second capability to update advertiser + * @tc.type: FUNC + * @tc.require: + */ HWTEST_F(DiscBleTest, StartActiveDiscovery002, TestSize.Level1) { DISC_LOGI(DISC_TEST, "StartActiveDiscovery002 begin ----"); BleMock bleMock; bleMock.SetupSuccessStub(); - EXPECT_CALL(bleMock, SoftBusUpdateAdv(_, NotNull(), NotNull())) + EXPECT_CALL(bleMock, UpdateBroadcasting(_, NotNull(), NotNull())) .WillRepeatedly(BleMock::ActionOfUpdateAdvForActiveDiscovery); BusCenterMock busMock; @@ -245,17 +249,17 @@ HWTEST_F(DiscBleTest, StartActiveDiscovery002, TestSize.Level1) } /* -* @tc.name: UpdateLocalDeviceInfo001 -* @tc.desc: update local device info -* @tc.type: FUNC -* @tc.require: -*/ + * @tc.name: UpdateLocalDeviceInfo001 + * @tc.desc: update local device info + * @tc.type: FUNC + * @tc.require: + */ HWTEST_F(DiscBleTest, UpdateLocalDeviceInfo001, TestSize.Level1) { DISC_LOGI(DISC_TEST, "UpdateLocalDeviceInfo001 begin ----"); BleMock bleMock; bleMock.SetupSuccessStub(); - EXPECT_CALL(bleMock, SoftBusUpdateAdv(_, NotNull(), NotNull())) + EXPECT_CALL(bleMock, UpdateBroadcasting(_, NotNull(), NotNull())) .WillRepeatedly(BleMock::ActionOfUpdateAdvForActiveDiscovery); BusCenterMock busMock; @@ -269,11 +273,11 @@ HWTEST_F(DiscBleTest, UpdateLocalDeviceInfo001, TestSize.Level1) } /* -* @tc.name: ReceivePassivePublishPacket001 -* @tc.desc: receive passive publish packet -* @tc.type: FUNC -* @tc.require: -*/ + * @tc.name: ReceivePassivePublishPacket001 + * @tc.desc: receive passive publish packet + * @tc.type: FUNC + * @tc.require: + */ HWTEST_F(DiscBleTest, ReceivePassivePublishPacket001, TestSize.Level1) { DISC_LOGI(DISC_TEST, "ReceivePassivePublishPacket001 begin ----"); @@ -292,16 +296,18 @@ HWTEST_F(DiscBleTest, ReceivePassivePublishPacket001, TestSize.Level1) } /* -* @tc.name: StopActiveDiscovery001 -* @tc.desc: stop active discovery successfully -* @tc.type: FUNC -* @tc.require: -*/ + * @tc.name: StopActiveDiscovery001 + * @tc.desc: stop active discovery successfully + * @tc.type: FUNC + * @tc.require: + */ HWTEST_F(DiscBleTest, StopActiveDiscovery001, TestSize.Level1) { DISC_LOGI(DISC_TEST, "StopActiveDiscovery001 begin ----"); BleMock bleMock; bleMock.SetupSuccessStub(); + EXPECT_CALL(bleMock, UpdateBroadcasting(_, NotNull(), NotNull())) + .WillRepeatedly(BleMock::ActionOfUpdateAdvForActiveDiscovery); BusCenterMock busMock; busMock.SetupSuccessStub(); @@ -316,11 +322,11 @@ HWTEST_F(DiscBleTest, StopActiveDiscovery001, TestSize.Level1) } /* -* @tc.name: StartActiveDiscovery001 -* @tc.desc: start active discovery successfully -* @tc.type: FUNC -* @tc.require: -*/ + * @tc.name: StartActiveDiscovery001 + * @tc.desc: start active discovery successfully + * @tc.type: FUNC + * @tc.require: + */ HWTEST_F(DiscBleTest, StartPassiveDiscovery001, TestSize.Level1) { DISC_LOGI(DISC_TEST, "StartPassiveDiscovery001 begin ----"); @@ -335,7 +341,6 @@ HWTEST_F(DiscBleTest, StartPassiveDiscovery001, TestSize.Level1) std::this_thread::sleep_for(std::chrono::seconds(1)); BleMock::InjectActiveNonPacket(); - std::this_thread::sleep_for(std::chrono::seconds(1)); EXPECT_EQ(strcmp(g_foundDeviceInfo.devId, FOUND_DEVICE_ID), 0); EXPECT_EQ(g_foundDeviceInfo.capabilityBitmap[0], 1 << CASTPLUS_CAPABILITY_BITMAP); @@ -344,11 +349,11 @@ HWTEST_F(DiscBleTest, StartPassiveDiscovery001, TestSize.Level1) } /* -* @tc.name: StopPassiveDiscovery001 -* @tc.desc: stop active discovery successfully -* @tc.type: FUNC -* @tc.require: -*/ + * @tc.name: StopPassiveDiscovery001 + * @tc.desc: stop active discovery successfully + * @tc.type: FUNC + * @tc.require: + */ HWTEST_F(DiscBleTest, StopPassiveDiscovery001, TestSize.Level1) { DISC_LOGI(DISC_TEST, "StopPassiveDiscovery001 begin ----"); @@ -369,17 +374,16 @@ HWTEST_F(DiscBleTest, StopPassiveDiscovery001, TestSize.Level1) } /* -* @tc.name: StartActivePublish001 -* @tc.desc: start active publish successfully -* @tc.type: FUNC -* @tc.require: -*/ + * @tc.name: StartActivePublish001 + * @tc.desc: start active publish successfully + * @tc.type: FUNC + * @tc.require: + */ HWTEST_F(DiscBleTest, StartActivePublish001, TestSize.Level1) { DISC_LOGI(DISC_TEST, "StartActivePublish001 begin ----"); BleMock bleMock; bleMock.SetupSuccessStub(); - EXPECT_CALL(bleMock, SoftBusSetAdvData(_, NotNull())).WillRepeatedly(BleMock::ActionOfSetAdvDataForActivePublish); BusCenterMock busMock; busMock.SetupSuccessStub(); @@ -392,11 +396,11 @@ HWTEST_F(DiscBleTest, StartActivePublish001, TestSize.Level1) } /* -* @tc.name: StopActivePublish001 -* @tc.desc: stop active publish successfully -* @tc.type: FUNC -* @tc.require: -*/ + * @tc.name: StopActivePublish001 + * @tc.desc: stop active publish successfully + * @tc.type: FUNC + * @tc.require: + */ HWTEST_F(DiscBleTest, StopActivePublish001, TestSize.Level1) { DISC_LOGI(DISC_TEST, "StopActivePublish001 begin ----"); @@ -414,11 +418,11 @@ HWTEST_F(DiscBleTest, StopActivePublish001, TestSize.Level1) } /* -* @tc.name: StartPassivePublish001 -* @tc.desc: start passive publish successfully -* @tc.type: FUNC -* @tc.require: -*/ + * @tc.name: StartPassivePublish001 + * @tc.desc: start passive publish successfully + * @tc.type: FUNC + * @tc.require: + */ HWTEST_F(DiscBleTest, StartPassivePublish001, TestSize.Level1) { DISC_LOGI(DISC_TEST, "StartPassivePublish001 begin ----"); @@ -436,33 +440,34 @@ HWTEST_F(DiscBleTest, StartPassivePublish001, TestSize.Level1) } /* -* @tc.name: ReceiveActiveDiscoveryPacket001 -* @tc.desc: when receiving active discovery packet, handle it successfully -* @tc.type: FUNC -* @tc.require: -*/ + * @tc.name: ReceiveActiveDiscoveryPacket001 + * @tc.desc: when receiving active discovery packet, handle it successfully + * @tc.type: FUNC + * @tc.require: + */ HWTEST_F(DiscBleTest, ReceiveActiveDiscoveryPacket001, TestSize.Level1) { DISC_LOGI(DISC_TEST, "ReceiveActiveDiscoveryPacket001 begin ----"); BleMock bleMock; bleMock.SetupSuccessStub(); - EXPECT_CALL(bleMock, SoftBusSetAdvData(_, NotNull())) - .WillRepeatedly(BleMock::ActionOfSetAdvDataForPassivePublish); + EXPECT_CALL(bleMock, UpdateBroadcasting(_, NotNull(), NotNull())) + .WillRepeatedly(BleMock::ActionOfUpdateAdvForPassivePublish); BusCenterMock busMock; busMock.SetupSuccessStub(); BleMock::InjectActiveConPacket(); + EXPECT_EQ(bleMock.GetAsyncAdvertiseResult(), true); DISC_LOGI(DISC_TEST, "ReceiveActiveDiscoveryPacket001 end ----"); } /* -* @tc.name: StopPassivePublish001 -* @tc.desc: stop passive publish successfully -* @tc.type: FUNC -* @tc.require: -*/ + * @tc.name: StopPassivePublish001 + * @tc.desc: stop passive publish successfully + * @tc.type: FUNC + * @tc.require: + */ HWTEST_F(DiscBleTest, StopPassivePublish001, TestSize.Level1) { DISC_LOGI(DISC_TEST, "StopPassivePublish001 begin ----"); @@ -480,11 +485,11 @@ HWTEST_F(DiscBleTest, StopPassivePublish001, TestSize.Level1) } /* -* @tc.name: IsConcernCapability001 -* @tc.desc: test ble discovery supported capability -* @tc.type: FUNC -* @tc.require: -*/ + * @tc.name: IsConcernCapability001 + * @tc.desc: test ble discovery supported capability + * @tc.type: FUNC + * @tc.require: + */ HWTEST_F(DiscBleTest, IsConcernCapability001, TestSize.Level1) { DISC_LOGI(DISC_TEST, "IsConcernCapability001 begin ----"); @@ -504,11 +509,11 @@ HWTEST_F(DiscBleTest, IsConcernCapability001, TestSize.Level1) } /* -* @tc.name: DiscBleDeInit001 -* @tc.desc: stop passive publish successfully -* @tc.type: FUNC -* @tc.require: -*/ + * @tc.name: DiscBleDeInit001 + * @tc.desc: stop passive publish successfully + * @tc.type: FUNC + * @tc.require: + */ HWTEST_F(DiscBleTest, DiscBleDeInit001, TestSize.Level1) { DISC_LOGI(DISC_TEST, "DiscBleDeInit001 begin ----"); @@ -523,4 +528,4 @@ HWTEST_F(DiscBleTest, DiscBleDeInit001, TestSize.Level1) EXPECT_EQ(BleMock::IsDeInitSuccess(), true); DISC_LOGI(DISC_TEST, "DiscBleDeInit001 end ----"); } -} \ No newline at end of file +} // namespace OHOS \ No newline at end of file diff --git a/tests/core/frame/weak_func_client.c b/tests/core/frame/weak_func_client.c index 235d797be..e31f1547b 100644 --- a/tests/core/frame/weak_func_client.c +++ b/tests/core/frame/weak_func_client.c @@ -13,10 +13,11 @@ * limitations under the License. */ -#include "softbus_log_old.h" +#include "comm_log.h" int OnStartDiscoveryWeak(const char *pkgName, const void *info) { - LOG_INFO("client OnStartDiscovery Strong pkgName = %s\n", pkgName); + COMM_LOGI(COMM_INIT, "client OnStartDiscovery Strong pkgName = %s", pkgName); + (void)info; return 0; } \ No newline at end of file diff --git a/tests/core/frame/weak_func_server.c b/tests/core/frame/weak_func_server.c index cbfb097a9..22d99a187 100644 --- a/tests/core/frame/weak_func_server.c +++ b/tests/core/frame/weak_func_server.c @@ -14,11 +14,11 @@ */ #include "softbus_interface.h" -#include "softbus_log_old.h" +#include "comm_log.h" int StartDiscoveryWeak(const char *pkgName, const void *info) { - LOG_INFO("StartDiscovery Strong pkgName = %s\n", pkgName); + COMM_LOGI(COMM_INIT, "StartDiscovery Strong pkgName = %s", pkgName); GetClientProvideInterface()->onChannelOpened(pkgName, NULL); return 0; } \ No newline at end of file diff --git a/tests/core/transmission/trans_channel/auth_channel/trans_auth_manager_test.cpp b/tests/core/transmission/trans_channel/auth_channel/trans_auth_manager_test.cpp index 930d7e94e..4c9602521 100644 --- a/tests/core/transmission/trans_channel/auth_channel/trans_auth_manager_test.cpp +++ b/tests/core/transmission/trans_channel/auth_channel/trans_auth_manager_test.cpp @@ -16,7 +16,6 @@ #include #include -#include "softbus_log_old.h" #include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_adapter_mem.h" diff --git a/tests/core/transmission/trans_channel/common/trans_lane_test.cpp b/tests/core/transmission/trans_channel/common/trans_lane_test.cpp index 2db5d1ddc..996f4b92f 100644 --- a/tests/core/transmission/trans_channel/common/trans_lane_test.cpp +++ b/tests/core/transmission/trans_channel/common/trans_lane_test.cpp @@ -504,13 +504,13 @@ HWTEST_F(TransLaneTest, TransLaneTest013, TestSize.Level1) (void)TransReqLanePendingInit(); (void)memcpy_s(&requestOption.requestInfo, sizeof(TransOption), &trans, sizeof(TransOption)); - ret = TransAddLaneReqToPendingAndWaiting(laneMgr,laneId, NULL); + ret = TransAddLaneReqToPendingAndWaiting(laneMgr, laneId, NULL); EXPECT_TRUE(ret != SOFTBUS_OK); - ret = TransAddLaneReqToPendingAndWaiting(laneMgr,laneId, &requestOption); + ret = TransAddLaneReqToPendingAndWaiting(laneMgr, laneId, &requestOption); EXPECT_TRUE(ret != SOFTBUS_OK); - ret = TransAddLaneReqToPendingAndWaiting(laneMgr,laneId, &requestOption); + ret = TransAddLaneReqToPendingAndWaiting(laneMgr, laneId, &requestOption); EXPECT_TRUE(ret != SOFTBUS_OK); (void)TransDelLaneReqFromPendingList(laneId); diff --git a/tests/core/transmission/trans_channel/manager/trans_channel_manager_test/trans_channel_manager_test.cpp b/tests/core/transmission/trans_channel/manager/trans_channel_manager_test/trans_channel_manager_test.cpp index a420bb32c..9697ea410 100644 --- a/tests/core/transmission/trans_channel/manager/trans_channel_manager_test/trans_channel_manager_test.cpp +++ b/tests/core/transmission/trans_channel/manager/trans_channel_manager_test/trans_channel_manager_test.cpp @@ -197,29 +197,29 @@ HWTEST_F(TransChannelManagerTest, TransGetChannelType001, TestSize.Level1) ASSERT_TRUE(transInfo != nullptr); memset_s(transInfo, sizeof(TransInfo), 0, sizeof(TransInfo)); - transInfo->channelType = TransGetChannelType(NULL, connInfo); + transInfo->channelType = TransGetChannelType(NULL, connInfo->type); EXPECT_EQ(CHANNEL_TYPE_BUTT, transInfo->channelType); connInfo->type = LANE_BR; - transInfo->channelType = TransGetChannelType(param, connInfo); + transInfo->channelType = TransGetChannelType(param, connInfo->type); EXPECT_EQ(CHANNEL_TYPE_PROXY, transInfo->channelType); connInfo->type = LANE_P2P; tmp = 2; param->attr = &g_sessionAttr[tmp]; - transInfo->channelType = TransGetChannelType(param, connInfo); + transInfo->channelType = TransGetChannelType(param, connInfo->type); EXPECT_EQ(CHANNEL_TYPE_UDP, transInfo->channelType); tmp = 0; param->attr = &g_sessionAttr[tmp]; connInfo->type = LANE_BR; - transInfo->channelType = TransGetChannelType(param, connInfo); + transInfo->channelType = TransGetChannelType(param, connInfo->type); EXPECT_EQ(CHANNEL_TYPE_PROXY, transInfo->channelType); connInfo->type = LANE_P2P; tmp = 1; param->attr = &g_sessionAttr[tmp]; - transInfo->channelType = TransGetChannelType(param, connInfo); + transInfo->channelType = TransGetChannelType(param, connInfo->type); EXPECT_EQ(CHANNEL_TYPE_TCP_DIRECT, transInfo->channelType); SoftBusFree(param); diff --git a/tests/sdk/transmission/trans_channel/tcp_direct/trans_sdk_tcp_direct_test.cpp b/tests/sdk/transmission/trans_channel/tcp_direct/trans_sdk_tcp_direct_test.cpp index 2051269be..6f00d7943 100644 --- a/tests/sdk/transmission/trans_channel/tcp_direct/trans_sdk_tcp_direct_test.cpp +++ b/tests/sdk/transmission/trans_channel/tcp_direct/trans_sdk_tcp_direct_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 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 diff --git a/tests/sdk/transmission/trans_channel/tcp_direct/trans_tcp_direct_test.cpp b/tests/sdk/transmission/trans_channel/tcp_direct/trans_tcp_direct_test.cpp index 0c1b7dae3..cfc9e18d8 100644 --- a/tests/sdk/transmission/trans_channel/tcp_direct/trans_tcp_direct_test.cpp +++ b/tests/sdk/transmission/trans_channel/tcp_direct/trans_tcp_direct_test.cpp @@ -554,19 +554,19 @@ HWTEST_F(TransTcpDirectTest, TransTdcSetPendingPacketTest001, TestSize.Level0) int32_t seqNum = 1; int type = 1; int32_t ret = TransTdcSetPendingPacket(channelId, data, len); - EXPECT_TRUE(ret == SOFTBUS_ERR); + EXPECT_EQ(SOFTBUS_ERR, ret); ret = PendingInit(type); ASSERT_TRUE(ret == SOFTBUS_OK); ret = ProcPendingPacket(channelId, seqNum, type); - EXPECT_TRUE(ret != SOFTBUS_OK); + EXPECT_NE(SOFTBUS_OK, ret); len = ACK_SIZE; channelId = INVALID_VALUE; ret = TransTdcSetPendingPacket(channelId, data, len); - EXPECT_TRUE(ret == SOFTBUS_ERR); + EXPECT_EQ(SOFTBUS_ERR, ret); channelId = 1; ret = TransTdcSetPendingPacket(channelId, data, len); - EXPECT_TRUE(ret == SOFTBUS_ERR); + EXPECT_EQ(SOFTBUS_ERR, ret); PendingDeinit(type); } @@ -696,7 +696,7 @@ HWTEST_F(TransTcpDirectTest, TransTdcProcessDataTest001, TestSize.Level0) info->fd = g_fd; int32_t ret = TransTdcProcessData(channelId); - EXPECT_TRUE(ret == SOFTBUS_ERR); + EXPECT_EQ(SOFTBUS_ERR, ret); IClientSessionCallBack *cb = GetClientSessionCb(); ret = TransTdcManagerInit(cb); ASSERT_EQ(ret, SOFTBUS_OK); @@ -705,7 +705,7 @@ HWTEST_F(TransTcpDirectTest, TransTdcProcessDataTest001, TestSize.Level0) EXPECT_TRUE(ret != SOFTBUS_OK); ret = TransTdcProcessData(channelId); - EXPECT_TRUE(ret == SOFTBUS_ERR); + EXPECT_EQ(SOFTBUS_ERR, ret); ret = TransDataListInit(); ASSERT_EQ(ret, SOFTBUS_OK); @@ -714,7 +714,7 @@ HWTEST_F(TransTcpDirectTest, TransTdcProcessDataTest001, TestSize.Level0) ASSERT_EQ(ret, SOFTBUS_OK); ret = TransTdcProcessData(channelId); - EXPECT_TRUE(ret != SOFTBUS_OK); + EXPECT_NE(SOFTBUS_OK, ret); TransDataListDeinit(); TransTdcManagerDeinit(); diff --git a/tests/sdk/transmission/trans_channel/udp/stream/dstream_adaptor_client_test.c b/tests/sdk/transmission/trans_channel/udp/stream/dstream_adaptor_client_test.c index 68c66cf96..35faeb31a 100644 --- a/tests/sdk/transmission/trans_channel/udp/stream/dstream_adaptor_client_test.c +++ b/tests/sdk/transmission/trans_channel/udp/stream/dstream_adaptor_client_test.c @@ -87,13 +87,13 @@ int SendVtpStreamTest(VtpStreamOpenParam *p1, VtpStreamOpenParam *p2, const IStr } int ret = StartVtpStreamChannelClient(CHANNELID, p1, callback); - if (ret ==SOFTBUS_ERR) { + if (ret == SOFTBUS_ERR) { return SOFTBUS_ERR; } printf("[client]:StartChannelClient ret:%d\n", ret); ret = StartVtpStreamChannelClient(CHANNELID2, p2, callback); - if (ret ==SOFTBUS_ERR) { + if (ret == SOFTBUS_ERR) { return SOFTBUS_ERR; } printf("[client]:StartChannelClient ret:%d\n", ret); diff --git a/tests/utils/exception_branch_checker.cpp b/tests/utils/exception_branch_checker.cpp index 4ab7302d3..4720971a0 100644 --- a/tests/utils/exception_branch_checker.cpp +++ b/tests/utils/exception_branch_checker.cpp @@ -29,7 +29,7 @@ static void SoftBusLogExtraInfoFormat(char *line, const char *fileName, int line (void)sprintf_s(line, LOG_LINE_MAX_LENGTH + 1, "[%s:%d] %s# ", fileName, lineNum, funName); } -static void SoftBusLogPrint(const char *buf, SoftBusDfxLogLevel level, unsigned int domain, const char *tag) +static void SoftBusLogPrint(const char *buf, SoftBusLogLevel level, unsigned int domain, const char *tag) { #ifdef SOFTBUS_PRINTF (void)level; @@ -41,7 +41,7 @@ static void SoftBusLogPrint(const char *buf, SoftBusDfxLogLevel level, unsigned #endif } -void SoftBusLogInnerImpl(SoftBusDfxLogLevel level, SoftBusLogLabel label, const char *fileName, int lineNum, +void SoftBusLogInnerImpl(SoftBusLogLevel level, SoftBusLogLabel label, const char *fileName, int lineNum, const char *funName, const char *fmt, ...) { uint32_t pos;