diff --git a/adapter/BUILD.gn b/adapter/BUILD.gn index 29cd93b68..c9c983c8f 100644 --- a/adapter/BUILD.gn +++ b/adapter/BUILD.gn @@ -57,8 +57,8 @@ if (defined(ohos_lite)) { external_deps = [ "bounds_checking_function:libsec_static", "init:libbegetutil", - "json:nlohmann_json_static", ] + public_external_deps = [ "json:nlohmann_json_static" ] if (board_name == "hispark_pegasus") { include_dirs += [ "$hispark_pegasus_sdk_path/third_party/lwip_sack/include" ] @@ -183,7 +183,7 @@ if (defined(ohos_lite)) { "bounds_checking_function:libsec_shared", "init:libbegetutil", ] - external_deps += [ "json:nlohmann_json_static" ] + public_external_deps = [ "json:nlohmann_json_static" ] if (dsoftbus_feature_encrypt == 0) { sources += [ @@ -259,7 +259,10 @@ if (defined(ohos_lite)) { "$dsoftbus_dfx_path/event:softbus_dfx_event", "$dsoftbus_dfx_path/log:softbus_dfx_log", ] - public_external_deps = [ "bounds_checking_function:libsec_shared" ] + public_external_deps = [ + "bounds_checking_function:libsec_shared", + "json:nlohmann_json_static", + ] ble_enhanced_impl = "dsoftbus_enhance/adapter/common/range/softbus_adapter_range.c" diff --git a/adapter/common/bus_center/boot_event/lnn_boot_event_monitor.cpp b/adapter/common/bus_center/boot_event/lnn_boot_event_monitor.cpp index 201927e5c..0ad5b17f2 100644 --- a/adapter/common/bus_center/boot_event/lnn_boot_event_monitor.cpp +++ b/adapter/common/bus_center/boot_event/lnn_boot_event_monitor.cpp @@ -24,6 +24,7 @@ #include "lnn_ohos_account.h" #include "softbus_error_code.h" #include "parameter.h" +#include "lnn_settingdata_event_monitor.h" #define BOOTEVENT_ACCOUNT_READY "bootevent.account.ready" @@ -32,6 +33,7 @@ static void ProcessBootEvent(void *para) (void)para; LNN_LOGI(LNN_EVENT, "start process account ready event"); LnnUpdateOhosAccount(true); + LnnInitDeviceNameMonitorImpl(); if (LnnIsDefaultOhosAccount() && !IsAuthHasTrustedRelation()) { LNN_LOGE(LNN_EVENT, "not trusted releation, heartbeat(HB) process start later"); return; diff --git a/adapter/common/bus_center/network/lnn_linkwatch.c b/adapter/common/bus_center/network/lnn_linkwatch.c index 2c376e83e..b31744006 100644 --- a/adapter/common/bus_center/network/lnn_linkwatch.c +++ b/adapter/common/bus_center/network/lnn_linkwatch.c @@ -103,7 +103,9 @@ static int32_t RtNetlinkTalk(struct nlmsghdr *nlMsgHdr, struct nlmsghdr *answer, } while (true) { + LNN_LOGI(LNN_BUILDER, "SoftBusSocketRecv begin"); status = SoftBusSocketRecv(fd, answer, maxlen, 0); + LNN_LOGI(LNN_BUILDER, "SoftBusSocketRecv end"); if (status < 0) { if (status == SOFTBUS_ADAPTER_SOCKET_EINTR || status == SOFTBUS_ADAPTER_SOCKET_EAGAIN) { continue; 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 index 9efafcb8f..35566c978 100644 --- 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 @@ -36,7 +36,7 @@ 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 SoftbusSetManufactureData(BleScanNativeFilter *nativeFilter, uint8_t filterSize); +void SoftbusSetManufactureFilter(BleScanNativeFilter *nativeFilter, 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); @@ -44,6 +44,8 @@ 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 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 97f13d59d..5deff3fb5 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 @@ -476,6 +476,7 @@ static int32_t StartBleAdv(int32_t advId, int *btAdvId, const SoftbusBroadcastPa return SOFTBUS_BC_ADAPTER_ASSEMBLE_FAIL; } } + DumpSoftbusAdapterData("mgr pkg:", advRawData.advData, advRawData.advDataLen); int ret = BleStartAdvEx(btAdvId, advRawData, advParam); SoftBusFree(advRawData.advData); SoftBusFree(advRawData.rspData); @@ -766,7 +767,7 @@ static bool SoftbusSetLpParam(LpServerType type, return false; } if (type == SOFTBUS_HEARTBEAT_TYPE) { - SoftbusSetManufactureData(lpParam.filter, scanParam->filterSize); + SoftbusSetManufactureFilter(lpParam.filter, scanParam->filterSize); } SoftbusFilterToBt(lpParam.filter, scanParam->filter, scanParam->filterSize); lpParam.filterSize = (unsigned int)scanParam->filterSize; 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 index e63c28a19..4f262594e 100644 --- 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 @@ -280,11 +280,12 @@ void SoftbusFilterToBt(BleScanNativeFilter *nativeFilter, const SoftBusBcScanFil } } -void SoftbusSetManufactureData(BleScanNativeFilter *nativeFilter, uint8_t filterSize) +void SoftbusSetManufactureFilter(BleScanNativeFilter *nativeFilter, uint8_t filterSize) { while (filterSize-- > 0) { uint8_t *manufactureData = (uint8_t *)SoftBusCalloc(MANUFACTURE_DATA_LEN); if (manufactureData == NULL) { + DISC_LOGW(DISC_BLE_ADAPTER, "malloc manufacture data failed"); return; } manufactureData[0] = MANUFACTURE_DATA_UUID_LOW & BC_BYTE_MASK; @@ -292,6 +293,7 @@ void SoftbusSetManufactureData(BleScanNativeFilter *nativeFilter, uint8_t filter uint8_t *manufactureMask = (uint8_t *)SoftBusCalloc(MANUFACTURE_DATA_LEN); if (manufactureMask == NULL) { SoftBusFree(manufactureData); + DISC_LOGW(DISC_BLE_ADAPTER, "malloc manufacture mask failed"); return; } manufactureMask[0] = BC_BYTE_MASK; @@ -491,3 +493,19 @@ int32_t ParseScanResult(const uint8_t *advData, uint8_t advLen, SoftBusBcScanRes } 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, "description=%{public}s, softbusData=%{public}s", description, softbusData); + + SoftBusFree(softbusData); +} diff --git a/adapter/common/openssl/softbus_aes_encrypt.c b/adapter/common/openssl/softbus_aes_encrypt.c index b11ecf17d..28722cf09 100644 --- a/adapter/common/openssl/softbus_aes_encrypt.c +++ b/adapter/common/openssl/softbus_aes_encrypt.c @@ -75,7 +75,7 @@ int32_t SoftBusGenerateHmacHash( if (outBufLen != SHA256_MAC_LEN) { COMM_LOGE(COMM_ADAPTER, "outBufLen is invalid length for hash."); (void)memset_s(tempOutputData, sizeof(tempOutputData), 0, sizeof(tempOutputData)); - return SOFTBUS_ERR; + return SOFTBUS_HMAC_ERR; } if (memcpy_s(hash, hashLen, tempOutputData, outBufLen) != EOK) { COMM_LOGE(COMM_ADAPTER, "hash result memcpy_s failed."); @@ -168,7 +168,7 @@ static int32_t GenerateIvAndSessionKey(const EncryptKey *randomKey, EncryptKey * (void)memset_s(cipherKey->iv, cipherKey->ivLen, 0, cipherKey->ivLen); SoftBusFree(cipherKey->key); SoftBusFree(cipherKey->iv); - return SOFTBUS_ERR; + return SOFTBUS_GENERATE_KEY_FAIL; } return SOFTBUS_OK; } @@ -190,7 +190,7 @@ int32_t SoftBusAesCfbRootEncrypt(const AesInputData *inData, const EncryptKey *r if (GenerateIvAndSessionKey(randomKey, rootKey, &cipherKey) != SOFTBUS_OK) { COMM_LOGE(COMM_ADAPTER, "GenerateIvAndSessionKey failed!"); SoftBusFree(encryptData.data); - return SOFTBUS_ERR; + return SOFTBUS_GENERATE_KEY_FAIL; } if (OpensslAesCfbEncrypt(&cipherKey, inData, encMode, &encryptData) != SOFTBUS_OK) { COMM_LOGE(COMM_ADAPTER, "OpensslAesCfb encrypt or decrypt by root key failed."); @@ -283,12 +283,12 @@ static int32_t GcmOpensslEvpInit(EVP_CIPHER_CTX **ctx, uint32_t keyLen, int32_t EVP_CIPHER *cipher = GetSslGcmAlgorithmByKeyLen(keyLen); if (cipher == NULL) { COMM_LOGE(COMM_ADAPTER, "GetSslGcmAlgorithmByKeyLen failed."); - return SOFTBUS_ERR; + return SOFTBUS_INVALID_PARAM; } *ctx = EVP_CIPHER_CTX_new(); if (*ctx == NULL) { COMM_LOGE(COMM_ADAPTER, "EVP_CIPHER_CTX_new failed."); - return SOFTBUS_ERR; + return SOFTBUS_MALLOC_ERR; } EVP_CIPHER_CTX_set_padding(*ctx, OPENSSL_EVP_PADDING_FUNC_CLOSE); if (encMode == ENCRYPT_MODE) { @@ -310,7 +310,7 @@ static int32_t GcmOpensslEvpInit(EVP_CIPHER_CTX **ctx, uint32_t keyLen, int32_t COMM_LOGE(COMM_ADAPTER, "EVP_CIPHER_CTX_ctrl failed."); EVP_CIPHER_CTX_free(*ctx); *ctx = NULL; - return SOFTBUS_ERR; + return SOFTBUS_GCM_SET_IV_FAIL; } return SOFTBUS_OK; } @@ -325,7 +325,7 @@ static int32_t OpensslAesGcmEncrypt( } EVP_CIPHER_CTX *ctx = NULL; int32_t ret = GcmOpensslEvpInit(&ctx, cipherKey->keyLen, ENCRYPT_MODE); - COMM_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, SOFTBUS_ERR, COMM_ADAPTER, "GcmOpensslEvpInit failed."); + COMM_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, SOFTBUS_ENCRYPT_ERR, COMM_ADAPTER, "GcmOpensslEvpInit failed."); if (EVP_EncryptInit_ex(ctx, NULL, NULL, cipherKey->key, cipherKey->iv) != 1) { COMM_LOGE(COMM_ADAPTER, "EVP_EncryptInit_ex failed."); goto EXIT; @@ -379,7 +379,7 @@ static int32_t OpensslAesGcmDecrypt( EVP_CIPHER_CTX *ctx = NULL; if (GcmOpensslEvpInit(&ctx, cipherKey->keyLen, DECRYPT_MODE) != SOFTBUS_OK) { COMM_LOGE(COMM_ADAPTER, "GcmOpensslEvpInit failed."); - return SOFTBUS_ERR; + return SOFTBUS_DECRYPT_ERR; } if (EVP_DecryptInit_ex(ctx, NULL, NULL, cipherKey->key, cipherKey->iv) != 1) { COMM_LOGE(COMM_ADAPTER, "EVP_DecryptInit_ex failed."); diff --git a/bundle.json b/bundle.json index e0361ca76..646bff317 100644 --- a/bundle.json +++ b/bundle.json @@ -122,38 +122,10 @@ } ], "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", - "//foundation/communication/dsoftbus/tests/core/broadcast:fuzztest", - "//foundation/communication/dsoftbus/tests/core/broadcast:unittest", - "//foundation/communication/dsoftbus/tests/core/bus_center:unittest", - "//foundation/communication/dsoftbus/tests/core/bus_center:fuzztest", - "//foundation/communication/dsoftbus/tests/core/common:fuzztest", - "//foundation/communication/dsoftbus/tests/core/common:unittest", - "//foundation/communication/dsoftbus/tests/core/connection:fuzztest", - "//foundation/communication/dsoftbus/tests/core/connection:unittest", - "//foundation/communication/dsoftbus/tests/core/discovery:unittest", - "//foundation/communication/dsoftbus/tests/core/discovery:fuzztest", - "//foundation/communication/dsoftbus/tests/core/frame:fuzztest", - "//foundation/communication/dsoftbus/tests/core/transmission:unittest", - "//foundation/communication/dsoftbus/tests/core/transmission:fuzztest", - "//foundation/communication/dsoftbus/tests/sdk/bus_center:fuzztest", - "//foundation/communication/dsoftbus/tests/sdk/bus_center:unittest", - "//foundation/communication/dsoftbus/tests/sdk/discovery:fuzztest", - "//foundation/communication/dsoftbus/tests/sdk/discovery:unittest", - "//foundation/communication/dsoftbus/tests/sdk/transmission:fuzztest", - "//foundation/communication/dsoftbus/tests/sdk/transmission:unittest", - "//foundation/communication/dsoftbus/tests/sdk/bus_center:benchmarktest", - "//foundation/communication/dsoftbus/tests/sdk/discovery:benchmarktest", - "//foundation/communication/dsoftbus/tests/sdk/transmission:benchmarktest", - "//foundation/communication/dsoftbus/tests/sdk/transmission:integration_test", - "//foundation/communication/dsoftbus/tests/sdk/frame/common:unittest", - "//foundation/communication/dsoftbus/tests/sdk/frame/standard:unittest", - "//foundation/communication/dsoftbus/tests/sdk/frame:fuzztest" + "//foundation/communication/dsoftbus/tests:benchmarktest", + "//foundation/communication/dsoftbus/tests:fuzztest", + "//foundation/communication/dsoftbus/tests:integration_test", + "//foundation/communication/dsoftbus/tests:unittest" ] } } 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 45249ac4a..f7a2ba91b 100644 --- a/core/adapter/bus_center/src/lnn_ohos_account_adapter.cpp +++ b/core/adapter/bus_center/src/lnn_ohos_account_adapter.cpp @@ -15,6 +15,7 @@ #include +#include "anonymizer.h" #include "lnn_log.h" #include "lnn_ohos_account_adapter.h" #include "ohos_account_kits.h" @@ -44,7 +45,10 @@ int32_t GetOsAccountId(char *id, uint32_t idLen, uint32_t *len) } *len = accountInfo.second.name_.length(); - LNN_LOGI(LNN_STATE, "uid=%{public}s, len=%{public}d", accountInfo.second.name_.c_str(), *len); + char *anonyUid = nullptr; + Anonymize(accountInfo.second.name_.c_str(), &anonyUid); + LNN_LOGI(LNN_STATE, "uid=%{public}s, len=%{public}d", AnonymizeWrapper(anonyUid), *len); + AnonymizeFree(anonyUid); if (memcmp(DEFAULT_ACCOUNT_NAME, accountInfo.second.name_.c_str(), *len) == 0) { LNN_LOGE(LNN_STATE, "not login account"); @@ -74,8 +78,10 @@ int32_t GetCurrentAccount(int64_t *account) LNN_LOGE(LNN_STATE, "accountInfo name_ is empty"); return SOFTBUS_OK; } - - LNN_LOGI(LNN_STATE, "name_=%{public}s", accountInfo.second.name_.c_str()); + char *anonyUid = nullptr; + Anonymize(accountInfo.second.name_.c_str(), &anonyUid); + LNN_LOGI(LNN_STATE, "name_=%{public}s", AnonymizeWrapper(anonyUid)); + AnonymizeFree(anonyUid); if (memcmp(DEFAULT_ACCOUNT_NAME, accountInfo.second.name_.c_str(), accountInfo.second.name_.length()) == 0) { LNN_LOGE(LNN_STATE, "not login account"); 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 0bc76f77d..8e72a7f18 100644 --- a/core/adapter/bus_center/src/lnn_settingdata_event_monitor.cpp +++ b/core/adapter/bus_center/src/lnn_settingdata_event_monitor.cpp @@ -30,6 +30,7 @@ #include "softbus_errcode.h" #include "system_ability_definition.h" #include "uri.h" +#include "lnn_ohos_account_adapter.h" static LnnDeviceNameHandler g_eventHandler = nullptr; @@ -37,10 +38,13 @@ 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_SECURE_URI = + "datashare:///com.ohos.settingsdata/entry/settingsdata/USER_SETTINGSDATA_SECURE_"; 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"; +static constexpr const char *USER_DEFINED_STRING = "settings.general.user_defined_device_name"; static const uint32_t SOFTBUS_SA_ID = 4700; class LnnSettingDataEventMonitor : public AAFwk::DataAbilityObserverStub { @@ -72,35 +76,25 @@ std::shared_ptr CreateDataShareHelperInstance(void) return DataShare::DataShareHelper::Creator(remoteObject, SETTINGS_DATA_BASE_URI, SETTINGS_DATA_EXT_URI); } -static int32_t GetDeviceNameFromDataShareHelper(char *deviceName, uint32_t len) +static int32_t GetDeviceNameFromDataShareHelper(std::shared_ptr &dataShareHelper, + std::shared_ptr &uri, const char *key, char *deviceName, uint32_t len) { - auto dataShareHelper = OHOS::BusCenter::CreateDataShareHelperInstance(); - if (dataShareHelper == nullptr) { - LNN_LOGE(LNN_STATE, "CreateDataShareHelperInstance fail."); - return SOFTBUS_ERR; - } - - LNN_LOGI(LNN_STATE, "GetDeviceNameFromDataShareHelper enter."); int32_t numRows = 0; std::string val; - - std::shared_ptr uri = std::make_shared(SETTINGS_DATA_BASE_URI + "&key=" + PREDICATES_STRING); std::vector columns; columns.emplace_back(SETTINGS_DATA_FIELD_VALUE); DataShare::DataSharePredicates predicates; - predicates.EqualTo(SETTINGS_DATA_FIELD_KEYWORD, PREDICATES_STRING); + predicates.EqualTo(SETTINGS_DATA_FIELD_KEYWORD, key); auto resultSet = dataShareHelper->Query(*uri, predicates, columns); if (resultSet == nullptr) { - LNN_LOGE(LNN_STATE, "GetDeviceNameFromDataShareHelper query fail."); - dataShareHelper->Release(); + LNN_LOGE(LNN_STATE, "query fail."); return SOFTBUS_ERR; } resultSet->GetRowCount(numRows); if (numRows <= 0) { - LNN_LOGE(LNN_STATE, "GetDeviceNameFromDataShareHelper row zero."); + LNN_LOGE(LNN_STATE, "row zero."); resultSet->Close(); - dataShareHelper->Release(); return SOFTBUS_ERR; } @@ -110,21 +104,40 @@ static int32_t GetDeviceNameFromDataShareHelper(char *deviceName, uint32_t len) if (resultSet->GetString(columnIndex, val) != SOFTBUS_OK) { LNN_LOGE(LNN_STATE, "GetString val fail"); resultSet->Close(); - dataShareHelper->Release(); return SOFTBUS_ERR; } if (strncpy_s(deviceName, len, val.c_str(), strlen(val.c_str())) != EOK) { LNN_LOGE(LNN_STATE, "strncpy_s fail."); resultSet->Close(); - dataShareHelper->Release(); return SOFTBUS_ERR; } - LNN_LOGI(LNN_STATE, "GetDeviceNameFromDataShareHelper, deviceName=%{public}s.", deviceName); + LNN_LOGI(LNN_STATE, "deviceName=%{public}s.", deviceName); resultSet->Close(); - dataShareHelper->Release(); return SOFTBUS_OK; } +static int32_t GetDefaultDeviceName(std::shared_ptr &dataShareHelper, + char *deviceName, uint32_t len) +{ + std::shared_ptr uri = std::make_shared(SETTINGS_DATA_BASE_URI + "&key=" + PREDICATES_STRING); + LNN_LOGI(LNN_STATE, "get default deviceName"); + return GetDeviceNameFromDataShareHelper(dataShareHelper, uri, PREDICATES_STRING, deviceName, len); +} + +static int32_t GetUserDefinedDeviceName(std::shared_ptr &dataShareHelper, + char *deviceName, uint32_t len) +{ + int32_t osAccountId = GetActiveOsAccountIds(); + if (osAccountId == SOFTBUS_ERR) { + return SOFTBUS_NO_INIT; + } + std::string accountIdStr = std::to_string(osAccountId); + std::shared_ptr uri = std::make_shared(SETTINGS_DATA_SECURE_URI + accountIdStr + "?Proxy=true&key=" + + USER_DEFINED_STRING); + LNN_LOGI(LNN_STATE, "get user defined deviceName, accountIdStr=%{public}s", accountIdStr.c_str()); + return GetDeviceNameFromDataShareHelper(dataShareHelper, uri, USER_DEFINED_STRING, deviceName, len); +} + static void RegisterNameMonitorHelper(void) { auto dataShareHelper = OHOS::BusCenter::CreateDataShareHelperInstance(); @@ -135,6 +148,15 @@ static void RegisterNameMonitorHelper(void) auto uri = std::make_shared(SETTINGS_DATA_BASE_URI + "&key=" + PREDICATES_STRING); sptr settingDataObserver = std::make_unique().release(); dataShareHelper->RegisterObserver(*uri, settingDataObserver); + + int32_t osAccountId = GetActiveOsAccountIds(); + if (osAccountId == SOFTBUS_ERR) { + return; + } + std::string accountIdStr = std::to_string(osAccountId); + uri = std::make_shared(SETTINGS_DATA_SECURE_URI + accountIdStr + "?Proxy=true&key=" + USER_DEFINED_STRING); + dataShareHelper->RegisterObserver(*uri, settingDataObserver); + dataShareHelper->Release(); LNN_LOGI(LNN_STATE, "success"); } @@ -147,11 +169,27 @@ int32_t LnnGetSettingDeviceName(char *deviceName, uint32_t len) LNN_LOGE(LNN_STATE, "invalid para"); return SOFTBUS_ERR; } - if (OHOS::BusCenter::GetDeviceNameFromDataShareHelper(deviceName, len) != SOFTBUS_OK) { - LNN_LOGE(LNN_STATE, "GetDeviceNameFromDataShareHelper fail"); - return SOFTBUS_ERR; + auto dataShareHelper = OHOS::BusCenter::CreateDataShareHelperInstance(); + if (dataShareHelper == nullptr) { + LNN_LOGE(LNN_STATE, "CreateDataShareHelperInstance fail."); + return SOFTBUS_NO_INIT; } - return SOFTBUS_OK; + + int32_t ret = OHOS::BusCenter::GetUserDefinedDeviceName(dataShareHelper, deviceName, len); + if (ret == SOFTBUS_NO_INIT) { + LNN_LOGI(LNN_STATE, "account not ready, try again"); + dataShareHelper->Release(); + return ret; + } + if (ret == SOFTBUS_OK) { + LNN_LOGI(LNN_STATE, "get user defined deviceName=%{public}s", deviceName); + dataShareHelper->Release(); + return SOFTBUS_OK; + } + ret = OHOS::BusCenter::GetDefaultDeviceName(dataShareHelper, deviceName, len); + LNN_LOGI(LNN_STATE, "get default deviceName=%{public}s, ret=%{public}d", deviceName, ret); + dataShareHelper->Release(); + return ret; } int32_t LnnInitGetDeviceName(LnnDeviceNameHandler handler) diff --git a/core/adapter/huks/src/softbus_rsa_encrypt.c b/core/adapter/huks/src/softbus_rsa_encrypt.c index 5b566c3c2..b9001f86c 100644 --- a/core/adapter/huks/src/softbus_rsa_encrypt.c +++ b/core/adapter/huks/src/softbus_rsa_encrypt.c @@ -215,7 +215,7 @@ static int32_t EncryptByPublicKey(const uint8_t *src, uint32_t srcLen, const RSA if ((BN_num_bits(modNum) > OPENSSL_RSA_MAX_MODULUS_BITS) || (BN_ucmp(modNum, exp) <= 0) || ((BN_num_bits(modNum) > OPENSSL_RSA_SMALL_MODULUS_BITS) && (BN_num_bits(exp) > OPENSSL_RSA_MAX_PUBEXP_BITS))) { COMM_LOGE(COMM_UTILS, "invalid param rsa."); - return SOFTBUS_ERR; + return SOFTBUS_INVALID_PARAM; } do { ctx = GetRsaBigNum(modNum, &base, &result, &buf, &bufNum); diff --git a/core/authentication/include/auth_manager.h b/core/authentication/include/auth_manager.h index a74ae5db6..5d1b5afc0 100644 --- a/core/authentication/include/auth_manager.h +++ b/core/authentication/include/auth_manager.h @@ -86,6 +86,7 @@ void DelAuthManager(AuthManager *auth, int32_t type); void DelDupAuthManager(AuthManager *auth); void RemoveAuthManagerByAuthId(AuthHandle authHandle); int32_t AuthDeviceGetPreferConnInfo(const char *uuid, AuthConnInfo *connInfo); +int32_t AuthDeviceGetConnInfoByType(const char *uuid, AuthLinkType type, AuthConnInfo *connInfo); int32_t AuthDeviceGetP2pConnInfo(const char *uuid, AuthConnInfo *connInfo); int32_t AuthDeviceGetHmlConnInfo(const char *uuid, AuthConnInfo *connInfo); /*check whether AUTH device is exist or not*/ diff --git a/core/authentication/interface/auth_interface.h b/core/authentication/interface/auth_interface.h index 0be87827b..ca5a08d7a 100644 --- a/core/authentication/interface/auth_interface.h +++ b/core/authentication/interface/auth_interface.h @@ -184,6 +184,7 @@ int32_t AuthOpenConn(const AuthConnInfo *info, uint32_t requestId, const AuthCon int32_t AuthPostTransData(AuthHandle authHandle, const AuthTransData *dataInfo); void AuthCloseConn(AuthHandle authHandle); int32_t AuthGetPreferConnInfo(const char *uuid, AuthConnInfo *connInfo, bool isMeta); +int32_t AuthGetConnInfoByType(const char *uuid, AuthLinkType type, AuthConnInfo *connInfo, bool isMeta); int32_t AuthGetP2pConnInfo(const char *uuid, AuthConnInfo *connInfo, bool isMeta); int32_t AuthGetHmlConnInfo(const char *uuid, AuthConnInfo *connInfo, bool isMeta); int32_t AuthGetLatestAuthSeqList(const char *udid, int64_t *seqList, uint32_t num); diff --git a/core/authentication/src/auth_connection.c b/core/authentication/src/auth_connection.c index 3bbfded3b..7d9210eaf 100644 --- a/core/authentication/src/auth_connection.c +++ b/core/authentication/src/auth_connection.c @@ -29,11 +29,12 @@ #include "softbus_def.h" #include "wifi_direct_manager.h" -#define AUTH_CONN_DATA_HEAD_SIZE 24 -#define AUTH_CONN_CONNECT_TIMEOUT_MS 11000 -#define AUTH_REPEAT_DEVICE_ID_HANDLE_DELAY 1000 -#define AUTH_CONN_MAX_RETRY_TIMES 1 -#define AUTH_CONN_RETRY_DELAY_MILLIS 3000 +#define AUTH_CONN_DATA_HEAD_SIZE 24 +#define AUTH_ENHANCE_P2P_CONNECT_TIMEOUT_MS 4500 +#define AUTH_CONN_CONNECT_TIMEOUT_MS 11000 +#define AUTH_REPEAT_DEVICE_ID_HANDLE_DELAY 1000 +#define AUTH_CONN_MAX_RETRY_TIMES 1 +#define AUTH_CONN_RETRY_DELAY_MILLIS 3000 typedef struct { uint32_t requestId; @@ -271,10 +272,15 @@ static void HandleConnConnectTimeout(const void *para) NotifyClientConnected(requestId, 0, SOFTBUS_AUTH_CONN_TIMEOUT, NULL); } -static void PostConnConnectTimeout(uint32_t requestId) +static void PostConnConnectTimeout(uint32_t requestId, AuthLinkType type) { - PostAuthEvent( - EVENT_CONNECT_TIMEOUT, HandleConnConnectTimeout, &requestId, sizeof(requestId), AUTH_CONN_CONNECT_TIMEOUT_MS); + if (type == AUTH_LINK_TYPE_ENHANCED_P2P) { + PostAuthEvent(EVENT_CONNECT_TIMEOUT, HandleConnConnectTimeout, &requestId, sizeof(requestId), + AUTH_ENHANCE_P2P_CONNECT_TIMEOUT_MS); + } else { + PostAuthEvent(EVENT_CONNECT_TIMEOUT, HandleConnConnectTimeout, &requestId, sizeof(requestId), + AUTH_CONN_CONNECT_TIMEOUT_MS); + } } static int32_t RemoveFunc(const void *obj, void *param) @@ -610,7 +616,7 @@ int32_t ConnectAuthDevice(uint32_t requestId, const AuthConnInfo *connInfo, Conn CHECK_NULL_PTR_RETURN_VALUE(connInfo, SOFTBUS_INVALID_PARAM); AUTH_LOGI(AUTH_CONN, "requestId=%{public}u, connType=%{public}d, sideType=%{public}d", requestId, connInfo->type, sideType); - PostConnConnectTimeout(requestId); + PostConnConnectTimeout(requestId, connInfo->type); int32_t ret = 0; switch (connInfo->type) { case AUTH_LINK_TYPE_WIFI: { diff --git a/core/authentication/src/auth_interface.c b/core/authentication/src/auth_interface.c index b3642d4e1..a91d5ab89 100644 --- a/core/authentication/src/auth_interface.c +++ b/core/authentication/src/auth_interface.c @@ -307,6 +307,14 @@ int32_t AuthGetPreferConnInfo(const char *uuid, AuthConnInfo *connInfo, bool isM return AuthDeviceGetPreferConnInfo(uuid, connInfo); } +int32_t AuthGetConnInfoByType(const char *uuid, AuthLinkType type, AuthConnInfo *connInfo, bool isMeta) +{ + if (isMeta) { + return SOFTBUS_INVALID_PARAM; + } + return AuthDeviceGetConnInfoByType(uuid, type, connInfo); +} + int32_t AuthGetP2pConnInfo(const char *uuid, AuthConnInfo *connInfo, bool isMeta) { if (isMeta) { diff --git a/core/authentication/src/auth_manager.c b/core/authentication/src/auth_manager.c index 005358656..b98ddbb26 100644 --- a/core/authentication/src/auth_manager.c +++ b/core/authentication/src/auth_manager.c @@ -1671,6 +1671,27 @@ int32_t AuthDeviceGetPreferConnInfo(const char *uuid, AuthConnInfo *connInfo) return TryGetBrConnInfo(uuid, connInfo); } +int32_t AuthDeviceGetConnInfoByType(const char *uuid, AuthLinkType type, AuthConnInfo *connInfo) +{ + if (uuid == NULL || uuid[0] == '\0' || connInfo == NULL) { + AUTH_LOGE(AUTH_CONN, "invalid uuid or connInfo"); + return SOFTBUS_INVALID_PARAM; + } + if (GetAuthConnInfoByUuid(uuid, type, connInfo) != SOFTBUS_OK) { + if (type == AUTH_LINK_TYPE_BR) { + return TryGetBrConnInfo(uuid, connInfo); + } + return SOFTBUS_AUTH_NOT_FOUND; + } + if (type == AUTH_LINK_TYPE_BLE) { + if (!CheckActiveAuthConnection(connInfo)) { + AUTH_LOGI(AUTH_CONN, "auth ble connection not active"); + return SOFTBUS_ERR; + } + } + return SOFTBUS_OK; +} + int32_t AuthDeviceGetP2pConnInfo(const char *uuid, AuthConnInfo *connInfo) { if (uuid == NULL || uuid[0] == '\0' || connInfo == NULL) { diff --git a/core/authentication/src/auth_session_fsm.c b/core/authentication/src/auth_session_fsm.c index 7c7359ead..805c3ac7e 100644 --- a/core/authentication/src/auth_session_fsm.c +++ b/core/authentication/src/auth_session_fsm.c @@ -633,6 +633,27 @@ static void SyncDevIdStateEnter(FsmStateMachine *fsm) SoftbusHitraceStop(); } +static void SaveLastAuthSeq(const unsigned char *udidHash, int64_t authSeq) +{ + AUTH_LOGI(AUTH_FSM, "save auth seq.authSeq=%{public}" PRId64, authSeq); + char hashStr[SHORT_UDID_HASH_HEX_LEN + 1] = {0}; + if (ConvertBytesToHexString(hashStr, SHORT_UDID_HASH_HEX_LEN + 1, + udidHash, SHORT_UDID_HASH_HEX_LEN / HEXIFY_UNIT_LEN) != SOFTBUS_OK) { + AUTH_LOGE(AUTH_FSM, "convert udidhash to hexstr fail."); + return; + } + NodeInfo deviceInfo; + (void)memset_s(&deviceInfo, sizeof(NodeInfo), 0, sizeof(NodeInfo)); + if (LnnRetrieveDeviceInfo(hashStr, &deviceInfo) != SOFTBUS_OK) { + AUTH_LOGE(AUTH_FSM, "no this device info."); + return; + } + deviceInfo.lastAuthSeq = authSeq; + if (LnnSaveRemoteDeviceInfo(&deviceInfo) != SOFTBUS_OK) { + AUTH_LOGE(AUTH_FSM, "save device info fail."); + } +} + static int32_t RecoveryNormalizedDeviceKey(AuthFsm *authFsm) { if (authFsm->info.normalizedKey == NULL) { @@ -653,6 +674,9 @@ static int32_t RecoveryNormalizedDeviceKey(AuthFsm *authFsm) } AuthUpdateNormalizeKeyIndex(udidShortHash, authFsm->info.normalizedIndex, authFsm->info.connInfo.type, authFsm->info.normalizedKey, authFsm->info.isServer); + if (authFsm->info.connInfo.type == AUTH_LINK_TYPE_BLE) { + SaveLastAuthSeq(hash, authFsm->authSeq); + } ret = AuthSessionSaveSessionKey(authFsm->authSeq, authFsm->info.normalizedKey->value, authFsm->info.normalizedKey->len); if (ret != SOFTBUS_OK) { diff --git a/core/authentication/src/auth_session_json.c b/core/authentication/src/auth_session_json.c index 97c2f95ef..326ff50d7 100644 --- a/core/authentication/src/auth_session_json.c +++ b/core/authentication/src/auth_session_json.c @@ -34,6 +34,7 @@ #include "lnn_local_net_ledger.h" #include "lnn_node_info.h" #include "lnn_settingdata_event_monitor.h" +#include "softbus_adapter_bt_common.h" #include "softbus_adapter_json.h" #include "softbus_adapter_mem.h" #include "softbus_adapter_socket.h" @@ -185,6 +186,8 @@ #define BLE_CONNECTION_CLOSE_DELAY (10 * 1000L) #define BLE_MAC_AUTO_REFRESH_SWITCH 1 +#define INVALID_BR_MAC_ADDR "00:00:00:00:00:00" + static void OptString(const JsonObj *json, const char * const key, char *target, uint32_t targetLen, const char *defaultValue) { @@ -1160,13 +1163,17 @@ static void PackCommP2pInfo(JsonObj *json, const NodeInfo *info) (void)JSON_AddInt32ToObject(json, STA_FREQUENCY, LnnGetStaFrequency(info)); } +static void AuthPrintBase64Ptk(const char *ptk) +{ + char *anonyPtk = NULL; + Anonymize(ptk, &anonyPtk); + AUTH_LOGD(AUTH_FSM, "base Ptk=%{public}s", anonyPtk); + AnonymizeFree(anonyPtk); +} + static void PackWifiDirectInfo( const AuthConnInfo *connInfo, JsonObj *json, const NodeInfo *info, const char *remoteUuid, bool isMetaAuth) { - if (json == NULL) { - AUTH_LOGE(AUTH_FSM, "invalid param"); - return; - } unsigned char encodePtk[PTK_ENCODE_LEN] = {0}; char localPtk[PTK_DEFAULT_LEN] = {0}; if (isMetaAuth || remoteUuid == NULL) { @@ -1193,6 +1200,7 @@ static void PackWifiDirectInfo( AUTH_LOGE(AUTH_FSM, "encode ptk fail"); return; } + AuthPrintBase64Ptk((const char *)encodePtk); if (!JSON_AddStringToObject(json, PTK, (char *)encodePtk)) { AUTH_LOGE(AUTH_FSM, "add ptk string to json fail"); return; @@ -1230,6 +1238,21 @@ static int32_t FillBroadcastCipherKey(BroadcastCipherKey *broadcastKey, const No return SOFTBUS_OK; } +static void DumpRpaCipherKey(char *cipherKey, char *cipherIv, const char *peerIrk, const char *log) +{ + char *anonyIrk = NULL; + char *anonyCipherKey = NULL; + char *anonyCipherIv = NULL; + Anonymize(cipherKey, &anonyCipherKey); + Anonymize(cipherIv, &anonyCipherIv); + Anonymize(peerIrk, &anonyIrk); + AUTH_LOGI(AUTH_FSM, "log=%{public}s, cipherKey=%{public}s, cipherIv=%{public}s, peerIrk=%{public}s", log, + anonyCipherKey, anonyCipherIv, anonyIrk); + AnonymizeFree(anonyCipherKey); + AnonymizeFree(anonyCipherIv); + AnonymizeFree(anonyIrk); +} + static int32_t PackCipherRpaInfo(JsonObj *json, const NodeInfo *info) { char cipherKey[SESSION_KEY_STR_LEN] = {0}; @@ -1274,7 +1297,7 @@ static int32_t PackCipherRpaInfo(JsonObj *json, const NodeInfo *info) (void)memset_s(&broadcastKey, sizeof(BroadcastCipherKey), 0, sizeof(BroadcastCipherKey)); return SOFTBUS_ERR; } - AUTH_LOGI(AUTH_FSM, "update broadcast cipher key success!"); + DumpRpaCipherKey(cipherKey, cipherIv, peerIrk, "pack broadcast cipher key"); (void)memset_s(&broadcastKey, sizeof(BroadcastCipherKey), 0, sizeof(BroadcastCipherKey)); return SOFTBUS_OK; } @@ -1314,7 +1337,7 @@ static void UnpackCipherRpaInfo(const JsonObj *json, NodeInfo *info) AUTH_LOGE(AUTH_FSM, "convert publicAddress to bytes fail."); break; } - AUTH_LOGI(AUTH_FSM, "unpack cipher and rpa info success!"); + DumpRpaCipherKey(cipherKey, cipherIv, peerIrk, "unpack broadcast cipher key"); } while (0); (void)memset_s(cipherKey, SESSION_KEY_STR_LEN, 0, SESSION_KEY_STR_LEN); (void)memset_s(cipherIv, BROADCAST_IV_STR_LEN, 0, BROADCAST_IV_STR_LEN); @@ -1413,7 +1436,39 @@ static int32_t PackCommon(JsonObj *json, const NodeInfo *info, SoftBusVersion ve return SOFTBUS_OK; } -static void UnpackWifiDirectInfo(const JsonObj *json, NodeInfo *info) +static void UnpackMetaPtk(char *remoteMetaPtk, char *decodePtk) +{ + size_t len = 0; + if (SoftBusBase64Decode((unsigned char *)remoteMetaPtk, PTK_DEFAULT_LEN, &len, + (const unsigned char *)decodePtk, strlen((char *)decodePtk)) != SOFTBUS_OK) { + AUTH_LOGE(AUTH_FSM, "decode remote meta ptk fail"); + return; + } + LnnDumpRemotePtk(NULL, remoteMetaPtk, "unpack meta wifi direct info"); + if (len != PTK_DEFAULT_LEN) { + AUTH_LOGE(AUTH_FSM, "decode data len error"); + return; + } + return; +} + +static void UnpackPtk(char *remotePtk, char *decodePtk) +{ + size_t len = 0; + if (SoftBusBase64Decode((unsigned char *)remotePtk, PTK_DEFAULT_LEN, &len, + (const unsigned char *)decodePtk, strlen((char *)decodePtk)) != SOFTBUS_OK) { + AUTH_LOGE(AUTH_FSM, "decode remote ptk fail"); + return; + } + LnnDumpRemotePtk(NULL, remotePtk, "unpack wifi direct info"); + if (len != PTK_DEFAULT_LEN) { + AUTH_LOGE(AUTH_FSM, "decode data len error"); + return; + } + return; +} + +static void UnpackWifiDirectInfo(const JsonObj *json, NodeInfo *info, bool isMetaAuth) { char staticCap[STATIC_CAP_STR_LEN] = {0}; if (!JSON_GetInt32FromOject(json, STATIC_CAP_LENGTH, &info->staticCapLen)) { @@ -1430,20 +1485,15 @@ static void UnpackWifiDirectInfo(const JsonObj *json, NodeInfo *info) return; } char encodePtk[PTK_ENCODE_LEN] = {0}; - size_t len = 0; if (!JSON_GetStringFromOject(json, PTK, encodePtk, PTK_ENCODE_LEN)) { AUTH_LOGE(AUTH_FSM, "get encode ptk fail"); return; } - if (SoftBusBase64Decode((unsigned char *)info->remotePtk, PTK_DEFAULT_LEN, - &len, (const unsigned char *)encodePtk, strlen((char *)encodePtk)) != SOFTBUS_OK) { - AUTH_LOGE(AUTH_FSM, "decode static cap fail"); - return; - } - LnnDumpRemotePtk(NULL, info->remotePtk, "unpack wifi direct info"); - if (len != PTK_DEFAULT_LEN) { - AUTH_LOGE(AUTH_FSM, "decode data len error"); - return; + AuthPrintBase64Ptk((const char *)encodePtk); + if (isMetaAuth) { + UnpackMetaPtk(info->remoteMetaPtk, encodePtk); + } else { + UnpackPtk(info->remotePtk, encodePtk); } } @@ -1853,6 +1903,45 @@ static int32_t UnpackCertificateInfo(JsonObj *json, NodeInfo *nodeInfo, const Au return SOFTBUS_OK; } +static void UpdateLocalNetBrMac(void) +{ + NodeInfo info; + if (memset_s(&info, sizeof(NodeInfo), 0, sizeof(NodeInfo)) != EOK) { + AUTH_LOGE(AUTH_FSM, "memset_s fail"); + return; + } + if (LnnGetLocalNodeInfoSafe(&info) != SOFTBUS_OK) { + AUTH_LOGE(AUTH_FSM, "get local node info fail"); + return; + } + const char *brMacTemp = LnnGetBtMac(&info); + int32_t lenBrMac = strlen(brMacTemp); + if ((lenBrMac == 0 || (strncmp(brMacTemp, INVALID_BR_MAC_ADDR, BT_MAC_LEN) == 0)) && + SoftBusGetBtState() == BLE_ENABLE) { + char brMac[BT_MAC_LEN] = {0}; + SoftBusBtAddr mac = {0}; + int32_t ret = 0; + ret = SoftBusGetBtMacAddr(&mac); + if (ret != SOFTBUS_OK) { + AUTH_LOGE(AUTH_FSM, "get bt mac addr fail, do not update local brmac"); + return; + } + ret = ConvertBtMacToStr(brMac, BT_MAC_LEN, mac.addr, sizeof(mac.addr)); + if (ret != SOFTBUS_OK || strlen(brMac) == 0) { + AUTH_LOGE(AUTH_FSM, "convert bt mac to str fail, do not update local brmac"); + return; + } + if (LnnSetLocalStrInfo(STRING_KEY_BT_MAC, brMac) != SOFTBUS_OK) { + AUTH_LOGE(AUTH_FSM, "set local brmac fail, do not update local brmac"); + return; + } + char *anonyMac = NULL; + Anonymize(brMac, &anonyMac); + AUTH_LOGI(AUTH_FSM, "update local brmac=%{public}s", anonyMac); + AnonymizeFree(anonyMac); + } +} + char *PackDeviceInfoMessage(const AuthConnInfo *connInfo, SoftBusVersion version, bool isMetaAuth, const char *remoteUuid, const AuthSessionInfo *info) { @@ -1862,6 +1951,7 @@ char *PackDeviceInfoMessage(const AuthConnInfo *connInfo, SoftBusVersion version return NULL; } AUTH_LOGI(AUTH_FSM, "connType=%{public}d", connInfo->type); + UpdateLocalNetBrMac(); const NodeInfo *nodeInfo = LnnGetLocalNodeInfo(); if (nodeInfo == NULL) { AUTH_LOGE(AUTH_FSM, "local info is null"); @@ -1949,7 +2039,7 @@ int32_t UnpackDeviceInfoMessage(const DevInfoData *devInfo, NodeInfo *nodeInfo, } else { ret = UnpackBt(json, nodeInfo, devInfo->version, isMetaAuth); } - UnpackWifiDirectInfo(json, nodeInfo); + UnpackWifiDirectInfo(json, nodeInfo, isMetaAuth); if (UnpackCertificateInfo(json, nodeInfo, info) != SOFTBUS_OK) { JSON_Delete(json); return SOFTBUS_ERR; 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 f21d65e5e..e4e6a6ef4 100644 --- a/core/bus_center/ipc/include/lnn_bus_center_ipc.h +++ b/core/bus_center/ipc/include/lnn_bus_center_ipc.h @@ -53,6 +53,7 @@ int32_t LnnIpcNotifyLeaveResult(const char *networkId, int32_t retCode); int32_t LnnIpcNotifyOnlineState(bool isOnline, void *info, uint32_t infoTypeLen); int32_t LnnIpcNotifyBasicInfoChanged(void *info, uint32_t infoTypeLen, int32_t type); int32_t LnnIpcLocalNetworkIdChanged(void); +int32_t LnnIpcNotifyDeviceNotTrusted(const char *msg); int32_t LnnIpcNotifyTimeSyncResult( const char *pkgName, int32_t pid, const void *info, uint32_t infoTypeLen, int32_t retCode); 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 b53acdee2..abbbcf4f8 100644 --- a/core/bus_center/ipc/mini/lnn_bus_center_ipc.c +++ b/core/bus_center/ipc/mini/lnn_bus_center_ipc.c @@ -182,6 +182,12 @@ int32_t LnnIpcLocalNetworkIdChanged(void) return SOFTBUS_OK; } +int32_t LnnIpcNotifyDeviceNotTrusted(const char *msg) +{ + LNN_LOGI(LNN_EVENT, "not implement"); + return SOFTBUS_OK; +} + int32_t LnnIpcNotifyTimeSyncResult(const char *pkgName, int32_t pid, const void *info, uint32_t infoTypeLen, int32_t retCode) { 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 0a9fbe8de..2ba296df7 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 @@ -436,6 +436,12 @@ int32_t LnnIpcLocalNetworkIdChanged(void) return SOFTBUS_OK; } +int32_t LnnIpcNotifyDeviceNotTrusted(const char *msg) +{ + LNN_LOGI(LNN_EVENT, "not implement"); + return SOFTBUS_OK; +} + int32_t LnnIpcNotifyTimeSyncResult(const char *pkgName, int32_t pid, const void *info, uint32_t infoTypeLen, int32_t retCode) { diff --git a/core/bus_center/ipc/standard/include/bus_center_client_proxy.h b/core/bus_center/ipc/standard/include/bus_center_client_proxy.h index cc6df834a..b19063e2e 100644 --- a/core/bus_center/ipc/standard/include/bus_center_client_proxy.h +++ b/core/bus_center/ipc/standard/include/bus_center_client_proxy.h @@ -39,6 +39,7 @@ int32_t ClientOnLeaveLNNResult(const char *pkgName, int32_t pid, const char *net int32_t ClinetOnNodeOnlineStateChanged(bool isOnline, void *info, uint32_t infoTypeLen); int32_t ClinetOnNodeBasicInfoChanged(void *info, uint32_t infoTypeLen, int32_t type); int32_t ClinetOnLocalNetworkIdChanged(void); +int32_t ClinetNotifyDeviceNotTrusted(const char *msg); int32_t ClientOnTimeSyncResult( const char *pkgName, int32_t pid, const void *info, uint32_t infoTypeLen, int32_t retCode); int32_t ClientOnPublishLNNResult(const char *pkgName, int32_t pid, int32_t publishId, int32_t reason); diff --git a/core/bus_center/ipc/standard/include/bus_center_client_proxy_standard.h b/core/bus_center/ipc/standard/include/bus_center_client_proxy_standard.h index 92ac56ccd..a0174038a 100644 --- a/core/bus_center/ipc/standard/include/bus_center_client_proxy_standard.h +++ b/core/bus_center/ipc/standard/include/bus_center_client_proxy_standard.h @@ -47,6 +47,7 @@ public: int32_t OnNodeOnlineStateChanged(const char *pkgName, bool isOnline, void *info, uint32_t infoTypeLen) override; int32_t OnNodeBasicInfoChanged(const char *pkgName, void *info, uint32_t infoTypeLen, int32_t type) override; int32_t OnLocalNetworkIdChanged(const char *pkgName) override; + int32_t OnNodeDeviceNotTrusted(const char *pkgName, const char *msg) override; int32_t OnTimeSyncResult(const void *info, uint32_t infoTypeLen, int32_t retCode) override; void OnPublishLNNResult(int32_t publishId, int32_t reason) override; void OnRefreshLNNResult(int32_t refreshId, int32_t reason) override; diff --git a/core/bus_center/ipc/standard/src/bus_center_client_proxy.cpp b/core/bus_center/ipc/standard/src/bus_center_client_proxy.cpp index 49b2a6248..82052da2b 100644 --- a/core/bus_center/ipc/standard/src/bus_center_client_proxy.cpp +++ b/core/bus_center/ipc/standard/src/bus_center_client_proxy.cpp @@ -95,6 +95,21 @@ int32_t ClinetOnLocalNetworkIdChanged() return SOFTBUS_OK; } +int32_t ClinetNotifyDeviceNotTrusted(const char *msg) +{ + std::multimap> proxyMap; + SoftbusClientInfoManager::GetInstance().GetSoftbusClientProxyMap(proxyMap); + for (auto proxy : proxyMap) { + const char *dmPkgName = "ohos.distributedhardware.devicemanager"; + if (strcmp(dmPkgName, proxy.first.c_str()) != 0) { + continue; + } + sptr clientProxy = new (std::nothrow) BusCenterClientProxy(proxy.second); + clientProxy->OnNodeDeviceNotTrusted(proxy.first.c_str(), msg); + } + return SOFTBUS_OK; +} + int32_t ClientOnTimeSyncResult(const char *pkgName, int32_t pid, const void *info, uint32_t infoTypeLen, int32_t retCode) { diff --git a/core/bus_center/ipc/standard/src/bus_center_client_proxy_standard.cpp b/core/bus_center/ipc/standard/src/bus_center_client_proxy_standard.cpp index 80dcb3b33..024033b3a 100644 --- a/core/bus_center/ipc/standard/src/bus_center_client_proxy_standard.cpp +++ b/core/bus_center/ipc/standard/src/bus_center_client_proxy_standard.cpp @@ -368,6 +368,39 @@ int32_t BusCenterClientProxy::OnLocalNetworkIdChanged(const char *pkgName) return SOFTBUS_OK; } +int32_t BusCenterClientProxy::OnNodeDeviceNotTrusted(const char *pkgName, const char *msg) +{ + sptr remote = Remote(); + if (remote == nullptr) { + LNN_LOGE(LNN_EVENT, "remote is nullptr"); + return SOFTBUS_IPC_ERR; + } + if (pkgName == nullptr|| msg == nullptr) { + LNN_LOGE(LNN_EVENT, "invalid parameters"); + return SOFTBUS_INVALID_PARAM; + } + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor())) { + LNN_LOGE(LNN_EVENT, "write InterfaceToken failed!"); + return SOFTBUS_IPC_ERR; + } + if (!data.WriteCString(pkgName)) { + LNN_LOGE(LNN_EVENT, "write pkgName failed"); + return SOFTBUS_IPC_ERR; + } + if (!data.WriteCString(msg)) { + LNN_LOGE(LNN_EVENT, "write msg failed"); + return SOFTBUS_IPC_ERR; + } + MessageParcel reply; + MessageOption option = { MessageOption::TF_ASYNC }; + if (remote->SendRequest(CLIENT_ON_NODE_DEVICE_NOT_TRUST, data, reply, option) != 0) { + LNN_LOGE(LNN_EVENT, "send request failed"); + return SOFTBUS_IPC_ERR; + } + return SOFTBUS_OK; +} + int32_t BusCenterClientProxy::OnTimeSyncResult(const void *info, uint32_t infoTypeLen, int32_t retCode) { sptr remote = Remote(); 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 adff59ba2..4aab1a2ca 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 @@ -491,6 +491,11 @@ int32_t LnnIpcLocalNetworkIdChanged(void) return ClinetOnLocalNetworkIdChanged(); } +int32_t LnnIpcNotifyDeviceNotTrusted(const char *msg) +{ + return ClinetNotifyDeviceNotTrusted(msg); +} + int32_t LnnIpcNotifyTimeSyncResult(const char *pkgName, int32_t pid, const void *info, uint32_t infoTypeLen, int32_t retCode) { diff --git a/core/bus_center/lnn/lane_hub/heartbeat/include/lnn_heartbeat_utils.h b/core/bus_center/lnn/lane_hub/heartbeat/include/lnn_heartbeat_utils.h index 572b8356f..5f1d48dfa 100644 --- a/core/bus_center/lnn/lane_hub/heartbeat/include/lnn_heartbeat_utils.h +++ b/core/bus_center/lnn/lane_hub/heartbeat/include/lnn_heartbeat_utils.h @@ -32,6 +32,7 @@ extern "C" { #define HB_SHORT_ACCOUNT_HASH_LEN 2 #define HB_FSM_NAME_LEN 32 +#define HB_TIME_FACTOR_TWO_HUNDRED_MS (200LL) #define HB_TIME_FACTOR (1000LL) #define HB_START_DELAY_LEN (10 * HB_TIME_FACTOR) #define HB_CLOUD_SYNC_DELAY_LEN (13 * HB_TIME_FACTOR) diff --git a/core/bus_center/lnn/lane_hub/heartbeat/src/lnn_heartbeat_ctrl.c b/core/bus_center/lnn/lane_hub/heartbeat/src/lnn_heartbeat_ctrl.c index 3c3ab23dd..b34fb8042 100644 --- a/core/bus_center/lnn/lane_hub/heartbeat/src/lnn_heartbeat_ctrl.c +++ b/core/bus_center/lnn/lane_hub/heartbeat/src/lnn_heartbeat_ctrl.c @@ -593,6 +593,10 @@ static void HbScreenLockChangeEventHandler(const LnnEventBasicInfo *info) LnnAsyncCallbackDelayHelper(GetLooper(LOOP_TYPE_DEFAULT), HbDelayConditionChanged, NULL, HbTryCloudSync() == SOFTBUS_OK ? HB_CLOUD_SYNC_DELAY_LEN : 0); } + if (g_hbConditionState.screenState == SOFTBUS_SCREEN_ON && + g_hbConditionState.accountState != SOFTBUS_ACCOUNT_LOG_IN) { + HbConditionChanged(false); + } break; case SOFTBUS_SCREEN_LOCK: LNN_LOGI(LNN_HEART_BEAT, "HB handle SOFTBUS_SCREEN_LOCK"); diff --git a/core/bus_center/lnn/lane_hub/heartbeat/src/lnn_heartbeat_medium_mgr.c b/core/bus_center/lnn/lane_hub/heartbeat/src/lnn_heartbeat_medium_mgr.c index b0ff91752..6aabc7786 100644 --- a/core/bus_center/lnn/lane_hub/heartbeat/src/lnn_heartbeat_medium_mgr.c +++ b/core/bus_center/lnn/lane_hub/heartbeat/src/lnn_heartbeat_medium_mgr.c @@ -38,6 +38,7 @@ #include "lnn_heartbeat_strategy.h" #include "lnn_heartbeat_utils.h" #include "lnn_lane_vap_info.h" +#include "lnn_local_net_ledger.h" #include "lnn_log.h" #include "lnn_net_builder.h" #include "lnn_node_info.h" @@ -50,6 +51,8 @@ #include "softbus_errcode.h" #include "softbus_utils.h" +#define INVALID_BR_MAC_ADDR "00:00:00:00:00:00" + #define HB_RECV_INFO_SAVE_LEN (60 * 60 * HB_TIME_FACTOR) #define HB_REAUTH_TIME (10 * HB_TIME_FACTOR) #define HB_DFX_DELAY_TIME (7 * HB_TIME_FACTOR) @@ -435,6 +438,19 @@ static bool IsStateVersionChanged( return false; } +static bool IsInvalidBrmac(const char *macAddr) +{ + if (strlen(macAddr) == 0) { + LNN_LOGE(LNN_HEART_BEAT, "macAddr is null"); + return true; + } + if (strcmp(macAddr, INVALID_BR_MAC_ADDR) == 0) { + LNN_LOGE(LNN_HEART_BEAT, "macAddr is invalid"); + return true; + } + return false; +} + static bool IsNeedConnectOnLine(DeviceInfo *device, HbRespData *hbResp, ConnectOnlineReason *connectReason) { if (hbResp == NULL || hbResp->stateVersion == STATE_VERSION_INVALID) { @@ -450,7 +466,7 @@ static bool IsNeedConnectOnLine(DeviceInfo *device, HbRespData *hbResp, ConnectO return true; } if (LnnRetrieveDeviceInfo(device->devId, &deviceInfo) != SOFTBUS_OK || - strlen(deviceInfo.connectInfo.macAddr) == 0) { + IsInvalidBrmac(deviceInfo.connectInfo.macAddr)) { *connectReason = BLE_FIRST_CONNECT; LNN_LOGI(LNN_HEART_BEAT, "don't support ble direct online because retrieve fail, " "stateVersion=%{public}d->%{public}d", deviceInfo.stateVersion, (int32_t)hbResp->stateVersion); diff --git a/core/bus_center/lnn/lane_hub/heartbeat/src/lnn_heartbeat_strategy.c b/core/bus_center/lnn/lane_hub/heartbeat/src/lnn_heartbeat_strategy.c index 3a4222f94..f85ce5bae 100644 --- a/core/bus_center/lnn/lane_hub/heartbeat/src/lnn_heartbeat_strategy.c +++ b/core/bus_center/lnn/lane_hub/heartbeat/src/lnn_heartbeat_strategy.c @@ -329,7 +329,7 @@ static int32_t RelayHeartbeatV0Split( .isRelay = msgPara->isRelay, .isLastEnd = true, }; - delayTime += HB_SEND_RELAY_LEN; + delayTime += HB_SEND_RELAY_LEN + HB_TIME_FACTOR_TWO_HUNDRED_MS; if (LnnPostSendEndMsgToHbFsm(hbFsm, &endData, delayTime) != SOFTBUS_OK) { LNN_LOGE(LNN_HEART_BEAT, "HB send once last end fail, hbType=%{public}d", registedHbType); return SOFTBUS_ERR; @@ -341,7 +341,7 @@ static int32_t RelayHeartbeatV0Split( LNN_LOGE(LNN_HEART_BEAT, "HB send once first begin fail, hbType=%{public}d", registedHbType); return SOFTBUS_ERR; } - delayTime += HB_SEND_RELAY_LEN; + delayTime += HB_SEND_RELAY_LEN + HB_TIME_FACTOR_TWO_HUNDRED_MS; msgPara->hasScanRsp = true; if (LnnPostSendBeginMsgToHbFsm(hbFsm, registedHbType, wakeupFlag, msgPara, delayTime) != SOFTBUS_OK) { LNN_LOGE(LNN_HEART_BEAT, "HB send once first begin fail, hbType=%{public}d", registedHbType); diff --git a/core/bus_center/lnn/lane_hub/heartbeat/src/lnn_heartbeat_utils.c b/core/bus_center/lnn/lane_hub/heartbeat/src/lnn_heartbeat_utils.c index a48a7de1b..2e5d82c14 100644 --- a/core/bus_center/lnn/lane_hub/heartbeat/src/lnn_heartbeat_utils.c +++ b/core/bus_center/lnn/lane_hub/heartbeat/src/lnn_heartbeat_utils.c @@ -373,18 +373,29 @@ void LnnDumpLocalBasicInfo(void) char *anonyUdidHash = NULL; char *anonyNetworkId = NULL; char *anonyP2pMac = NULL; + char *anonyUdid = NULL; + char *anonyUuid = NULL; char localIp[IP_LEN] = { 0 }; char localP2PMac[MAC_LEN] = { 0 }; char localBtMac[BT_MAC_LEN] = { 0 }; + char localUdid[UDID_BUF_LEN] = { 0 }; + char localUuid[UUID_BUF_LEN] = { 0 }; char udidShortHash[HB_SHORT_UDID_HASH_HEX_LEN + 1] = { 0 }; int32_t onlineNodeNum = 0; NodeBasicInfo localInfo = { 0 }; (void)LnnGetLocalDeviceInfo(&localInfo); + (void)LnnGetLocalStrInfo(STRING_KEY_UUID, localUuid, UUID_BUF_LEN); + (void)LnnGetLocalStrInfo(STRING_KEY_DEV_UDID, localUdid, UDID_BUF_LEN); Anonymize(udidShortHash, &anonyUdidHash); + Anonymize(localUuid, &anonyUuid); + Anonymize(localUdid, &anonyUdid); Anonymize(localInfo.networkId, &anonyNetworkId); - LNN_LOGW(LNN_HEART_BEAT, "local DeviceInfo udidShortHash=%{public}s, networkId=%{public}s", anonyUdidHash, - anonyNetworkId); + LNN_LOGW(LNN_HEART_BEAT, + "local DeviceInfo, uuid=%{public}s, udid=%{public}s, udidShortHash=%{public}s, networkId=%{public}s", + anonyUuid, anonyUdid, anonyUdidHash, anonyNetworkId); + AnonymizeFree(anonyUuid); + AnonymizeFree(anonyUdid); AnonymizeFree(anonyUdidHash); AnonymizeFree(anonyNetworkId); const char *devTypeStr = LnnConvertIdToDeviceType(localInfo.deviceTypeId); diff --git a/core/bus_center/lnn/lane_hub/lane_manager/include/lnn_lane_link.h b/core/bus_center/lnn/lane_hub/lane_manager/include/lnn_lane_link.h index 1ec756063..1eb574b7f 100644 --- a/core/bus_center/lnn/lane_hub/lane_manager/include/lnn_lane_link.h +++ b/core/bus_center/lnn/lane_hub/lane_manager/include/lnn_lane_link.h @@ -35,6 +35,13 @@ extern "C" { #define HML_LATENCY 1500 #define BR_REUSE_LATENCY 1000 +typedef struct { + uint32_t activeHml; + int32_t passiveHml; + int32_t rawHml; + bool isDisableLowPower; +} PowerControlInfo; + typedef struct { char peerNetworkId[NETWORK_ID_BUF_LEN]; bool networkDelegate; @@ -122,6 +129,7 @@ void LaneAddP2pAddress(const char *networkId, const char *ipAddr, uint16_t port) void LaneAddP2pAddressByIp(const char *ipAddr, uint16_t port); void LaneUpdateP2pAddressByIp(const char *ipAddr, const char *networkId); +void DetectDisableWifiDirectApply(void); int32_t FindLaneResourceByLinkAddr(const LaneLinkInfo *info, LaneResource *resource); int32_t FindLaneResourceByLinkType(const char *peerUdid, LaneLinkType type, LaneResource *resource); diff --git a/core/bus_center/lnn/lane_hub/lane_manager/include/lnn_lane_select.h b/core/bus_center/lnn/lane_hub/lane_manager/include/lnn_lane_select.h index 75885eed1..7701f8ba8 100755 --- a/core/bus_center/lnn/lane_hub/lane_manager/include/lnn_lane_select.h +++ b/core/bus_center/lnn/lane_hub/lane_manager/include/lnn_lane_select.h @@ -44,6 +44,8 @@ int32_t SelectAuthLane(const char *networkId, LanePreferredLinkList *request, int32_t LaneCapCheck(const char *networkId, LaneLinkType linkType); +int32_t GetErrCodeOfLink(const char *networkId, LaneLinkType linkType); + #ifdef __cplusplus } #endif 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 8b1e18ae6..301c09a68 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 @@ -56,7 +56,6 @@ #define TYPE_BUF_LEN 2 #define LANE_ID_BUF_LEN (UDID_BUF_LEN + UDID_BUF_LEN + TYPE_BUF_LEN) #define LANE_ID_HASH_LEN 32 -#define POWER_CONTROL_CLIENT 3 static bool g_enabledLowPower = false; @@ -240,10 +239,10 @@ static int32_t GetRemoteMacAddrByLocalIp(const char *localIp, char *macAddr, uin return SOFTBUS_OK; } -static void SetWifiDirectLinkInfo(P2pLinkInfo *p2pInfo, WifiDirectLinkInfo *wifiDirectInfo) +static void SetWifiDirectLinkInfo(P2pLinkInfo *p2pInfo, WifiDirectLinkInfo *wifiDirectInfo, uint32_t bandWidth) { wifiDirectInfo->linkType = LANE_HML; - wifiDirectInfo->bandWidth = LANE_BW_160M; + wifiDirectInfo->bandWidth = bandWidth; int32_t ret = GetRemoteMacAddrByLocalIp(p2pInfo->connInfo.localIp, wifiDirectInfo->wifiDirectMac, LNN_MAC_LEN); if (ret != SOFTBUS_OK) { @@ -252,33 +251,36 @@ static void SetWifiDirectLinkInfo(P2pLinkInfo *p2pInfo, WifiDirectLinkInfo *wifi } } -static void HandleDetectWifiDirectApply(bool isDisableLowPower, WifiDirectLinkInfo *wifiDirectInfo, - int32_t activeHml, int32_t passiveHml, int32_t rawHml) +static void SetLanePowerStatus(bool status) { if (LaneLock() != SOFTBUS_OK) { LNN_LOGE(LNN_LANE, "lane lock fail"); return; } - if (isDisableLowPower) { - DisablePowerControl(wifiDirectInfo); - g_enabledLowPower = false; - } else if ((activeHml == 1) && (passiveHml == 0) && (rawHml == 0) && (!g_enabledLowPower)) { - int32_t ret = EnablePowerControl(wifiDirectInfo); - g_enabledLowPower = true; - if (ret != SOFTBUS_OK) { - LNN_LOGE(LNN_LANE, "enable fail, ret=%{public}d", ret); - g_enabledLowPower = false; - } - } + g_enabledLowPower = status; LaneUnlock(); } -static void DetectDisableWifiDirectApply(void) +static void HandleDetectWifiDirectApply(PowerControlInfo *powerInfo, WifiDirectLinkInfo *wifiDirectInfo) { - int32_t activeHml = 0; - int32_t passiveHml = 0; - int32_t rawHml = 0; - bool isDisableLowPower = false; + if (powerInfo->isDisableLowPower) { + DisablePowerControl(wifiDirectInfo); + SetLanePowerStatus(false); + } else if ((powerInfo->activeHml == 1) && (powerInfo->passiveHml == 0) && (powerInfo->rawHml == 0) + && (!g_enabledLowPower)) { + int32_t ret = EnablePowerControl(wifiDirectInfo); + SetLanePowerStatus(true); + if (ret != SOFTBUS_OK) { + LNN_LOGE(LNN_LANE, "enable fail, ret=%{public}d", ret); + SetLanePowerStatus(false); + } + } +} + +void DetectDisableWifiDirectApply(void) +{ + PowerControlInfo powerInfo; + (void)memset_s(&powerInfo, sizeof(powerInfo), 0, sizeof(powerInfo)); WifiDirectLinkInfo wifiDirectInfo; (void)memset_s(&wifiDirectInfo, sizeof(wifiDirectInfo), 0, sizeof(wifiDirectInfo)); if (LaneLock() != SOFTBUS_OK) { @@ -288,41 +290,39 @@ static void DetectDisableWifiDirectApply(void) LaneResource *item = NULL; LaneResource *next = NULL; LIST_FOR_EACH_ENTRY_SAFE(item, next, &g_laneResource.list, LaneResource, node) { - LNN_LOGI(LNN_LANE, "link.type=%{public}d, link.linkInfo.p2p.bw=%{public}d", - item->link.type, item->link.linkInfo.p2p.bw); + LNN_LOGI(LNN_LANE, "link.type=%{public}d, link.bw=%{public}d", item->link.type, item->link.linkInfo.p2p.bw); if (item->link.type == LANE_HML) { if (item->clientRef > 0) { - activeHml++; + powerInfo.activeHml++; } if (item->isServerSide) { - passiveHml++; - SetWifiDirectLinkInfo(&item->link.linkInfo.p2p, &wifiDirectInfo); + powerInfo.passiveHml++; + SetWifiDirectLinkInfo(&item->link.linkInfo.p2p, &wifiDirectInfo, item->link.linkInfo.p2p.bw); } - if (item->link.linkInfo.p2p.bw == LANE_BW_160M) { - SetWifiDirectLinkInfo(&item->link.linkInfo.p2p, &wifiDirectInfo); + if (item->link.linkInfo.p2p.bw == LANE_BW_160M || item->link.linkInfo.p2p.bw == LANE_BW_80P80M) { + SetWifiDirectLinkInfo(&item->link.linkInfo.p2p, &wifiDirectInfo, item->link.linkInfo.p2p.bw); } } - if (activeHml == 1) { - isDisableLowPower = true; - break; - } - if (((activeHml == 0) || (passiveHml > 0) || (rawHml > 0)) && g_enabledLowPower) { - isDisableLowPower = true; - break; + if (item->link.type == LANE_HML_RAW) { + powerInfo.rawHml++; } } + if (powerInfo.activeHml == 1) { + powerInfo.isDisableLowPower = true; + } + if (((powerInfo.activeHml == 0) || (powerInfo.passiveHml > 0) || (powerInfo.rawHml > 0)) && g_enabledLowPower) { + powerInfo.isDisableLowPower = true; + } LaneUnlock(); - LNN_LOGI(LNN_LANE, "activeHml=%{public}d, passiveHml=%{public}d, rawHml=%{public}d", activeHml, passiveHml, rawHml); - HandleDetectWifiDirectApply(isDisableLowPower, &wifiDirectInfo, activeHml, passiveHml, rawHml); + LNN_LOGI(LNN_LANE, "activeHml=%{public}d, passiveHml=%{public}d, rawHml=%{public}d", + powerInfo.activeHml, powerInfo.passiveHml, powerInfo.rawHml); + HandleDetectWifiDirectApply(&powerInfo, &wifiDirectInfo); } static void DetectEnableWifiDirectApply(void) { - int32_t activeHml = 0; - int32_t passiveHml = 0; - int32_t rawHml = 0; - uint32_t clientHml = 0; - bool isDisableLowPower = false; + PowerControlInfo powerInfo; + (void)memset_s(&powerInfo, sizeof(powerInfo), 0, sizeof(powerInfo)); WifiDirectLinkInfo wifiDirectInfo; (void)memset_s(&wifiDirectInfo, sizeof(wifiDirectInfo), 0, sizeof(wifiDirectInfo)); if (LaneLock() != SOFTBUS_OK) { @@ -332,35 +332,33 @@ static void DetectEnableWifiDirectApply(void) LaneResource *item = NULL; LaneResource *next = NULL; LIST_FOR_EACH_ENTRY_SAFE(item, next, &g_laneResource.list, LaneResource, node) { - LNN_LOGI(LNN_LANE, "link.type=%{public}d, link.linkInfo.p2p.bw=%{public}d", - item->link.type, item->link.linkInfo.p2p.bw); + LNN_LOGI(LNN_LANE, "link.type=%{public}d, link.bw=%{public}d", item->link.type, item->link.linkInfo.p2p.bw); if (item->link.type == LANE_HML) { if (item->clientRef > 0) { - activeHml++; - } - if (item->clientRef > 0) { - clientHml = item->clientRef; + powerInfo.activeHml = item->clientRef; } if (item->isServerSide) { - passiveHml++; - SetWifiDirectLinkInfo(&item->link.linkInfo.p2p, &wifiDirectInfo); + powerInfo.passiveHml++; + SetWifiDirectLinkInfo(&item->link.linkInfo.p2p, &wifiDirectInfo, item->link.linkInfo.p2p.bw); } - if (item->link.linkInfo.p2p.bw == LANE_BW_160M) { - SetWifiDirectLinkInfo(&item->link.linkInfo.p2p, &wifiDirectInfo); + if (item->link.linkInfo.p2p.bw == LANE_BW_160M || item->link.linkInfo.p2p.bw == LANE_BW_80P80M) { + SetWifiDirectLinkInfo(&item->link.linkInfo.p2p, &wifiDirectInfo, item->link.linkInfo.p2p.bw); } } - if (clientHml >= POWER_CONTROL_CLIENT) { - isDisableLowPower = true; - break; - } - if (((activeHml == 0) || (passiveHml > 0) || (rawHml > 0)) && g_enabledLowPower) { - isDisableLowPower = true; - break; + if (item->link.type == LANE_HML_RAW) { + powerInfo.rawHml++; } } + if (powerInfo.activeHml > 1) { + powerInfo.isDisableLowPower = true; + } + if (((powerInfo.activeHml == 0) || (powerInfo.passiveHml > 0) || (powerInfo.rawHml > 0)) && g_enabledLowPower) { + powerInfo.isDisableLowPower = true; + } LaneUnlock(); - LNN_LOGI(LNN_LANE, "activeHml=%{public}d, passiveHml=%{public}d, rawHml=%{public}d", activeHml, passiveHml, rawHml); - HandleDetectWifiDirectApply(isDisableLowPower, &wifiDirectInfo, activeHml, passiveHml, rawHml); + LNN_LOGI(LNN_LANE, "activeHml=%{public}d, passiveHml=%{public}d, rawHml=%{public}d", + powerInfo.activeHml, powerInfo.passiveHml, powerInfo.rawHml); + HandleDetectWifiDirectApply(&powerInfo, &wifiDirectInfo); } static int32_t CreateNewLaneResource(const LaneLinkInfo *linkInfo, uint64_t laneId, bool isServerSide) 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 a7e3f2878..43583a9a6 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 @@ -1557,12 +1557,51 @@ static void GuideChannelDetect(uint32_t authRequestId, AuthHandle authHandle) AuthChannelDetectSucc(laneReqId, authRequestId, authHandle); } +static int32_t GetPreferAuthByType(const char *networkId, AuthLinkType type, AuthConnInfo *connInfo, bool isMetaAuth) +{ + char uuid[UDID_BUF_LEN] = {0}; + if (LnnGetRemoteStrInfo(networkId, STRING_KEY_UUID, uuid, sizeof(uuid)) != SOFTBUS_OK) { + LNN_LOGE(LNN_LANE, "get peer uuid fail"); + return SOFTBUS_LANE_GET_LEDGER_INFO_ERR; + } + return AuthGetConnInfoByType(uuid, type, connInfo, isMetaAuth); +} + +static int32_t GetCurrentGuideType(uint32_t laneReqId, LaneLinkType linkType, WdGuideType *guideType) +{ + WdGuideInfo guideInfo = {0}; + if (GetGuideInfo(laneReqId, linkType, &guideInfo) != SOFTBUS_OK) { + LNN_LOGE(LNN_LANE, "get guide channel info fail."); + return SOFTBUS_LANE_NOT_FOUND; + } + *guideType = guideInfo.guideList[guideInfo.guideIdx]; + return SOFTBUS_OK; +} + +static int32_t GetAuthConnInfo(const LinkRequest *request, uint32_t laneReqId, AuthConnInfo *connInfo, bool isMetaAuth) +{ + WdGuideType guideType = LANE_CHANNEL_BUTT; + int32_t ret = GetCurrentGuideType(laneReqId, request->linkType, &guideType); + if (ret != SOFTBUS_OK) { + LNN_LOGE(LNN_LANE, "get current guide channel info fail"); + return ret; + } + if (!isMetaAuth && (guideType == LANE_NEW_AUTH_TRIGGER || guideType == LANE_ACTIVE_BR_NEGO || + guideType == LANE_NEW_AUTH_NEGO)) { + LNN_LOGI(LNN_LANE, "current guideType=%{public}d", guideType); + ret = GetPreferAuthByType(request->peerNetworkId, AUTH_LINK_TYPE_BR, connInfo, isMetaAuth); + } else { + ret = GetPreferAuth(request->peerNetworkId, connInfo, isMetaAuth); + } + return ret; +} + static int32_t OpenAuthToConnP2p(const LinkRequest *request, uint32_t laneReqId, const LaneLinkCb *callback) { AuthConnInfo connInfo; (void)memset_s(&connInfo, sizeof(AuthConnInfo), 0, sizeof(AuthConnInfo)); bool isMetaAuth = GetAuthType(request->peerNetworkId); - int32_t ret = GetPreferAuth(request->peerNetworkId, &connInfo, isMetaAuth); + int32_t ret = GetAuthConnInfo(request, laneReqId, &connInfo, isMetaAuth); if (ret != SOFTBUS_OK) { LNN_LOGE(LNN_LANE, "no auth conn exist"); return ret; @@ -1590,7 +1629,7 @@ static int32_t OpenAuthTriggerToConn(const LinkRequest *request, uint32_t laneRe AuthConnInfo connInfo; (void)memset_s(&connInfo, sizeof(AuthConnInfo), 0, sizeof(AuthConnInfo)); bool isMetaAuth = GetAuthType(request->peerNetworkId); - int32_t ret = GetPreferAuth(request->peerNetworkId, &connInfo, isMetaAuth); + int32_t ret = GetAuthConnInfo(request, laneReqId, &connInfo, isMetaAuth); if (ret != SOFTBUS_OK) { LNN_LOGE(LNN_LANE, "no auth conn exist"); return ret; @@ -2159,7 +2198,7 @@ static int32_t LnnP2pInit(void) return SOFTBUS_MALLOC_ERR; } if (SoftBusMutexInit(&g_AuthTagLock, NULL) != SOFTBUS_OK) { - LNN_LOGE(LNN_INIT, "mutex init fail"); + (void)SoftBusMutexDestroy(&g_p2pLinkMutex); SoftBusFree(g_p2pLinkList); SoftBusFree(g_p2pLinkedList); SoftBusFree(g_guideInfoList); diff --git a/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_listener.c b/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_listener.c index 268b49d40..6517cea04 100644 --- a/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_listener.c +++ b/core/bus_center/lnn/lane_hub/lane_manager/src/lnn_lane_listener.c @@ -20,6 +20,7 @@ #include "anonymizer.h" #include "lnn_distributed_net_ledger.h" #include "lnn_lane_common.h" +#include "lnn_lane_link.h" #include "lnn_log.h" #include "lnn_node_info.h" #include "lnn_trans_lane.h" @@ -407,6 +408,7 @@ static void LnnOnWifiDirectDeviceOffline(const char *peerMac, const char *peerIp LNN_LOGE(LNN_STATE, "get lane state notify info fail"); return; } + DetectDisableWifiDirectApply(); if (PostLaneStateChangeMessage(LANE_STATE_LINKDOWN, laneLinkInfo.peerUdid, &laneLinkInfo) != SOFTBUS_OK) { LNN_LOGE(LNN_LANE, "post laneState linkdown msg fail"); } 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 a1aff0bfc..0be19483f 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 @@ -165,7 +165,7 @@ static void DumpPreferredLink(LaneLinkType preferredLink, uint32_t priority) LNN_LOGD(LNN_LANE, "priority=%{public}u, linkType=%{public}s", priority, GetLinkTypeStrng(preferredLink)); } -static int32_t GetErrCodeOfLink(const char *networkId, LaneLinkType linkType) +int32_t GetErrCodeOfLink(const char *networkId, LaneLinkType linkType) { if ((linkType == LANE_WLAN_2P4G || linkType == LANE_WLAN_5G || linkType == LANE_P2P || linkType == LANE_P2P_REUSE || linkType == LANE_HML) && 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 5d7677ee2..10e68b51a 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 @@ -614,6 +614,9 @@ static int32_t SpecifiedLinkConvert(const char *networkId, LaneSpecifiedLink lin preferLink->linkType[resNum] = optionalLink[i]; resNum++; } + if (resNum == 0) { + return GetErrCodeOfLink(networkId, optionalLink[0]); + } preferLink->linkTypeNum = resNum; return SOFTBUS_OK; } @@ -1009,11 +1012,6 @@ static void NotifyLaneAllocSuccess(uint32_t laneReqId, uint64_t laneId, const La LNN_LOGE(LNN_LANE, "get lane reqInfo fail"); return; } - if (reqInfo.isWithQos && reqInfo.isCanceled) { - LNN_LOGI(LNN_LANE, "lane has canceled not need notify succ, laneReqId=%{public}u", laneReqId); - (void)Free(laneReqId); - return; - } LaneProfile profile; LaneConnInfo connInfo; (void)memset_s(&profile, sizeof(LaneProfile), 0, sizeof(LaneProfile)); @@ -1024,6 +1022,12 @@ static void NotifyLaneAllocSuccess(uint32_t laneReqId, uint64_t laneId, const La LNN_LOGI(LNN_LANE, "Notify laneAlloc succ, laneReqId=%{public}u, linkType=%{public}d, " "laneId=%{public}" PRIu64 "", laneReqId, info->type, laneId); if (reqInfo.isWithQos) { + if (reqInfo.isCanceled) { + LNN_LOGE(LNN_LANE, "lane has canceled only notify fail, laneReqId=%{public}u", laneReqId); + reqInfo.listener.onLaneAllocFail(laneReqId, SOFTBUS_LANE_SUCC_AFTER_CANCELED); + (void)Free(laneReqId); + return; + } connInfo.laneId = laneId; reqInfo.listener.onLaneAllocSuccess(laneReqId, &connInfo); } else { @@ -1042,10 +1046,7 @@ static void NotifyLaneAllocFail(uint32_t laneReqId, int32_t reason) return; } if (reqInfo.isWithQos && reqInfo.isCanceled) { - LNN_LOGI(LNN_LANE, "lane has canceled not need notify fail, laneReqId=%{public}u", laneReqId); - DeleteRequestNode(laneReqId); - FreeLaneReqId(laneReqId); - return; + LNN_LOGE(LNN_LANE, "lane has canceled only notify fail, laneReqId=%{public}u", laneReqId); } LNN_LOGE(LNN_LANE, "Notify laneAlloc fail, laneReqId=%{public}u, reason=%{public}d", laneReqId, reason); if (reqInfo.isWithQos) { diff --git a/core/bus_center/lnn/net_builder/include/lnn_device_info_recovery.h b/core/bus_center/lnn/net_builder/include/lnn_device_info_recovery.h index 5c10b203a..80633f6c5 100644 --- a/core/bus_center/lnn/net_builder/include/lnn_device_info_recovery.h +++ b/core/bus_center/lnn/net_builder/include/lnn_device_info_recovery.h @@ -90,6 +90,7 @@ extern "C" { #define DEVICE_INFO_JSON_KEY_TIMESTAMP_BEGIN "JSON_KEY_TIMESTAMP_BEGIN" #define DEVICE_INFO_JSON_KEY_CURRENT_INDEX "JSON_KEY_CURRENT_INDEX" #define DEVICE_INFO_TIMESTAMP "TIMESTAMP" +#define DEVICE_INFO_LAST_AUTH_SEQ "LAST_AUTH_SEQ" #define IS_SUPPORT_IPV6 "IS_SUPPORT_IPV6" #define IS_AUTH_EXCHANGE_UDID "IS_AUTH_EXCHANGE_UDID" diff --git a/core/bus_center/lnn/net_builder/src/lnn_data_cloud_sync.c b/core/bus_center/lnn/net_builder/src/lnn_data_cloud_sync.c index 500dbb3a0..6beb78d90 100644 --- a/core/bus_center/lnn/net_builder/src/lnn_data_cloud_sync.c +++ b/core/bus_center/lnn/net_builder/src/lnn_data_cloud_sync.c @@ -737,6 +737,12 @@ static void PrintSyncNodeInfo(const NodeInfo *cacheInfo) LNN_LOGE(LNN_BUILDER, "invalid param"); return; } + char accountId[INT64_TO_STR_MAX_LEN] = {0}; + if (!Int64ToString(cacheInfo->accountId, accountId, INT64_TO_STR_MAX_LEN)) { + LNN_LOGE(LNN_BUILDER, "accountId to str fail"); + } + char *anonyAccountId = NULL; + Anonymize(accountId, &anonyAccountId); char *anonyP2pMac = NULL; Anonymize(cacheInfo->p2pInfo.p2pMac, &anonyP2pMac); char *anonyMacAddr = NULL; @@ -751,7 +757,7 @@ static void PrintSyncNodeInfo(const NodeInfo *cacheInfo) Anonymize(cacheInfo->deviceInfo.deviceVersion, &anonyDeviceVersion); LNN_LOGI(LNN_BUILDER, "Sync NodeInfo: WIFI_VERSION=%{public}" PRId64 ", BLE_VERSION=%{public}" PRId64 - ", ACCOUNT_ID=%{public}" PRId64 ", TRANSPORT_PROTOCOL=%{public}" PRIu64 ", FEATURE=%{public}" PRIu64 + ", ACCOUNT_ID=%{public}s, TRANSPORT_PROTOCOL=%{public}" PRIu64 ", FEATURE=%{public}" PRIu64 ", CONN_SUB_FEATURE=%{public}" PRIu64 ", TIMESTAMP=%{public}" PRIu64 ", " "P2P_MAC_ADDR=%{public}s, PKG_VERSION=%{public}s, DEVICE_NAME=%{public}s, " "UNIFIED_DEFAULT_DEVICE_NAME=%{public}s, UNIFIED_DEVICE_NAME=%{public}s, SETTINGS_NICK_NAME=%{public}s, " @@ -760,7 +766,7 @@ static void PrintSyncNodeInfo(const NodeInfo *cacheInfo) "NETWORK_ID=%{public}s, STATE_VERSION=%{public}d, BROADCAST_CIPHER_KEY=%{public}02x, " "BROADCAST_CIPHER_IV=%{public}02x, IRK=%{public}02x, PUB_MAC=%{public}02x, PTK=%{public}02x, " "DEVICE_VERSION=%{public}s", - cacheInfo->wifiVersion, cacheInfo->bleVersion, cacheInfo->accountId, cacheInfo->supportedProtocols, + cacheInfo->wifiVersion, cacheInfo->bleVersion, AnonymizeWrapper(anonyAccountId), cacheInfo->supportedProtocols, cacheInfo->feature, cacheInfo->connSubFeature, cacheInfo->updateTimestamp, anonyP2pMac, cacheInfo->pkgVersion, cacheInfo->deviceInfo.deviceName, cacheInfo->deviceInfo.unifiedDefaultName, cacheInfo->deviceInfo.unifiedName, cacheInfo->deviceInfo.nickName, cacheInfo->authCapacity, cacheInfo->deviceInfo.osType, @@ -768,6 +774,7 @@ static void PrintSyncNodeInfo(const NodeInfo *cacheInfo) cacheInfo->softBusVersion, anonyUdid, anonyUuid, anonyNetworkId, cacheInfo->stateVersion, *cacheInfo->cipherInfo.key, *cacheInfo->cipherInfo.iv, *cacheInfo->rpaInfo.peerIrk, *cacheInfo->rpaInfo.publicAddress, *cacheInfo->remotePtk, anonyDeviceVersion); + AnonymizeFree(anonyAccountId); AnonymizeFree(anonyP2pMac); AnonymizeFree(anonyMacAddr); AnonymizeFree(anonyUdid); @@ -776,6 +783,48 @@ static void PrintSyncNodeInfo(const NodeInfo *cacheInfo) AnonymizeFree(anonyDeviceVersion); } +static int32_t LnnSaveAndUpdateDistributedNode(NodeInfo *cacheInfo) +{ + if (cacheInfo == NULL) { + LNN_LOGE(LNN_BUILDER, "invalid param"); + return SOFTBUS_INVALID_PARAM; + } + NodeInfo localCacheInfo = { 0 }; + int32_t ret = LnnGetLocalCacheNodeInfo(&localCacheInfo); + if (ret != SOFTBUS_OK || cacheInfo->accountId != localCacheInfo.accountId) { + char accountId[INT64_TO_STR_MAX_LEN] = {0}; + char localAccountId[INT64_TO_STR_MAX_LEN] = {0}; + if (!Int64ToString(cacheInfo->accountId, accountId, INT64_TO_STR_MAX_LEN)) { + LNN_LOGE(LNN_BUILDER, "accountId to str fail"); + } + if (!Int64ToString(localCacheInfo.accountId, localAccountId, INT64_TO_STR_MAX_LEN)) { + LNN_LOGE(LNN_BUILDER, "local accountId to str fail"); + } + char *anonyAccountId = NULL; + char *anonyLocalAccountId = NULL; + Anonymize(accountId, &anonyAccountId); + Anonymize(localAccountId, &anonyLocalAccountId); + LNN_LOGE(LNN_BUILDER, "don't set, ret=%{public}d, accountId=%{public}s, local accountId=%{public}s", + ret, AnonymizeWrapper(anonyAccountId), AnonymizeWrapper(anonyLocalAccountId)); + AnonymizeFree(anonyAccountId); + AnonymizeFree(anonyLocalAccountId); + return ret; + } + cacheInfo->localStateVersion = localCacheInfo.stateVersion; + (void)LnnSaveRemoteDeviceInfo(cacheInfo); + char *anonyUdid = NULL; + Anonymize(cacheInfo->deviceInfo.deviceUdid, &anonyUdid); + LNN_LOGI(LNN_BUILDER, + "success. udid=%{public}s, stateVersion=%{public}d, localStateVersion=%{public}d, updateTimestamp=%{public}" + "" PRIu64, anonyUdid, cacheInfo->stateVersion, cacheInfo->localStateVersion, cacheInfo->updateTimestamp); + AnonymizeFree(anonyUdid); + if (LnnUpdateDistributedNodeInfo(cacheInfo, cacheInfo->deviceInfo.deviceUdid) != SOFTBUS_OK) { + LNN_LOGE(LNN_BUILDER, "fail:Cache info sync to Ledger fail"); + return SOFTBUS_MEM_ERR; + } + return SOFTBUS_OK; +} + int32_t LnnDBDataChangeSyncToCacheInner(const char *key, const char *value) { if (key == NULL || value == NULL) { @@ -806,21 +855,8 @@ int32_t LnnDBDataChangeSyncToCacheInner(const char *key, const char *value) cacheInfo.updateTimestamp)) { return SOFTBUS_ERR; } - NodeInfo localCacheInfo = { 0 }; - int32_t ret = LnnGetLocalCacheNodeInfo(&localCacheInfo); - if (ret != SOFTBUS_OK) { - return ret; - } - cacheInfo.localStateVersion = localCacheInfo.stateVersion; - (void)LnnSaveRemoteDeviceInfo(&cacheInfo); - char *anonyUdid = NULL; - Anonymize(cacheInfo.deviceInfo.deviceUdid, &anonyUdid); - LNN_LOGI(LNN_BUILDER, - "success. udid=%{public}s, stateVersion=%{public}d, localStateVersion=%{public}d, updateTimestamp=%{public}" - "" PRIu64, anonyUdid, cacheInfo.stateVersion, cacheInfo.localStateVersion, cacheInfo.updateTimestamp); - AnonymizeFree(anonyUdid); - if (LnnUpdateDistributedNodeInfo(&cacheInfo, cacheInfo.deviceInfo.deviceUdid) != SOFTBUS_OK) { - LNN_LOGE(LNN_BUILDER, "fail:Cache info sync to Ledger fail"); + if (LnnSaveAndUpdateDistributedNode(&cacheInfo) != SOFTBUS_OK) { + LNN_LOGE(LNN_BUILDER, "save and update distribute node info fail"); (void)memset_s(&cacheInfo, sizeof(NodeInfo), 0, sizeof(NodeInfo)); return SOFTBUS_ERR; } diff --git a/core/bus_center/lnn/net_builder/src/lnn_devicename_info.c b/core/bus_center/lnn/net_builder/src/lnn_devicename_info.c index 7d0d3eb4b..a11ca2ad7 100644 --- a/core/bus_center/lnn/net_builder/src/lnn_devicename_info.c +++ b/core/bus_center/lnn/net_builder/src/lnn_devicename_info.c @@ -47,6 +47,7 @@ #define KEY_ACCOUNT "KEY_ACCOUNT" static int32_t g_tryGetDevnameNums = 0; +static bool g_isDevnameInited = false; static int32_t LnnSyncDeviceName(const char *networkId) { @@ -365,12 +366,10 @@ static void UpdataLocalFromSetting(void *p) char unifiedName[DEVICE_NAME_BUF_LEN] = {0}; char unifiedDefaultName[DEVICE_NAME_BUF_LEN] = {0}; char nickName[DEVICE_NAME_BUF_LEN] = {0}; - LNN_LOGD(LNN_BUILDER, "UpdateLocalFromSetting enter"); if (LnnGetSettingDeviceName(deviceName, DEVICE_NAME_BUF_LEN) != SOFTBUS_OK) { - LNN_LOGE(LNN_BUILDER, "UpdataLocalFromSetting fail"); g_tryGetDevnameNums++; + LNN_LOGI(LNN_BUILDER, "g_tryGetDevnameNums=%{public}d", g_tryGetDevnameNums); if (g_tryGetDevnameNums < MAX_TRY) { - LNN_LOGI(LNN_BUILDER, "g_tryGetDevnameNums=%{public}d", g_tryGetDevnameNums); SoftBusLooper *looper = GetLooper(LOOP_TYPE_DEFAULT); if (looper == NULL) { LNN_LOGE(LNN_BUILDER, "looper is null"); @@ -404,20 +403,25 @@ static void UpdataLocalFromSetting(void *p) } } RegisterNameMonitor(); + g_isDevnameInited = true; DiscDeviceInfoChanged(TYPE_LOCAL_DEVICE_NAME); LnnNotifyLocalNetworkIdChanged(); LNN_LOGI(LNN_BUILDER, "UpdateLocalFromSetting done, deviceName=%{public}s, unifiedName=%{public}s, " "unifiedDefaultName=%{public}s, nickName=%{public}s", deviceName, unifiedName, unifiedDefaultName, nickName); } -static void UpdateDeviceNameFromSetting(void) +static void RegisterDeviceNameHandle(void) { LnnInitGetDeviceName(LnnHandlerGetDeviceName); } void UpdateDeviceName(void *p) { - UpdateDeviceNameFromSetting(); + if (g_isDevnameInited) { + LNN_LOGI(LNN_BUILDER, "device name already inited"); + return; + } + RegisterDeviceNameHandle(); UpdataLocalFromSetting(p); } diff --git a/core/bus_center/lnn/net_buscenter/src/lnn_ip_network_impl.c b/core/bus_center/lnn/net_buscenter/src/lnn_ip_network_impl.c index e2e9ab79b..defeba9f9 100644 --- a/core/bus_center/lnn/net_buscenter/src/lnn_ip_network_impl.c +++ b/core/bus_center/lnn/net_buscenter/src/lnn_ip_network_impl.c @@ -114,9 +114,6 @@ static void RetryGetAvailableIpAddr(void *para) static int32_t GetAvailableIpAddr(const char *ifName, char *ip, uint32_t size) { static int32_t retryTime = GET_IP_RETRY_TIMES; - if (!LnnIsLinkReady(ifName)) { - LNN_LOGE(LNN_BUILDER, "link not ready. ifName=%{public}s", ifName); - } if (strcmp(ifName, WLAN_IFNAME) != 0) { retryTime = 0; } @@ -124,7 +121,7 @@ static int32_t GetAvailableIpAddr(const char *ifName, char *ip, uint32_t size) retryTime = GET_IP_RETRY_TIMES; return SOFTBUS_OK; } - LNN_LOGD(LNN_BUILDER, "get ip retry time=%{public}d", retryTime); + LNN_LOGI(LNN_BUILDER, "get ip retry time=%{public}d", retryTime); if (--retryTime > 0 && LnnAsyncCallbackDelayHelper(GetLooper(LOOP_TYPE_DEFAULT), RetryGetAvailableIpAddr, NULL, GET_IP_INTERVAL_TIME) != SOFTBUS_OK) { LNN_LOGE(LNN_BUILDER, "LnnAsyncCallbackDelayHelper get available ip fail"); @@ -362,11 +359,13 @@ static int32_t RequestMainPort(const char *ifName, const char *address) LNN_LOGE(LNN_BUILDER, "loopback ip not allowed"); return SOFTBUS_ERR; } + LNN_LOGI(LNN_BUILDER, "get local ifName begin"); char oldMainIf[NET_IF_NAME_LEN] = {0}; if (LnnGetLocalStrInfo(STRING_KEY_NET_IF_NAME, oldMainIf, sizeof(oldMainIf)) != SOFTBUS_OK) { LNN_LOGE(LNN_BUILDER, "get local ifName error"); return SOFTBUS_ERR; } + LNN_LOGI(LNN_BUILDER, "get local ifName end"); if (strcmp(oldMainIf, ifName) != 0 && strcmp(oldMainIf, LNN_LOOPBACK_IFNAME) != 0) { LNN_LOGE(LNN_BUILDER, "Only 1 local subnet is allowed"); return SOFTBUS_ERR; @@ -466,7 +465,7 @@ static void TransactIpSubnetState(LnnPhysicalSubnet *subnet, IpSubnetManagerEven [IP_SUBNET_MANAGER_EVENT_IF_CHANGED] = {LNN_SUBNET_RESETTING, subnet->status} }; subnet->status = transactMap[event][isAccepted ? IP_EVENT_RESULT_ACCEPTED : IP_EVENT_RESULT_REJECTED]; - LNN_LOGD(LNN_BUILDER, "subnet state change. ifName=%{public}s, protocolId=%{public}u, status=%{public}d", + LNN_LOGI(LNN_BUILDER, "subnet state change. ifName=%{public}s, protocolId=%{public}u, status=%{public}d", subnet->ifName, subnet->protocol->id, subnet->status); } diff --git a/core/bus_center/lnn/net_ledger/common/include/lnn_net_ledger.h b/core/bus_center/lnn/net_ledger/common/include/lnn_net_ledger.h index e491a2c60..0f1c83894 100644 --- a/core/bus_center/lnn/net_ledger/common/include/lnn_net_ledger.h +++ b/core/bus_center/lnn/net_ledger/common/include/lnn_net_ledger.h @@ -24,6 +24,7 @@ extern "C" { int32_t LnnInitNetLedger(void); int32_t LnnInitNetLedgerDelay(void); +int32_t LnnInitEventMoniterDelay(void); void RestoreLocalDeviceInfo(void); void LnnDeinitNetLedger(void); diff --git a/core/bus_center/lnn/net_ledger/common/include/lnn_node_info.h b/core/bus_center/lnn/net_ledger/common/include/lnn_node_info.h index 478d28467..2717f691a 100644 --- a/core/bus_center/lnn/net_ledger/common/include/lnn_node_info.h +++ b/core/bus_center/lnn/net_ledger/common/include/lnn_node_info.h @@ -142,8 +142,6 @@ typedef struct { uint32_t discoveryType; DeviceBasicInfo deviceInfo; ConnectInfo connectInfo; - int64_t authSeqNum; - int32_t authChannelId[CONNECTION_ADDR_MAX][AUTH_SIDE_MAX]; BssTransInfo bssTransInfo; bool isBleP2p; // true: this device support connect p2p via ble connection P2pInfo p2pInfo; @@ -181,8 +179,11 @@ typedef struct { uint8_t staticCapability[STATIC_CAP_LEN]; int32_t staticCapLen; char remotePtk[PTK_DEFAULT_LEN]; + char remoteMetaPtk[PTK_DEFAULT_LEN]; int32_t deviceSecurityLevel; uint8_t relation[CONNECTION_ADDR_MAX]; + int64_t authSeqNum; + int32_t authChannelId[CONNECTION_ADDR_MAX][AUTH_SIDE_MAX]; uint64_t heartbeatTimestamp; uint64_t bleDirectTimestamp; uint64_t onlinetTimestamp; @@ -190,6 +191,7 @@ typedef struct { bool isAuthExchangeUdid; bool isSupportIpv6; uint32_t stateVersionReason; + int64_t lastAuthSeq; } NodeInfo; const char *LnnGetDeviceUdid(const NodeInfo *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 7e235a8ab..63e7b5d8b 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 @@ -199,6 +199,11 @@ int32_t LnnInitNetLedgerDelay(void) LNN_LOGE(LNN_LEDGER, "delay init decision db fail"); return SOFTBUS_ERR; } + return SOFTBUS_OK; +} + +int32_t LnnInitEventMoniterDelay(void) +{ if (LnnInitCommonEventMonitorImpl() != SOFTBUS_OK) { LNN_LOGE(LNN_LEDGER, "delay init LnnInitCommonEventMonitorImpl fail"); return SOFTBUS_ERR; diff --git a/core/bus_center/lnn/net_ledger/distributed_ledger/include/lnn_distributed_net_ledger.h b/core/bus_center/lnn/net_ledger/distributed_ledger/include/lnn_distributed_net_ledger.h index 654b6b409..b6825662a 100644 --- a/core/bus_center/lnn/net_ledger/distributed_ledger/include/lnn_distributed_net_ledger.h +++ b/core/bus_center/lnn/net_ledger/distributed_ledger/include/lnn_distributed_net_ledger.h @@ -68,6 +68,7 @@ int32_t LnnGetDLHeartbeatTimestamp(const char *networkId, uint64_t *timestamp); int32_t LnnGetDLOnlineTimestamp(const char *networkId, uint64_t *timestamp); int32_t LnnSetDLHeartbeatTimestamp(const char *networkId, const uint64_t timestamp); int32_t LnnGetDLBleDirectTimestamp(const char *networkId, uint64_t *timestamp); +int32_t LnnGetDLUpdateTimestamp(const char *udid, uint64_t *timestamp); int32_t LnnSetDLBleDirectTimestamp(const char *networkId, uint64_t timestamp); int32_t LnnGetDLAuthCapacity(const char *networkId, uint32_t *authCapacity); bool LnnGetOnlineStateById(const char *id, IdCategory type); 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 ff8ead49b..0ae929e93 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 @@ -726,22 +726,27 @@ int32_t LnnAddMetaInfo(NodeInfo *info) } oldInfo = (NodeInfo *)LnnMapGet(&map->udidMap, udid); if (oldInfo != NULL && strcmp(oldInfo->networkId, info->networkId) == 0) { - MetaInfo temp = info->metaInfo; LNN_LOGI(LNN_LEDGER, "old capa=%{public}u new capa=%{public}u", oldInfo->netCapacity, info->netCapacity); oldInfo->connectInfo.sessionPort = info->connectInfo.sessionPort; oldInfo->connectInfo.authPort = info->connectInfo.authPort; oldInfo->connectInfo.proxyPort = info->connectInfo.proxyPort; oldInfo->netCapacity = info->netCapacity; - if (memcpy_s(info, sizeof(NodeInfo), oldInfo, sizeof(NodeInfo)) != EOK) { - LNN_LOGE(LNN_LEDGER, "LnnAddMetaInfo copy fail!"); - SoftBusMutexUnlock(&g_distributedNetLedger.lock); - return SOFTBUS_MEM_ERR; - } if (strcpy_s(oldInfo->connectInfo.deviceIp, IP_LEN, info->connectInfo.deviceIp) != EOK) { LNN_LOGE(LNN_LEDGER, "strcpy ip fail!"); SoftBusMutexUnlock(&g_distributedNetLedger.lock); return SOFTBUS_STRCPY_ERR; } + if (strcpy_s(oldInfo->uuid, UUID_BUF_LEN, info->uuid) != EOK) { + LNN_LOGE(LNN_LEDGER, "strcpy uuid fail!"); + SoftBusMutexUnlock(&g_distributedNetLedger.lock); + return SOFTBUS_STRCPY_ERR; + } + MetaInfo temp = info->metaInfo; + if (memcpy_s(info, sizeof(NodeInfo), oldInfo, sizeof(NodeInfo)) != EOK) { + LNN_LOGE(LNN_LEDGER, "LnnAddMetaInfo copy fail!"); + SoftBusMutexUnlock(&g_distributedNetLedger.lock); + return SOFTBUS_MEM_ERR; + } info->metaInfo.isMetaNode = true; info->metaInfo.metaDiscType = info->metaInfo.metaDiscType | temp.metaDiscType; } @@ -779,6 +784,7 @@ int32_t LnnDeleteMetaInfo(const char *udid, AuthLinkType type) info->metaInfo.isMetaNode = false; } LnnClearAuthTypeValue(&info->AuthTypeValue, ONLINE_METANODE); + (void)memset_s(info->remoteMetaPtk, PTK_DEFAULT_LEN, 0, PTK_DEFAULT_LEN); int32_t ret = LnnMapSet(&map->udidMap, udid, info, sizeof(NodeInfo)); if (ret != SOFTBUS_OK) { LNN_LOGE(LNN_LEDGER, "lnn map set failed, ret=%{public}d", ret); @@ -1076,6 +1082,32 @@ static void TryUpdateDeviceSecurityLevel(NodeInfo *info) } } +static void ReversionLastAuthSeq(NodeInfo *info) +{ + NodeInfo deviceInfo; + (void)memset_s(&deviceInfo, sizeof(NodeInfo), 0, sizeof(NodeInfo)); + uint8_t udidHash[SHA_256_HASH_LEN] = {0}; + char hashStr[SHORT_UDID_HASH_HEX_LEN + 1] = {0}; + if (SoftBusGenerateStrHash((const unsigned char *)info->deviceInfo.deviceUdid, + strlen(info->deviceInfo.deviceUdid), udidHash) != SOFTBUS_OK) { + LNN_LOGE(LNN_LEDGER, "generate udidhash fail"); + return; + } + if (ConvertBytesToHexString(hashStr, SHORT_UDID_HASH_HEX_LEN + 1, udidHash, + SHORT_UDID_HASH_HEX_LEN / HEXIFY_UNIT_LEN) != SOFTBUS_OK) { + LNN_LOGE(LNN_LEDGER, "convert udidhash to hexstr fail"); + return; + } + if (LnnRetrieveDeviceInfo(hashStr, &deviceInfo) != SOFTBUS_OK) { + LNN_LOGE(LNN_LEDGER, "get deviceInfo by udidhash fail"); + return; + } + if (info->lastAuthSeq == 0 && deviceInfo.lastAuthSeq != 0) { + info->lastAuthSeq = deviceInfo.lastAuthSeq; + LNN_LOGI(LNN_LEDGER, "reversion lastAuthSeq:0->%{public}" PRId64, info->lastAuthSeq); + } +} + ReportCategory LnnAddOnlineNode(NodeInfo *info) { if (info == NULL) { @@ -1083,7 +1115,6 @@ ReportCategory LnnAddOnlineNode(NodeInfo *info) } // judge map info->onlinetTimestamp = (uint64_t)LnnUpTimeMs(); - if (LnnHasDiscoveryType(info, DISCOVERY_TYPE_BR)) { LNN_LOGI(LNN_LEDGER, "DiscoveryType = BR."); AddCnnCode(&g_distributedNetLedger.cnnCode.connectionCode, info->uuid, DISCOVERY_TYPE_BR, info->authSeqNum); @@ -1102,6 +1133,7 @@ ReportCategory LnnAddOnlineNode(NodeInfo *info) LnnSetAuthTypeValue(&info->AuthTypeValue, ONLINE_HICHAIN); UpdateNewNodeAccountHash(info); TryUpdateDeviceSecurityLevel(info); + ReversionLastAuthSeq(info); int32_t ret = LnnMapSet(&map->udidMap, udid, info, sizeof(NodeInfo)); if (ret != SOFTBUS_OK) { LNN_LOGE(LNN_LEDGER, "lnn map set failed, ret=%{public}d", ret); diff --git a/core/bus_center/lnn/net_ledger/distributed_ledger/src/lnn_distributed_net_ledger_manager.c b/core/bus_center/lnn/net_ledger/distributed_ledger/src/lnn_distributed_net_ledger_manager.c index 88f42de9d..f88c7d362 100644 --- a/core/bus_center/lnn/net_ledger/distributed_ledger/src/lnn_distributed_net_ledger_manager.c +++ b/core/bus_center/lnn/net_ledger/distributed_ledger/src/lnn_distributed_net_ledger_manager.c @@ -1513,6 +1513,27 @@ int32_t LnnGetDLBleDirectTimestamp(const char *networkId, uint64_t *timestamp) return SOFTBUS_OK; } +int32_t LnnGetDLUpdateTimestamp(const char *udid, uint64_t *timestamp) +{ + if (udid == NULL || timestamp == NULL) { + LNN_LOGE(LNN_LEDGER, "invalid param"); + return SOFTBUS_INVALID_PARAM; + } + if (SoftBusMutexLock(&(LnnGetDistributedNetLedger()->lock)) != 0) { + LNN_LOGE(LNN_LEDGER, "lock mutex fail"); + return SOFTBUS_LOCK_ERR; + } + NodeInfo *nodeInfo = LnnGetNodeInfoById(udid, CATEGORY_UDID); + if (nodeInfo == NULL) { + LNN_LOGE(LNN_LEDGER, "get info fail"); + (void)SoftBusMutexUnlock(&(LnnGetDistributedNetLedger()->lock)); + return SOFTBUS_NOT_FIND; + } + *timestamp = nodeInfo->updateTimestamp; + (void)SoftBusMutexUnlock(&(LnnGetDistributedNetLedger()->lock)); + return SOFTBUS_OK; +} + int32_t LnnGetDLAuthCapacity(const char *networkId, uint32_t *authCapacity) { if (SoftBusMutexLock(&(LnnGetDistributedNetLedger()->lock)) != 0) { diff --git a/core/bus_center/service/include/bus_center_event.h b/core/bus_center/service/include/bus_center_event.h index 2a06d5964..cf9fb4939 100644 --- a/core/bus_center/service/include/bus_center_event.h +++ b/core/bus_center/service/include/bus_center_event.h @@ -249,6 +249,7 @@ void LnnNotifyLeaveResult(const char *networkId, int32_t retCode); void LnnNotifyOnlineState(bool isOnline, NodeBasicInfo *info); void LnnNotifyBasicInfoChanged(NodeBasicInfo *info, NodeBasicInfoType type); void LnnNotifyLocalNetworkIdChanged(void); +void LnnNotifyDeviceNotTrusted(const char *msg); void LnnNotifyMigrate(bool isOnline, NodeBasicInfo *info); void LnnNotifyWlanStateChangeEvent(void *state); diff --git a/core/bus_center/service/src/bus_center_event.c b/core/bus_center/service/src/bus_center_event.c index 0957191db..bfb587b9a 100644 --- a/core/bus_center/service/src/bus_center_event.c +++ b/core/bus_center/service/src/bus_center_event.c @@ -380,6 +380,15 @@ void LnnNotifyLocalNetworkIdChanged(void) (void)PostNotifyMessageDelay(NOTIFY_LOCAL_NETWORKID_UPDATE, 0); } +void LnnNotifyDeviceNotTrusted(const char *msg) +{ + if (msg == NULL) { + LNN_LOGE(LNN_EVENT, "msg is null"); + return; + } + (void)LnnIpcNotifyDeviceNotTrusted(msg); +} + void LnnNotifyJoinResult(ConnectionAddr *addr, const char *networkId, int32_t retCode) { if (addr == NULL) { diff --git a/core/bus_center/service/src/bus_center_manager.c b/core/bus_center/service/src/bus_center_manager.c index c6a054f4e..74f1d7dcb 100644 --- a/core/bus_center/service/src/bus_center_manager.c +++ b/core/bus_center/service/src/bus_center_manager.c @@ -60,6 +60,7 @@ typedef int32_t (*LnnInitDelayImpl)(void); typedef enum { INIT_LOCAL_LEDGER_DELAY_TYPE = 0, + INIT_EVENT_MONITER_DELAY_TYPE, INIT_NETWORK_MANAGER_DELAY_TYPE, INIT_NETBUILDER_DELAY_TYPE, INIT_LANEHUB_DELAY_TYPE, @@ -91,6 +92,10 @@ static LnnLocalConfigInit g_lnnLocalConfigInit = { .implInit = LnnInitNetLedgerDelay, .isInit = false, }, + [INIT_EVENT_MONITER_DELAY_TYPE] = { + .implInit = LnnInitEventMoniterDelay, + .isInit = false, + }, [INIT_NETWORK_MANAGER_DELAY_TYPE] = { .implInit = LnnInitNetworkManagerDelay, .isInit = false, diff --git a/core/common/include/softbus_server_ipc_interface_code.h b/core/common/include/softbus_server_ipc_interface_code.h index ae74a595b..2afdba211 100644 --- a/core/common/include/softbus_server_ipc_interface_code.h +++ b/core/common/include/softbus_server_ipc_interface_code.h @@ -103,6 +103,7 @@ enum SoftBusFuncId { CLIENT_ON_JOIN_METANODE_RESULT, CLIENT_ON_LEAVE_RESULT, CLIENT_ON_LEAVE_METANODE_RESULT, + CLIENT_ON_NODE_DEVICE_NOT_TRUST, CLIENT_ON_NODE_ONLINE_STATE_CHANGED, CLIENT_ON_NODE_BASIC_INFO_CHANGED, CLIENT_ON_LOCAL_NETWORK_ID_CHANGED, diff --git a/core/common/include/softbus_utils.h b/core/common/include/softbus_utils.h index 9ac1e2bf0..bca220c2e 100644 --- a/core/common/include/softbus_utils.h +++ b/core/common/include/softbus_utils.h @@ -31,6 +31,7 @@ extern "C" { #define DEC_MAX_NUM 10 #define HEX_MAX_BIT_NUM 4 #define MAX_QUERY_LEN 64 +#define INT64_TO_STR_MAX_LEN 21 #define TIMER_TIMEOUT 1000 // 1s #define BT_MAC_NO_COLON_LEN 13 @@ -90,6 +91,7 @@ int32_t ConvertBtMacToU64(const char *strMac, uint32_t strMacLen, uint64_t *u64M int32_t ConvertU64MacToStr(uint64_t u64Mac, char *strMac, uint32_t strMacLen); +bool Int64ToString(int64_t src, char *buf, uint32_t bufLen); int32_t StrCmpIgnoreCase(const char *str1, const char *str2); int32_t StringToUpperCase(const char *str, char *buf, int32_t size); diff --git a/core/common/utils/softbus_utils.c b/core/common/utils/softbus_utils.c index 2f53493cd..7bfc83002 100644 --- a/core/common/utils/softbus_utils.c +++ b/core/common/utils/softbus_utils.c @@ -449,6 +449,18 @@ int32_t StringToLowerCase(const char *str, char *buf, int32_t size) return SOFTBUS_OK; } +bool Int64ToString(int64_t src, char *buf, uint32_t bufLen) +{ + if (buf == NULL) { + return false; + } + if (sprintf_s(buf, bufLen, "%" PRId64"", src) < 0) { + COMM_LOGE(COMM_UTILS, "convert int64 to str fail"); + return false; + } + return true; +} + int32_t StrCmpIgnoreCase(const char *str1, const char *str2) { if (str1 == NULL || str2 == NULL) { diff --git a/core/connection/ble/src/softbus_conn_ble_trans.c b/core/connection/ble/src/softbus_conn_ble_trans.c index 2944ae1f8..1cb06c3fd 100644 --- a/core/connection/ble/src/softbus_conn_ble_trans.c +++ b/core/connection/ble/src/softbus_conn_ble_trans.c @@ -268,7 +268,7 @@ static void FreeSendNode(SendQueueNode *node) static int32_t ConnGattTransSend(ConnBleConnection *connection, const uint8_t *data, uint32_t dataLen, int32_t module) { -#define BLE_SEND_PACKET_DELAY_MILLIS 10 +#define BLE_SEND_PACKET_DELAY_MILLIS 20 const uint8_t *waitSendData = data; uint32_t waitSendLen = dataLen; uint32_t offset = 0; @@ -306,10 +306,8 @@ static int32_t ConnGattTransSend(ConnBleConnection *connection, const uint8_t *d waitSendData += amount; waitSendLen -= amount; offset += amount; - if (waitSendLen > 0) { - // Temporarily add delay to avoid packet loss - SoftBusSleepMs(BLE_SEND_PACKET_DELAY_MILLIS); - } + // Temporarily add delay to avoid packet loss + SoftBusSleepMs(BLE_SEND_PACKET_DELAY_MILLIS); } return SOFTBUS_OK; } @@ -569,7 +567,6 @@ uint8_t *ConnCocTransRecv(uint32_t connectionId, LimitedBuffer *buffer, int32_t static int32_t ConnCocTransSend(ConnBleConnection *connection, const uint8_t *data, uint32_t dataLen, int32_t module) { - #define BLE_SEND_PACKET_DELAY_MILLIS 10 uint32_t sentLen = 0; while (dataLen > sentLen) { uint32_t amount = (uint32_t)g_flowController->apply(g_flowController, (int32_t)dataLen); diff --git a/core/connection/wifi_direct_cpp/adapter/p2p_adapter.cpp b/core/connection/wifi_direct_cpp/adapter/p2p_adapter.cpp index 12bea4c27..8139bea4e 100644 --- a/core/connection/wifi_direct_cpp/adapter/p2p_adapter.cpp +++ b/core/connection/wifi_direct_cpp/adapter/p2p_adapter.cpp @@ -195,7 +195,6 @@ int32_t P2pAdapter::GetStationFrequencyWithFilter() { int32_t frequency = P2pAdapter::GetStationFrequency(); CONN_CHECK_AND_RETURN_RET_LOGW(frequency > 0, FREQUENCY_INVALID, CONN_WIFI_DIRECT, "invalid frequency"); - if (WifiDirectUtils::Is5GBand(frequency)) { std::vector channelArray; auto ret = P2pAdapter::GetChannel5GListIntArray(channelArray); @@ -359,10 +358,6 @@ int32_t P2pAdapter::GetGroupConfig(std::string &groupConfigString) int32_t P2pAdapter::GetIpAddress(std::string &ipString) { auto groupInfo = std::make_shared(); - if (groupInfo == nullptr) { - CONN_LOGE(CONN_WIFI_DIRECT, "alloc failed"); - return SOFTBUS_MALLOC_ERR; - } int32_t ret = GetCurrentGroup(groupInfo.get()); if (ret != WIFI_SUCCESS) { CONN_LOGE(CONN_WIFI_DIRECT, "get current group failed, error=%{public}d", ToSoftBusErrorCode(ret)); diff --git a/core/connection/wifi_direct_cpp/command/connect_command.h b/core/connection/wifi_direct_cpp/command/connect_command.h index 1d24325ed..95ffd3053 100644 --- a/core/connection/wifi_direct_cpp/command/connect_command.h +++ b/core/connection/wifi_direct_cpp/command/connect_command.h @@ -22,6 +22,11 @@ #include "conn_event.h" namespace OHOS::SoftBus { +enum class ConnectCommandRetryReason { + RETRY_FOR_NOTHING = 0, + RETRY_FOR_PASSIVE_SWITCH_CHANNEL, +}; + struct ConnectInfo { WifiDirectConnectInfo info_; std::shared_ptr channel_; @@ -44,7 +49,8 @@ public: virtual void PreferNegotiateChannel(); void SetRetried(bool retried) { hasRetried_ = retried; } bool HasRetried() const { return hasRetried_; } - + void SetRetryReason(ConnectCommandRetryReason reason) { retryReason_ = reason; } + ConnectCommandRetryReason GetReTryReason() const { return retryReason_; } void OnSuccess(const WifiDirectLink &link) const; void OnFailure(int reason) const; bool IsSameCommand(const WifiDirectConnectInfo &info) const; @@ -55,7 +61,7 @@ protected: WifiDirectConnectCallback callback_; mutable std::string remoteDeviceId_; bool hasRetried_ = false; - + ConnectCommandRetryReason retryReason_ = ConnectCommandRetryReason::RETRY_FOR_NOTHING; private: static constexpr uint64_t ABANDON_CONNECT_COMMAND_PERIOD = 500; }; diff --git a/core/connection/wifi_direct_cpp/processor/p2p_v1_processor.cpp b/core/connection/wifi_direct_cpp/processor/p2p_v1_processor.cpp index acb819dbd..9f850b606 100644 --- a/core/connection/wifi_direct_cpp/processor/p2p_v1_processor.cpp +++ b/core/connection/wifi_direct_cpp/processor/p2p_v1_processor.cpp @@ -115,7 +115,8 @@ bool P2pV1Processor::CanAcceptNegotiateDataAtState(WifiDirectCommand &command) if (nc == nullptr) { return false; } - return nc->GetNegotiateMessage().GetLegacyP2pCommandType() != LegacyCommandType::CMD_INVALID; + return nc->GetNegotiateMessage().GetLegacyP2pCommandType() != LegacyCommandType::CMD_INVALID && + nc->GetNegotiateMessage().GetLegacyP2pCommandType() != LegacyCommandType::CMD_DISCONNECT_V1_REQ; } void P2pV1Processor::HandleCommandAfterTerminate(WifiDirectCommand &command) @@ -1437,10 +1438,9 @@ int P2pV1Processor::ProcessConnectResponseAtWaitAuthHandShake(std::shared_ptrGetConnectInfo().info_.requestId; auto pid = connectCommand_->GetConnectInfo().info_.pid; - bool alreadyAuthHandShake = false; WifiDirectLink dlink {}; auto success = LinkManager::GetInstance().ProcessIfPresent( - remoteMac, [msg, requestId, pid, &dlink, &alreadyAuthHandShake](InnerLink &link) { + remoteMac, [msg, requestId, pid, &dlink](InnerLink &link) { link.SetState(InnerLink::LinkState::CONNECTED); link.GenerateLink(requestId, pid, dlink, true); dlink.channelId = WifiDirectUtils::FrequencyToChannel(link.GetFrequency()); diff --git a/core/connection/wifi_direct_cpp/wifi_direct_manager.cpp b/core/connection/wifi_direct_cpp/wifi_direct_manager.cpp index 66167dd63..74c8bcfd1 100644 --- a/core/connection/wifi_direct_cpp/wifi_direct_manager.cpp +++ b/core/connection/wifi_direct_cpp/wifi_direct_manager.cpp @@ -452,6 +452,19 @@ static void RegisterEnhanceManager(WifiDirectEnhanceManager *manager) g_enhanceManager = *manager; } +static bool IsHmlConnected() +{ + bool ret = false; + OHOS::SoftBus::LinkManager::GetInstance().ForEach([&] (const OHOS::SoftBus::InnerLink &innerLink) { + if (innerLink.GetLinkType() == OHOS::SoftBus::InnerLink::LinkType::HML) { + ret = true; + return true; + } + return false; + }); + return ret; +} + static void NotifyPtkSyncResult(const char *remoteDeviceId, int result) { if (g_syncPtkListener == nullptr) { @@ -493,6 +506,7 @@ static struct WifiDirectManager g_manager = { .isWifiP2pEnabled = IsWifiP2pEnabled, .getStationFrequency = GetStationFrequency, + .isHmlConnected = IsHmlConnected, .init = Init, .notifyOnline = NotifyOnline, diff --git a/core/connection/wifi_direct_cpp/wifi_direct_manager.h b/core/connection/wifi_direct_cpp/wifi_direct_manager.h index e9f32c70c..454bbcdc7 100644 --- a/core/connection/wifi_direct_cpp/wifi_direct_manager.h +++ b/core/connection/wifi_direct_cpp/wifi_direct_manager.h @@ -63,6 +63,7 @@ struct WifiDirectManager { bool (*isWifiP2pEnabled)(void); int (*getStationFrequency)(void); + bool (*isHmlConnected)(void); int32_t (*init)(void); diff --git a/core/connection/wifi_direct_cpp/wifi_direct_manager_virtual.c b/core/connection/wifi_direct_cpp/wifi_direct_manager_virtual.c index e3f2615e0..7ce7b9959 100644 --- a/core/connection/wifi_direct_cpp/wifi_direct_manager_virtual.c +++ b/core/connection/wifi_direct_cpp/wifi_direct_manager_virtual.c @@ -155,6 +155,11 @@ static int GetStationFrequency(void) return SOFTBUS_NOT_IMPLEMENT; } +static bool IsHmlConnected() +{ + return false; +} + static void RegisterEnhanceManager(struct WifiDirectEnhanceManager *manager) { (void)manager; @@ -194,6 +199,7 @@ static struct WifiDirectManager g_manager = { .isWifiP2pEnabled = IsWifiP2pEnabled, .getStationFrequency = GetStationFrequency, + .isHmlConnected = IsHmlConnected, .init = Init, .notifyOnline = NotifyOnline, diff --git a/core/connection/wifi_direct_cpp/wifi_direct_scheduler.h b/core/connection/wifi_direct_cpp/wifi_direct_scheduler.h index 3e2c0799f..cf3fe1b43 100644 --- a/core/connection/wifi_direct_cpp/wifi_direct_scheduler.h +++ b/core/connection/wifi_direct_cpp/wifi_direct_scheduler.h @@ -151,6 +151,13 @@ public: virtual bool ProcessNextCommand(WifiDirectExecutor *executor, std::shared_ptr &processor); + bool CheckExecutorRunning(const std::string &remoteDeviceId) + { + std::lock_guard executorLock(executorLock_); + auto iterator = executors_.find(remoteDeviceId); + return iterator != executors_.end(); + } + protected: int ScheduleActiveCommand(const std::shared_ptr &command, std::shared_ptr &executor); diff --git a/core/discovery/ble/disc_ble.gni b/core/discovery/ble/disc_ble.gni index e119b0fe4..cf6832a32 100644 --- a/core/discovery/ble/disc_ble.gni +++ b/core/discovery/ble/disc_ble.gni @@ -28,8 +28,8 @@ ble_discovery_inc = [ "$dsoftbus_root_path/core/discovery/ble/dispatcher/include", "$dsoftbus_root_path/core/discovery/ble/approach_ble/include", "$dsoftbus_root_path/core/discovery/ble/share_ble/include", - "$dsoftbus_root_path/core/discovery/ble/touch_ble/include", "$dsoftbus_root_path/core/discovery/ble/softbus_ble/include", + "$dsoftbus_root_path/core/discovery/ble/touch_ble/include", "$dsoftbus_root_path/core/discovery/ble/virtual_link_ble/include", "$dsoftbus_root_path/core/common/include", "$dsoftbus_root_path/core/common/dfx/hisysevent_adapter/include", @@ -58,6 +58,8 @@ if (dsoftbus_feature_disc_ble && disc_enhanced) { ble_discovery_src += vlink_sources ble_discovery_inc += vlink_include_dirs ble_discovery_deps += vlink_deps +} else { + ble_discovery_src += [ "$dsoftbus_root_path/core/discovery/ble/virtual_link_ble/src/disc_virtual_link_ble_virtual.c" ] } if (disc_enhanced) { @@ -68,14 +70,14 @@ if (disc_enhanced) { import( "$dsoftbus_root_path/dsoftbus_enhance/core/discovery/ble/touch_ble/touch_ble.gni") - ble_discovery_src += share_sources + approach_sources + vlink_sources + touch_sources - ble_discovery_inc += share_include_dirs + approach_include_dirs + vlink_include_dirs + touch_include_dirs - ble_discovery_deps += share_deps + approach_deps + vlink_deps + touch_deps + ble_discovery_src += share_sources + approach_sources + touch_sources + ble_discovery_inc += + share_include_dirs + approach_include_dirs + touch_include_dirs + ble_discovery_deps += share_deps + approach_deps + touch_deps } else { ble_discovery_src += [ "$dsoftbus_root_path/core/discovery/ble/share_ble/src/disc_share_ble_virtual.c", "$dsoftbus_root_path/core/discovery/ble/approach_ble/src/disc_approach_ble_virtual.c", - "$dsoftbus_root_path/core/discovery/ble/touch_ble/src/touch_ble_virtual.c", - "$dsoftbus_root_path/core/discovery/ble/virtual_link_ble/src/disc_virtual_link_ble_virtual.c", + "$dsoftbus_root_path/core/discovery/ble/touch_ble/src/disc_touch_ble_virtual.c", ] } diff --git a/core/discovery/ble/dispatcher/src/disc_ble_dispatcher.c b/core/discovery/ble/dispatcher/src/disc_ble_dispatcher.c index 6a40d11c1..ab62e766c 100644 --- a/core/discovery/ble/dispatcher/src/disc_ble_dispatcher.c +++ b/core/discovery/ble/dispatcher/src/disc_ble_dispatcher.c @@ -24,7 +24,7 @@ #include "disc_virtual_link_ble.h" #include "softbus_errcode.h" -#define DISPATCHER_SIZE 4 +#define DISPATCHER_SIZE 5 static DiscoveryBleDispatcherInterface *g_dispatchers[DISPATCHER_SIZE]; static uint32_t g_dispatcherSize = 0; @@ -45,7 +45,7 @@ static DiscoveryFuncInterface *FindDiscoveryFuncInterface(uint32_t capability) static int32_t BleDispatchPublishOption(const PublishOption *option, DiscoverMode mode, InterfaceFuncType type) { - DISC_CHECK_AND_RETURN_RET_LOGW(option != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, "option is null"); + DISC_CHECK_AND_RETURN_RET_LOGE(option != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, "option is null"); DiscoveryFuncInterface *interface = FindDiscoveryFuncInterface(option->capabilityBitmap[0]); if (interface == NULL) { DISC_LOGE(DISC_BLE, @@ -68,7 +68,7 @@ static int32_t BleDispatchPublishOption(const PublishOption *option, DiscoverMod case UNPUBLISH_FUNC: return mode == DISCOVER_MODE_ACTIVE ? interface->Unpublish(option) : interface->StopScan(option); default: - DISC_LOGW(DISC_BLE, + DISC_LOGE(DISC_BLE, "dispatch publish action failed: unsupport type. type=%{public}d, capability=%{public}u", type, option->capabilityBitmap[0]); return SOFTBUS_DISCOVER_BLE_DISPATCHER_FAIL; @@ -78,7 +78,7 @@ static int32_t BleDispatchPublishOption(const PublishOption *option, DiscoverMod static int32_t BleDispatchSubscribeOption(const SubscribeOption *option, DiscoverMode mode, InterfaceFuncType type) { - DISC_CHECK_AND_RETURN_RET_LOGW(option != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, "option is null"); + DISC_CHECK_AND_RETURN_RET_LOGE(option != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, "option is null"); DiscoveryFuncInterface *interface = FindDiscoveryFuncInterface(option->capabilityBitmap[0]); if (interface == NULL) { DISC_LOGE(DISC_BLE, "dispatch subcribe action failed: no implement support capability. capability=%{public}u", @@ -100,7 +100,7 @@ static int32_t BleDispatchSubscribeOption(const SubscribeOption *option, Discove case STOPDISCOVERY_FUNC: return mode == DISCOVER_MODE_ACTIVE ? interface->StopAdvertise(option) : interface->Unsubscribe(option); default: - DISC_LOGW(DISC_BLE, "dispatch subcribe action failed: unsupport. type=%{public}d, capability=%{public}u", + DISC_LOGE(DISC_BLE, "dispatch subcribe action failed: unsupport. type=%{public}d, capability=%{public}u", type, option->capabilityBitmap[0]); return SOFTBUS_DISCOVER_BLE_DISPATCHER_FAIL; } @@ -193,11 +193,24 @@ static void DfxRecordBleInitEnd(int32_t stage, int32_t reason) } } +static int32_t DiscBleInitExt(DiscInnerCallback *discInnerCb) +{ + DiscoveryBleDispatcherInterface *touchInterface = DiscTouchBleInit(discInnerCb); + if (touchInterface == NULL) { + DfxRecordBleInitEnd(EVENT_STAGE_TOUCH_BLE_INIT, SOFTBUS_DISCOVER_MANAGER_INIT_FAIL); + DISC_LOGE(DISC_INIT, "DiscTouchBleInit err"); + return SOFTBUS_DISCOVER_MANAGER_INIT_FAIL; + } + g_dispatchers[g_dispatcherSize++] = touchInterface; + DfxRecordBleInitEnd(EVENT_STAGE_TOUCH_BLE_INIT, SOFTBUS_OK); + return SOFTBUS_OK; +} + DiscoveryFuncInterface *DiscBleInit(DiscInnerCallback *discInnerCb) { if (discInnerCb == NULL) { DfxRecordBleInitEnd(EVENT_STAGE_INIT, SOFTBUS_INVALID_PARAM); - DISC_LOGW(DISC_INIT, "discInnerCb err"); + DISC_LOGE(DISC_INIT, "discInnerCb err"); return NULL; } DISC_LOGI(DISC_INIT, "DiscBleFrameInit"); @@ -238,14 +251,8 @@ DiscoveryFuncInterface *DiscBleInit(DiscInnerCallback *discInnerCb) g_dispatchers[g_dispatcherSize++] = vlinkInterface; DfxRecordBleInitEnd(EVENT_STAGE_VLINK_BLE_INIT, SOFTBUS_OK); - DiscoveryBleDispatcherInterface *touchInterface = DiscTouchBleInit(discInnerCb); - if (vlinkInterface == NULL) { - DfxRecordBleInitEnd(EVENT_STAGE_TOUCH_BLE_INIT, SOFTBUS_DISCOVER_MANAGER_INIT_FAIL); - DISC_LOGE(DISC_INIT, "DiscTouchBleInit err"); - return NULL; - } - g_dispatchers[g_dispatcherSize++] = touchInterface; - DfxRecordBleInitEnd(EVENT_STAGE_TOUCH_BLE_INIT, SOFTBUS_OK); + DISC_CHECK_AND_RETURN_RET_LOGE(DiscBleInitExt(discInnerCb) == SOFTBUS_OK, + NULL, DISC_INIT, "disc ble init ext failed"); DfxRecordBleInitEnd(EVENT_STAGE_INIT, SOFTBUS_OK); return &g_discBleFrameFuncInterface; diff --git a/core/discovery/ble/softbus_ble/src/disc_ble.c b/core/discovery/ble/softbus_ble/src/disc_ble.c index b2727d91f..135c6fed4 100644 --- a/core/discovery/ble/softbus_ble/src/disc_ble.c +++ b/core/discovery/ble/softbus_ble/src/disc_ble.c @@ -1816,8 +1816,10 @@ static void RemoveRecvMessage(uint64_t key) return; } - g_discBleHandler.looper->RemoveMessageCustom(g_discBleHandler.looper, &g_discBleHandler, MessageRemovePredicate, - (void *)key); + if (g_discBleHandler.looper && g_discBleHandler.looper->RemoveMessageCustom) { + g_discBleHandler.looper->RemoveMessageCustom(g_discBleHandler.looper, &g_discBleHandler, + MessageRemovePredicate, (void *)key); + } if (msg->needBrMac) { g_recvMessageInfo.numNeedBrMac--; } @@ -1833,6 +1835,10 @@ static void ClearRecvMessage(void) while (!IsListEmpty(head)) { RecvMessage *msg = LIST_ENTRY(head->next, RecvMessage, node); ListDelete(&msg->node); + if (g_discBleHandler.looper && g_discBleHandler.looper->RemoveMessageCustom) { + g_discBleHandler.looper->RemoveMessageCustom(g_discBleHandler.looper, &g_discBleHandler, + MessageRemovePredicate, (void *)msg->key); + } SoftBusFree(msg); } } 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 703658369..020e485b0 100644 --- a/core/discovery/ble/softbus_ble/src/disc_ble_utils.c +++ b/core/discovery/ble/softbus_ble/src/disc_ble_utils.c @@ -208,7 +208,7 @@ static int32_t CalculateMbsTruncateSize(const char *multiByteStr, uint32_t capac return SOFTBUS_OK; } DISC_CHECK_AND_RETURN_RET_LOGE(multiByteStrLen <= WIDE_STR_MAX_LEN, SOFTBUS_INVALID_PARAM, DISC_BLE, - "multi byte str too long: %zu", multiByteStrLen); + "multi byte str too long: %{public}zu", multiByteStrLen); char *localeBefore = NULL; int32_t ret = SetLocale(&localeBefore); @@ -420,13 +420,13 @@ static int32_t ParseRecvTlvs(DeviceWrapper *device, const uint8_t *data, uint32_ int32_t GetDeviceInfoFromDisAdvData(DeviceWrapper *device, const uint8_t *data, uint32_t dataLen) { - DISC_CHECK_AND_RETURN_RET_LOGW(device != NULL && device->info != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, + DISC_CHECK_AND_RETURN_RET_LOGE(device != NULL && device->info != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, "device is null"); 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, + DISC_CHECK_AND_RETURN_RET_LOGE(reportInfo != NULL, SOFTBUS_INVALID_PARAM, DISC_BLE, "reportInfo=NULL is invalid"); + DISC_CHECK_AND_RETURN_RET_LOGE(dataLen == sizeof(BroadcastReportInfo), SOFTBUS_INVALID_PARAM, DISC_BLE, "bcData.payload=NULL is invalid"); - DISC_CHECK_AND_RETURN_RET_LOGW( + DISC_CHECK_AND_RETURN_RET_LOGE( 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; diff --git a/core/discovery/event_manager/src/disc_event_manager.c b/core/discovery/event_manager/src/disc_event_manager.c index d18134a52..e36e0a22b 100644 --- a/core/discovery/event_manager/src/disc_event_manager.c +++ b/core/discovery/event_manager/src/disc_event_manager.c @@ -16,6 +16,7 @@ #include "disc_approach_ble.h" #include "disc_event_manager.h" #include "disc_log.h" +#include "disc_touch_ble.h" #include "disc_virtual_link_ble.h" #include "softbus_error_code.h" @@ -27,6 +28,9 @@ int32_t DiscEventManagerInit(void) ret = DiscVLinkBleEventInit(); DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, DISC_INIT, "init vlink ble event failed"); + ret = DiscTouchBleEventInit(); + DISC_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, DISC_INIT, "init touch ble event failed"); + DISC_LOGI(DISC_INIT, "disc event manager init succ"); return SOFTBUS_OK; } @@ -35,5 +39,6 @@ void DiscEventManagerDeinit(void) { DiscApproachBleEventDeinit(); DiscVLinkBleEventDeinit(); + DiscTouchBleEventDeinit(); } diff --git a/core/discovery/manager/src/disc_manager.c b/core/discovery/manager/src/disc_manager.c index 3b404eb5f..66794a9f1 100644 --- a/core/discovery/manager/src/disc_manager.c +++ b/core/discovery/manager/src/disc_manager.c @@ -368,8 +368,8 @@ static void InnerDeviceFound(DiscInfo *infoNode, const DeviceInfo *device, static void DiscOnDeviceFound(const DeviceInfo *device, const InnerDeviceInfoAddtions *additions) { - DISC_CHECK_AND_RETURN_LOGW(device != NULL, DISC_CONTROL, "device is null"); - DISC_CHECK_AND_RETURN_LOGW(additions != NULL, DISC_CONTROL, "additions is null"); + DISC_CHECK_AND_RETURN_LOGE(device != NULL, DISC_CONTROL, "device is null"); + DISC_CHECK_AND_RETURN_LOGE(additions != NULL, DISC_CONTROL, "additions is null"); DISC_LOGD(DISC_CONTROL, "capabilityBitmap=%{public}d, medium=%{public}d", device->capabilityBitmap[0], additions->medium); @@ -910,9 +910,9 @@ int32_t DiscPublish(DiscModule moduleId, const PublishInfo *info) SOFTBUS_INVALID_PARAM, DISC_CONTROL, "invalid parameters"); DISC_CHECK_AND_RETURN_RET_LOGW(info->mode == DISCOVER_MODE_ACTIVE, SOFTBUS_INVALID_PARAM, DISC_CONTROL, "mode is not active"); - DISC_CHECK_AND_RETURN_RET_LOGW(CheckPublishInfo(info) == SOFTBUS_OK, SOFTBUS_INVALID_PARAM, DISC_CONTROL, + DISC_CHECK_AND_RETURN_RET_LOGE(CheckPublishInfo(info) == SOFTBUS_OK, SOFTBUS_INVALID_PARAM, DISC_CONTROL, "invalid info"); - DISC_CHECK_AND_RETURN_RET_LOGW(g_isInited == true, SOFTBUS_DISCOVER_MANAGER_NOT_INIT, DISC_CONTROL, + DISC_CHECK_AND_RETURN_RET_LOGE(g_isInited == true, SOFTBUS_DISCOVER_MANAGER_NOT_INIT, DISC_CONTROL, "manager is not inited"); DiscInfo *infoNode = CreateDiscInfoForPublish(info); @@ -932,9 +932,9 @@ int32_t DiscStartScan(DiscModule moduleId, const PublishInfo *info) SOFTBUS_INVALID_PARAM, DISC_CONTROL, "invalid parameters"); DISC_CHECK_AND_RETURN_RET_LOGW(info->mode == DISCOVER_MODE_PASSIVE, SOFTBUS_INVALID_PARAM, DISC_CONTROL, "mode is not passive"); - DISC_CHECK_AND_RETURN_RET_LOGW(CheckPublishInfo(info) == SOFTBUS_OK, SOFTBUS_INVALID_PARAM, DISC_CONTROL, + DISC_CHECK_AND_RETURN_RET_LOGE(CheckPublishInfo(info) == SOFTBUS_OK, SOFTBUS_INVALID_PARAM, DISC_CONTROL, "invalid info"); - DISC_CHECK_AND_RETURN_RET_LOGW(g_isInited == true, SOFTBUS_DISCOVER_MANAGER_NOT_INIT, DISC_CONTROL, + DISC_CHECK_AND_RETURN_RET_LOGE(g_isInited == true, SOFTBUS_DISCOVER_MANAGER_NOT_INIT, DISC_CONTROL, "manager is not inited"); DiscInfo *infoNode = CreateDiscInfoForPublish(info); @@ -964,9 +964,9 @@ int32_t DiscStartAdvertise(DiscModule moduleId, const SubscribeInfo *info) SOFTBUS_INVALID_PARAM, DISC_CONTROL, "invalid parameters"); DISC_CHECK_AND_RETURN_RET_LOGW(info->mode == DISCOVER_MODE_ACTIVE, SOFTBUS_INVALID_PARAM, DISC_CONTROL, "mode is not active"); - DISC_CHECK_AND_RETURN_RET_LOGW(CheckSubscribeInfo(info) == SOFTBUS_OK, SOFTBUS_INVALID_PARAM, DISC_CONTROL, + DISC_CHECK_AND_RETURN_RET_LOGE(CheckSubscribeInfo(info) == SOFTBUS_OK, SOFTBUS_INVALID_PARAM, DISC_CONTROL, "invalid info"); - DISC_CHECK_AND_RETURN_RET_LOGW(g_isInited == true, SOFTBUS_DISCOVER_MANAGER_NOT_INIT, DISC_CONTROL, + DISC_CHECK_AND_RETURN_RET_LOGE(g_isInited == true, SOFTBUS_DISCOVER_MANAGER_NOT_INIT, DISC_CONTROL, "manager is not inited"); DiscInfo *infoNode = CreateDiscInfoForSubscribe(info); @@ -986,9 +986,9 @@ int32_t DiscSubscribe(DiscModule moduleId, const SubscribeInfo *info) SOFTBUS_INVALID_PARAM, DISC_CONTROL, "invalid parameters"); DISC_CHECK_AND_RETURN_RET_LOGW(info->mode == DISCOVER_MODE_PASSIVE, SOFTBUS_INVALID_PARAM, DISC_CONTROL, "mode is not passive"); - DISC_CHECK_AND_RETURN_RET_LOGW(CheckSubscribeInfo(info) == SOFTBUS_OK, SOFTBUS_INVALID_PARAM, DISC_CONTROL, + DISC_CHECK_AND_RETURN_RET_LOGE(CheckSubscribeInfo(info) == SOFTBUS_OK, SOFTBUS_INVALID_PARAM, DISC_CONTROL, "invalid info"); - DISC_CHECK_AND_RETURN_RET_LOGW(g_isInited == true, SOFTBUS_DISCOVER_MANAGER_NOT_INIT, DISC_CONTROL, + DISC_CHECK_AND_RETURN_RET_LOGE(g_isInited == true, SOFTBUS_DISCOVER_MANAGER_NOT_INIT, DISC_CONTROL, "manager is not inited"); DiscInfo *infoNode = CreateDiscInfoForSubscribe(info); @@ -1014,13 +1014,13 @@ int32_t DiscStopAdvertise(DiscModule moduleId, int32_t subscribeId) int32_t DiscPublishService(const char *packageName, const PublishInfo *info) { - DISC_CHECK_AND_RETURN_RET_LOGW(packageName != NULL && info != NULL, SOFTBUS_INVALID_PARAM, DISC_CONTROL, + DISC_CHECK_AND_RETURN_RET_LOGE(packageName != NULL && info != NULL, SOFTBUS_INVALID_PARAM, DISC_CONTROL, "invalid parameters"); DISC_CHECK_AND_RETURN_RET_LOGW(strlen(packageName) < PKG_NAME_SIZE_MAX, SOFTBUS_INVALID_PARAM, DISC_CONTROL, "package name too long"); DISC_CHECK_AND_RETURN_RET_LOGW(CheckPublishInfo(info) == SOFTBUS_OK, SOFTBUS_INVALID_PARAM, DISC_CONTROL, "invalid info"); - DISC_CHECK_AND_RETURN_RET_LOGW(g_isInited == true, SOFTBUS_DISCOVER_MANAGER_NOT_INIT, DISC_CONTROL, + DISC_CHECK_AND_RETURN_RET_LOGE(g_isInited == true, SOFTBUS_DISCOVER_MANAGER_NOT_INIT, DISC_CONTROL, "manager is not inited"); DiscInfo *infoNode = CreateDiscInfoForPublish(info); @@ -1051,9 +1051,9 @@ int32_t DiscStartDiscovery(const char *packageName, const SubscribeInfo *info, SOFTBUS_INVALID_PARAM, DISC_CONTROL, "invalid package name"); DISC_CHECK_AND_RETURN_RET_LOGW(info != NULL && cb != NULL, SOFTBUS_INVALID_PARAM, DISC_CONTROL, "invalid parameters"); - DISC_CHECK_AND_RETURN_RET_LOGW(g_isInited == true, SOFTBUS_DISCOVER_MANAGER_NOT_INIT, DISC_CONTROL, + DISC_CHECK_AND_RETURN_RET_LOGE(g_isInited == true, SOFTBUS_DISCOVER_MANAGER_NOT_INIT, DISC_CONTROL, "manager is not inited"); - DISC_CHECK_AND_RETURN_RET_LOGW(CheckSubscribeInfo(info) == SOFTBUS_OK, SOFTBUS_INVALID_PARAM, DISC_CONTROL, + DISC_CHECK_AND_RETURN_RET_LOGE(CheckSubscribeInfo(info) == SOFTBUS_OK, SOFTBUS_INVALID_PARAM, DISC_CONTROL, "invalid info"); DiscInfo *infoNode = CreateDiscInfoForSubscribe(info); @@ -1221,8 +1221,8 @@ static void RemoveDiscInfoForDiscovery(const char *pkgName) void DiscMgrDeathCallback(const char *pkgName) { - DISC_CHECK_AND_RETURN_LOGW(pkgName != NULL, DISC_CONTROL, "pkgName is null"); - DISC_CHECK_AND_RETURN_LOGW(g_isInited == true, DISC_CONTROL, "disc manager is not inited"); + DISC_CHECK_AND_RETURN_LOGE(pkgName != NULL, DISC_CONTROL, "pkgName is null"); + DISC_CHECK_AND_RETURN_LOGE(g_isInited == true, DISC_CONTROL, "disc manager is not inited"); DISC_LOGD(DISC_CONTROL, "pkg is dead. pkgName=%{public}s", pkgName); RemoveDiscInfoForPublish(pkgName); @@ -1231,7 +1231,7 @@ void DiscMgrDeathCallback(const char *pkgName) int32_t DiscMgrInit(void) { - DISC_CHECK_AND_RETURN_RET_LOGW(g_isInited == false, SOFTBUS_OK, DISC_INIT, "already inited"); + DISC_CHECK_AND_RETURN_RET_LOGE(g_isInited == false, SOFTBUS_OK, DISC_INIT, "already inited"); g_discMgrMediumCb.OnDeviceFound = DiscOnDeviceFound; diff --git a/core/transmission/trans_channel/common/src/trans_channel_common.c b/core/transmission/trans_channel/common/src/trans_channel_common.c index 89c750f44..61146885a 100644 --- a/core/transmission/trans_channel/common/src/trans_channel_common.c +++ b/core/transmission/trans_channel/common/src/trans_channel_common.c @@ -387,9 +387,6 @@ static int32_t CancelWaitLaneState(const char *sessionName, int32_t sessionId) TransFreeLane(laneHandle, isQosLane, isAsync); } } - if (!isAsync && laneHandle != INVALID_LANE_REQ_ID) { - TransCancelLaneItemCondByLaneHandle(laneHandle, false, false, SOFTBUS_TRANS_REQUEST_LANE_TIMEOUT); - } if (isAsync && laneHandle != INVALID_LANE_REQ_ID) { (void)TransDeleteLaneReqItemByLaneHandle(laneHandle, isAsync); } 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 8069acccc..e9a1a756f 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 @@ -355,15 +355,13 @@ static void BuildTransEventExtra( static void CallbackOpenChannelFailed(const SessionParam *param, const AppInfo *appInfo, int32_t errCode) { - if (param->isAsync) { - ChannelMsg data = { - .msgChannelId = param->sessionId, - .msgChannelType = CHANNEL_TYPE_UNDEFINED, - .msgPkgName = appInfo->myData.pkgName, - .msgPid = appInfo->myData.pid, - }; - (void)ClientIpcOnChannelOpenFailed(&data, errCode); - } + ChannelMsg data = { + .msgChannelId = param->sessionId, + .msgChannelType = CHANNEL_TYPE_UNDEFINED, + .msgPkgName = appInfo->myData.pkgName, + .msgPid = appInfo->myData.pid, + }; + (void)ClientIpcOnChannelOpenFailed(&data, errCode); } static int32_t CopyAsyncReqItemSessionParamIds(const SessionParam *source, SessionParam *target) 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 c12840d85..a98ac131a 100644 --- a/core/transmission/trans_channel/manager/src/trans_channel_manager.c +++ b/core/transmission/trans_channel/manager/src/trans_channel_manager.c @@ -244,7 +244,7 @@ int32_t TransOpenChannel(const SessionParam *param, TransInfo *transInfo) TransBuildTransOpenChannelStartEvent(&extra, appInfo, &nodeInfo, peerRet); TransSetFirstTokenInfo(appInfo, &extra); TRANS_EVENT(EVENT_SCENE_OPEN_CHANNEL, EVENT_STAGE_OPEN_CHANNEL_START, extra); - if (param->isAsync) { + if (param->isQosLane) { uint32_t callingTokenId = TransACLGetCallingTokenID(); ret = TransAsyncGetLaneInfo(param, &laneHandle, callingTokenId, appInfo->timeStart); if (ret != SOFTBUS_OK) { 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 69453cd8f..04460a615 100644 --- a/core/transmission/trans_channel/proxy/src/softbus_proxychannel_manager.c +++ b/core/transmission/trans_channel/proxy/src/softbus_proxychannel_manager.c @@ -119,11 +119,8 @@ static bool ResetChanIsEqual(int8_t status, ProxyChannelInfo *a, ProxyChannelInf int32_t TransProxyGetAppInfoType(int16_t myId, const char *identity, AppType *appType) { - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "fail to lock mutex!"); - return SOFTBUS_LOCK_ERR; - } - + TRANS_CHECK_AND_RETURN_RET_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, SOFTBUS_LOCK_ERR, TRANS_CTRL, "fail to lock mutex!"); ProxyChannelInfo *item = NULL; LIST_FOR_EACH_ENTRY(item, &g_proxyChannelList->list, ProxyChannelInfo, node) { if ((item->myId == myId) && (strcmp(item->identity, identity) == 0)) { @@ -138,16 +135,10 @@ int32_t TransProxyGetAppInfoType(int16_t myId, const char *identity, AppType *ap static int32_t TransProxyUpdateAckInfo(ProxyChannelInfo *info) { - if (g_proxyChannelList == NULL || info == NULL) { - TRANS_LOGE(TRANS_CTRL, "g_proxyChannelList or item is null"); - return SOFTBUS_INVALID_PARAM; - } - - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "lock mutex fail!"); - return SOFTBUS_LOCK_ERR; - } - + TRANS_CHECK_AND_RETURN_RET_LOGE((g_proxyChannelList != NULL && info != NULL), SOFTBUS_INVALID_PARAM, TRANS_CTRL, + "g_proxyChannelList or item is null"); + TRANS_CHECK_AND_RETURN_RET_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, SOFTBUS_LOCK_ERR, TRANS_CTRL, "lock mutex fail!"); ProxyChannelInfo *item = NULL; LIST_FOR_EACH_ENTRY(item, &g_proxyChannelList->list, ProxyChannelInfo, node) { if ((item->myId == info->myId) && (strncmp(item->identity, info->identity, sizeof(item->identity)) == 0)) { @@ -177,15 +168,10 @@ static int32_t TransProxyUpdateAckInfo(ProxyChannelInfo *info) int32_t TransRefreshProxyTimesNative(int32_t channelId) { - if (g_proxyChannelList == NULL) { - TRANS_LOGE(TRANS_CTRL, "g_proxyChannelList or item is null"); - return SOFTBUS_NO_INIT; - } - - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "lock mutex fail!"); - return SOFTBUS_LOCK_ERR; - } + TRANS_CHECK_AND_RETURN_RET_LOGE( + g_proxyChannelList != NULL, SOFTBUS_NO_INIT, TRANS_CTRL, "g_proxyChannelList is null"); + TRANS_CHECK_AND_RETURN_RET_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, SOFTBUS_LOCK_ERR, TRANS_CTRL, "lock mutex fail!"); ProxyChannelInfo *item = NULL; LIST_FOR_EACH_ENTRY(item, &g_proxyChannelList->list, ProxyChannelInfo, node) { @@ -201,16 +187,11 @@ int32_t TransRefreshProxyTimesNative(int32_t channelId) static int32_t TransProxyAddChanItem(ProxyChannelInfo *chan) { - TRANS_LOGD(TRANS_CTRL, "enter."); - if ((chan == NULL) || (g_proxyChannelList == NULL)) { - TRANS_LOGE(TRANS_CTRL, "trans proxy add channel param nullptr!"); - return SOFTBUS_INVALID_PARAM; - } + TRANS_CHECK_AND_RETURN_RET_LOGE((g_proxyChannelList != NULL && chan != NULL), SOFTBUS_INVALID_PARAM, TRANS_CTRL, + "trans proxy add channel param nullptr!"); + TRANS_CHECK_AND_RETURN_RET_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, SOFTBUS_LOCK_ERR, TRANS_CTRL, "lock mutex fail!"); - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "lock mutex fail!"); - return SOFTBUS_LOCK_ERR; - } ListAdd(&(g_proxyChannelList->list), &(chan->node)); g_proxyChannelList->cnt++; (void)SoftBusMutexUnlock(&g_proxyChannelList->lock); @@ -219,15 +200,10 @@ static int32_t TransProxyAddChanItem(ProxyChannelInfo *chan) int32_t TransProxySpecialUpdateChanInfo(ProxyChannelInfo *channelInfo) { - if (g_proxyChannelList == NULL || channelInfo == NULL) { - TRANS_LOGE(TRANS_CTRL, "g_proxyChannelList or channelInfo is NULL!"); - return SOFTBUS_INVALID_PARAM; - } - - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "lock mutex fail!"); - return SOFTBUS_LOCK_ERR; - } + TRANS_CHECK_AND_RETURN_RET_LOGE((g_proxyChannelList != NULL && channelInfo != NULL), SOFTBUS_INVALID_PARAM, + TRANS_CTRL, "g_proxyChannelList or channelInfo is NULL!"); + TRANS_CHECK_AND_RETURN_RET_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, SOFTBUS_LOCK_ERR, TRANS_CTRL, "lock mutex fail!"); ProxyChannelInfo *item = NULL; ProxyChannelInfo *nextNode = NULL; @@ -258,23 +234,14 @@ 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; - } + TRANS_CHECK_AND_RETURN_RET_LOGE((g_proxyChannelList != NULL && chan != NULL), SOFTBUS_INVALID_PARAM, TRANS_CTRL, + "trans proxy get channel param nullptr!"); + TRANS_CHECK_AND_RETURN_RET_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, SOFTBUS_LOCK_ERR, TRANS_CTRL, "lock mutex fail!"); + ProxyChannelInfo *item = NULL; ProxyChannelInfo *nextNode = NULL; - if (g_proxyChannelList == NULL || chan == NULL) { - TRANS_LOGE(TRANS_CTRL, "trans proxy get channel param nullptr!"); - return SOFTBUS_INVALID_PARAM; - } - - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "lock mutex fail!"); - return SOFTBUS_LOCK_ERR; - } - LIST_FOR_EACH_ENTRY_SAFE(item, nextNode, &g_proxyChannelList->list, ProxyChannelInfo, node) { if (item->channelId == chanId) { if (memcpy_s(chan, sizeof(ProxyChannelInfo), item, sizeof(ProxyChannelInfo)) != EOK) { @@ -294,14 +261,10 @@ int32_t TransProxyGetChanByChanId(int32_t chanId, ProxyChannelInfo *chan) int32_t TransProxyGetChanByReqId(int32_t reqId, ProxyChannelInfo *chan) { ProxyChannelInfo *item = NULL; - if (g_proxyChannelList == NULL) { - return SOFTBUS_NO_INIT; - } - - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "lock mutex fail!"); - return SOFTBUS_LOCK_ERR; - } + TRANS_CHECK_AND_RETURN_RET_LOGE( + g_proxyChannelList != NULL, SOFTBUS_NO_INIT, TRANS_CTRL, "g_proxyChannelList is null"); + TRANS_CHECK_AND_RETURN_RET_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, SOFTBUS_LOCK_ERR, TRANS_CTRL, "lock mutex fail!"); LIST_FOR_EACH_ENTRY(item, &g_proxyChannelList->list, ProxyChannelInfo, node) { if (item->reqId == reqId && item->status == PROXY_CHANNEL_STATUS_PYH_CONNECTING) { @@ -318,14 +281,10 @@ void TransProxyDelChanByReqId(int32_t reqId, int32_t errCode) ProxyChannelInfo *item = NULL; ProxyChannelInfo *nextNode = NULL; - if (g_proxyChannelList == NULL) { - return; - } - - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "lock mutex fail!"); - return; - } + TRANS_CHECK_AND_RETURN_LOGE( + g_proxyChannelList != NULL, TRANS_CTRL, "g_proxyChannelList is null"); + TRANS_CHECK_AND_RETURN_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, TRANS_CTRL, "lock mutex fail!"); LIST_FOR_EACH_ENTRY_SAFE(item, nextNode, &g_proxyChannelList->list, ProxyChannelInfo, node) { if ((item->reqId == reqId) && @@ -348,14 +307,10 @@ void TransProxyDelChanByChanId(int32_t chanlId) ProxyChannelInfo *item = NULL; ProxyChannelInfo *nextNode = NULL; - if (g_proxyChannelList == NULL) { - return; - } - - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "lock mutex fail!"); - return; - } + TRANS_CHECK_AND_RETURN_LOGE( + g_proxyChannelList != NULL, TRANS_CTRL, "g_proxyChannelList is null"); + TRANS_CHECK_AND_RETURN_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, TRANS_CTRL, "lock mutex fail!"); LIST_FOR_EACH_ENTRY_SAFE(item, nextNode, &g_proxyChannelList->list, ProxyChannelInfo, node) { if (item->channelId == chanlId) { @@ -379,14 +334,10 @@ void TransProxyDelChanByChanId(int32_t chanlId) void TransProxyChanProcessByReqId(int32_t reqId, uint32_t connId) { ProxyChannelInfo *item = NULL; - if (g_proxyChannelList == NULL) { - return; - } - - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "lock mutex fail!"); - return; - } + TRANS_CHECK_AND_RETURN_LOGE( + g_proxyChannelList != NULL, TRANS_CTRL, "g_proxyChannelList is null"); + TRANS_CHECK_AND_RETURN_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, TRANS_CTRL, "lock mutex fail!"); bool isUsing = false; LIST_FOR_EACH_ENTRY(item, &g_proxyChannelList->list, ProxyChannelInfo, node) { @@ -425,9 +376,8 @@ static void TransProxyCloseProxyOtherRes(int32_t channelId, const ProxyChannelIn static void TransProxyReleaseChannelList(ListNode *proxyChannelList, int32_t errCode) { TRANS_LOGI(TRANS_CTRL, "enter."); - if (proxyChannelList == NULL || IsListEmpty(proxyChannelList)) { - return; - } + TRANS_CHECK_AND_RETURN_LOGE((g_proxyChannelList != NULL && !IsListEmpty(proxyChannelList)), TRANS_CTRL, + "g_proxyChannelList is null or empty"); ProxyChannelInfo *removeNode = NULL; ProxyChannelInfo *nextNode = NULL; LIST_FOR_EACH_ENTRY_SAFE(removeNode, nextNode, proxyChannelList, ProxyChannelInfo, node) { @@ -451,14 +401,10 @@ void TransProxyDelByConnId(uint32_t connId) ProxyChannelInfo *nextNode = NULL; ListNode proxyChannelList; - if (g_proxyChannelList == NULL) { - return; - } - - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "lock mutex fail!"); - return; - } + TRANS_CHECK_AND_RETURN_LOGE( + g_proxyChannelList != NULL, TRANS_CTRL, "g_proxyChannelList is null"); + TRANS_CHECK_AND_RETURN_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, TRANS_CTRL, "lock mutex fail!"); ListInit(&proxyChannelList); LIST_FOR_EACH_ENTRY_SAFE(removeNode, nextNode, &g_proxyChannelList->list, ProxyChannelInfo, node) { @@ -479,14 +425,10 @@ static int32_t TransProxyDelByChannelId(int32_t channelId, ProxyChannelInfo *cha ProxyChannelInfo *removeNode = NULL; ProxyChannelInfo *nextNode = NULL; - if (g_proxyChannelList == NULL) { - return SOFTBUS_NO_INIT; - } - - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "lock mutex fail!"); - return SOFTBUS_LOCK_ERR; - } + TRANS_CHECK_AND_RETURN_RET_LOGE( + g_proxyChannelList != NULL, SOFTBUS_NO_INIT, TRANS_CTRL, "g_proxyChannelList is null"); + TRANS_CHECK_AND_RETURN_RET_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, SOFTBUS_LOCK_ERR, TRANS_CTRL, "lock mutex fail!"); LIST_FOR_EACH_ENTRY_SAFE(removeNode, nextNode, &g_proxyChannelList->list, ProxyChannelInfo, node) { if (removeNode->channelId == channelId) { @@ -514,14 +456,10 @@ static int32_t TransProxyResetChan(ProxyChannelInfo *chanInfo) ProxyChannelInfo *removeNode = NULL; ProxyChannelInfo *nextNode = NULL; - if (g_proxyChannelList == NULL) { - return SOFTBUS_NO_INIT; - } - - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "lock mutex fail!"); - return SOFTBUS_LOCK_ERR; - } + TRANS_CHECK_AND_RETURN_RET_LOGE( + g_proxyChannelList != NULL, SOFTBUS_NO_INIT, TRANS_CTRL, "g_proxyChannelList is null"); + TRANS_CHECK_AND_RETURN_RET_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, SOFTBUS_LOCK_ERR, TRANS_CTRL, "lock mutex fail!"); LIST_FOR_EACH_ENTRY_SAFE(removeNode, nextNode, &g_proxyChannelList->list, ProxyChannelInfo, node) { if (ResetChanIsEqual(removeNode->status, removeNode, chanInfo)) { @@ -551,14 +489,10 @@ static int32_t TransProxyGetRecvMsgChanInfo(int16_t myId, int16_t peerId, ProxyC { ProxyChannelInfo *item = NULL; - if (g_proxyChannelList == NULL) { - return SOFTBUS_NO_INIT; - } - - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "lock mutex fail!"); - return SOFTBUS_LOCK_ERR; - } + TRANS_CHECK_AND_RETURN_RET_LOGE( + g_proxyChannelList != NULL, SOFTBUS_NO_INIT, TRANS_CTRL, "g_proxyChannelList is null"); + TRANS_CHECK_AND_RETURN_RET_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, SOFTBUS_LOCK_ERR, TRANS_CTRL, "lock mutex fail!"); LIST_FOR_EACH_ENTRY(item, &g_proxyChannelList->list, ProxyChannelInfo, node) { if ((item->myId == myId) && (item->peerId == peerId)) { @@ -582,14 +516,10 @@ static int32_t TransProxyKeepAliveChan(ProxyChannelInfo *chanInfo) { ProxyChannelInfo *item = NULL; - if (g_proxyChannelList == NULL) { - return SOFTBUS_NO_INIT; - } - - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "lock mutex fail!"); - return SOFTBUS_LOCK_ERR; - } + TRANS_CHECK_AND_RETURN_RET_LOGE( + g_proxyChannelList != NULL, SOFTBUS_NO_INIT, TRANS_CTRL, "g_proxyChannelList is null"); + TRANS_CHECK_AND_RETURN_RET_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, SOFTBUS_LOCK_ERR, TRANS_CTRL, "lock mutex fail!"); LIST_FOR_EACH_ENTRY(item, &g_proxyChannelList->list, ProxyChannelInfo, node) { if (ChanIsEqual(item, chanInfo)) { @@ -614,14 +544,10 @@ int32_t TransProxyGetSendMsgChanInfo(int32_t channelId, ProxyChannelInfo *chanIn { ProxyChannelInfo *item = NULL; - if (g_proxyChannelList == NULL) { - return SOFTBUS_NO_INIT; - } - - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "lock mutex fail!"); - return SOFTBUS_LOCK_ERR; - } + TRANS_CHECK_AND_RETURN_RET_LOGE( + g_proxyChannelList != NULL, SOFTBUS_NO_INIT, TRANS_CTRL, "g_proxyChannelList is null"); + TRANS_CHECK_AND_RETURN_RET_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, SOFTBUS_LOCK_ERR, TRANS_CTRL, "lock mutex fail!"); LIST_FOR_EACH_ENTRY(item, &g_proxyChannelList->list, ProxyChannelInfo, node) { if (item->channelId == channelId) { @@ -646,14 +572,10 @@ int32_t TransProxyGetNewChanSeq(int32_t channelId) ProxyChannelInfo *item = NULL; int32_t seq = 0; - if (g_proxyChannelList == NULL) { - return seq; - } - - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "lock mutex fail!"); - return seq; - } + TRANS_CHECK_AND_RETURN_RET_LOGE( + g_proxyChannelList != NULL, seq, TRANS_CTRL, "g_proxyChannelList is null"); + TRANS_CHECK_AND_RETURN_RET_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, seq, TRANS_CTRL, "lock mutex fail!"); LIST_FOR_EACH_ENTRY(item, &g_proxyChannelList->list, ProxyChannelInfo, node) { if (item->channelId == channelId) { @@ -669,20 +591,13 @@ int32_t TransProxyGetNewChanSeq(int32_t channelId) int32_t TransProxyGetAuthId(int32_t channelId, AuthHandle *authHandle) { - if (authHandle == NULL) { - return SOFTBUS_INVALID_PARAM; - } + TRANS_CHECK_AND_RETURN_RET_LOGE( + authHandle != NULL, SOFTBUS_INVALID_PARAM, TRANS_CTRL, "authHandle is null"); ProxyChannelInfo *item = NULL; - if (g_proxyChannelList == NULL) { - TRANS_LOGE(TRANS_CTRL, "g_proxyChannelList is null"); - return SOFTBUS_NO_INIT; - } - - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "lock mutex fail!"); - return SOFTBUS_LOCK_ERR; - } - + TRANS_CHECK_AND_RETURN_RET_LOGE( + g_proxyChannelList != NULL, SOFTBUS_NO_INIT, TRANS_CTRL, "g_proxyChannelList is null"); + TRANS_CHECK_AND_RETURN_RET_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, SOFTBUS_LOCK_ERR, TRANS_CTRL, "lock mutex fail!"); LIST_FOR_EACH_ENTRY(item, &g_proxyChannelList->list, ProxyChannelInfo, node) { if (item->channelId == channelId) { *authHandle = item->authHandle; @@ -696,22 +611,13 @@ int32_t TransProxyGetAuthId(int32_t channelId, AuthHandle *authHandle) int32_t TransProxyGetSessionKeyByChanId(int32_t channelId, char *sessionKey, uint32_t sessionKeySize) { - if (sessionKey == NULL) { - TRANS_LOGE(TRANS_CTRL, "invalid param"); - return SOFTBUS_INVALID_PARAM; - } - - if (g_proxyChannelList == NULL) { - TRANS_LOGE(TRANS_CTRL, "proxy channel list not init"); - return SOFTBUS_NO_INIT; - } - + TRANS_CHECK_AND_RETURN_RET_LOGE( + sessionKey != NULL, SOFTBUS_INVALID_PARAM, TRANS_CTRL, "sessionKey is null"); ProxyChannelInfo *item = NULL; - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "lock mutex fail!"); - return SOFTBUS_LOCK_ERR; - } - + TRANS_CHECK_AND_RETURN_RET_LOGE( + g_proxyChannelList != NULL, SOFTBUS_NO_INIT, TRANS_CTRL, "g_proxyChannelList is null"); + TRANS_CHECK_AND_RETURN_RET_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, SOFTBUS_LOCK_ERR, TRANS_CTRL, "lock mutex fail!"); LIST_FOR_EACH_ENTRY(item, &g_proxyChannelList->list, ProxyChannelInfo, node) { if (item->channelId == channelId) { if (item->status == PROXY_CHANNEL_STATUS_COMPLETED) { @@ -735,12 +641,8 @@ int32_t TransProxyGetSessionKeyByChanId(int32_t channelId, char *sessionKey, uin static inline void TransProxyProcessErrMsg(ProxyChannelInfo *info, int32_t errCode) { TRANS_LOGW(TRANS_CTRL, "TransProxyProcessErrMsg errCode=%{public}d", errCode); - - if (TransProxyGetChanByChanId(info->myId, info) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "TransProxyGetChanByChanId fail"); - return; - } - + TRANS_CHECK_AND_RETURN_LOGE( + TransProxyGetChanByChanId(info->myId, info) == SOFTBUS_OK, TRANS_CTRL, "TransProxyGetChanByChanId fail"); if ((info->appInfo.appType == APP_TYPE_NORMAL) || (info->appInfo.appType == APP_TYPE_AUTH)) { TransProxyDelChanByChanId(info->channelId); (void)TransProxyOpenProxyChannelFail(info->channelId, &(info->appInfo), errCode); @@ -751,14 +653,10 @@ static int32_t TransProxyGetAppInfo(int16_t myId, AppInfo *appInfo) { ProxyChannelInfo *item = NULL; - if (g_proxyChannelList == NULL) { - return SOFTBUS_NO_INIT; - } - - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "lock mutex fail!"); - return SOFTBUS_LOCK_ERR; - } + TRANS_CHECK_AND_RETURN_RET_LOGE( + g_proxyChannelList != NULL, SOFTBUS_NO_INIT, TRANS_CTRL, "g_proxyChannelList is null"); + TRANS_CHECK_AND_RETURN_RET_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, SOFTBUS_LOCK_ERR, TRANS_CTRL, "lock mutex fail!"); LIST_FOR_EACH_ENTRY(item, &g_proxyChannelList->list, ProxyChannelInfo, node) { if (item->myId == myId) { @@ -1790,14 +1688,10 @@ void TransProxyTimerProc(void) ProxyChannelInfo *nextNode = NULL; ListNode proxyProcList; - if (g_proxyChannelList == NULL) { - TRANS_LOGD(TRANS_INIT, "g_proxyChannelList is null or empty"); - return; - } - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_INIT, "lock mutex fail"); - return; - } + TRANS_CHECK_AND_RETURN_LOGE( + g_proxyChannelList != NULL, TRANS_CTRL, "g_proxyChannelList is null"); + TRANS_CHECK_AND_RETURN_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, TRANS_CTRL, "lock mutex fail!"); if (g_proxyChannelList->cnt <= 0) { (void)SoftBusMutexUnlock(&g_proxyChannelList->lock); return; @@ -1956,15 +1850,10 @@ int32_t TransProxyManagerInit(const IServerChannelCallBack *cb) int32_t TransProxyGetNameByChanId(int32_t chanId, char *pkgName, char *sessionName, uint16_t pkgLen, uint16_t sessionLen) { - if (pkgName == NULL || sessionName == NULL) { - TRANS_LOGE(TRANS_CTRL, "invalid param"); - return SOFTBUS_INVALID_PARAM; - } + TRANS_CHECK_AND_RETURN_RET_LOGE((pkgName != NULL && sessionName != NULL), SOFTBUS_INVALID_PARAM, TRANS_CTRL, + "invalid param"); ProxyChannelInfo *chan = (ProxyChannelInfo *)SoftBusCalloc(sizeof(ProxyChannelInfo)); - if (chan == NULL) { - TRANS_LOGE(TRANS_CTRL, "malloc err"); - return SOFTBUS_MALLOC_ERR; - } + TRANS_CHECK_AND_RETURN_RET_LOGE(chan != NULL, SOFTBUS_MALLOC_ERR, TRANS_CTRL, "malloc err"); int32_t ret = TransProxyGetChanByChanId(chanId, chan); (void)memset_s(chan->appInfo.sessionKey, sizeof(chan->appInfo.sessionKey), 0, sizeof(chan->appInfo.sessionKey)); if (ret != SOFTBUS_OK) { @@ -1989,16 +1878,12 @@ int32_t TransProxyGetNameByChanId(int32_t chanId, char *pkgName, char *sessionNa static void TransProxyManagerDeinitInner(void) { - if (g_proxyChannelList == NULL) { - TRANS_LOGW(TRANS_INIT, "g_proxyChannelList is null"); - return; - } + TRANS_CHECK_AND_RETURN_LOGE( + g_proxyChannelList != NULL, TRANS_INIT, "g_proxyChannelList is null"); + TRANS_CHECK_AND_RETURN_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, TRANS_INIT, "lock mutex fail!"); ProxyChannelInfo *item = NULL; ProxyChannelInfo *nextNode = NULL; - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_INIT, "lock mutex fail!"); - return; - } LIST_FOR_EACH_ENTRY_SAFE(item, nextNode, &g_proxyChannelList->list, ProxyChannelInfo, node) { ReleaseProxyChannelId(item->channelId); ListDelete(&(item->node)); @@ -2022,10 +1907,8 @@ void TransProxyManagerDeinit(void) static void TransProxyDestroyChannelList(const ListNode *destroyList) { TRANS_LOGD(TRANS_CTRL, "enter."); - if ((destroyList == NULL) || IsListEmpty(destroyList)) { - return; - } - + TRANS_CHECK_AND_RETURN_LOGE( + (destroyList != NULL && !IsListEmpty(destroyList)), TRANS_INIT, "destroyList is null"); ProxyChannelInfo *destroyNode = NULL; ProxyChannelInfo *nextDestroyNode = NULL; LIST_FOR_EACH_ENTRY_SAFE(destroyNode, nextDestroyNode, destroyList, ProxyChannelInfo, node) { @@ -2044,10 +1927,8 @@ static void TransProxyDestroyChannelList(const ListNode *destroyList) void TransProxyDeathCallback(const char *pkgName, int32_t pid) { - if ((pkgName == NULL) || (g_proxyChannelList == NULL)) { - TRANS_LOGE(TRANS_CTRL, "pkgName or proxy channel list is null."); - return; - } + TRANS_CHECK_AND_RETURN_LOGE( + (pkgName != NULL && g_proxyChannelList != NULL), TRANS_CTRL, "pkgName or proxy channel list is null."); TRANS_LOGW(TRANS_CTRL, "TransProxyDeathCallback: pkgName=%{public}s, pid=%{public}d", pkgName, pid); ListNode destroyList; ListInit(&destroyList); @@ -2073,21 +1954,16 @@ void TransProxyDeathCallback(const char *pkgName, int32_t pid) int32_t TransProxyGetAppInfoByChanId(int32_t chanId, AppInfo *appInfo) { - if (appInfo == NULL) { - TRANS_LOGE(TRANS_CTRL, "param invalid"); - return SOFTBUS_INVALID_PARAM; - } + TRANS_CHECK_AND_RETURN_RET_LOGE(appInfo != NULL, SOFTBUS_INVALID_PARAM, TRANS_CTRL, + "invalid param"); + ProxyChannelInfo *item = NULL; ProxyChannelInfo *nextNode = NULL; - if (g_proxyChannelList == NULL) { - return SOFTBUS_NO_INIT; - } - - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "lock mutex fail!"); - return SOFTBUS_LOCK_ERR; - } + TRANS_CHECK_AND_RETURN_RET_LOGE( + g_proxyChannelList != NULL, SOFTBUS_NO_INIT, TRANS_CTRL, "g_proxyChannelList is null"); + TRANS_CHECK_AND_RETURN_RET_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, SOFTBUS_LOCK_ERR, TRANS_CTRL, "lock mutex fail!"); LIST_FOR_EACH_ENTRY_SAFE(item, nextNode, &g_proxyChannelList->list, ProxyChannelInfo, node) { if (item->channelId == chanId) { @@ -2107,18 +1983,16 @@ 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_NO_INIT; - } + TRANS_CHECK_AND_RETURN_RET_LOGE(connId != NULL, SOFTBUS_INVALID_PARAM, TRANS_CTRL, + "invalid param"); + ProxyChannelInfo *item = NULL; - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "lock mutex fail!"); - return SOFTBUS_LOCK_ERR; - } + + TRANS_CHECK_AND_RETURN_RET_LOGE( + g_proxyChannelList != NULL, SOFTBUS_NO_INIT, TRANS_CTRL, "g_proxyChannelList is null"); + TRANS_CHECK_AND_RETURN_RET_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, SOFTBUS_LOCK_ERR, TRANS_CTRL, "lock mutex fail!"); + LIST_FOR_EACH_ENTRY(item, &g_proxyChannelList->list, ProxyChannelInfo, node) { if (item->channelId == channelId) { if (item->status == PROXY_CHANNEL_STATUS_COMPLETED || @@ -2139,10 +2013,8 @@ int32_t TransProxyGetConnIdByChanId(int32_t channelId, int32_t *connId) int32_t TransProxyGetConnOptionByChanId(int32_t channelId, ConnectOption *connOpt) { - if (connOpt == NULL) { - TRANS_LOGW(TRANS_CTRL, "invalid param."); - return SOFTBUS_INVALID_PARAM; - } + TRANS_CHECK_AND_RETURN_RET_LOGE(connOpt != NULL, SOFTBUS_INVALID_PARAM, TRANS_CTRL, + "invalid param"); int32_t connId = -1; int32_t ret = TransProxyGetConnIdByChanId(channelId, &connId); @@ -2164,15 +2036,10 @@ int32_t TransProxySetAuthHandleByChanId(int32_t channelId, AuthHandle authHandle ProxyChannelInfo *item = NULL; ProxyChannelInfo *nextNode = NULL; - if (g_proxyChannelList == NULL) { - TRANS_LOGE(TRANS_CTRL, "trans proxy get channel param nullptr."); - return SOFTBUS_NO_INIT; - } - - if (SoftBusMutexLock(&g_proxyChannelList->lock) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_CTRL, "lock mutex fail."); - return SOFTBUS_LOCK_ERR; - } + TRANS_CHECK_AND_RETURN_RET_LOGE( + g_proxyChannelList != NULL, SOFTBUS_NO_INIT, TRANS_CTRL, "g_proxyChannelList is null"); + TRANS_CHECK_AND_RETURN_RET_LOGE( + SoftBusMutexLock(&g_proxyChannelList->lock) == SOFTBUS_OK, SOFTBUS_LOCK_ERR, TRANS_CTRL, "lock mutex fail!"); LIST_FOR_EACH_ENTRY_SAFE(item, nextNode, &g_proxyChannelList->list, ProxyChannelInfo, node) { if (item->channelId == channelId) { 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 ff5421af1..ae540449c 100644 --- a/core/transmission/trans_channel/proxy/src/softbus_proxychannel_message.c +++ b/core/transmission/trans_channel/proxy/src/softbus_proxychannel_message.c @@ -82,14 +82,18 @@ static int32_t GetRemoteUdidByBtMac(const char *peerMac, char *udid, int32_t len char networkId[NETWORK_ID_BUF_LEN] = {0}; char *tmpMac = NULL; Anonymize(peerMac, &tmpMac); - AnonymizeFree(tmpMac); int32_t ret = LnnGetNetworkIdByBtMac(peerMac, networkId, sizeof(networkId)); - TRANS_CHECK_AND_RETURN_RET_LOGE( - ret == SOFTBUS_OK, ret, TRANS_CTRL, "LnnGetNetworkIdByBtMac fail, peerMac=%{public}s", tmpMac); + if (ret != SOFTBUS_OK) { + TRANS_LOGE(TRANS_CTRL, "LnnGetNetworkIdByBtMac fail, peerMac=%{public}s", tmpMac); + AnonymizeFree(tmpMac); + return ret; + } ret = LnnGetRemoteStrInfo(networkId, STRING_KEY_DEV_UDID, udid, len); - TRANS_CHECK_AND_RETURN_RET_LOGE( - ret == SOFTBUS_OK, ret, TRANS_CTRL, "LnnGetRemoteStrInfo UDID fail, peerMac=%{public}s", tmpMac); - return SOFTBUS_OK; + if (ret != SOFTBUS_OK) { + TRANS_LOGE(TRANS_CTRL, "LnnGetRemoteStrInfo UDID fail, peerMac=%{public}s", tmpMac); + } + AnonymizeFree(tmpMac); + return ret; } static int32_t GetRemoteBtMacByUdidHash(const uint8_t *udidHash, uint32_t udidHashLen, char *brMac, int32_t len) diff --git a/interfaces/kits/bus_center/softbus_bus_center.h b/interfaces/kits/bus_center/softbus_bus_center.h index e46b1b63e..6c776e295 100644 --- a/interfaces/kits/bus_center/softbus_bus_center.h +++ b/interfaces/kits/bus_center/softbus_bus_center.h @@ -459,6 +459,15 @@ typedef struct { * @version 1.0 */ void (*onLocalNetworkIdChanged)(void); + /** + * @brief Called when the device is not trusted. + * + * @param msg Indicates the pointer to untrusted device information. + * + * @since 1.0 + * @version 1.0 + */ + void (*onNodeDeviceNotTrusted)(const char *msg); /** * @brief Called when the running status of a device changes. * diff --git a/interfaces/kits/common/softbus_error_code.h b/interfaces/kits/common/softbus_error_code.h index 30f4847a2..48b104a14 100644 --- a/interfaces/kits/common/softbus_error_code.h +++ b/interfaces/kits/common/softbus_error_code.h @@ -153,6 +153,8 @@ enum SoftBusErrNo { SOFTBUS_COND_INIT_FAILED, SOFTBUS_GET_SYSTIME_FAILED, SOFTBUS_BYTE_CONVERT_FAIL, + SOFTBUS_GENERATE_KEY_FAIL, + SOFTBUS_GCM_SET_IV_FAIL, // set ivlen fail for aes-gcm encrypt /* errno begin: -((203 << 21) | (5 << 16) | 0xFFFF) */ SOFTBUS_TRANS_ERR_BASE = SOFTBUS_ERRNO(TRANS_SUB_MODULE_CODE), @@ -442,6 +444,10 @@ enum SoftBusErrNo { SOFTBUS_AUTH_ADD_PTK_LISTEN_ERR, SOFTBUS_AUTH_META_INIT_FAIL, SOFTBUS_AUTH_SYNC_DEVINFO_ACK_FAIL, + SOFTBUS_CHANNEL_AUTH_INVALID_PROTOCOL, + SOFTBUS_CHANNEL_AUTH_START_TIMEOUT, + SOFTBUS_CHANNEL_AUTH_HANDLE_DATA_FAIL, + SOFTBUS_CHANNEL_AUTH_PACK_DATA_FAIL, /* errno begin: -((203 << 21) | (4 << 16) | 0xFFFF) */ SOFTBUS_NETWORK_ERR_BASE = SOFTBUS_ERRNO(LNN_SUB_MODULE_CODE), @@ -537,6 +543,7 @@ enum SoftBusErrNo { SOFTBUS_LANE_WIFI_BAND_ERR, SOFTBUS_LANE_GET_WIFI_INFO_FAIL, SOFTBUS_LANE_CHANNEL_UNKNOWN, + SOFTBUS_LANE_SUCC_AFTER_CANCELED, /* errno begin: -((203 << 21) | (2 << 16) | 0xFFFF) */ SOFTBUS_CONN_ERR_BASE = SOFTBUS_ERRNO(CONN_SUB_MODULE_CODE), @@ -818,6 +825,7 @@ enum SoftBusErrNo { SOFTBUS_CONN_NO_WIFI_CONFIG_INFO = SOFTBUS_CONN_ERR_BASE + 703, SOFTBUS_CONN_HV3_WAIT_CONNECTION_TIMEOUT = SOFTBUS_CONN_ERR_BASE + 704, SOFTBUS_CONN_HV3_WAITING_HANDSHAKE_RESPONSE_TIMEOUT = SOFTBUS_CONN_ERR_BASE + 705, + SOFTBUS_CONN_HV2_SWITCHED_CONNECT_TIMEOUT = SOFTBUS_CONN_ERR_BASE + 706, /* soft bus connection mapping short range conflict error code */ SOFTBUS_CONN_SHORT_RANGE_BASE = SOFTBUS_CONN_ERR_BASE + 1000, @@ -854,6 +862,84 @@ enum SoftBusErrNo { SOFTBUS_CONN_ACTIVE_TYPE_HML_NUM_LIMITED_CONFLICT = SOFTBUS_CONN_ERR_BASE + 1031, SOFTBUS_CONN_PASSIVE_TYPE_HML_NUM_LIMITED_CONFLICT = SOFTBUS_CONN_ERR_BASE + 1032, + /* soft bus connection legacy modules error code */ + SOFTBUS_CONN_NEARBY_CONTROL_CHANNEL_CONNECT_FAILED = SOFTBUS_CONN_ERR_BASE + 2000, + SOFTBUS_CONN_NEARBY_CONTROL_CHANNEL_DATA_EXCEPTION = SOFTBUS_CONN_ERR_BASE + 2001, + SOFTBUS_CONN_NEARBY_NO_AVAILABLE_DATA_CHANNEL = SOFTBUS_CONN_ERR_BASE + 2002, + SOFTBUS_CONN_NEARBY_DEVICE_CONNECT_FAILED = SOFTBUS_CONN_ERR_BASE + 2003, + SOFTBUS_CONN_NEARBY_DATA_SEND_FAILED = SOFTBUS_CONN_ERR_BASE + 2004, + SOFTBUS_CONN_NEARBY_SAME_BID_BTAG = SOFTBUS_CONN_ERR_BASE + 2005, + SOFTBUS_CONN_NEARBY_TIMEOUT = SOFTBUS_CONN_ERR_BASE + 2006, + SOFTBUS_CONN_NEARBY_PEER_DEVICE_BUSY = SOFTBUS_CONN_ERR_BASE + 2007, + SOFTBUS_CONN_NEARBY_LOCAL_DEVICE_BUSY = SOFTBUS_CONN_ERR_BASE + 2008, + SOFTBUS_CONN_NEARBY_ERROR_PEER_DEVICE_IMPORT_DATA = SOFTBUS_CONN_ERR_BASE + 2009, + SOFTBUS_CONN_NEARBY_PEER_DEVICE_HOSTSPOT_ON = SOFTBUS_CONN_ERR_BASE + 2010, + SOFTBUS_CONN_NEARBY_LOCAL_DEVICE_HOSTSPOT_ON = SOFTBUS_CONN_ERR_BASE + 2011, + SOFTBUS_CONN_NEARBY_PEER_SHARE_BUSY = SOFTBUS_CONN_ERR_BASE + 2012, + SOFTBUS_CONN_NEARBY_CREATE_SOCKET_TIMEOUT = SOFTBUS_CONN_ERR_BASE + 2013, + SOFTBUS_CONN_NEARBY_CLIENT_CONNECT_FAILED = SOFTBUS_CONN_ERR_BASE + 2014, + SOFTBUS_CONN_NEARBY_MESSAGE_OPEN_NEARBY_SOCKET_TIMEOUT = SOFTBUS_CONN_ERR_BASE + 2015, + SOFTBUS_CONN_NEARBY_MESSAGE_REMOTE_REJECTED = SOFTBUS_CONN_ERR_BASE + 2016, + SOFTBUS_CONN_NEARBY_CONFLICT_REUSE_FAIL = SOFTBUS_CONN_ERR_BASE + 2017, + SOFTBUS_CONN_NEARBY_ROLE_LOCAL_ALREADY_GC = SOFTBUS_CONN_ERR_BASE + 2018, + SOFTBUS_CONN_NEARBY_DATACHANNEL_LOCAL_BUSY = SOFTBUS_CONN_ERR_BASE + 2019, + SOFTBUS_CONN_LEGACY_CONFLICT_NOTIFY_DISCONENCT = SOFTBUS_CONN_ERR_BASE + 2020, + + SOFTBUS_CONN_LEGACY_BLE_CONNECT_TIMEOUT_ERR = SOFTBUS_CONN_ERR_BASE + 2200, + SOFTBUS_CONN_LEGACY_BLE_CONNECT_INTERNAL_ERR = SOFTBUS_CONN_ERR_BASE + 2201, + SOFTBUS_CONN_LEGACY_BLE_INTERNAL_ERR = SOFTBUS_CONN_ERR_BASE + 2202, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_CLIENT_REGISTER_ERR = SOFTBUS_CONN_ERR_BASE + 2203, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_CLIENT_CONNECT_ERR = SOFTBUS_CONN_ERR_BASE + 2204, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_CLIENT_CONNECT_FAIL = SOFTBUS_CONN_ERR_BASE + 2205, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_CLIENT_SEARCH_SERVICE_ERR = SOFTBUS_CONN_ERR_BASE + 2206, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_CLIENT_SEARCH_SERVICE_FAIL = SOFTBUS_CONN_ERR_BASE + 2207, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_CLIENT_GET_SERVICE_ERR = SOFTBUS_CONN_ERR_BASE + 2208, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_CLIENT_REGISTER_NOTIFICATION_ERR = SOFTBUS_CONN_ERR_BASE + 2209, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_CLIENT_REGISTER_NOTIFICATION_FAIL = SOFTBUS_CONN_ERR_BASE + 2210, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_CLIENT_CONFIGURE_MTU_ERR = SOFTBUS_CONN_ERR_BASE + 2211, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_CLIENT_CONFIGURE_MTU_FAIL = SOFTBUS_CONN_ERR_BASE + 2212, + SOFTBUS_CONN_LEGACY_BLE_DISCONNECT_DIRECTLY_ERR = SOFTBUS_CONN_ERR_BASE + 2213, + SOFTBUS_CONN_LEGACY_BLE_DISCONNECT_WAIT_TIMEOUT_ERR = SOFTBUS_CONN_ERR_BASE + 2214, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_SERVER_REGISTER_CALLBACK_ERR = SOFTBUS_CONN_ERR_BASE + 2215, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_SERVER_ADD_SERVICE_ERR = SOFTBUS_CONN_ERR_BASE + 2216, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_SERVER_ADD_SERVICE_FAIL = SOFTBUS_CONN_ERR_BASE + 2217, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_UNKNOWN_SERVICE_ERR = SOFTBUS_CONN_ERR_BASE + 2218, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_CHARACTERISTIC_ADD_ERR = SOFTBUS_CONN_ERR_BASE + 2219, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_CHARACTERISTIC_ADD_FAIL = SOFTBUS_CONN_ERR_BASE + 2220, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_DESCRIPTOR_ADD_ERR = SOFTBUS_CONN_ERR_BASE + 2221, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_SERVICE_HANDLE_MISMATCH_ERR = SOFTBUS_CONN_ERR_BASE + 2222, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_SERVICE_START_ERR = SOFTBUS_CONN_ERR_BASE + 2223, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_SERVICE_START_FAIL = SOFTBUS_CONN_ERR_BASE + 2224, + SOFTBUS_CONN_LEGACY_BLE_SERVER_STATE_UNEXPECTED_ERR = SOFTBUS_CONN_ERR_BASE + 2225, + SOFTBUS_CONN_LEGACY_BLE_SERVER_START_SERVER_TIMEOUT_ERR = SOFTBUS_CONN_ERR_BASE + 2226, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_SERVICE_STOP_ERR = SOFTBUS_CONN_ERR_BASE + 2227, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_SERVICE_STOP_FAIL = SOFTBUS_CONN_ERR_BASE + 2228, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_SERVICE_DELETE_ERR = SOFTBUS_CONN_ERR_BASE + 2229, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_SERVICE_DELETE_FAIL = SOFTBUS_CONN_ERR_BASE + 2230, + SOFTBUS_CONN_LEGACY_BLE_SERVER_STOP_SERVER_TIMEOUT_ERR = SOFTBUS_CONN_ERR_BASE + 2231, + SOFTBUS_CONN_LEGACY_BLE_CLIENT_STATE_UNEXPECTED_ERR = SOFTBUS_CONN_ERR_BASE + 2232, + SOFTBUS_CONN_LEGACY_BLE_REPEAT_CONNECT_ERR = SOFTBUS_CONN_ERR_BASE + 2233, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_DESCRIPTOR_ADD_FAIL = SOFTBUS_CONN_ERR_BASE + 2234, + SOFTBUS_CONN_LEGACY_BLE_UNDERLAY_UNKNOWN_DESCRIPTOR_ERR = SOFTBUS_CONN_ERR_BASE + 2235, + + SOFTBUS_CONN_LEGACY_HML_UNDERLAY_EXCEPTION = SOFTBUS_CONN_ERR_BASE + 2400, + SOFTBUS_CONN_LEGACY_HML_SOCKET_CONNECT_TIMEOUT = SOFTBUS_CONN_ERR_BASE + 2401, + SOFTBUS_CONN_LEGACY_P2P_SEND_GET_GC_MAC_REQ_FAIL = SOFTBUS_CONN_ERR_BASE + 2402, + SOFTBUS_CONN_LEGACY_P2P_CONNECT_DEVICE_FAIL = SOFTBUS_CONN_ERR_BASE + 2403, + SOFTBUS_CONN_LEGACY_P2P_DISCONNECT_DEVICE_FAIL = SOFTBUS_CONN_ERR_BASE + 2404, + SOFTBUS_CONN_LEGACY_P2P_REUSE_LINK_FAIL = SOFTBUS_CONN_ERR_BASE + 2405, + SOFTBUS_CONN_LEGACY_P2P_COMMAND_SET_DATA_FAIL = SOFTBUS_CONN_ERR_BASE + 2406, + SOFTBUS_CONN_LEGACY_P2P_SEND_COMMAND_FAIL = SOFTBUS_CONN_ERR_BASE + 2407, + SOFTBUS_CONN_LEGACY_P2P_START_SERVER_SOCKET_FAIL = SOFTBUS_CONN_ERR_BASE + 2408, + SOFTBUS_CONN_LEGACY_P2P_GO_SEND_CONFIG_INFO_FAIL = SOFTBUS_CONN_ERR_BASE + 2409, + SOFTBUS_CONN_LEGACY_P2P_CREATE_GROUP_FAIL = SOFTBUS_CONN_ERR_BASE + 2410, + SOFTBUS_CONN_LEGACY_P2P_CREATE_GROUP_TIMEOUT = SOFTBUS_CONN_ERR_BASE + 2411, + SOFTBUS_CONN_LEGACY_P2P_CONNECT_GROUP_FAIL = SOFTBUS_CONN_ERR_BASE + 2412, + SOFTBUS_CONN_LEGACY_P2P_CONNECT_GROUP_TIMEOUT = SOFTBUS_CONN_ERR_BASE + 2413, + SOFTBUS_CONN_LEGACY_P2P_REMOVE_GROUP_FAIL = SOFTBUS_CONN_ERR_BASE + 2414, + SOFTBUS_CONN_LEGACY_P2P_ADD_SEVER_TCP_CHANNEL_FAIL = SOFTBUS_CONN_ERR_BASE + 2415, + SOFTBUS_CONN_LEGACY_P2P_NOT_AVAILABLE = SOFTBUS_CONN_ERR_BASE + 2416, + /* errno begin: -((203 << 21) | (1 << 16) | 0xFFFF) */ SOFTBUS_DISCOVER_ERR_BASE = SOFTBUS_ERRNO(DISC_SUB_MODULE_CODE), /* errno begin: -((203 << 21) | (1 << 16) | (1 << 12) | 0x0FFF) */ @@ -947,8 +1033,6 @@ enum SoftBusErrNo { SOFTBUS_DISCOVER_ACTION_START_FAILED, SOFTBUS_DISCOVER_ACTION_STOP_FAILED, SOFTBUS_DISCOVER_ACTION_REPLY_FAILED, - SOFTBUS_DISCOVER_ACTION_REPEAT_TYPE, - SOFTBUS_DISCOVER_ACTION_HAD_PRELINK, /* softbus ok */ SOFTBUS_OK = 0, diff --git a/interfaces/kits/transport/trans_type.h b/interfaces/kits/transport/trans_type.h index b4d6609e9..cd9e39e38 100644 --- a/interfaces/kits/transport/trans_type.h +++ b/interfaces/kits/transport/trans_type.h @@ -261,6 +261,33 @@ typedef enum { OPT_LEVEL_SOFTBUS, /**< @reserved Softbus level option. */ OPT_LEVEL_BUTT, } OptLevel; + +/** + * @brief Enumerate frame event status. + * + * @since 2.0 + * @version 2.0 + */ +typedef enum { + FRAME_UNSEND, + FRAME_SENDING, + FRAME_RETRING, + FRAME_RECEIVED, + FRAME_DROPPED, + FRAME_UNMANAGED, +} FrameEvtStatus; + +typedef struct { + int32_t seq; + int32_t level; + int32_t subSeqNum; + FrameEvtStatus status; + uint32_t interval; /**< frame sending interval */ + uint32_t queueUsage; /**< send queue percentage of use */ + uint32_t cachedFrameCnt; /**< frame count in VTP */ +} FrameEvtCbInfo; + +typedef int (*OnFrameEvt)(int fd, const FrameEvtCbInfo *info); #ifdef __cplusplus } #endif diff --git a/sdk/bus_center/manager/include/client_bus_center_manager.h b/sdk/bus_center/manager/include/client_bus_center_manager.h index e5056631c..52560d322 100644 --- a/sdk/bus_center/manager/include/client_bus_center_manager.h +++ b/sdk/bus_center/manager/include/client_bus_center_manager.h @@ -59,6 +59,7 @@ int32_t LnnOnLeaveResult(const char *networkId, int32_t retCode); int32_t LnnOnNodeOnlineStateChanged(const char *pkgName, bool isOnline, void *info); int32_t LnnOnNodeBasicInfoChanged(const char *pkgName, void *info, int32_t type); int32_t LnnOnLocalNetworkIdChanged(const char *pkgName); +int32_t LnnOnNodeDeviceNotTrusted(const char *pkgName, const char *msg); int32_t LnnOnTimeSyncResult(const void *info, int32_t retCode); void LnnOnPublishLNNResult(int32_t publishId, int32_t reason); void LnnOnRefreshLNNResult(int32_t refreshId, int32_t reason); diff --git a/sdk/bus_center/manager/src/client_bus_center_manager.c b/sdk/bus_center/manager/src/client_bus_center_manager.c index 861488cb7..23d06629f 100644 --- a/sdk/bus_center/manager/src/client_bus_center_manager.c +++ b/sdk/bus_center/manager/src/client_bus_center_manager.c @@ -1212,6 +1212,39 @@ int32_t LnnOnLocalNetworkIdChanged(const char *pkgName) return SOFTBUS_OK; } +int32_t LnnOnNodeDeviceNotTrusted(const char *pkgName, const char *msg) +{ + NodeStateCallbackItem *item = NULL; + ListNode dupList; + + if (pkgName == NULL) { + LNN_LOGE(LNN_STATE, "pkgName is null"); + return SOFTBUS_INVALID_PARAM; + } + if (!g_busCenterClient.isInit) { + LNN_LOGE(LNN_STATE, "buscenter client not init"); + return SOFTBUS_NO_INIT; + } + + if (SoftBusMutexLock(&g_busCenterClient.lock) != SOFTBUS_OK) { + LNN_LOGE(LNN_STATE, "lock local cb list in notify"); + return SOFTBUS_LOCK_ERR; + } + ListInit(&dupList); + DuplicateNodeStateCbList(&dupList); + if (SoftBusMutexUnlock(&g_busCenterClient.lock) != SOFTBUS_OK) { + LNN_LOGE(LNN_STATE, "unlock local cb list in notify"); + } + LIST_FOR_EACH_ENTRY(item, &dupList, NodeStateCallbackItem, node) { + if (((strcmp(item->pkgName, pkgName) == 0) || (strlen(pkgName) == 0)) && + (item->cb.onNodeDeviceNotTrusted) != NULL) { + item->cb.onNodeDeviceNotTrusted(msg); + } + } + ClearNodeStateCbList(&dupList); + return SOFTBUS_OK; +} + int32_t LnnOnTimeSyncResult(const void *info, int32_t retCode) { TimeSyncCallbackItem *item = NULL; diff --git a/sdk/frame/standard/include/if_softbus_client.h b/sdk/frame/standard/include/if_softbus_client.h index 4be86db69..ce5b3065f 100644 --- a/sdk/frame/standard/include/if_softbus_client.h +++ b/sdk/frame/standard/include/if_softbus_client.h @@ -69,6 +69,8 @@ public: virtual int32_t OnLocalNetworkIdChanged(const char *pkgName); + virtual int32_t OnNodeDeviceNotTrusted(const char *pkgName, const char *msg); + virtual int32_t OnTimeSyncResult(const void *info, uint32_t infoTypeLen, int32_t retCode); virtual void OnPublishLNNResult(int32_t publishId, int32_t reason); diff --git a/sdk/frame/standard/include/softbus_client_stub.h b/sdk/frame/standard/include/softbus_client_stub.h index 65dacc0af..8774fb9aa 100644 --- a/sdk/frame/standard/include/softbus_client_stub.h +++ b/sdk/frame/standard/include/softbus_client_stub.h @@ -54,6 +54,7 @@ public: int32_t OnNodeOnlineStateChanged(const char *pkgName, bool isOnline, void *info, uint32_t infoTypeLen) override; int32_t OnNodeBasicInfoChanged(const char *pkgName, void *info, uint32_t infoTypeLen, int32_t type) override; int32_t OnLocalNetworkIdChanged(const char *pkgName) override; + int32_t OnNodeDeviceNotTrusted(const char *pkgName, const char *msg) override; int32_t OnTimeSyncResult(const void *info, uint32_t infoTypeLen, int32_t retCode) override; void OnPublishLNNResult(int32_t publishId, int32_t reason) override; void OnRefreshLNNResult(int32_t refreshId, int32_t reason) override; @@ -80,6 +81,7 @@ private: int32_t OnNodeOnlineStateChangedInner(MessageParcel &data, MessageParcel &reply); int32_t OnNodeBasicInfoChangedInner(MessageParcel &data, MessageParcel &reply); int32_t OnLocalNetworkIdChangedInner(MessageParcel &data, MessageParcel &reply); + int32_t OnNodeDeviceNotTrustedInner(MessageParcel &data, MessageParcel &reply); int32_t OnTimeSyncResultInner(MessageParcel &data, MessageParcel &reply); int32_t OnPublishLNNResultInner(MessageParcel &data, MessageParcel &reply); int32_t OnRefreshLNNResultInner(MessageParcel &data, MessageParcel &reply); diff --git a/sdk/frame/standard/src/if_softbus_client.cpp b/sdk/frame/standard/src/if_softbus_client.cpp index 777291fba..80870529a 100644 --- a/sdk/frame/standard/src/if_softbus_client.cpp +++ b/sdk/frame/standard/src/if_softbus_client.cpp @@ -130,6 +130,12 @@ int32_t ISoftBusClient::OnLocalNetworkIdChanged(const char *pkgName) return SOFTBUS_OK; } +int32_t ISoftBusClient::OnNodeDeviceNotTrusted(const char *pkgName, const char *msg) +{ + COMM_LOGI(COMM_EVENT, "ipc default impl"); + return SOFTBUS_OK; +} + int32_t ISoftBusClient::OnTimeSyncResult(const void *info, uint32_t infoTypeLen, int32_t retCode) { COMM_LOGI(COMM_EVENT, "ipc default impl"); diff --git a/sdk/frame/standard/src/softbus_client_stub.cpp b/sdk/frame/standard/src/softbus_client_stub.cpp index 794d1f0a9..96f7412a3 100644 --- a/sdk/frame/standard/src/softbus_client_stub.cpp +++ b/sdk/frame/standard/src/softbus_client_stub.cpp @@ -52,6 +52,7 @@ SoftBusClientStub::SoftBusClientStub() memberFuncMap_[CLIENT_ON_NODE_ONLINE_STATE_CHANGED] = &SoftBusClientStub::OnNodeOnlineStateChangedInner; memberFuncMap_[CLIENT_ON_NODE_BASIC_INFO_CHANGED] = &SoftBusClientStub::OnNodeBasicInfoChangedInner; memberFuncMap_[CLIENT_ON_LOCAL_NETWORK_ID_CHANGED] = &SoftBusClientStub::OnLocalNetworkIdChangedInner; + memberFuncMap_[CLIENT_ON_NODE_DEVICE_NOT_TRUST] = &SoftBusClientStub::OnNodeDeviceNotTrustedInner; memberFuncMap_[CLIENT_ON_TIME_SYNC_RESULT] = &SoftBusClientStub::OnTimeSyncResultInner; memberFuncMap_[CLIENT_ON_PUBLISH_LNN_RESULT] = &SoftBusClientStub::OnPublishLNNResultInner; memberFuncMap_[CLIENT_ON_REFRESH_LNN_RESULT] = &SoftBusClientStub::OnRefreshLNNResultInner; @@ -552,6 +553,26 @@ int32_t SoftBusClientStub::OnLocalNetworkIdChangedInner(MessageParcel &data, Mes return SOFTBUS_OK; } +int32_t SoftBusClientStub::OnNodeDeviceNotTrustedInner(MessageParcel &data, MessageParcel &reply) +{ + const char *pkgName = data.ReadCString(); + if (pkgName == nullptr || strlen(pkgName) == 0) { + COMM_LOGE(COMM_SDK, "Invalid package name, or length is zero"); + return SOFTBUS_INVALID_PARAM; + } + const char *msg = data.ReadCString(); + if (msg == nullptr) { + COMM_LOGE(COMM_SDK, "OnNodeDeviceNotTrustedInner read msg failed!"); + return SOFTBUS_TRANS_PROXY_READCSTRING_FAILED; + } + int32_t retReply = OnNodeDeviceNotTrusted(pkgName, msg); + if (!reply.WriteInt32(retReply)) { + COMM_LOGE(COMM_SDK, "OnNodeDeviceNotTrustedInner write reply failed!"); + return SOFTBUS_IPC_ERR; + } + return SOFTBUS_OK; +} + int32_t SoftBusClientStub::OnTimeSyncResultInner(MessageParcel &data, MessageParcel &reply) { uint32_t infoTypeLen; @@ -695,6 +716,11 @@ int32_t SoftBusClientStub::OnLocalNetworkIdChanged(const char *pkgName) return LnnOnLocalNetworkIdChanged(pkgName); } +int32_t SoftBusClientStub::OnNodeDeviceNotTrusted(const char *pkgName, const char *msg) +{ + return LnnOnNodeDeviceNotTrusted(pkgName, msg); +} + int32_t SoftBusClientStub::OnTimeSyncResult(const void *info, uint32_t infoTypeLen, int32_t retCode) { (void)infoTypeLen; diff --git a/sdk/libsoftbus_client_map b/sdk/libsoftbus_client_map index 479f71187..34e2cd945 100644 --- a/sdk/libsoftbus_client_map +++ b/sdk/libsoftbus_client_map @@ -198,6 +198,7 @@ "ServerIpcDeactiveMetaNode"; "LnnOnNodeBasicInfoChanged"; "LnnOnLocalNetworkIdChanged"; + "LnnOnNodeDeviceNotTrusted"; "OpenSessionSync"; "ReadMaxSendMessageSize"; "ReadSessionLinkType"; diff --git a/sdk/transmission/session/include/client_trans_session_manager.h b/sdk/transmission/session/include/client_trans_session_manager.h index 45ee19a17..0113ba1d3 100644 --- a/sdk/transmission/session/include/client_trans_session_manager.h +++ b/sdk/transmission/session/include/client_trans_session_manager.h @@ -141,10 +141,12 @@ typedef struct { int32_t sessionId; int32_t channelId; ChannelType channelType; + bool isAsync; void (*OnSessionClosed)(int sessionId); void (*OnShutdown)(int32_t socket, ShutdownReason reason); char sessionName[SESSION_NAME_SIZE_MAX]; char pkgName[PKG_NAME_SIZE_MAX]; + SocketLifecycleData lifecycle; } DestroySessionInfo; int32_t ClientAddNewSession(const char *sessionName, SessionInfo *session); @@ -174,6 +176,8 @@ int32_t ClientGetChannelBusinessTypeBySessionId(int32_t sessionId, int32_t *busi int32_t GetEncryptByChannelId(int32_t channelId, int32_t channelType, int32_t *data); +int32_t ClientGetSessionStateByChannelId(int32_t channelId, int32_t channelType, SessionState *sessionState); + int32_t ClientGetSessionIdByChannelId(int32_t channelId, int32_t channelType, int32_t *sessionId); int32_t ClientGetSessionIsAsyncBySessionId(int32_t sessionId, bool *isAsync); diff --git a/sdk/transmission/session/src/client_trans_session_callback.c b/sdk/transmission/session/src/client_trans_session_callback.c index 9da70f120..b8f96e8f5 100644 --- a/sdk/transmission/session/src/client_trans_session_callback.c +++ b/sdk/transmission/session/src/client_trans_session_callback.c @@ -142,6 +142,16 @@ NO_SANITIZE("cfi") static int32_t TransOnBindFailed(int32_t sessionId, const ISocketListener *socketCallback, int32_t errCode) { (void)ClientHandleBindWaitTimer(sessionId, 0, TIMER_ACTION_STOP); + bool isAsync = true; + int32_t ret = ClientGetSessionIsAsyncBySessionId(sessionId, &isAsync); + if (ret != SOFTBUS_OK) { + TRANS_LOGE(TRANS_SDK, "get is async type failed, sessionId=%{public}d, ret=%{public}d", sessionId, ret); + return ret; + } + if (!isAsync) { + (void)ClientSignalSyncBind(sessionId, errCode); + return SOFTBUS_OK; + } if (socketCallback == NULL || socketCallback->OnError == NULL) { TRANS_LOGE(TRANS_SDK, "Invalid OnBind callback function"); return SOFTBUS_INVALID_PARAM; @@ -149,7 +159,7 @@ static int32_t TransOnBindFailed(int32_t sessionId, const ISocketListener *socke SocketLifecycleData lifecycle; (void)memset_s(&lifecycle, sizeof(SocketLifecycleData), 0, sizeof(SocketLifecycleData)); - int32_t ret = GetSocketLifecycleAndSessionNameBySessionId(sessionId, NULL, &lifecycle); + ret = GetSocketLifecycleAndSessionNameBySessionId(sessionId, NULL, &lifecycle); (void)SetSessionStateBySessionId(sessionId, SESSION_STATE_INIT, 0); if (ret == SOFTBUS_OK && lifecycle.sessionState == SESSION_STATE_CANCELLING) { TRANS_LOGW(TRANS_SDK, "socket is cancelling, no need call back, socket=%{public}d, bindErrCode=%{public}d", @@ -341,9 +351,9 @@ NO_SANITIZE("cfi") int32_t TransOnSessionOpenFailed(int32_t channelId, int32_t c SessionListenerAdapter sessionCallback; (void)memset_s(&sessionCallback, sizeof(SessionListenerAdapter), 0, sizeof(SessionListenerAdapter)); if (channelType == CHANNEL_TYPE_UNDEFINED) { + sessionId = channelId; (void)ClientSetEnableStatusBySocket(sessionId, ENABLE_STATUS_FAILED); // only client async bind failed call - sessionId = channelId; bool tmpIsServer = false; ClientGetSessionCallbackAdapterById(sessionId, &sessionCallback, &tmpIsServer); (void)TransOnBindFailed(sessionId, &sessionCallback.socketClient, errCode); diff --git a/sdk/transmission/session/src/client_trans_session_manager.c b/sdk/transmission/session/src/client_trans_session_manager.c index eb94b05b9..d28615ab6 100644 --- a/sdk/transmission/session/src/client_trans_session_manager.c +++ b/sdk/transmission/session/src/client_trans_session_manager.c @@ -737,6 +737,8 @@ int32_t ClientSetChannelBySessionId(int32_t sessionId, TransInfo *transInfo) } sessionNode->channelId = transInfo->channelId; sessionNode->channelType = (ChannelType)transInfo->channelType; + TRANS_LOGI(TRANS_SDK, "Client set channel by sessionId success, sessionId=%{public}d, channelId=%{public}d, " + "channelType=%{public}d", sessionId, sessionNode->channelId, sessionNode->channelType); UnlockClientSessionServerList(); return SOFTBUS_OK; @@ -777,6 +779,41 @@ int32_t GetEncryptByChannelId(int32_t channelId, int32_t channelType, int32_t *d return SOFTBUS_TRANS_SESSION_INFO_NOT_FOUND; } +int32_t ClientGetSessionStateByChannelId(int32_t channelId, int32_t channelType, SessionState *sessionState) +{ + if ((channelId < 0) || (sessionState == NULL)) { + TRANS_LOGW(TRANS_SDK, "Invalid param, channelId=%{public}d, channelType=%{public}d", channelId, channelType); + return SOFTBUS_INVALID_PARAM; + } + + int32_t ret = LockClientSessionServerList(); + if (ret != SOFTBUS_OK) { + TRANS_LOGE(TRANS_SDK, "lock failed"); + return ret; + } + + ClientSessionServer *serverNode = NULL; + SessionInfo *sessionNode = NULL; + + LIST_FOR_EACH_ENTRY(serverNode, &(g_clientSessionServerList->list), ClientSessionServer, node) { + if (IsListEmpty(&serverNode->sessionList)) { + continue; + } + + LIST_FOR_EACH_ENTRY(sessionNode, &(serverNode->sessionList), SessionInfo, node) { + if (sessionNode->channelId == channelId && sessionNode->channelType == (ChannelType)channelType) { + *sessionState = sessionNode->lifecycle.sessionState; + UnlockClientSessionServerList(); + return SOFTBUS_OK; + } + } + } + + UnlockClientSessionServerList(); + TRANS_LOGE(TRANS_SDK, "not found session by channelId=%{public}d", channelId); + return SOFTBUS_TRANS_SESSION_INFO_NOT_FOUND; +} + int32_t ClientGetSessionIdByChannelId(int32_t channelId, int32_t channelType, int32_t *sessionId) { if ((channelId < 0) || (sessionId == NULL)) { diff --git a/sdk/transmission/session/src/client_trans_session_service.c b/sdk/transmission/session/src/client_trans_session_service.c index cded3533d..539334676 100644 --- a/sdk/transmission/session/src/client_trans_session_service.c +++ b/sdk/transmission/session/src/client_trans_session_service.c @@ -462,7 +462,7 @@ void NotifyAuthSuccess(int sessionId) static int32_t CheckSessionIsOpened(int32_t sessionId, bool isCancelCheck) { #define SESSION_STATUS_CHECK_MAX_NUM 100 -#define SESSION_STATUS_CANCEL_CHECK_MAX_NUM 10 +#define SESSION_STATUS_CANCEL_CHECK_MAX_NUM 5 #define SESSION_CHECK_PERIOD 200000 int32_t checkMaxNum = isCancelCheck ? SESSION_STATUS_CANCEL_CHECK_MAX_NUM : SESSION_STATUS_CHECK_MAX_NUM; int32_t i = 0; @@ -1097,13 +1097,9 @@ int32_t ClientBind(int32_t socket, const QosTV qos[], uint32_t qosCount, const I TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_SDK, "open session failed, ret=%{public}d", ret); if (!isAsync) { - ret = ClientSetChannelBySessionId(socket, &transInfo); - TRANS_CHECK_AND_RETURN_RET_LOGE( - ret == SOFTBUS_OK, ret, TRANS_SDK, "set channel by socket=%{public}d failed, ret=%{public}d", socket, ret); ret = CheckSessionCancelState(socket); TRANS_CHECK_AND_RETURN_RET_LOGE( ret == SOFTBUS_OK, ret, TRANS_SDK, "check session cancel state failed, ret=%{public}d", ret); - SetSessionStateBySessionId(socket, SESSION_STATE_OPENED, 0); ret = ClientWaitSyncBind(socket); TRANS_CHECK_AND_RETURN_RET_LOGE( ret == SOFTBUS_OK, ret, TRANS_SDK, "ClientWaitSyncBind err, ret=%{public}d", ret); @@ -1111,6 +1107,7 @@ int32_t ClientBind(int32_t socket, const QosTV qos[], uint32_t qosCount, const I ret = ClientSetSocketState(socket, maxIdleTimeout, SESSION_ROLE_CLIENT); TRANS_CHECK_AND_RETURN_RET_LOGE(ret == SOFTBUS_OK, ret, TRANS_SDK, "set session role failed, ret=%{public}d", ret); if (!isAsync) { + (void)ClientGetChannelBySessionId(socket, &(transInfo.channelId), &(transInfo.channelType), NULL); TRANS_LOGI(TRANS_SDK, "Bind ok: socket=%{public}d, channelId=%{public}d, channelType=%{public}d", socket, transInfo.channelId, transInfo.channelType); } else { @@ -1176,6 +1173,10 @@ void ClientShutdown(int32_t socket, int32_t cancelReason) if (ret != SOFTBUS_OK) { TRANS_LOGE(TRANS_SDK, "Call sa delete socket failed: ret=%{public}d", ret); } + ret = ClientSignalSyncBind(socket, 0); + if (ret != SOFTBUS_OK) { + TRANS_LOGE(TRANS_SDK, "sync signal bind failed, ret=%{public}d, socket=%{public}d", ret, socket); + } } else if (lifecycle.sessionState == SESSION_STATE_OPENED || lifecycle.sessionState == SESSION_STATE_CALLBACK_FINISHED) { if (lifecycle.sessionState == SESSION_STATE_OPENED) { diff --git a/sdk/transmission/session/src/client_trans_socket_manager.c b/sdk/transmission/session/src/client_trans_socket_manager.c index d15ce9aeb..eb9a444b7 100644 --- a/sdk/transmission/session/src/client_trans_socket_manager.c +++ b/sdk/transmission/session/src/client_trans_socket_manager.c @@ -103,6 +103,13 @@ NO_SANITIZE("cfi") DestroySessionInfo *CreateDestroySessionNode(SessionInfo *ses destroyNode->sessionId = sessionNode->sessionId; destroyNode->channelId = sessionNode->channelId; destroyNode->channelType = sessionNode->channelType; + destroyNode->isAsync = sessionNode->isAsync; + if (memcpy_s(&(destroyNode->lifecycle), sizeof(SocketLifecycleData), &(sessionNode->lifecycle), + sizeof(SocketLifecycleData)) != EOK) { + TRANS_LOGE(TRANS_SDK, "memcpy_s lifecycle fail."); + SoftBusFree(destroyNode); + return NULL; + } if (memcpy_s(destroyNode->sessionName, SESSION_NAME_SIZE_MAX, server->sessionName, SESSION_NAME_SIZE_MAX) != EOK) { TRANS_LOGE(TRANS_SDK, "memcpy_s sessionName fail."); SoftBusFree(destroyNode); @@ -136,6 +143,9 @@ NO_SANITIZE("cfi") void ClientDestroySession(const ListNode *destroyList, Shutdo int32_t id = destroyNode->sessionId; (void)ClientDeleteRecvFileList(id); (void)ClientTransCloseChannel(destroyNode->channelId, destroyNode->channelType); + if ((!destroyNode->isAsync) && destroyNode->lifecycle.sessionState == SESSION_STATE_CANCELLING) { + (void)SoftBusCondSignal(&(destroyNode->lifecycle.callbackCond)); + } if (destroyNode->OnSessionClosed != NULL) { destroyNode->OnSessionClosed(id); } else if (destroyNode->OnShutdown != NULL) { @@ -653,6 +663,12 @@ void ClientCleanUpWaitTimeoutSocket(int32_t waitOutSocket[], uint32_t waitOutNum SessionListenerAdapter callback = { 0 }; for (uint32_t i = 0; i < waitOutNum; ++i) { TRANS_LOGI(TRANS_SDK, "time out shutdown socket=%{public}d", waitOutSocket[i]); + SessionEnableStatus enableStatus = ENABLE_STATUS_INIT; + int32_t ret = ClientGetChannelBySessionId(waitOutSocket[i], NULL, NULL, &enableStatus); + if (ret != SOFTBUS_OK || enableStatus == ENABLE_STATUS_SUCCESS) { + TRANS_LOGI(TRANS_SDK, "socket has enabled, need not shutdown, socket=%{public}d", waitOutSocket[i]); + continue; + } ClientGetSessionCallbackAdapterById(waitOutSocket[i], &callback, &tmpIsServer); if (callback.socketClient.OnError != NULL) { (void)callback.socketClient.OnError(waitOutSocket[i], SOFTBUS_TRANS_STOP_BIND_BY_TIMEOUT); diff --git a/sdk/transmission/trans_channel/proxy/src/client_trans_proxy_file_helper.c b/sdk/transmission/trans_channel/proxy/src/client_trans_proxy_file_helper.c index 9c2316fb5..fb75a20c3 100644 --- a/sdk/transmission/trans_channel/proxy/src/client_trans_proxy_file_helper.c +++ b/sdk/transmission/trans_channel/proxy/src/client_trans_proxy_file_helper.c @@ -401,7 +401,7 @@ static int32_t GetAbsFullPath(const char *fullPath, char *recvAbsPath, int32_t p TRANS_LOGE(TRANS_FILE, "get full abs file failed"); goto EXIT_ERR; } - TRANS_LOGI(TRANS_FILE, "dirPath=%{public}s, absFullDir=%{public}s", dirPath, absFullDir); + TRANS_LOGI(TRANS_FILE, "dirPath=%{private}s, absFullDir=%{private}s", dirPath, absFullDir); fileNameLength = (int32_t)strlen(fileName); dirPathLength = (int32_t)strlen(absFullDir); if (pathSize < (fileNameLength + dirPathLength + 1)) { @@ -409,12 +409,12 @@ static int32_t GetAbsFullPath(const char *fullPath, char *recvAbsPath, int32_t p dirPathLength, fileNameLength); goto EXIT_ERR; } - TRANS_LOGI(TRANS_FILE, "fileName=%{public}s, fileNameLen=%{public}d", fileName, fileNameLength); + TRANS_LOGI(TRANS_FILE, "fileName=%{private}s, fileNameLen=%{public}d", fileName, fileNameLength); if (sprintf_s(recvAbsPath, pathSize, "%s/%s", absFullDir, fileName) < 0) { TRANS_LOGE(TRANS_FILE, "sprintf_s filename error"); goto EXIT_ERR; } - TRANS_LOGI(TRANS_FILE, "recvAbsPath=%{public}s", recvAbsPath); + TRANS_LOGI(TRANS_FILE, "recvAbsPath=%{private}s", recvAbsPath); SoftBusFree(absFullDir); SoftBusFree(dirPath); return SOFTBUS_OK; 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 3f0d1aec1..4bbca0081 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 @@ -713,13 +713,13 @@ static int32_t SendSingleFile(const SendListenerInfo *sendInfo, const char *sour TRANS_LOGE(TRANS_FILE, "sourfile or dstfile is null"); return SOFTBUS_INVALID_PARAM; } - TRANS_LOGI(TRANS_FILE, "channelId=%{public}d, srcFile=%{public}s, dstFile=%{public}s", - sendInfo->channelId, sourceFile, destFile); + TRANS_LOGI(TRANS_FILE, "channelId=%{public}d, srcFile=%{private}s, dstFile=%{public}s", sendInfo->channelId, + sourceFile, destFile); int32_t ret = FileToFrameAndSendFile((SendListenerInfo *)sendInfo, sourceFile, destFile); ClearSendInfo((SendListenerInfo *)sendInfo); TRANS_LOGI( - TRANS_FILE, "channelId=%{public}d, srcFile=%{public}s, ret=%{public}d", sendInfo->channelId, sourceFile, ret); + TRANS_FILE, "channelId=%{public}d, srcFile=%{private}s, ret=%{public}d", sendInfo->channelId, sourceFile, ret); return ret; } @@ -1208,7 +1208,7 @@ static int32_t GetFileInfoByStartFrame(const FileFrame *fileFrame, const FileRec } const char *rootDir = info->fileListener.rootDir; if (strstr(rootDir, "..") != NULL) { - TRANS_LOGE(TRANS_FILE, "rootDir is not canonical form. rootDir=%{public}s", rootDir); + TRANS_LOGE(TRANS_FILE, "rootDir is not canonical form. rootDir=%{private}s", rootDir); return SOFTBUS_FILE_ERR; } int32_t ret = UnpackFileTransStartInfo((FileFrame *)fileFrame, info, file); @@ -1218,10 +1218,10 @@ static int32_t GetFileInfoByStartFrame(const FileFrame *fileFrame, const FileRec } char *filePath = file->filePath; if (!CheckDestFilePathValid(filePath)) { - TRANS_LOGE(TRANS_FILE, "recv filePath form is wrong. filePath=%{public}s", filePath); + TRANS_LOGE(TRANS_FILE, "recv filePath form is wrong. filePath=%{private}s", filePath); return SOFTBUS_FILE_ERR; } - TRANS_LOGI(TRANS_FILE, "dst filePath=%{public}s, rootDir=%{public}s", filePath, rootDir); + TRANS_LOGI(TRANS_FILE, "dst filePath=%{private}s, rootDir=%{private}s", filePath, rootDir); char *fullRecvPath = GetFullRecvPath(filePath, rootDir); if (!IsPathValid(fullRecvPath)) { TRANS_LOGE(TRANS_FILE, "destFilePath is invalid"); @@ -1342,7 +1342,7 @@ static int32_t CreateFileFromFrame(int32_t sessionId, int32_t channelId, const F TRANS_LOGE(TRANS_FILE, "get file info by start frame fail"); goto EXIT_ERR; } - TRANS_LOGI(TRANS_FILE, "null filePath. filePath=%{public}s, seq=%{public}u", file->filePath, file->seq); + TRANS_LOGI(TRANS_FILE, "null filePath. filePath=%{private}s, seq=%{public}u", file->filePath, file->seq); if (PutToRecvFileList(recipient, file) != SOFTBUS_OK) { TRANS_LOGE(TRANS_FILE, "put to recv files failed. sessionId=%{public}u", recipient->sessionId); goto EXIT_ERR; 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 3bde3a93d..2ca4b781e 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 @@ -34,6 +34,7 @@ typedef struct { SeqVerifyInfo verifyInfo; char sessionKey[SESSION_KEY_LENGTH]; char myIp[IP_LEN]; + SoftBusMutex fdLock; SoftBusList *pendingPacketsList; } TcpDirectChannelDetail; 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 b6ebe3701..37c706933 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 @@ -150,6 +150,7 @@ void TransTdcCloseChannel(int32_t channelId) if (item->channelId == channelId) { TransTdcReleaseFd(item->detail.fd); ListDelete(&item->node); + SoftBusMutexDestroy(&(item->detail.fdLock)); SoftBusFree(item); item = NULL; (void)SoftBusMutexUnlock(&g_tcpDirectChannelInfoList->lock); @@ -177,6 +178,11 @@ static TcpDirectChannelInfo *TransGetNewTcpChannel(const ChannelInfo *channel) item->channelId = channel->channelId; item->detail.fd = channel->fd; item->detail.channelType = channel->channelType; + if (SoftBusMutexInit(&(item->detail.fdLock), NULL) != SOFTBUS_OK) { + SoftBusFree(item); + TRANS_LOGE(TRANS_SDK, "init fd lock failed"); + return NULL; + } if (memcpy_s(item->detail.sessionKey, SESSION_KEY_LENGTH, channel->sessionKey, SESSION_KEY_LENGTH) != EOK) { SoftBusFree(item); TRANS_LOGE(TRANS_SDK, "sessionKey copy failed"); @@ -226,6 +232,7 @@ static void TransTdcDelChannelInfo(int32_t channelId) if (item->channelId == channelId) { TransTdcReleaseFd(item->detail.fd); ListDelete(&item->node); + SoftBusMutexDestroy(&(item->detail.fdLock)); SoftBusFree(item); item = NULL; (void)SoftBusMutexUnlock(&g_tcpDirectChannelInfoList->lock); 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 0fc6dc629..fea3ea25c 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 @@ -177,10 +177,7 @@ static int32_t TransTdcProcessPostData(const TcpDirectChannelInfo *channel, cons { uint32_t outLen = 0; char *buf = TransTdcPackData(channel, data, len, flags, &outLen); - if (buf == NULL) { - TRANS_LOGE(TRANS_SDK, "failed to pack bytes."); - return SOFTBUS_ENCRYPT_ERR; - } + TRANS_CHECK_AND_RETURN_RET_LOGE(buf != NULL, SOFTBUS_ENCRYPT_ERR, TRANS_SDK, "failed to pack bytes."); if (outLen != len + OVERHEAD_LEN) { TRANS_LOGE(TRANS_SDK, "pack bytes len error, outLen=%{public}d", outLen); SoftBusFree(buf); @@ -201,12 +198,26 @@ static int32_t TransTdcProcessPostData(const TcpDirectChannelInfo *channel, cons SoftBusFree(buf); return SOFTBUS_TCP_SOCKET_ERR; } + TcpDirectChannelInfo info; + (void)memset_s(&info, sizeof(TcpDirectChannelInfo), 0, sizeof(TcpDirectChannelInfo)); + if (TransTdcGetInfoById(channel->channelId, &info) == NULL) { + TRANS_LOGE(TRANS_SDK, "get channel fd lock fail. channelId=%{public}d", channel->channelId); + SoftBusFree(buf); + return SOFTBUS_TRANS_TDC_CHANNEL_NOT_FOUND; + } + if (SoftBusMutexLock(&(info.detail.fdLock)) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_SDK, "failed to lock fd. channelId=%{public}d", channel->channelId); + SoftBusFree(buf); + return SOFTBUS_LOCK_ERR; + } ssize_t ret = ConnSendSocketData(channel->detail.fd, buf, outLen + DC_DATA_HEAD_SIZE, 0); if (ret != (ssize_t)outLen + DC_DATA_HEAD_SIZE) { TRANS_LOGE(TRANS_SDK, "failed to send tcp data. ret=%{public}zd", ret); SoftBusFree(buf); + (void)SoftBusMutexUnlock(&(info.detail.fdLock)); return SOFTBUS_TRANS_SEND_LEN_BEYOND_LIMIT; } + (void)SoftBusMutexUnlock(&(info.detail.fdLock)); SoftBusFree(buf); buf = NULL; 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 8b2aaa43d..faca20f8c 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 @@ -368,24 +368,27 @@ static int32_t RleaseUdpResources(int32_t channelId) return ServerIpcReleaseResources(channelId); } -static int32_t CloseUdpChannel(int32_t channelId, ShutdownReason reason) +static void NotifyCb(UdpChannel *channel, int32_t channelId, ShutdownReason reason) { - UdpChannel channel; - (void)memset_s(&channel, sizeof(UdpChannel), 0, sizeof(UdpChannel)); - TRANS_LOGI(TRANS_SDK, "close udp channelId=%{public}d.", channelId); - if (TransGetUdpChannel(channelId, &channel) != SOFTBUS_OK) { - TRANS_LOGE(TRANS_SDK, "get udp channel by channelId=%{public}d failed.", channelId); - return SOFTBUS_TRANS_UDP_GET_CHANNEL_FAILED; - } - if (channel.businessType == BUSINESS_TYPE_FILE) { - TRANS_LOGD(TRANS_SDK, "close udp channel get file list start"); - int32_t ret = NSTACKX_DFileSessionGetFileList(channel.dfileId); - if (ret != SOFTBUS_OK) { - TRANS_LOGE(TRANS_SDK, "close udp channel to get file list failed. channelId=%{public}d, ret=%{public}d", - channelId, ret); + if (channel != NULL && (!channel->isEnable) && g_sessionCb != NULL && g_sessionCb->OnSessionOpenFailed != NULL) { + SessionState sessionState = SESSION_STATE_INIT; + if (ClientGetSessionStateByChannelId(channelId, CHANNEL_TYPE_UDP, &sessionState) == SOFTBUS_OK && + (sessionState == SESSION_STATE_OPENED || sessionState == SESSION_STATE_CALLBACK_FINISHED)) { + if (ClosePeerUdpChannel(channelId) != SOFTBUS_OK) { + TRANS_LOGW(TRANS_SDK, "trans close peer udp channel failed. channelId=%{public}d", channelId); + } } + g_sessionCb->OnSessionOpenFailed(channelId, CHANNEL_TYPE_UDP, SOFTBUS_TRANS_STOP_BIND_BY_TIMEOUT); + return; } + if (g_sessionCb != NULL && g_sessionCb->OnSessionClosed != NULL) { + g_sessionCb->OnSessionClosed(channelId, CHANNEL_TYPE_UDP, reason); + return; + } +} +static int32_t CloseUdpChannelProc(UdpChannel *channel, int32_t channelId, ShutdownReason reason) +{ if (TransDeleteUdpChannel(channelId) != SOFTBUS_OK) { TRANS_LOGW(TRANS_SDK, "trans del udp channel failed. channelId=%{public}d", channelId); } @@ -410,20 +413,41 @@ static int32_t CloseUdpChannel(int32_t channelId, ShutdownReason reason) break; } - int32_t ret = TransDeleteBusinnessChannel(&channel); - if (ret != SOFTBUS_OK) { - TRANS_LOGE(TRANS_SDK, "CloseUdpChannel del business channel failed. channelId=%{public}d", channelId); - return ret; + if (channel != NULL) { + int32_t ret = TransDeleteBusinnessChannel(channel); + if (ret != SOFTBUS_OK) { + TRANS_LOGE(TRANS_SDK, "del business channel failed. channelId=%{public}d", channelId); + return ret; + } } if (reason != SHUTDOWN_REASON_LOCAL) { - if (g_sessionCb != NULL && g_sessionCb->OnSessionClosed != NULL) { - g_sessionCb->OnSessionClosed(channelId, CHANNEL_TYPE_UDP, reason); - } + NotifyCb(channel, channelId, reason); } return SOFTBUS_OK; } +static int32_t CloseUdpChannel(int32_t channelId, ShutdownReason reason) +{ + UdpChannel channel; + (void)memset_s(&channel, sizeof(UdpChannel), 0, sizeof(UdpChannel)); + TRANS_LOGI(TRANS_SDK, "close udp channelId=%{public}d, reason=%{public}d", channelId, reason); + if (TransGetUdpChannel(channelId, &channel) != SOFTBUS_OK) { + TRANS_LOGE(TRANS_SDK, "get udp channel by channelId=%{public}d failed.", channelId); + CloseUdpChannelProc(NULL, channelId, reason); + return SOFTBUS_TRANS_UDP_GET_CHANNEL_FAILED; + } + if (channel.businessType == BUSINESS_TYPE_FILE) { + TRANS_LOGD(TRANS_SDK, "close udp channel get file list start"); + int32_t ret = NSTACKX_DFileSessionGetFileList(channel.dfileId); + if (ret != SOFTBUS_OK) { + TRANS_LOGE(TRANS_SDK, "close udp channel to get file list failed. channelId=%{public}d, ret=%{public}d", + channelId, ret); + } + } + return CloseUdpChannelProc(&channel, channelId, reason); +} + int32_t TransOnUdpChannelClosed(int32_t channelId, ShutdownReason reason) { return CloseUdpChannel(channelId, reason); 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 38afb29bc..68187b173 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 @@ -435,7 +435,7 @@ static int32_t UpdateFileRecvPath(int32_t channelId, FileListener *fileListener, char *absPath = realpath(rootDir, NULL); if (absPath == NULL) { TRANS_LOGE(TRANS_SDK, - "rootDir not exist, rootDir=%{public}s, errno=%{public}d.", + "rootDir not exist, rootDir=%{private}s, errno=%{public}d.", (rootDir == NULL ? "null" : rootDir), errno); return SOFTBUS_FILE_ERR; } @@ -450,7 +450,7 @@ static int32_t UpdateFileRecvPath(int32_t channelId, FileListener *fileListener, if (NSTACKX_DFileSetStoragePath(fileSession, fileListener->rootDir) != SOFTBUS_OK) { NSTACKX_DFileClose(fileSession); - TRANS_LOGE(TRANS_SDK, "set storage path failed. rootDir=%{public}s", fileListener->rootDir); + TRANS_LOGE(TRANS_SDK, "set storage path failed. rootDir=%{private}s", fileListener->rootDir); return SOFTBUS_FILE_ERR; } return SOFTBUS_OK; diff --git a/sdk/transmission/trans_channel/udp/stream/adaptor/include/client_trans_udp_stream_interface.h b/sdk/transmission/trans_channel/udp/stream/adaptor/include/client_trans_udp_stream_interface.h index b735fe3e6..a3f3aa830 100644 --- a/sdk/transmission/trans_channel/udp/stream/adaptor/include/client_trans_udp_stream_interface.h +++ b/sdk/transmission/trans_channel/udp/stream/adaptor/include/client_trans_udp_stream_interface.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 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 @@ -68,6 +68,7 @@ int32_t StartVtpStreamChannelClient(int32_t channelId, const VtpStreamOpenParam const IStreamListener *callback); int32_t SendVtpStream(int32_t channelId, const StreamData *data, const StreamData *ext, const StreamFrameInfo *param); int32_t CloseVtpStreamChannel(int32_t channelId, const char *pkgName); +int32_t SetVtpStreamMultiLayerOpt(int32_t channelId, const void *optValue); #ifdef __cplusplus #if __cplusplus 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 86b606c8c..8e4a530f5 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 @@ -143,6 +143,25 @@ int32_t SendVtpStream(int32_t channelId, const StreamData *inData, const StreamD return adaptor->GetStreamManager()->Send(std::move(stream)) ? SOFTBUS_OK : SOFTBUS_TRANS_MAKE_STREAM_FAILED; } +int32_t SetVtpStreamMultiLayerOpt(int32_t channelId, const void *optValue) +{ + if (optValue == nullptr) { + TRANS_LOGE(TRANS_STREAM, "invalid argument optValue"); + return SOFTBUS_INVALID_PARAM; + } + std::shared_ptr adaptor = nullptr; + { + std::lock_guard lock(g_mutex); + auto it = g_adaptorMap.find(channelId); + if (it == g_adaptorMap.end()) { + TRANS_LOGE(TRANS_STREAM, "channelId %{public}u adaptor not existed!", channelId); + return SOFTBUS_TRANS_ADAPTOR_NOT_EXISTED; + } + adaptor = it->second; + } + return adaptor->GetStreamManager()->SetMultiLayer(optValue); +} + int32_t StartVtpStreamChannelServer(int32_t channelId, const VtpStreamOpenParam *param, const IStreamListener *callback) { if (channelId < 0 || param == nullptr || param->pkgName == nullptr || callback == nullptr) { diff --git a/sdk/transmission/trans_channel/udp/stream/include/client_trans_stream.h b/sdk/transmission/trans_channel/udp/stream/include/client_trans_stream.h index e2275726f..f5735e77b 100644 --- a/sdk/transmission/trans_channel/udp/stream/include/client_trans_stream.h +++ b/sdk/transmission/trans_channel/udp/stream/include/client_trans_stream.h @@ -1,5 +1,5 @@ /* - * 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 @@ -34,6 +34,8 @@ int32_t TransOnstreamChannelOpened(const ChannelInfo *channel, int32_t *streamPo int32_t TransCloseStreamChannel(int32_t channelId); int32_t TransSendStream(int32_t channelId, const StreamData *data, const StreamData *ext, const StreamFrameInfo *param); + +int32_t TransSetStreamMultiLayer(int32_t channelId, const void *optValue); #ifdef __cplusplus } #endif 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 556216ce9..4c5714def 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-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 @@ -75,6 +75,7 @@ public: virtual bool Send(std::unique_ptr stream) = 0; virtual bool SetOption(int type, const StreamAttr &value) = 0; + virtual int32_t SetMultiLayer(const void *para) = 0; virtual StreamAttr GetOption(int type) const = 0; virtual bool SetStreamListener(std::shared_ptr receiver) = 0; @@ -90,7 +91,7 @@ protected: static constexpr int DEFAULT_UDP_BUFFER_RCV_SIZE = 1024 * 1024; static constexpr int STREAM_BUFFER_THRESHOLD = 5; - virtual int CreateAndBindSocket(IpAndPort &local) = 0; + virtual int CreateAndBindSocket(IpAndPort &local, bool isServer) = 0; virtual bool Accept() = 0; virtual int EpollTimeout(int fd, int timeout) = 0; diff --git a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/include/i_stream_manager.h b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/include/i_stream_manager.h index 2d47780a3..ff97cfbae 100644 --- a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/include/i_stream_manager.h +++ b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/include/i_stream_manager.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 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 @@ -64,6 +64,7 @@ public: virtual bool Send(std::unique_ptr) = 0; virtual bool SetOption(int type, const StreamAttr &value) = 0; + virtual int32_t SetMultiLayer(const void *para) = 0; virtual StreamAttr GetOption(int type) const = 0; virtual void SetStreamRecvListener(std::shared_ptr recvListener) = 0; diff --git a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/libsoftbus_stream.gni b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/libsoftbus_stream.gni index accff7fb6..891eef34a 100644 --- a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/libsoftbus_stream.gni +++ b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/libsoftbus_stream.gni @@ -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 @@ -13,6 +13,7 @@ import("../../../../../../dsoftbus.gni") libsoftbus_stream_sdk_path = "$dsoftbus_root_path/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream" +vtp_stream_opt_ext_path = "$dsoftbus_root_path/dsoftbus_enhance/sdk/transmission/trans_channel/udp/stream/src" dstream_native_source_path = rebase_path("$dsoftbus_root_path") dstream_dep_file = "components/nstackx_enhanced/fillp/BUILD.gn" @@ -23,7 +24,10 @@ enhanced = exec_script("$dsoftbus_root_path/check_sub_module.py", ], "value") -libsoftbus_stream_inc = [ "$libsoftbus_stream_sdk_path/include" ] +libsoftbus_stream_inc = [ + "$libsoftbus_stream_sdk_path/include", + "$libsoftbus_stream_sdk_path", +] if (enhanced) { libsoftbus_stream_inc += [ @@ -46,6 +50,12 @@ libsoftbus_stream_src = [ "$libsoftbus_stream_sdk_path/vtp_stream_socket.cpp", ] +if (enhanced) { + libsoftbus_stream_src += [ "$vtp_stream_opt_ext_path/vtp_stream_opt_ext.c" ] +} else { + libsoftbus_stream_src += [ "$libsoftbus_stream_sdk_path/vtp_stream_opt.c" ] +} + libsoftbus_stream_ext_deps = [] if (defined(ohos_lite)) { libsoftbus_stream_inc += [ 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 3698ae866..c9e84213f 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 @@ -1,5 +1,5 @@ /* - * 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 @@ -138,6 +138,17 @@ bool StreamManager::SetOption(int type, const StreamAttr &value) return false; } +int32_t StreamManager::SetMultiLayer(const void *para) +{ + auto it = socketMap_.find(curProtocol_); + if (it != socketMap_.end()) { + auto streamSocket = it->second; + return streamSocket->SetMultiLayer(para); + } + TRANS_LOGE(TRANS_STREAM, "do not found curProtocol=%{public}d", curProtocol_); + return SOFTBUS_TRANS_SESSION_SET_CHANNEL_FAILED; +} + StreamAttr StreamManager::GetOption(int type) const { auto it = socketMap_.find(curProtocol_); diff --git a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_manager.h b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_manager.h index ce0830c81..4685c9fa3 100644 --- a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_manager.h +++ b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_manager.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 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 @@ -89,6 +89,7 @@ public: bool Send(std::unique_ptr data) override; bool SetOption(int type, const StreamAttr &value) override; + int32_t SetMultiLayer(const void *para) override; StreamAttr GetOption(int type) const override; void SetStreamRecvListener(std::shared_ptr recvListener) override; diff --git a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/vtp_stream_opt.c b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/vtp_stream_opt.c new file mode 100644 index 000000000..7b939294b --- /dev/null +++ b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/vtp_stream_opt.c @@ -0,0 +1,40 @@ +/* + * Copyright (c) 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 + * + * 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 "vtp_stream_opt.h" + +#include "softbus_errcode.h" + +int32_t VtpSetSocketMultiLayer(int fd, OnFrameEvt *cb, const void *para) +{ + (void)fd; + (void)cb; + (void)para; + return SOFTBUS_FUNC_NOT_SUPPORT; +} + +bool IsVtpFrameSentEvt(const FtEventCbkInfo *info) +{ + (void)info; + return false; +} + +int HandleVtpFrameEvt(int fd, OnFrameEvt cb, const FtEventCbkInfo *info) +{ + (void)fd; + (void)cb; + (void)info; + return SOFTBUS_FUNC_NOT_SUPPORT; +} \ No newline at end of file diff --git a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/vtp_stream_opt.h b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/vtp_stream_opt.h new file mode 100644 index 000000000..298eeded3 --- /dev/null +++ b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/vtp_stream_opt.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 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 + * + * 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 VTP_STREAM_OPT_H +#define VTP_STREAM_OPT_H + +#include +#include "fillpinc.h" +#include "trans_type.h" + +#ifdef __cplusplus +extern "C" { +#endif +int32_t VtpSetSocketMultiLayer(int fd, OnFrameEvt *cb, const void *para); + +bool IsVtpFrameSentEvt(const FtEventCbkInfo *info); + +int HandleVtpFrameEvt(int fd, OnFrameEvt cb, const FtEventCbkInfo *info); +#ifdef __cplusplus +} +#endif +#endif // VTP_STREAM_OPT_H \ No newline at end of file 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 8736d4b13..cf50f08a9 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 @@ -35,6 +35,7 @@ #include "stream_common_data.h" #include "stream_depacketizer.h" #include "stream_packetizer.h" +#include "vtp_stream_opt.h" namespace Communication { namespace SoftBus { @@ -249,6 +250,33 @@ int VtpStreamSocket::HandleRipplePolicy(int fd, const FtEventCbkInfo *info) return SOFTBUS_OK; } +int VtpStreamSocket::HandleFillpFrameEvt(int fd, const FtEventCbkInfo *info) +{ + if (info == nullptr) { + TRANS_LOGE(TRANS_STREAM, "fd is %{public}d, info is nullptr", fd); + return SOFTBUS_INVALID_PARAM; + } + std::lock_guard guard(g_streamSocketMapLock_); + auto itListener = g_streamSocketMap.find(fd); + if (itListener != g_streamSocketMap.end()) { + return itListener->second->HandleFillpFrameEvtInner(fd, info); + } else { + TRANS_LOGE(TRANS_STREAM, "OnFillpFrameEvt for the fd is empty in the map. fd=%{public}d", fd); + } + return SOFTBUS_OK; +} + +int VtpStreamSocket::HandleFillpFrameEvtInner(int fd, const FtEventCbkInfo *info) +{ + if (onStreamEvtCb_ != nullptr) { + TRANS_LOGD(TRANS_STREAM, "onStreamEvtCb_ enter"); + return HandleVtpFrameEvt(fd, onStreamEvtCb_, info); + } else { + TRANS_LOGD(TRANS_STREAM, "onStreamEvtCb_ is nullptr"); + } + return SOFTBUS_OK; +} + #ifdef FILLP_SUPPORT_BW_DET void VtpStreamSocket::FillSupportDet(int fd, const FtEventCbkInfo *info, QosTv *metricList) { @@ -284,9 +312,9 @@ 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 || fd <= 0) { + if (info == nullptr || fd < 0) { TRANS_LOGE(TRANS_STREAM, "param invalid"); - return -1; + return SOFTBUS_INVALID_PARAM; } if (info->evt == FT_EVT_FRAME_STATS) { TRANS_LOGI(TRANS_STREAM, "recv fillp frame stats"); @@ -294,6 +322,9 @@ int VtpStreamSocket::FillpStatistics(int fd, const FtEventCbkInfo *info) } else if (info->evt == FT_EVT_TRAFFIC_DATA) { TRANS_LOGI(TRANS_STREAM, "recv fillp traffic data"); return HandleRipplePolicy(fd, info); + } else if (IsVtpFrameSentEvt(info)) { + TRANS_LOGI(TRANS_STREAM, "fd %{public}d recv fillp frame send evt", fd); + return HandleFillpFrameEvt(fd, info); } #ifdef FILLP_SUPPORT_BW_DET if (info->evt == FT_EVT_BW_DET || info->evt == FT_EVT_JITTER_DET) { @@ -387,7 +418,7 @@ void VtpStreamSocket::FillpAppStatistics() bool VtpStreamSocket::CreateClient(IpAndPort &local, int streamType, std::pair sessionKey) { - int fd = CreateAndBindSocket(local); + int fd = CreateAndBindSocket(local, false); if (fd == -1) { TRANS_LOGE(TRANS_STREAM, "CreateAndBindSocket failed, errno=%{public}d", FtGetErrno()); DestroyStreamSocket(); @@ -436,7 +467,7 @@ bool VtpStreamSocket::CreateClient(IpAndPort &local, const IpAndPort &remote, in bool VtpStreamSocket::CreateServer(IpAndPort &local, int streamType, std::pair sessionKey) { TRANS_LOGD(TRANS_STREAM, "enter."); - listenFd_ = CreateAndBindSocket(local); + listenFd_ = CreateAndBindSocket(local, true); if (listenFd_ == -1) { TRANS_LOGE(TRANS_STREAM, "create listenFd failed, errno=%{public}d", FtGetErrno()); DestroyStreamSocket(); @@ -710,7 +741,7 @@ void VtpStreamSocket::DestroyVtpInstance(const std::string &pkgName) TRANS_LOGD(TRANS_STREAM, "ok"); } -int VtpStreamSocket::CreateAndBindSocket(IpAndPort &local) +int VtpStreamSocket::CreateAndBindSocket(IpAndPort &local, bool isServer) { localIpPort_ = local; vtpInstance_->UpdateSocketStreamCount(true); @@ -724,6 +755,10 @@ int VtpStreamSocket::CreateAndBindSocket(IpAndPort &local) TRANS_LOGE(TRANS_STREAM, "FtSocket failed, errno=%{public}d", FtGetErrno()); return -1; } + if (!isServer) { + TRANS_LOGI(TRANS_STREAM, "FtSocket set client, errno=%{public}d", FtGetErrno()); + streamFd_ = sockFd; + } SetDefaultConfig(sockFd); // bind @@ -1555,6 +1590,12 @@ ssize_t VtpStreamSocket::Decrypt(const void *in, ssize_t inLen, void *out, ssize return outLen; } +int32_t VtpStreamSocket::SetMultiLayer(const void *para) +{ + int fd = GetStreamSocketFd(FD).GetIntValue(); + return VtpSetSocketMultiLayer(fd, &onStreamEvtCb_, para); +} + void VtpStreamSocket::CreateServerProcessThread() { auto self = this->GetSelf(); diff --git a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/vtp_stream_socket.h b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/vtp_stream_socket.h index 05d300a27..6f5c2e7ad 100644 --- a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/vtp_stream_socket.h +++ b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/vtp_stream_socket.h @@ -30,6 +30,7 @@ #include "i_stream_socket.h" #include "stream_common.h" #include "vtp_instance.h" +#include "vtp_stream_opt.h" namespace Communication { namespace SoftBus { @@ -65,6 +66,7 @@ public: bool Send(std::unique_ptr stream) override; bool SetOption(int type, const StreamAttr &value) override; + int32_t SetMultiLayer(const void *para) override; StreamAttr GetOption(int type) const override; bool SetStreamListener(std::shared_ptr receiver) override; @@ -106,7 +108,7 @@ private: bool ProcessCommonDataStream(std::unique_ptr &dataBuffer, int32_t &dataLength, std::unique_ptr &extBuffer, int32_t &extLen, StreamFrameInfo &info); void InsertElementToFuncMap(int type, ValueType valueType, MySetFunc set, MyGetFunc get); - int CreateAndBindSocket(IpAndPort &local) override; + int CreateAndBindSocket(IpAndPort &local, bool isServer) override; bool Accept() override; int EpollTimeout(int fd, int timeout) override; @@ -184,6 +186,10 @@ private: static int HandleRipplePolicy(int fd, const FtEventCbkInfo *info); + static int HandleFillpFrameEvt(int fd, const FtEventCbkInfo *info); + + int HandleFillpFrameEvtInner(int fd, const FtEventCbkInfo *info); + static int FillpStatistics(int fd, const FtEventCbkInfo *info); void FillpAppStatistics(); @@ -206,6 +212,7 @@ private: int scene_ = UNKNOWN_SCENE; int streamHdrSize_ = 0; bool isDestroyed_ = false; + OnFrameEvt onStreamEvtCb_; }; } // namespace SoftBus } // namespace Communication 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 54afc70aa..d344c0e34 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 @@ -214,6 +214,15 @@ int32_t TransSendStream(int32_t channelId, const StreamData *data, const StreamD return SendVtpStream(channelId, data, ext, param); } +int32_t TransSetStreamMultiLayer(int32_t channelId, const void *optValue) +{ + if (channelId < 0) { + TRANS_LOGE(TRANS_STREAM, "param invalid"); + return SOFTBUS_INVALID_PARAM; + } + return SetVtpStreamMultiLayerOpt(channelId, optValue); +} + int32_t TransCloseStreamChannel(int32_t channelId) { TRANS_LOGI(TRANS_STREAM, "close stream channel. channelId=%{public}d", channelId); diff --git a/tests/BUILD.gn b/tests/BUILD.gn index 445130a85..331a48c2b 100644 --- a/tests/BUILD.gn +++ b/tests/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 @@ -11,20 +11,82 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//build/lite/config/component/lite_component.gni") +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") -lite_component("softbus_test") { - if (ohos_kernel_type == "liteos_m") { - features = [] - } else { - features = [] - if (ohos_build_type == "debug") { - features += [ - "sdk/discovery/unittest:DiscSdkTest", - "adapter/unittest:AdapterTest", - "sdk/transmission/trans_channel:TransSdkStreamTest", - "sdk/bus_center/unittest:BusCenterSdkRefreshSmall", + lite_component("softbus_test") { + if (ohos_kernel_type == "liteos_m") { + features = [] + } else { + features = [] + if (ohos_build_type == "debug") { + features += [ + "adapter/unittest:AdapterTest", + "sdk/bus_center/unittest:BusCenterSdkRefreshSmall", + "sdk/discovery/unittest:DiscSdkTest", + "sdk/transmission/trans_channel:TransSdkStreamTest", + ] + } + } + } +} else { + import("//build/test.gni") + import("../dsoftbus.gni") + + group("unittest") { + testonly = true + deps = [] + if (!use_libfuzzer) { + deps += [ + "adapter:unittest", + "core/adapter:unittest", + "core/authentication:unittest", + "core/broadcast:unittest", + "core/bus_center:unittest", + "core/common:unittest", + "core/connection:unittest", + "core/discovery:unittest", + "core/transmission:unittest", + "sdk/bus_center:unittest", + "sdk/discovery:unittest", + "sdk/frame/common:unittest", + "sdk/frame/standard:unittest", + "sdk/transmission:unittest", ] } } + + group("fuzztest") { + testonly = true + deps = [ + "adapter:fuzztest", + "core/adapter:fuzztest", + "core/authentication:fuzztest", + "core/broadcast:fuzztest", + "core/bus_center:fuzztest", + "core/common:fuzztest", + "core/connection:fuzztest", + "core/discovery:fuzztest", + "core/frame:fuzztest", + "core/transmission:fuzztest", + "sdk/bus_center:fuzztest", + "sdk/discovery:fuzztest", + "sdk/frame:fuzztest", + "sdk/transmission:fuzztest", + ] + } + + group("benchmarktest") { + testonly = true + deps = [ + "sdk/bus_center:benchmarktest", + "sdk/discovery:benchmarktest", + "sdk/transmission:benchmarktest", + ] + } + + group("integration_test") { + testonly = true + deps = [ "sdk/transmission:integration_test" ] + } } diff --git a/tests/common/include/fuzz_data_generator.h b/tests/common/include/fuzz_data_generator.h index 2078a96f6..d30f58117 100644 --- a/tests/common/include/fuzz_data_generator.h +++ b/tests/common/include/fuzz_data_generator.h @@ -45,7 +45,7 @@ private: }; template -bool GenerateFromList(T &value, const std::vector &candidateValues) +inline bool GenerateFromList(T &value, const std::vector &candidateValues) { if (candidateValues.empty()) { return false; @@ -58,67 +58,67 @@ bool GenerateFromList(T &value, const std::vector &candidateValues) return true; } -bool GenerateBool(bool &value) +inline bool GenerateBool(bool &value) { return DataGenerator::GetInstance().ReadBool(value); } -bool GenerateInt8(int8_t &value) +inline bool GenerateInt8(int8_t &value) { return DataGenerator::GetInstance().ReadInt8(value); } -bool GenerateInt16(int16_t &value) +inline bool GenerateInt16(int16_t &value) { return DataGenerator::GetInstance().ReadInt16(value); } -bool GenerateInt32(int32_t &value) +inline bool GenerateInt32(int32_t &value) { return DataGenerator::GetInstance().ReadInt32(value); } -bool GenerateInt64(int64_t &value) +inline bool GenerateInt64(int64_t &value) { return DataGenerator::GetInstance().ReadInt64(value); } -bool GenerateUint8(uint8_t &value) +inline bool GenerateUint8(uint8_t &value) { return DataGenerator::GetInstance().ReadUint8(value); } -bool GenerateUint16(uint16_t &value) +inline bool GenerateUint16(uint16_t &value) { return DataGenerator::GetInstance().ReadUint16(value); } -bool GenerateUint32(uint32_t &value) +inline bool GenerateUint32(uint32_t &value) { return DataGenerator::GetInstance().ReadUint32(value); } -bool GenerateUint64(uint64_t &value) +inline bool GenerateUint64(uint64_t &value) { return DataGenerator::GetInstance().ReadUint64(value); } -bool GenerateFloat(float &value) +inline bool GenerateFloat(float &value) { return DataGenerator::GetInstance().ReadFloat(value); } -bool GenerateDouble(double &value) +inline bool GenerateDouble(double &value) { return DataGenerator::GetInstance().ReadDouble(value); } -bool GenerateString(std::string &value) +inline bool GenerateString(std::string &value) { return DataGenerator::GetInstance().ReadString(value); } -bool GeneratePayload(std::vector &payload, const std::vector &prefix = {}) +inline bool GeneratePayload(std::vector &payload, const std::vector &prefix = {}) { uint8_t len = 0; if (!DataGenerator::GetInstance().ReadUint8(len)) { diff --git a/tests/common/include/fuzz_environment.h b/tests/common/include/fuzz_environment.h new file mode 100644 index 000000000..71d52a3c6 --- /dev/null +++ b/tests/common/include/fuzz_environment.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 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 + * + * 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 FUZZ_ENVIRONMENT_H +#define FUZZ_ENVIRONMENT_H + +namespace OHOS::SoftBus { +class FuzzEnvironment { +public: + static bool IsFuzzEnable() + { + return fuzzEnable_; + }; + + static void EnableFuzz() + { + fuzzEnable_ = true; + }; + +private: + static inline bool fuzzEnable_ = false; +}; +} // namespace OHOS::SoftBus + +#endif // FUZZ_ENVIRONMENT_H diff --git a/tests/core/authentication/BUILD.gn b/tests/core/authentication/BUILD.gn index cf9c1b6d1..cac3c4caf 100644 --- a/tests/core/authentication/BUILD.gn +++ b/tests/core/authentication/BUILD.gn @@ -128,6 +128,7 @@ ohos_unittest("AuthEnhanceMockTest") { include_dirs = [ "$dsoftbus_root_path/adapter/common/include", + "$dsoftbus_root_path/adapter/common/net/bluetooth/include", "$dsoftbus_root_path/tests/core/bus_center/mock_common/include", "//base/security/device_auth/interfaces/inner_api", "$dsoftbus_root_path/core/authentication/include", @@ -236,6 +237,7 @@ ohos_unittest("AuthTestCallBackTest") { include_dirs = [ "$dsoftbus_root_path/adapter/common/include", + "$dsoftbus_root_path/adapter/common/net/bluetooth/include", "$dsoftbus_root_path/tests/core/bus_center/mock_common/include", "//base/security/device_auth/interfaces/inner_api", "$dsoftbus_root_path/core/authentication/include", @@ -442,6 +444,7 @@ ohos_unittest("AuthHichainTest") { include_dirs = [ "//base/security/device_auth/interfaces/inner_api", + "$dsoftbus_root_path/adapter/common/net/bluetooth/include", "$dsoftbus_root_path/core/authentication/include", "$dsoftbus_root_path/core/authentication/interface", "$dsoftbus_root_path/tests/core/authentication/unittest", diff --git a/tests/core/authentication/unittest/auth_common_mock.cpp b/tests/core/authentication/unittest/auth_common_mock.cpp index a907006e6..2f075f3c9 100644 --- a/tests/core/authentication/unittest/auth_common_mock.cpp +++ b/tests/core/authentication/unittest/auth_common_mock.cpp @@ -121,5 +121,10 @@ int32_t LnnRequestLeaveSpecific(const char *networkId, ConnectionAddrType addrTy { return GetCommonInterface()->LnnRequestLeaveSpecific(networkId, addrType); } + +int32_t SoftBusGetBtMacAddr(SoftBusBtAddr *mac) +{ + return GetCommonInterface()->SoftBusGetBtMacAddr(mac); +} } } // namespace OHOS \ No newline at end of file diff --git a/tests/core/authentication/unittest/auth_common_mock.h b/tests/core/authentication/unittest/auth_common_mock.h index 211a7a07b..07b53c068 100644 --- a/tests/core/authentication/unittest/auth_common_mock.h +++ b/tests/core/authentication/unittest/auth_common_mock.h @@ -27,6 +27,7 @@ #include "lnn_lane_interface.h" #include "lnn_ohos_account_adapter.h" #include "lnn_node_info.h" +#include "softbus_adapter_bt_common.h" namespace OHOS { class AuthCommonInterface { @@ -52,6 +53,7 @@ public: virtual int32_t LnnNotifyLeaveLnnByAuthHandle(AuthHandle *authHandle); virtual int32_t LnnRequestLeaveSpecific(const char *networkId, ConnectionAddrType addrType); virtual int32_t LnnGetRemoteNumU64Info(const char *networkId, InfoKey key, uint64_t *info) = 0; + virtual int32_t SoftBusGetBtMacAddr(SoftBusBtAddr *mac) = 0; }; class AuthCommonInterfaceMock : public AuthCommonInterface { public: @@ -74,6 +76,7 @@ public: MOCK_METHOD1(LnnNotifyEmptySessionKey, int32_t (int64_t)); MOCK_METHOD1(LnnNotifyLeaveLnnByAuthHandle, int32_t (AuthHandle *)); MOCK_METHOD2(LnnRequestLeaveSpecific, int32_t (const char *, ConnectionAddrType)); + MOCK_METHOD1(SoftBusGetBtMacAddr, int32_t (SoftBusBtAddr *)); }; } // namespace OHOS #endif // AUTH_COMMON_MOCK_H \ No newline at end of file diff --git a/tests/core/authentication/unittest/auth_manager_test.cpp b/tests/core/authentication/unittest/auth_manager_test.cpp index 3beb99f1f..7165ae3b3 100644 --- a/tests/core/authentication/unittest/auth_manager_test.cpp +++ b/tests/core/authentication/unittest/auth_manager_test.cpp @@ -38,6 +38,7 @@ constexpr uint64_t CONN_ID_2 = 12; constexpr uint64_t CONN_ID_3 = 13; constexpr int32_t PORT = 1; constexpr int32_t PORT_1 = 2; +constexpr int32_t KEY_INDEX = 1; constexpr int32_t GROUP_TYPE = 100; constexpr int32_t DEVICE_ID_HASH_LEN = 9; constexpr int32_t KEY_VALUE_LEN = 13; @@ -132,8 +133,10 @@ HWTEST_F(AuthManagerTest, NEW_AND_FIND_AUTH_MANAGER_TEST_001, TestSize.Level1) connInfo.type = AUTH_LINK_TYPE_WIFI; ASSERT_TRUE(memcpy_s(connInfo.info.ipInfo.ip, IP_LEN, IP_TEST, strlen(IP_TEST)) == EOK); EXPECT_TRUE(FindAuthManagerByConnInfo(&connInfo, false) != nullptr); + AuthNotifyAuthPassed(AUTH_SEQ, &info); ASSERT_TRUE(memcpy_s(connInfo.info.ipInfo.ip, IP_LEN, INVALID_IP_TEST, strlen(INVALID_IP_TEST)) == EOK); EXPECT_TRUE(FindAuthManagerByConnInfo(&connInfo, false) == nullptr); + AuthNotifyAuthPassed(AUTH_SEQ, &info); RemoveAuthManagerByConnInfo(&connInfo, false); PrintAuthConnInfo(&connInfo); (void)memset_s(&connInfo, sizeof(AuthConnInfo), 0, sizeof(AuthConnInfo)); @@ -192,6 +195,8 @@ HWTEST_F(AuthManagerTest, FIND_AUTH_MANAGER_TEST_001, TestSize.Level1) EXPECT_TRUE(UpdateAuthManagerByAuthId(AUTH_SEQ, MyUpdateFuncReturnOk, auth, AUTH_LINK_TYPE_WIFI) == SOFTBUS_OK); AuthConnInfo connInfo; EXPECT_EQ(GetAuthConnInfoByUuid(UUID_TEST, AUTH_LINK_TYPE_WIFI, &connInfo), SOFTBUS_OK); + AuthHandle authHandle = { .authId = AUTH_SEQ, .type = AUTH_LINK_TYPE_WIFI, }; + AuthHandleLeaveLNN(authHandle); } /* @@ -732,5 +737,180 @@ HWTEST_F(AuthManagerTest, AUTH_GET_LATEST_AUTH_SEQ_LIST_BY_TYPE_TEST_001, TestSi int32_t ret2 = AuthGetLatestAuthSeqListByType(UDID_TEST, authSeq, authVerifyTime, DISCOVERY_TYPE_BLE); EXPECT_TRUE(ret2 == SOFTBUS_OK); } -} // namespace OHOS +/* + * @tc.name: PROCESS_SESSION_KEY_TEST_001 + * @tc.desc: ProcessSessionKey test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthManagerTest, PROCESS_SESSION_KEY_TEST_001, TestSize.Level1) +{ + AuthSessionInfo info; + SetAuthSessionInfo(&info, CONN_ID, false, AUTH_LINK_TYPE_BLE); + info.normalizedType = NORMALIZED_SUPPORT; + AuthManager *auth = NewAuthManager(AUTH_SEQ, &info); + EXPECT_TRUE(auth != nullptr); + SessionKey sessionKey = { { 0 }, TEST_DATA_LEN }; + AuthManager *auth1 = GetExistAuthManager(AUTH_SEQ, &info); + EXPECT_TRUE(auth1 != nullptr); + info.connInfo.type = AUTH_LINK_TYPE_MAX; + int32_t keyIndex = KEY_INDEX; + info.connInfo.type = AUTH_LINK_TYPE_BLE; + auth->hasAuthPassed[AUTH_LINK_TYPE_BLE] = true; + int32_t ret = ProcessEmptySessionKey(&info, keyIndex, false, &sessionKey); + EXPECT_TRUE(ret == SOFTBUS_OK); + ret = AuthProcessEmptySessionKey(&info, keyIndex); + EXPECT_TRUE(ret == SOFTBUS_OK); + info.module = AUTH_MODULE_TRANS; + ret = AuthProcessEmptySessionKey(&info, keyIndex); + EXPECT_TRUE(ret == SOFTBUS_OK); + AuthManager *auth2 = FindAuthManagerByUdid(info.udid, info.connInfo.type, info.isServer); + EXPECT_TRUE(auth2 != nullptr); +} + +/* + * @tc.name: GENERATE_UDID_HASH_TEST_001 + * @tc.desc: GenerateUdidHash test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthManagerTest, GENERATE_UDID_HASH_TEST_001, TestSize.Level1) +{ + NodeInfo info; + AuthHandle authHandle = { .authId = AUTH_SEQ, .type = AUTH_LINK_TYPE_WIFI, }; + ReportAuthRequestPassed(REQUEST_ID_1, authHandle, &info); + ReportAuthRequestPassed(REQUEST_ID_1 + 1, authHandle, &info); + AuthSessionInfo sessionInfo; + PostCancelAuthMessage(AUTH_SEQ, &sessionInfo); + AuthNotifyAuthPassed(AUTH_SEQ, &sessionInfo); + AuthConnInfo connInfo; + AuthDataHead head; + HandleDecryptFailData(CONN_ID_1, &connInfo, true, &head, nullptr); + HandleCancelAuthData(CONN_ID_1, &connInfo, true, &head, nullptr); + connInfo.type = AUTH_LINK_TYPE_BLE; + bool fromServer = true; + CorrectFromServer(CONN_ID_1, &connInfo, &fromServer); + uint8_t hash[SHA_256_HASH_LEN]; + int32_t ret = GenerateUdidHash(UDID_TEST, hash); + EXPECT_TRUE(ret == SOFTBUS_OK); +} + +/* + * @tc.name: GET_ALL_HML_OR_P2P_AUTH_HANDLE_NUM_TEST_001 + * @tc.desc: GetAllHmlOrP2pAuthHandleNum test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthManagerTest, GET_ALL_HML_OR_P2P_AUTH_HANDLE_NUM_TEST_001, TestSize.Level1) +{ + AuthHandle authHandle1 = { .authId = AUTH_SEQ, .type = AUTH_LINK_TYPE_WIFI, }; + AuthDeviceGetLatestIdByUuid(UDID_TEST, AUTH_LINK_TYPE_BLE, &authHandle1); + AuthDeviceGetLatestIdByUuid(UDID_TEST, AUTH_LINK_TYPE_BR, &authHandle1); + uint32_t ret = GetAllHmlOrP2pAuthHandleNum(); + EXPECT_TRUE(ret == SOFTBUS_OK); + ret = GetHmlOrP2pAuthHandle(nullptr, nullptr); + EXPECT_TRUE(ret == 3868524547); + AuthHandle *authHandle = &authHandle1; + ret = GetHmlOrP2pAuthHandle(&authHandle, nullptr); + EXPECT_TRUE(ret == 3868524547); + int32_t num = 0; + ret = GetHmlOrP2pAuthHandle(&authHandle, &num); + EXPECT_TRUE(ret == 3868983317); +} + +/* + * @tc.name: AUTH_DEVICE_GET_AUTH_HANDLE_BY_INDEX_TEST_001 + * @tc.desc: AuthDeviceGetAuthHandleByIndex test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthManagerTest, AUTH_DEVICE_GET_AUTH_HANDLE_BY_INDEX_TEST_001, TestSize.Level1) +{ + AuthHandle authHandle; + int32_t ret = AuthDeviceGetAuthHandleByIndex(UDID_TEST, false, KEY_INDEX, &authHandle); + EXPECT_TRUE(ret == SOFTBUS_OK); + ret = AuthDeviceGetAuthHandleByIndex(UDID_TEST, false, KEY_INDEX, &authHandle); + EXPECT_TRUE(ret == SOFTBUS_OK); + ret = AuthDeviceGetAuthHandleByIndex(UDID_TEST, false, KEY_INDEX, &authHandle); + EXPECT_TRUE(ret == SOFTBUS_OK); +} + +/* + * @tc.name: AUTH_MAP_INIT_TEST_001 + * @tc.desc: AuthMapInit test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthManagerTest, AUTH_MAP_INIT_TEST_001, TestSize.Level1) +{ + uint64_t currentTime = 123456; + InsertToAuthLimitMap(UDID_TEST, currentTime); + AuthDeleteLimitMap(nullptr); + ClearAuthLimitMap(); + int32_t res = GetNodeFromAuthLimitMap(UDID_TEST, ¤tTime); + EXPECT_TRUE(res == SOFTBUS_OK); + bool ret = AuthMapInit(); + EXPECT_TRUE(ret == true); + InsertToAuthLimitMap(UDID_TEST, currentTime); + currentTime = 0; + InsertToAuthLimitMap(UUID_TEST, currentTime); + res = GetNodeFromAuthLimitMap(UDID_TEST, ¤tTime); + EXPECT_TRUE(res == SOFTBUS_OK); + res = GetNodeFromAuthLimitMap(INVALID_UDID_TEST, ¤tTime); + EXPECT_TRUE(res == SOFTBUS_INVALID_PARAM); +} + +/* + * @tc.name: IS_NEED_AUTH_LIMIT_TEST_001 + * @tc.desc: IsNeedAuthLimit test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthManagerTest, IS_NEED_AUTH_LIMIT_TEST_001, TestSize.Level1) +{ + bool ret = IsNeedAuthLimit(nullptr); + EXPECT_TRUE(ret == false); + ret = IsNeedAuthLimit(INVALID_UDID_TEST); + EXPECT_TRUE(ret == false); + ret = IsNeedAuthLimit(UUID_TEST); + EXPECT_TRUE(ret == false); + ret = IsNeedAuthLimit(UDID_TEST); + EXPECT_TRUE(ret == false); + AuthDeleteLimitMap(nullptr); + AuthDeleteLimitMap(INVALID_UDID_TEST); + AuthDeleteLimitMap(UUID_TEST); + AuthDeleteLimitMap(UDID_TEST); + ClearAuthLimitMap(); +} + +/* + * @tc.name: AUTH_DEVICE_ENCRYPT_TEST_002 + * @tc.desc: AuthDeviceEncrypt test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthManagerTest, AUTH_DEVICE_ENCRYPT_TEST_002, TestSize.Level1) +{ + AuthAddNodeToLimitMap(UDID_TEST, SOFTBUS_AUTH_HICHAIN_GROUP_NOT_EXIST); + AuthAddNodeToLimitMap(UDID_TEST, SOFTBUS_AUTH_HICHAIN_LOCAL_IDENTITY_NOT_EXIST); + AuthAddNodeToLimitMap(UDID_TEST, SOFTBUS_AUTH_HICHAIN_NO_CANDIDATE_GROUP); + AuthAddNodeToLimitMap(UDID_TEST, SOFTBUS_ERR); + AuthDeviceNotTrust(nullptr); + const char *peerUdid = ""; + AuthDeviceNotTrust(peerUdid); + AuthDeviceNotTrust(UDID_TEST); + AuthSessionInfo info; + SetAuthSessionInfo(&info, CONN_ID, false, AUTH_LINK_TYPE_WIFI); + AuthManager *auth = NewAuthManager(AUTH_SEQ, &info); + EXPECT_TRUE(auth != nullptr); + AuthHandle authHandle = { .authId = AUTH_SEQ_5, .type = AUTH_LINK_TYPE_WIFI, }; + uint8_t outData[LENTH] = {0}; + uint32_t outLen = LENTH + TMP_DATA_LEN + 32; + EXPECT_TRUE(AuthDeviceEncrypt(&authHandle, TMP_IN_DATA, + TMP_DATA_LEN, outData, &outLen) == SOFTBUS_AUTH_NOT_FOUND); + authHandle.authId = AUTH_SEQ; + EXPECT_TRUE(AuthDeviceEncrypt(&authHandle, TMP_IN_DATA, + TMP_DATA_LEN, outData, &outLen) == SOFTBUS_ENCRYPT_ERR); +} +} // namespace OHOS diff --git a/tests/core/authentication/unittest/auth_net_ledger_mock.cpp b/tests/core/authentication/unittest/auth_net_ledger_mock.cpp index a7165bef4..e6c960685 100644 --- a/tests/core/authentication/unittest/auth_net_ledger_mock.cpp +++ b/tests/core/authentication/unittest/auth_net_ledger_mock.cpp @@ -195,6 +195,11 @@ bool LnnGetOnlineStateById(const char *id, IdCategory type) { return GetNetLedgerInterface()->LnnGetOnlineStateById(id, type); } + +int32_t LnnGetLocalNodeInfoSafe(NodeInfo *info) +{ + return GetNetLedgerInterface()->LnnGetLocalNodeInfoSafe(info); +} } diff --git a/tests/core/authentication/unittest/auth_net_ledger_mock.h b/tests/core/authentication/unittest/auth_net_ledger_mock.h index 188f1bf64..e67b42917 100644 --- a/tests/core/authentication/unittest/auth_net_ledger_mock.h +++ b/tests/core/authentication/unittest/auth_net_ledger_mock.h @@ -66,6 +66,7 @@ public: virtual bool LnnSetDlPtk(const char *networkId, const char *remotePtk) = 0; virtual void LnnDumpRemotePtk(const char *oldPtk, const char *newPtk, const char *log) = 0; virtual bool LnnGetOnlineStateById(const char *id, IdCategory type) = 0; + virtual int32_t LnnGetLocalNodeInfoSafe(NodeInfo *info) = 0; }; class AuthNetLedgertInterfaceMock : public AuthNetLedgerInterface { public: @@ -101,6 +102,7 @@ public: MOCK_METHOD2(LnnSetDlPtk, bool (const char *, const char *)); MOCK_METHOD3(LnnDumpRemotePtk, void (const char *, const char *, const char *)); MOCK_METHOD2(LnnGetOnlineStateById, bool(const char *, IdCategory)); + MOCK_METHOD1(LnnGetLocalNodeInfoSafe, int32_t (NodeInfo *)); static inline bool isRuned; static inline SoftBusMutex mutex; diff --git a/tests/core/authentication/unittest/auth_other_test.cpp b/tests/core/authentication/unittest/auth_other_test.cpp index 95cea1a26..4bfb29987 100644 --- a/tests/core/authentication/unittest/auth_other_test.cpp +++ b/tests/core/authentication/unittest/auth_other_test.cpp @@ -46,6 +46,7 @@ constexpr uint32_t BLE_CONNID = 196609; constexpr uint32_t BR_CONNID = 65570; constexpr uint32_t WIFI_CONNID = 131073; constexpr uint32_t MSG_LEN = 50; +constexpr char NETWORK_ID[] = "testnetworkid123"; class AuthOtherTest : public testing::Test { public: @@ -1143,4 +1144,199 @@ HWTEST_F(AuthOtherTest, GET_AUTH_CONN_001, TestSize.Level1) SoftBusFree(connInfo); } + +/* + * @tc.name: AUTH_GET_AUTH_HANDLE_BY_INDEX_TEST_001 + * @tc.desc: AuthGetAuthHandleByIndex test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthOtherTest, AUTH_GET_AUTH_HANDLE_BY_INDEX_TEST_001, TestSize.Level1) +{ + AuthConnInfo connInfo = { + .info.ipInfo.ip = "192.168.12.1", + .type = AUTH_LINK_TYPE_WIFI, + }; + AuthHandle authHandle; + (void)memset_s(&authHandle, sizeof(AuthHandle), 0, sizeof(AuthHandle)); + EXPECT_TRUE(AuthGetAuthHandleByIndex(nullptr, true, 1, &authHandle) == SOFTBUS_INVALID_PARAM); + EXPECT_TRUE(AuthGetAuthHandleByIndex(&connInfo, true, 1, nullptr) == SOFTBUS_INVALID_PARAM); + EXPECT_TRUE(AuthGetAuthHandleByIndex(&connInfo, true, 1, &authHandle) == SOFTBUS_LOCK_ERR); + char UDID_TEST[UDID_BUF_LEN] = "123456789udidtest"; + connInfo.type = AUTH_LINK_TYPE_BLE; + ASSERT_TRUE(memcpy_s(connInfo.info.bleInfo.deviceIdHash, UDID_HASH_LEN, UDID_TEST, strlen(UDID_TEST)) == EOK); + EXPECT_TRUE(AuthGetAuthHandleByIndex(&connInfo, true, 1, &authHandle) == SOFTBUS_NOT_FIND); + char BR_MAC[BT_MAC_LEN] = "00:15:5d:de:d4:23"; + connInfo.type = AUTH_LINK_TYPE_BR; + ASSERT_TRUE(memcpy_s(connInfo.info.brInfo.brMac, BT_MAC_LEN, BR_MAC, strlen(BR_MAC)) == EOK); + EXPECT_TRUE(AuthGetAuthHandleByIndex(&connInfo, true, 1, &authHandle) == SOFTBUS_LOCK_ERR); + connInfo.type = AUTH_LINK_TYPE_MAX; + EXPECT_TRUE(AuthGetAuthHandleByIndex(&connInfo, true, 1, &authHandle) == SOFTBUS_INVALID_PARAM); +} + +/* + * @tc.name: AUTH_CHECK_SESSION_KEY_VALID_BY_CONN_INFO_TEST_001 + * @tc.desc: AuthCheckSessionKeyValidByConnInfo test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthOtherTest, AUTH_CHECK_SESSION_KEY_VALID_BY_CONN_INFO_TEST_001, TestSize.Level1) +{ + const char *networkId = "123456456"; + AuthConnInfo connInfo; + EXPECT_TRUE(AuthCheckSessionKeyValidByConnInfo(nullptr, &connInfo) == SOFTBUS_INVALID_PARAM); + EXPECT_TRUE(AuthCheckSessionKeyValidByConnInfo(networkId, nullptr) == SOFTBUS_INVALID_PARAM); + EXPECT_TRUE(AuthCheckSessionKeyValidByConnInfo(networkId, &connInfo) == SOFTBUS_NETWORK_GET_NODE_INFO_ERR); + EXPECT_TRUE(AuthCheckSessionKeyValidByAuthHandle(nullptr) == SOFTBUS_INVALID_PARAM); + AuthHandle authHandle = { .type = AUTH_LINK_TYPE_WIFI, .authId = 0, }; + EXPECT_TRUE(AuthCheckSessionKeyValidByAuthHandle(&authHandle) == SOFTBUS_AUTH_SESSION_KEY_INVALID); + authHandle.type = -1; + AuthTransData dataInfo; + AuthCloseConn(authHandle); + EXPECT_TRUE(AuthPostTransData(authHandle, &dataInfo) == SOFTBUS_INVALID_PARAM); + EXPECT_TRUE(AuthGetConnInfo(authHandle, &connInfo) == SOFTBUS_INVALID_PARAM); + authHandle.type = AUTH_LINK_TYPE_MAX; + AuthCloseConn(authHandle); + EXPECT_TRUE(AuthPostTransData(authHandle, &dataInfo) == SOFTBUS_INVALID_PARAM); + EXPECT_TRUE(AuthGetConnInfo(authHandle, &connInfo) == SOFTBUS_INVALID_PARAM); + AuthFreeConn(nullptr); + AuthConnCallback callback; + EXPECT_TRUE(AuthAllocConn(nullptr, 1, &callback) == SOFTBUS_INVALID_PARAM); + EXPECT_TRUE(AuthAllocConn(networkId, 1, nullptr) == SOFTBUS_INVALID_PARAM); + EXPECT_TRUE(AuthGetP2pConnInfo(nullptr, nullptr, true) == AUTH_INVALID_ID); + EXPECT_TRUE(AuthGetHmlConnInfo(nullptr, nullptr, true) == AUTH_INVALID_ID); + AuthGetLatestIdByUuid(nullptr, AUTH_LINK_TYPE_WIFI, true, nullptr); + AuthGetLatestIdByUuid(nullptr, AUTH_LINK_TYPE_WIFI, true, &authHandle); +} + +/* + * @tc.name: AUTH_DIRECT_ONLINE_PROCESS_SESSION_KEY_TEST_001 + * @tc.desc: AuthDirectOnlineProcessSessionKey test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthOtherTest, AUTH_DIRECT_ONLINE_PROCESS_SESSION_KEY_TEST_001, TestSize.Level1) +{ + AuthDeviceKeyInfo keyInfo = { .keyLen = strlen("testKey"), .isOldKey = true, }; + ASSERT_TRUE(memcpy_s(keyInfo.deviceKey, SESSION_KEY_LENGTH, "testKey", strlen("testKey")) == EOK); + AuthSessionInfo info = { .connInfo.type = AUTH_LINK_TYPE_BR, }; + int64_t authId; + EXPECT_TRUE(AuthDirectOnlineProcessSessionKey(&info, &keyInfo, &authId) == SOFTBUS_ERR); + EXPECT_TRUE(AuthDirectOnlineWithoutSessionKey(&info, &keyInfo, &authId) == SOFTBUS_ERR); + EXPECT_TRUE(AuthEncrypt(nullptr, nullptr, 0, nullptr, nullptr) == SOFTBUS_INVALID_PARAM); + EXPECT_TRUE(AuthDecrypt(nullptr, nullptr, 0, nullptr, nullptr) == SOFTBUS_INVALID_PARAM); +} + +/* + * @tc.name: IS_SAME_ACCOUNT_DEVICE_TEST_001 + * @tc.desc: IsSameAccountDevice test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthOtherTest, IS_SAME_ACCOUNT_DEVICE_TEST_001, TestSize.Level1) +{ + EXPECT_TRUE(LnnInitLocalLedger() == SOFTBUS_OK); + uint8_t accountHash[SHA_256_HASH_LEN] = "accounthashtest"; + EXPECT_TRUE(LnnSetLocalByteInfo(BYTE_KEY_ACCOUNT_HASH, accountHash, SHA_256_HASH_LEN) == SOFTBUS_OK); + EXPECT_TRUE(AuthIsPotentialTrusted(nullptr) == false); + DeviceInfo device = { .devId = "testId", .accountHash = "accounthashtest", }; + EXPECT_TRUE(AuthIsPotentialTrusted(&device) == true); + EXPECT_TRUE(IsSameAccountDevice(nullptr) == false); + EXPECT_TRUE(IsSameAccountDevice(&device) == true); + EXPECT_TRUE(AuthHasSameAccountGroup() == false); +} + +/* + * @tc.name: FILL_AUTH_SESSION_INFO_TEST_001 + * @tc.desc: FillAuthSessionInfo test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthOtherTest, FILL_AUTH_SESSION_INFO_TEST_001, TestSize.Level1) +{ + AuthSessionInfo info = { .connInfo.info.bleInfo.deviceIdHash = "123456789udidhashtest", }; + NodeInfo nodeInfo = { + .authCapacity = 127, + .uuid = "123456789uuidhashtest", + .deviceInfo.deviceUdid = "123456789udidtest", + }; + AuthDeviceKeyInfo keyInfo; + EXPECT_TRUE(FillAuthSessionInfo(&info, &nodeInfo, &keyInfo, true) == SOFTBUS_OK); + EXPECT_TRUE(FillAuthSessionInfo(&info, &nodeInfo, &keyInfo, false) == SOFTBUS_OK); +} + +/* + * @tc.name: DEL_AUTH_REQ_INFO_BY_AUTH_HANDLE_TEST_001 + * @tc.desc: DelAuthReqInfoByAuthHandle test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthOtherTest, DEL_AUTH_REQ_INFO_BY_AUTH_HANDLE_TEST_001, TestSize.Level1) +{ + InitAuthReqInfo(); + AuthConnCallback authConnCb = { + .onConnOpened = OnConnOpenedTest, + .onConnOpenFailed = OnConnOpenFailedTest, + }; + EXPECT_EQ(AddAuthReqNode(NETWORK_ID, 1, 1, &authConnCb), SOFTBUS_OK); + EXPECT_EQ(AddAuthReqNode(NETWORK_ID, 2, 2, &authConnCb), SOFTBUS_OK); + EXPECT_EQ(AddAuthReqNode(NETWORK_ID, 3, 3, &authConnCb), SOFTBUS_OK); + OnAuthConnOpenedFail(1, -1); + OnAuthConnOpenedFail(4, -1); + AuthHandle authHandle = { .authId = 2, .type = 1, }; + AuthFreeLane(&authHandle); + EXPECT_EQ(DelAuthReqInfoByAuthHandle(&authHandle), SOFTBUS_OK); + authHandle.type = 0; + AuthFreeLane(&authHandle); + EXPECT_EQ(DelAuthReqInfoByAuthHandle(&authHandle), SOFTBUS_OK); + authHandle.authId = 1; + AuthFreeLane(&authHandle); + EXPECT_EQ(DelAuthReqInfoByAuthHandle(&authHandle), SOFTBUS_OK); + authHandle.authId = 2; + AuthFreeLane(&authHandle); + EXPECT_EQ(DelAuthReqInfoByAuthHandle(&authHandle), SOFTBUS_OK); + DeInitAuthReqInfo(); +} + +/* + * @tc.name: IS_ENHANCE_P2P_MODULE_ID_Test_001 + * @tc.desc: IsEnhanceP2pModuleId test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthOtherTest, IS_ENHANCE_P2P_MODULE_ID_Test_001, TestSize.Level1) +{ + EXPECT_EQ(IsEnhanceP2pModuleId(AUTH_ENHANCED_P2P_START), true); + EXPECT_EQ(IsEnhanceP2pModuleId(DIRECT_CHANNEL_SERVER_P2P), false); + EXPECT_EQ(IsEnhanceP2pModuleId(AUTH_P2P), false); +} + +/* + * @tc.name: AUTH_START_LISTENING_FOR_WIFI_DIRECT_Test_001 + * @tc.desc: AuthStartListeningForWifiDirect test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthOtherTest, AUTH_START_LISTENING_FOR_WIFI_DIRECT_Test_001, TestSize.Level1) +{ + AsyncCallDeviceIdReceived(nullptr); + AuthStopListeningForWifiDirect(AUTH_LINK_TYPE_P2P, AUTH_ENHANCED_P2P_START); + AuthDataHead head; + const uint8_t data[TEST_DATA_LEN] = { 0 }; + (void)memset_s(&head, sizeof(AuthDataHead), 0, sizeof(AuthDataHead)); + OnWiFiDataReceived(PROXY, 0, &head, data); + OnWiFiDataReceived(AUTH, 0, &head, data); + OnWiFiDataReceived(AUTH_P2P, 0, &head, data); + OnWiFiDataReceived(AUTH_RAW_P2P_SERVER, 0, &head, data); + OnWiFiDataReceived(AUTH_ENHANCED_P2P_START, 0, &head, data); + const char *ip = "192.138.33.33"; + ListenerModule moduleId; + (void)memset_s(&moduleId, sizeof(ListenerModule), 0, sizeof(ListenerModule)); + EXPECT_EQ(AuthStartListeningForWifiDirect(AUTH_LINK_TYPE_P2P, ip, 37025, &moduleId), + SOFTBUS_INVALID_PORT); + EXPECT_EQ(AuthStartListeningForWifiDirect(AUTH_LINK_TYPE_ENHANCED_P2P, ip, 37025, &moduleId), + SOFTBUS_INVALID_PORT); + EXPECT_EQ(AuthStartListeningForWifiDirect(AUTH_LINK_TYPE_WIFI, ip, 37025, &moduleId), + SOFTBUS_INVALID_PARAM); +} } // namespace OHOS diff --git a/tests/core/authentication/unittest/auth_session_message_test.cpp b/tests/core/authentication/unittest/auth_session_message_test.cpp index 9876b5297..ee586f7db 100644 --- a/tests/core/authentication/unittest/auth_session_message_test.cpp +++ b/tests/core/authentication/unittest/auth_session_message_test.cpp @@ -21,6 +21,7 @@ #include "auth_session_json.c" #include "auth_session_message.h" #include "auth_session_message.c" +#include "softbus_adapter_crypto.h" #include "softbus_adapter_json.h" #include "softbus_errcode.h" @@ -436,15 +437,15 @@ HWTEST_F(AuthSessionMessageTest, UnpackWifiDirectInfo_TEST_001, TestSize.Level1) NodeInfo info; (void)memset_s(&info, sizeof(NodeInfo), 0, sizeof(NodeInfo)); ASSERT_TRUE(memcpy_s(info.staticCapability, STATIC_CAP_LEN, STATIC_CAPABILITY, CAPABILITY_LEN) == EOK); - UnpackWifiDirectInfo(json, &info); + UnpackWifiDirectInfo(json, &info, false); JSON_AddInt32ToObject(json, STATIC_CAP_LENGTH, 10); - UnpackWifiDirectInfo(json, &info); + UnpackWifiDirectInfo(json, &info, false); JSON_AddStringToObject(json, STATIC_CAP, "staticCap"); - UnpackWifiDirectInfo(json, &info); + UnpackWifiDirectInfo(json, &info, false); JSON_AddStringToObject(json, PTK, "encodePtk"); - UnpackWifiDirectInfo(json, &info); + UnpackWifiDirectInfo(json, &info, false); ASSERT_TRUE(memcpy_s(info.remotePtk, PTK_DEFAULT_LEN, REMOTE_PTK, strlen(REMOTE_PTK)) == EOK); - UnpackWifiDirectInfo(json, &info); + UnpackWifiDirectInfo(json, &info, false); UnpackCommon(json, &info, SOFTBUS_OLD_V1, true); JSON_AddStringToObject(json, DEVICE_TYPE, "TV"); JSON_AddStringToObject(json, DEVICE_UUID, "123456"); @@ -785,5 +786,162 @@ HWTEST_F(AuthSessionMessageTest, UPDATE_LOCAL_AUTH_STATE_TEST_001, TestSize.Leve ret = UpdateLocalAuthState(authSeq, &info); EXPECT_EQ(ret, SOFTBUS_OK); } + +/* + * @tc.name: PACK_FAST_AUTH_VALUE_TEST_002 + * @tc.desc: PackFastAuthValue test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthSessionMessageTest, PACK_FAST_AUTH_VALUE_TEST_002, TestSize.Level1) +{ + JsonObj *obj = JSON_CreateObject(); + EXPECT_TRUE(obj != nullptr); + AuthDeviceKeyInfo deviceCommKey; + (void)memset_s(&deviceCommKey, sizeof(AuthDeviceKeyInfo), 0, sizeof(AuthDeviceKeyInfo)); + EXPECT_EQ(SOFTBUS_OK, SoftBusGenerateRandomArray(deviceCommKey.deviceKey, SESSION_KEY_LENGTH)); + deviceCommKey.keyLen = SESSION_KEY_LENGTH; + deviceCommKey.keyIndex = 12345; + EXPECT_TRUE(PackFastAuthValue(obj, &deviceCommKey) == SOFTBUS_OK); + JSON_Delete(obj); +} + +/* + * @tc.name: GET_UDID_SHORT_HASH_TEST_001 + * @tc.desc: GetUdidShortHash test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthSessionMessageTest, GET_UDID_SHORT_HASH_TEST_001, TestSize.Level1) +{ + AuthSessionInfo info = { .connInfo.type = AUTH_LINK_TYPE_BR, .isServer = true, }; + uint32_t bufLen = UDID_SHORT_HASH_HEX_STR; + char udidHash[SHORT_UDID_HASH_HEX_LEN + 1]; + EXPECT_EQ(false, GetUdidShortHash(nullptr, nullptr, bufLen)); + EXPECT_EQ(false, GetUdidShortHash(&info, nullptr, bufLen)); + EXPECT_EQ(false, GetUdidShortHash(&info, udidHash, bufLen)); + bufLen++; + EXPECT_EQ(false, GetUdidShortHash(&info, udidHash, bufLen)); + info.connInfo.type = AUTH_LINK_TYPE_WIFI; + EXPECT_EQ(true, GetUdidShortHash(&info, udidHash, bufLen)); + info.connInfo.type = AUTH_LINK_TYPE_BLE; + EXPECT_EQ(true, GetUdidShortHash(&info, udidHash, bufLen)); + info.connInfo.type = AUTH_LINK_TYPE_P2P; + EXPECT_EQ(false, GetUdidShortHash(&info, udidHash, bufLen)); + info.isServer = false; + EXPECT_EQ(false, GetUdidShortHash(&info, udidHash, bufLen)); + ASSERT_TRUE(memcpy_s(info.udid, UDID_BUF_LEN, UDID, strlen(UDID)) == EOK); + EXPECT_EQ(true, GetUdidShortHash(&info, udidHash, bufLen)); +} + +/* + * @tc.name: PACK_NORMALIZED_KEY_VALUE_TEST_001 + * @tc.desc: PackNormalizedKeyValue test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthSessionMessageTest, PACK_NORMALIZED_KEY_VALUE_TEST_001, TestSize.Level1) +{ + SessionKey sessionKey = { .len = SESSION_KEY_LENGTH, }; + EXPECT_EQ(SOFTBUS_OK, SoftBusGenerateRandomArray(sessionKey.value, SESSION_KEY_LENGTH)); + JsonObj *obj = JSON_CreateObject(); + EXPECT_TRUE(obj != nullptr); + AuthSessionInfo info = { + .isNeedFastAuth = false, + .isServer = false, + .normalizedType = NORMALIZED_KEY_ERROR, + .localState = AUTH_STATE_WAIT, + .connInfo.type = AUTH_LINK_TYPE_WIFI, + .normalizedKey = nullptr, + }; + PackNormalizedKey(obj, &info); + info.isNeedFastAuth = true; + PackNormalizedKey(obj, &info); + info.isServer = true; + PackNormalizedKey(obj, &info); + info.normalizedType = NORMALIZED_NOT_SUPPORT; + info.localState = AUTH_STATE_START; + PackNormalizedKey(obj, &info); + info.normalizedKey = &sessionKey; + PackNormalizedKey(obj, &info); + ASSERT_TRUE(memcpy_s(info.connInfo.info.ipInfo.deviceIdHash, UUID_BUF_LEN, + UUID_TEST, strlen(UUID_TEST)) == EOK); + PackNormalizedKey(obj, &info); + EXPECT_EQ(SOFTBUS_OK, PackNormalizedKeyValue(obj, &sessionKey)); + JSON_Delete(obj); +} + +/* + * @tc.name: PARSE_NORMALIZED_KEY_VALUE_TEST_001 + * @tc.desc: ParseNormalizedKeyValue test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthSessionMessageTest, PARSE_NORMALIZED_KEY_VALUE_TEST_001, TestSize.Level1) +{ + const char *encNormalizedKey = "encnormalizedkeytest"; + SessionKey sessionKey = { .len = SESSION_KEY_LENGTH, }; + EXPECT_EQ(SOFTBUS_OK, SoftBusGenerateRandomArray(sessionKey.value, SESSION_KEY_LENGTH)); + AuthSessionInfo info; + EXPECT_EQ(SOFTBUS_ERR, ParseNormalizedKeyValue(&info, encNormalizedKey, &sessionKey)); + ASSERT_TRUE(memcpy_s(info.uuid, UUID_BUF_LEN, UUID_TEST, strlen(UUID_TEST)) == EOK); + AuthDeviceKeyInfo deviceKey; + EXPECT_EQ(SOFTBUS_ERR, ParseNormalizeData(&info, const_cast(encNormalizedKey), &deviceKey)); +} + +/* + * @tc.name: PACK_DEVICE_JSON_INFO_TEST_001 + * @tc.desc: PackDeviceJsonInfo test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthSessionMessageTest, PACK_DEVICE_JSON_INFO_TEST_001, TestSize.Level1) +{ + JsonObj *obj = JSON_CreateObject(); + EXPECT_TRUE(obj != nullptr); + SessionKey sessionKey; + AuthSessionInfo info = { + .connInfo.type = AUTH_LINK_TYPE_WIFI, + .isConnectServer = false, + .localState = AUTH_STATE_START, + .isServer = false, + .normalizedKey = &sessionKey, + }; + EXPECT_EQ(SOFTBUS_OK, PackDeviceJsonInfo(&info, obj)); + const char *encNormalizedKey = "encnormalizedkeytest"; + EXPECT_EQ(true, JSON_AddStringToObject(obj, NORMALIZED_DATA, encNormalizedKey)); + UnpackNormalizedKey(obj, &info, NORMALIZED_NOT_SUPPORT); + UnpackNormalizedKey(obj, &info, NORMALIZED_SUPPORT); + info.isServer = true; + info.normalizedKey = nullptr; + ASSERT_TRUE(memcpy_s(info.uuid, UUID_BUF_LEN, UUID_TEST, strlen(UUID_TEST)) == EOK); + UnpackNormalizedKey(obj, &info, NORMALIZED_SUPPORT); + info.isConnectServer = true; + EXPECT_EQ(SOFTBUS_OK, PackDeviceJsonInfo(&info, obj)); + info.connInfo.type = AUTH_LINK_TYPE_BLE; + EXPECT_EQ(SOFTBUS_OK, PackDeviceJsonInfo(&info, obj)); + JSON_Delete(obj); +} + +/* + * @tc.name: PACK_DEVICE_INFO_MESSAGE_TEST_001 + * @tc.desc: PackDeviceInfoMessage test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthSessionMessageTest, PACK_CERTIFICATE_INFO_TEST_001, TestSize.Level1) +{ + JsonObj *obj = JSON_CreateObject(); + EXPECT_TRUE(obj != nullptr); + NodeInfo info; + const char *staticCap = "staticCapTest"; + const char *encodePtk = "encodePtkTest"; + EXPECT_EQ(true, JSON_AddInt32ToObject(obj, STATIC_CAP_LENGTH, DATA_TEST_LEN)); + EXPECT_EQ(true, JSON_AddStringToObject(obj, STATIC_CAP, staticCap)); + EXPECT_EQ(true, JSON_AddStringToObject(obj, PTK, encodePtk)); + UnpackWifiDirectInfo(obj, &info, false); + EXPECT_EQ(nullptr, PackDeviceInfoMessage(nullptr, SOFTBUS_NEW_V1, false, nullptr, nullptr)); + JSON_Delete(obj); +} } // namespace OHOS diff --git a/tests/core/authentication/unittest/auth_tcp_connection_test.cpp b/tests/core/authentication/unittest/auth_tcp_connection_test.cpp index f22871cc1..d795ec819 100644 --- a/tests/core/authentication/unittest/auth_tcp_connection_test.cpp +++ b/tests/core/authentication/unittest/auth_tcp_connection_test.cpp @@ -247,4 +247,57 @@ HWTEST_F(AuthTcpConnectionTest, SOCKET_GET_CONN_INFO_TEST_001, TestSize.Level1) ret = SocketGetConnInfo(fd, &connInfo, &isServer); EXPECT_TRUE(ret == SOFTBUS_ERR); } + +/* + * @tc.name: SOCKET_CONNECT_INNER_TEST_001 + * @tc.desc: SocketConnectInner test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthTcpConnectionTest, SOCKET_CONNECT_INNER_TEST_001, TestSize.Level1) +{ + const char *localIp = "192.168.11.22"; + const char *peerIp = "192.168.11.33"; + int32_t ret = SocketConnectInner(nullptr, peerIp, 37025, AUTH, true); + EXPECT_TRUE(ret == AUTH_INVALID_FD); + ret = SocketConnectInner(localIp, nullptr, 37025, AUTH, true); + EXPECT_TRUE(ret == AUTH_INVALID_FD); + ret = SocketConnectInner(localIp, peerIp, 37025, AUTH, true); + EXPECT_TRUE(ret == SOFTBUS_CONN_SOCKET_GET_INTERFACE_ERR); +} + +/* + * @tc.name: NIP_SOCKET_CONNECT_DEVICE_TEST_001 + * @tc.desc: NipSocketConnectDevice test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthTcpConnectionTest, NIP_SOCKET_CONNECT_DEVICE_TEST_001, TestSize.Level1) +{ + const char *addr = "192.168.11.44"; + int32_t ret = NipSocketConnectDevice(AUTH, addr, 37025, true); + EXPECT_TRUE(ret == AUTH_INVALID_FD); + ret = NipSocketConnectDevice(AUTH, nullptr, 37025, true); + EXPECT_TRUE(ret == AUTH_INVALID_FD); +} + +/* + * @tc.name: AUTH_OPEN_CHANNEL_WITH_ALL_IP_TEST_001 + * @tc.desc: AuthOpenChannelWithAllIp test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthTcpConnectionTest, AUTH_OPEN_CHANNEL_WITH_ALL_IP_TEST_001, TestSize.Level1) +{ + const char *localIp = "192.168.11.22"; + const char *remoteIp = "192.168.11.33"; + int32_t ret = AuthOpenChannelWithAllIp(localIp, remoteIp, 37025); + EXPECT_TRUE(ret == INVALID_CHANNEL_ID); + ret = AuthOpenChannelWithAllIp(nullptr, remoteIp, 37025); + EXPECT_TRUE(ret == SOFTBUS_INVALID_PARAM); + ret = AuthOpenChannelWithAllIp(localIp, nullptr, 37025); + EXPECT_TRUE(ret == SOFTBUS_INVALID_PARAM); + ret = AuthOpenChannelWithAllIp(localIp, remoteIp, 0); + EXPECT_TRUE(ret == SOFTBUS_INVALID_PARAM); +} } // namespace OHOS diff --git a/tests/core/authentication/unittest/auth_test.cpp b/tests/core/authentication/unittest/auth_test.cpp index c40c6e6f1..25b9e87c7 100644 --- a/tests/core/authentication/unittest/auth_test.cpp +++ b/tests/core/authentication/unittest/auth_test.cpp @@ -2167,4 +2167,17 @@ HWTEST_F(AuthTest, GET_TCP_KEEPALIVE_OPTION_BY_CYCLE_Test_001, TestSize.Level1) ret = GetTcpKeepaliveOptionByCycle(DEFAULT_FREQ_CYCLE, &tcpKeepaliveOption); EXPECT_TRUE(ret == SOFTBUS_OK); } + +/* + * @tc.name: IS_ENHANCE_P2P_MODULE_ID_Test_001 + * @tc.desc: IsEnhanceP2pModuleId test + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AuthTest, IS_ENHANCE_P2P_MODULE_ID_Test_001, TestSize.Level1) +{ + EXPECT_EQ(IsEnhanceP2pModuleId(AUTH_ENHANCED_P2P_START), true); + EXPECT_EQ(IsEnhanceP2pModuleId(DIRECT_CHANNEL_SERVER_P2P), false); + EXPECT_EQ(IsEnhanceP2pModuleId(AUTH_P2P), false); +} } // namespace OHOS diff --git a/tests/core/bus_center/lnn/BUILD.gn b/tests/core/bus_center/lnn/BUILD.gn index f6dac5abe..d0d93942d 100644 --- a/tests/core/bus_center/lnn/BUILD.gn +++ b/tests/core/bus_center/lnn/BUILD.gn @@ -1663,6 +1663,7 @@ ohos_unittest("LNNDiscoveryInterfaceTest") { include_dirs = [ "disc_mgr", + "$dsoftbus_root_path/adapter/common/net/bluetooth/include", "$dsoftbus_root_path/adapter/common/include", "$dsoftbus_root_path/core/adapter/bus_center/include", "$dsoftbus_root_path/core/authentication/include", diff --git a/tests/core/bus_center/lnn/lane/include/lnn_lane_deps_mock.h b/tests/core/bus_center/lnn/lane/include/lnn_lane_deps_mock.h index 25c3ce4ae..1cf5f91e6 100644 --- a/tests/core/bus_center/lnn/lane/include/lnn_lane_deps_mock.h +++ b/tests/core/bus_center/lnn/lane/include/lnn_lane_deps_mock.h @@ -62,6 +62,7 @@ public: virtual int32_t LnnGetLocalStrInfo(InfoKey key, char *info, uint32_t len) = 0; virtual int32_t LnnGetRemoteStrInfo(const char *netWorkId, InfoKey key, char *info, uint32_t len) = 0; virtual int32_t AuthGetPreferConnInfo(const char *uuid, AuthConnInfo *connInfo, bool isMeta) = 0; + virtual int32_t AuthGetConnInfoByType(const char *uuid, AuthLinkType type, AuthConnInfo *connInfo, bool isMeta) = 0; virtual int32_t AuthGetP2pConnInfo(const char *uuid, AuthConnInfo *connInfo, bool isMeta) = 0; virtual int32_t AuthGetHmlConnInfo(const char *uuid, AuthConnInfo *connInfo, bool isMeta) = 0; virtual int32_t AuthOpenConn(const AuthConnInfo *info, uint32_t requestId, @@ -124,6 +125,7 @@ public: MOCK_METHOD3(LnnGetLocalStrInfo, int32_t (InfoKey, char*, uint32_t)); MOCK_METHOD4(LnnGetRemoteStrInfo, int32_t (const char*, InfoKey, char*, uint32_t)); MOCK_METHOD3(AuthGetPreferConnInfo, int32_t (const char*, AuthConnInfo*, bool)); + MOCK_METHOD4(AuthGetConnInfoByType, int32_t (const char*, AuthLinkType, AuthConnInfo *, bool)); MOCK_METHOD3(AuthGetP2pConnInfo, int32_t (const char*, AuthConnInfo*, bool)); MOCK_METHOD3(AuthGetHmlConnInfo, int32_t (const char*, AuthConnInfo*, bool)); MOCK_METHOD4(AuthOpenConn, int32_t (const AuthConnInfo*, uint32_t, const AuthConnCallback*, bool)); diff --git a/tests/core/bus_center/lnn/lane/src/lnn_lane_deps_mock.cpp b/tests/core/bus_center/lnn/lane/src/lnn_lane_deps_mock.cpp index 6c656113d..b97732390 100644 --- a/tests/core/bus_center/lnn/lane/src/lnn_lane_deps_mock.cpp +++ b/tests/core/bus_center/lnn/lane/src/lnn_lane_deps_mock.cpp @@ -197,6 +197,11 @@ int32_t AuthGetPreferConnInfo(const char *uuid, AuthConnInfo *connInfo, bool isM return GetLaneDepsInterface()->AuthGetPreferConnInfo(uuid, connInfo, isMeta); } +int32_t AuthGetConnInfoByType(const char *uuid, AuthLinkType type, AuthConnInfo *connInfo, bool isMeta) +{ + return GetLaneDepsInterface()->AuthGetConnInfoByType(uuid, type, connInfo, isMeta); +} + int32_t AuthGetP2pConnInfo(const char *uuid, AuthConnInfo *connInfo, bool isMeta) { return GetLaneDepsInterface()->AuthGetP2pConnInfo(uuid, connInfo, isMeta); diff --git a/tests/core/bus_center/lnn/lane/src/lnn_lane_test.cpp b/tests/core/bus_center/lnn/lane/src/lnn_lane_test.cpp index 1a406c322..2c7f8895f 100644 --- a/tests/core/bus_center/lnn/lane/src/lnn_lane_test.cpp +++ b/tests/core/bus_center/lnn/lane/src/lnn_lane_test.cpp @@ -265,7 +265,7 @@ static void OnLaneAllocSuccessForBle(uint32_t laneHandle, const LaneConnInfo *in static void OnLaneAllocFailNoExcept(uint32_t laneHandle, int32_t errCode) { GTEST_LOG_(INFO) << "alloc lane failed, laneReqId=" << laneHandle; - EXPECT_EQ(errCode, SOFTBUS_OK); + EXPECT_EQ(errCode, SOFTBUS_LANE_SUCC_AFTER_CANCELED); CondSignal(); } diff --git a/tests/core/bus_center/lnn/lane/trans_lane/lnn_trans_lane_deps_mock.cpp b/tests/core/bus_center/lnn/lane/trans_lane/lnn_trans_lane_deps_mock.cpp index 86eab9036..8a576581a 100644 --- a/tests/core/bus_center/lnn/lane/trans_lane/lnn_trans_lane_deps_mock.cpp +++ b/tests/core/bus_center/lnn/lane/trans_lane/lnn_trans_lane_deps_mock.cpp @@ -147,6 +147,11 @@ int32_t LaneCapCheck(const char *networkId, LaneLinkType linkType) return GetTransLaneIf()->LaneCapCheck(networkId, linkType); } +int32_t GetErrCodeOfLink(const char *networkId, LaneLinkType linkType) +{ + return GetTransLaneIf()->GetErrCodeOfLink(networkId, linkType); +} + int32_t CheckLaneResourceNumByLinkType(const char *peerUdid, LaneLinkType type, int32_t *laneNum) { return GetTransLaneIf()->CheckLaneResourceNumByLinkType(peerUdid, type, laneNum); diff --git a/tests/core/bus_center/lnn/lane/trans_lane/lnn_trans_lane_deps_mock.h b/tests/core/bus_center/lnn/lane/trans_lane/lnn_trans_lane_deps_mock.h index 0d07c7132..ebcbffca5 100644 --- a/tests/core/bus_center/lnn/lane/trans_lane/lnn_trans_lane_deps_mock.h +++ b/tests/core/bus_center/lnn/lane/trans_lane/lnn_trans_lane_deps_mock.h @@ -51,6 +51,7 @@ public: virtual int32_t LaneLinkdownNotify(const char *peerUdid, const LaneLinkInfo *laneLinkInfo) = 0; virtual uint64_t GenerateLaneId(const char *localUdid, const char *remoteUdid, LaneLinkType linkType) = 0; virtual int32_t LaneCapCheck(const char *networkId, LaneLinkType linkType) = 0; + virtual int32_t GetErrCodeOfLink(const char *networkId, LaneLinkType linkType) = 0; virtual int32_t CheckLaneResourceNumByLinkType(const char *peerUdid, LaneLinkType type, int32_t *laneNum) = 0; }; @@ -76,6 +77,7 @@ public: MOCK_METHOD2(LaneLinkdownNotify, int32_t (const char *peerUdid, const LaneLinkInfo *laneLinkInfo)); MOCK_METHOD3(GenerateLaneId, uint64_t (const char *localUdid, const char *remoteUdid, LaneLinkType linkType)); MOCK_METHOD2(LaneCapCheck, int32_t (const char *networkId, LaneLinkType linkType)); + MOCK_METHOD2(GetErrCodeOfLink, int32_t (const char *networkId, LaneLinkType linkType)); MOCK_METHOD3(CheckLaneResourceNumByLinkType, int32_t (const char *peerUdid, LaneLinkType type, int32_t *laneNum)); static int32_t ActionOfLaneLinkSuccess(const LinkRequest *reqInfo, uint32_t reqId, const LaneLinkCb *cb); 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 0167ff3be..9d6c2b24c 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 @@ -255,7 +255,7 @@ HWTEST_F(LNNLaneLinkTest, LnnConnectP2p_002, TestSize.Level1) EXPECT_CALL(linkMock, LnnGetRemoteStrInfo).WillRepeatedly(Return(SOFTBUS_NOT_FIND)); ret = LnnConnectP2p(&request, laneReqId, &cb); - EXPECT_EQ(SOFTBUS_LANE_GET_LEDGER_INFO_ERR, ret); + EXPECT_EQ(SOFTBUS_LANE_NOT_FOUND, ret); LnnDestroyP2p(); } @@ -833,6 +833,8 @@ HWTEST_F(LNNLaneLinkTest, GuideChannelRetryOfAsync_002, TestSize.Level1) EXPECT_CALL(linkMock, CheckActiveConnection).WillRepeatedly(Return(true)); EXPECT_CALL(linkMock, AuthGetPreferConnInfo) .WillRepeatedly(DoAll(SetArgPointee(connInfo), Return(SOFTBUS_OK))); + EXPECT_CALL(linkMock, AuthGetConnInfoByType) + .WillRepeatedly(DoAll(SetArgPointee(connInfo), Return(SOFTBUS_OK))); EXPECT_CALL(laneLinkMock, GetTransReqInfoByLaneReqId).WillRepeatedly(Return(SOFTBUS_OK)); EXPECT_CALL(linkMock, AuthGenRequestId).WillRepeatedly(Return(requestId)); EXPECT_CALL(linkMock, AuthOpenConn(_, requestId, NotNull(), _)).WillOnce(linkMock.ActionOfConnOpenFailed) @@ -888,7 +890,7 @@ HWTEST_F(LNNLaneLinkTest, GuideChannelRetryOfAsync_003, TestSize.Level1) .WillOnce(DoAll(SetArrayArgument(BRMAC, BRMAC + BT_MAC_LEN), Return(SOFTBUS_OK))) .WillRepeatedly(Return(SOFTBUS_OK)); EXPECT_CALL(linkMock, CheckActiveConnection).WillRepeatedly(Return(true)); - EXPECT_CALL(linkMock, AuthGetPreferConnInfo) + EXPECT_CALL(linkMock, AuthGetConnInfoByType) .WillOnce(Return(SOFTBUS_OK)).WillRepeatedly(Return(SOFTBUS_AUTH_GET_BR_CONN_INFO_FAIL)); EXPECT_CALL(laneLinkMock, GetTransReqInfoByLaneReqId).WillRepeatedly(Return(SOFTBUS_OK)); EXPECT_CALL(linkMock, AuthGenRequestId).WillRepeatedly(Return(requestId)); @@ -1314,6 +1316,8 @@ HWTEST_F(LNNLaneLinkTest, GuideChannelRetry_004, TestSize.Level1) .WillRepeatedly(DoAll(SetArgPointee(remote), Return(SOFTBUS_OK))); EXPECT_CALL(linkMock, AuthGetPreferConnInfo) .WillRepeatedly(DoAll(SetArgPointee(connInfo), Return(SOFTBUS_OK))); + EXPECT_CALL(linkMock, AuthGetConnInfoByType) + .WillRepeatedly(DoAll(SetArgPointee(connInfo), Return(SOFTBUS_OK))); EXPECT_CALL(laneLinkMock, GetTransReqInfoByLaneReqId).WillRepeatedly(Return(SOFTBUS_OK)); EXPECT_CALL(linkMock, AuthGenRequestId).WillRepeatedly(Return(requestId)); EXPECT_CALL(linkMock, AuthOpenConn(_, requestId, NotNull(), _)).WillOnce(Return(SOFTBUS_LANE_BUILD_LINK_FAIL)) @@ -1372,6 +1376,8 @@ HWTEST_F(LNNLaneLinkTest, GuideChannelDetect_001, TestSize.Level1) .WillRepeatedly(DoAll(SetArgPointee(remote), Return(SOFTBUS_OK))); EXPECT_CALL(linkMock, AuthGetPreferConnInfo) .WillRepeatedly(DoAll(SetArgPointee(connInfo), Return(SOFTBUS_OK))); + EXPECT_CALL(linkMock, AuthGetConnInfoByType) + .WillRepeatedly(DoAll(SetArgPointee(connInfo), Return(SOFTBUS_OK))); EXPECT_CALL(laneLinkMock, GetTransReqInfoByLaneReqId).WillRepeatedly(Return(SOFTBUS_OK)); EXPECT_CALL(linkMock, AuthGenRequestId).WillRepeatedly(Return(requestId)); EXPECT_CALL(linkMock, AuthOpenConn(_, requestId, NotNull(), _)).WillRepeatedly(linkMock.ActionOfConnOpened); diff --git a/tests/core/bus_center/lnn/lane_listener/lnn_lane_listener_deps_mock.cpp b/tests/core/bus_center/lnn/lane_listener/lnn_lane_listener_deps_mock.cpp index 6d864105b..307c97abb 100644 --- a/tests/core/bus_center/lnn/lane_listener/lnn_lane_listener_deps_mock.cpp +++ b/tests/core/bus_center/lnn/lane_listener/lnn_lane_listener_deps_mock.cpp @@ -90,5 +90,10 @@ int32_t DelLaneResourceByLaneId(uint64_t laneId, bool isServerSide) { return GetLaneListenerDepsInterface()->DelLaneResourceByLaneId(laneId, isServerSide); } + +void DetectDisableWifiDirectApply(void) +{ + GetLaneListenerDepsInterface()->DetectDisableWifiDirectApply(); +} } } // namespace OHOS diff --git a/tests/core/bus_center/lnn/lane_listener/lnn_lane_listener_deps_mock.h b/tests/core/bus_center/lnn/lane_listener/lnn_lane_listener_deps_mock.h index fef603613..84479295f 100644 --- a/tests/core/bus_center/lnn/lane_listener/lnn_lane_listener_deps_mock.h +++ b/tests/core/bus_center/lnn/lane_listener/lnn_lane_listener_deps_mock.h @@ -41,6 +41,7 @@ public: virtual void RemoveDelayDestroyMessage(uint64_t laneId) = 0; virtual int32_t AddLaneResourceToPool(const LaneLinkInfo *linkInfo, uint64_t laneId, bool isServerSide) = 0; virtual int32_t DelLaneResourceByLaneId(uint64_t laneId, bool isServerSide) = 0; + virtual void DetectDisableWifiDirectApply(void) = 0; }; class LaneListenerDepsInterfaceMock : public LaneListenerDepsInterface { @@ -62,6 +63,7 @@ public: MOCK_METHOD0(GetLaneManager, LnnLaneManager* (void)); MOCK_METHOD3(AddLaneResourceToPool, int32_t (const LaneLinkInfo *linkInfo, uint64_t laneId, bool isServerSide)); MOCK_METHOD2(DelLaneResourceByLaneId, int32_t (uint64_t laneId, bool isServerSide)); + MOCK_METHOD0(DetectDisableWifiDirectApply, void (void)); }; } // namespace OHOS #endif // LNN_LANE_LISTENER_DEPS_MOCK_H diff --git a/tests/core/bus_center/lnn/net_builder/src/lnn_data_cloud_sync_test.cpp b/tests/core/bus_center/lnn/net_builder/src/lnn_data_cloud_sync_test.cpp index e57956a1e..8841c85eb 100644 --- a/tests/core/bus_center/lnn/net_builder/src/lnn_data_cloud_sync_test.cpp +++ b/tests/core/bus_center/lnn/net_builder/src/lnn_data_cloud_sync_test.cpp @@ -70,7 +70,11 @@ HWTEST_F(LNNDataCloudSyncTest, LnnLedgerAllDataSyncToDB_Test_001, TestSize.Level info = (NodeInfo *)SoftBusCalloc(sizeof(NodeInfo)); info->accountId = 0; ret = LnnLedgerAllDataSyncToDB(info); - EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); + if (ret != SOFTBUS_NOT_IMPLEMENT) { + EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); + } else { + EXPECT_EQ(ret, SOFTBUS_NOT_IMPLEMENT); + } info->accountId = 18390933952; ret = LnnLedgerAllDataSyncToDB(info); EXPECT_NE(ret, SOFTBUS_OK); diff --git a/tests/core/bus_center/test/heartbeat/hb_fsm_test.cpp b/tests/core/bus_center/test/heartbeat/hb_fsm_test.cpp index 275a3296a..ba9a981d6 100644 --- a/tests/core/bus_center/test/heartbeat/hb_fsm_test.cpp +++ b/tests/core/bus_center/test/heartbeat/hb_fsm_test.cpp @@ -659,7 +659,15 @@ HWTEST_F(HeartBeatFSMTest, RemoveSendOneEndMsgTest_03, TestSize.Level1) ret = RemoveSendOneEndMsg(&ctrlMsgObj, &delMsg); EXPECT_TRUE(ret == SOFTBUS_OK); - msgPara->hbType = HEARTBEAT_TYPE_BLE_V0; + LnnHeartbeatSendEndData *msgPara1 = (LnnHeartbeatSendEndData *)SoftBusMalloc(sizeof(LnnHeartbeatSendEndData)); + msgPara1->wakeupFlag = true; + msgPara1->isRelay = false; + delMsgPara.wakeupFlag = true; + delMsgPara.isRelay =false; + delMsgPara.isRemoved = &isRemoved; + ctrlMsgObj.obj = reinterpret_cast(msgPara1); + delMsg.obj = reinterpret_cast(&delMsgPara); + msgPara1->hbType = HEARTBEAT_TYPE_BLE_V0; delMsgPara.hbType = HEARTBEAT_TYPE_BLE_V1; ret = RemoveSendOneEndMsg(&ctrlMsgObj, &delMsg); EXPECT_TRUE(ret == SOFTBUS_ERR); @@ -692,7 +700,14 @@ HWTEST_F(HeartBeatFSMTest, RemoveSendOneEndMsgTest_04, TestSize.Level1) ret = RemoveSendOneEndMsg(&ctrlMsgObj, &delMsg); EXPECT_TRUE(ret == SOFTBUS_OK); - msgPara->hbType = HEARTBEAT_TYPE_BLE_V1; + LnnHeartbeatSendEndData *msgPara1 = (LnnHeartbeatSendEndData *)SoftBusMalloc(sizeof(LnnHeartbeatSendEndData)); + msgPara1->wakeupFlag = true; + msgPara1->isRelay = false; + delMsgPara.wakeupFlag = true; + delMsgPara.isRelay =false; + delMsgPara.isRemoved = &isRemoved; + ctrlMsgObj.obj = reinterpret_cast(msgPara1); + msgPara1->hbType = HEARTBEAT_TYPE_BLE_V1; delMsgPara.hbType = HEARTBEAT_TYPE_BLE_V1; ret = RemoveSendOneEndMsg(&ctrlMsgObj, &delMsg); EXPECT_TRUE(ret == SOFTBUS_ERR); diff --git a/tests/core/bus_center/test/heartbeat/hb_medium_mgr_test.cpp b/tests/core/bus_center/test/heartbeat/hb_medium_mgr_test.cpp index 3065f465a..159b76b86 100644 --- a/tests/core/bus_center/test/heartbeat/hb_medium_mgr_test.cpp +++ b/tests/core/bus_center/test/heartbeat/hb_medium_mgr_test.cpp @@ -852,7 +852,7 @@ HWTEST_F(HeartBeatMediumTest, SoftBusNetNodeResult_TEST01, TestSize.Level1) ret = SoftBusNetNodeResult(&device, &hbResp, false, connectReason); EXPECT_TRUE(ret == SOFTBUS_NETWORK_NODE_DIRECT_ONLINE); ret = SoftBusNetNodeResult(&device, &hbResp, true, connectReason); - EXPECT_TRUE(ret == SOFTBUS_NETWORK_HEARTBEAT_UNTRUSTED); + EXPECT_TRUE(ret == SOFTBUS_NETWORK_NODE_OFFLINE); } /* diff --git a/tests/core/common/dfx/hidumper_adapter/fuzztest/softbushidumper_fuzzer/BUILD.gn b/tests/core/common/dfx/hidumper_adapter/fuzztest/softbushidumper_fuzzer/BUILD.gn index e5b2e1482..9b7d805b8 100644 --- a/tests/core/common/dfx/hidumper_adapter/fuzztest/softbushidumper_fuzzer/BUILD.gn +++ b/tests/core/common/dfx/hidumper_adapter/fuzztest/softbushidumper_fuzzer/BUILD.gn @@ -1,4 +1,4 @@ -# 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 @@ -28,6 +28,7 @@ ohos_fuzztest("SoftBusHiDumperFuzzTest") { include_dirs = [ "$dsoftbus_root_path/core/common/include", "$dsoftbus_root_path/core/common/dfx/hidumper_adapter/include", + "$dsoftbus_root_path/tests/common/include", ] sources = [ "softbushidumper_fuzzer.cpp" ] @@ -46,11 +47,10 @@ ohos_fuzztest("SoftBusHiDumperFuzzTest") { "$dsoftbus_root_path/core/frame:softbus_server", ] - if (is_standard_system) { - external_deps = [ "hilog:libhilog" ] - } else { - external_deps = [ "hilog:libhilog" ] - } + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + ] } ############################################################################### diff --git a/tests/core/common/dfx/hidumper_adapter/fuzztest/softbushidumper_fuzzer/softbushidumper_fuzzer.cpp b/tests/core/common/dfx/hidumper_adapter/fuzztest/softbushidumper_fuzzer/softbushidumper_fuzzer.cpp index cf6d5f9c4..54c2b0340 100644 --- a/tests/core/common/dfx/hidumper_adapter/fuzztest/softbushidumper_fuzzer/softbushidumper_fuzzer.cpp +++ b/tests/core/common/dfx/hidumper_adapter/fuzztest/softbushidumper_fuzzer/softbushidumper_fuzzer.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 @@ -15,11 +15,15 @@ #include "softbushidumper_fuzzer.h" -#include -#include #include + +#include "comm_log.h" +#include "fuzz_data_generator.h" +#include "message_handler.h" #include "softbus_error_code.h" #include "softbus_hidumper.h" +#include "softbus_hidumper_bc_mgr.h" +#include "softbus_hidumper_broadcast.h" #include "softbus_hidumper_buscenter.h" #include "softbus_hidumper_conn.h" #include "softbus_hidumper_disc.h" @@ -27,176 +31,88 @@ #include "softbus_hidumper_nstack.h" #include "softbus_hidumper_trans.h" -namespace OHOS { -static constexpr int TEST_ARGV_STRING_MAX_LEN = 255; -static constexpr int TEST_PKG_NAME_MAX_LEN = 65; -static constexpr int TEST_SESSION_NAME_MAX_LEN = 256; -static constexpr int TEST_DUMP_VAR_MAX_LEN = 32; -static constexpr int MAX_ARGV_NUM = 3; -int32_t SoftBusVarDumpCbFunc(int fd) +namespace { +const char *DUMP_CMD = "test"; + +std::vector CMD_ALARM = {"alert", "-l", DUMP_CMD}; +std::vector CMD_BCMGR = {"broadcastMgr", "-l", DUMP_CMD}; +std::vector CMD_BROADCAST = {"broadcast", "-l", DUMP_CMD}; +std::vector CMD_BUSCENTER = {"buscenter", "-l", DUMP_CMD}; +std::vector CMD_CONN = {"conn", "-l", DUMP_CMD}; +std::vector CMD_DISC = {"disc", "-l", DUMP_CMD}; +std::vector CMD_NSTACK_DSTREAM = {"dstream", "-l", DUMP_CMD}; +std::vector CMD_NSTACK_DFILE = {"dfile", "-l", DUMP_CMD}; +std::vector CMD_NSTACK_DFINDER = {"dfinder", "-l", DUMP_CMD}; +std::vector CMD_NSTACK_DMSG = {"dmsg", "-l", DUMP_CMD}; +std::vector CMD_STATS = {"stats", "-l", DUMP_CMD}; +std::vector CMD_TRANS = {"trans", "-l", DUMP_CMD}; + +const std::vector> DUMP_CMD_LIST = {CMD_ALARM, CMD_BCMGR, CMD_BROADCAST, CMD_BUSCENTER, + CMD_CONN, CMD_DISC, CMD_NSTACK_DSTREAM, CMD_NSTACK_DFILE, CMD_NSTACK_DFINDER, CMD_NSTACK_DMSG, CMD_STATS, + CMD_TRANS}; + +void DoDump(void) { - (void)fd; - return 0; + std::vector dumpCmd; + if (!GenerateFromList(dumpCmd, DUMP_CMD_LIST) || dumpCmd.empty()) { + return; + } + + SoftBusDumpDispatch(1, dumpCmd.size(), const_cast(&dumpCmd[0])); } -int32_t TransSessionShowInfoFunc(int fd) +static int32_t SoftBusVarDumpCallback(int32_t fd) { (void)fd; return SOFTBUS_OK; } -void SoftBusHiDumperFuzzTest(const uint8_t* data, size_t size) -{ - char tmpArgvString[TEST_ARGV_STRING_MAX_LEN] = {0}; - if (memcpy_s(tmpArgvString, sizeof(tmpArgvString) - 1, data, size) != EOK) { - return; - } - const char *tmpData[MAX_ARGV_NUM] = {nullptr}; - for (int32_t i = 0; i < MAX_ARGV_NUM; i++) { - tmpData[i] = tmpArgvString; - } - int32_t tmpValue = *(reinterpret_cast(data)); - SoftBusDumpDispatch(tmpValue, tmpValue, tmpData); -} +class TestEnv { +public: + TestEnv() + { + isInited_ = false; + int32_t ret = LooperInit(); + COMM_CHECK_AND_RETURN_LOGE(ret == SOFTBUS_OK, COMM_TEST, "init looper failed"); + ret = SoftBusHiDumperInit(); + COMM_CHECK_AND_RETURN_LOGE(ret == SOFTBUS_OK, COMM_TEST, "init hidumper failed"); -void SoftBusHiDumperBusCenterFuzzTest(const uint8_t* data, size_t size) -{ - char tmpDumpVar[TEST_DUMP_VAR_MAX_LEN] = {0}; - if (memcpy_s(tmpDumpVar, sizeof(tmpDumpVar) - 1, data, size) != EOK) { - return; - } - int32_t ret = SoftBusRegBusCenterVarDump(tmpDumpVar, &SoftBusVarDumpCbFunc); - if (ret != SOFTBUS_OK) { - return; + SoftBusRegBcMgrVarDump(DUMP_CMD, &SoftBusVarDumpCallback); + SoftBusRegBroadcastVarDump(DUMP_CMD, &SoftBusVarDumpCallback); + SoftBusRegBusCenterVarDump(const_cast(DUMP_CMD), &SoftBusVarDumpCallback); + SoftBusRegConnVarDump(DUMP_CMD, &SoftBusVarDumpCallback); + SoftBusRegDiscVarDump(const_cast(DUMP_CMD), &SoftBusVarDumpCallback); + SoftBusRegTransVarDump(DUMP_CMD, &SoftBusVarDumpCallback); + SoftBusRegConnVarDump(DUMP_CMD, &SoftBusVarDumpCallback); + isInited_ = true; } - char tmpArgvString[TEST_ARGV_STRING_MAX_LEN] = {0}; - if (memcpy_s(tmpArgvString, sizeof(tmpArgvString) - 1, data, size) != EOK) { - return; - } - const char *tmpData[MAX_ARGV_NUM] = {nullptr}; - for (int32_t i = 0; i < MAX_ARGV_NUM; i++) { - tmpData[i] = tmpArgvString; - } - int32_t tmpValue = *(reinterpret_cast(data)); - SoftBusDumpDispatch(tmpValue, tmpValue, tmpData); -} - -void SoftBusHiDumperConnFuzzTest(const uint8_t* data, size_t size) -{ - char tmpDumpVar[TEST_DUMP_VAR_MAX_LEN] = {0}; - if (memcpy_s(tmpDumpVar, sizeof(tmpDumpVar) - 1, data, size) != EOK) { - return; - } - int32_t ret = SoftBusRegConnVarDump(tmpDumpVar, &SoftBusVarDumpCbFunc); - if (ret != SOFTBUS_OK) { - return; + ~TestEnv() + { + isInited_ = false; + LooperDeinit(); + SoftBusHiDumperDeinit(); } - char tmpArgvString[TEST_ARGV_STRING_MAX_LEN] = {0}; - if (memcpy_s(tmpArgvString, sizeof(tmpArgvString) - 1, data, size) != EOK) { - return; - } - const char *tmpData[MAX_ARGV_NUM] = {nullptr}; - for (int32_t i = 0; i < MAX_ARGV_NUM; i++) { - tmpData[i] = tmpArgvString; - } - int32_t tmpValue = *(reinterpret_cast(data)); - SoftBusDumpDispatch(tmpValue, tmpValue, tmpData); -} - -void SoftBusHiDumperDiscFuzzTest(const uint8_t* data, size_t size) -{ - char tmpDumpVar[TEST_DUMP_VAR_MAX_LEN] = {0}; - if (memcpy_s(tmpDumpVar, sizeof(tmpDumpVar) - 1, data, size) != EOK) { - return; - } - int32_t ret = SoftBusRegDiscVarDump(tmpDumpVar, &SoftBusVarDumpCbFunc); - if (ret != SOFTBUS_OK) { - return; + bool IsInited(void) + { + return isInited_; } - char tmpArgvString[TEST_ARGV_STRING_MAX_LEN] = {0}; - if (memcpy_s(tmpArgvString, sizeof(tmpArgvString) - 1, data, size) != EOK) { - return; - } - const char *tmpData[MAX_ARGV_NUM] = {nullptr}; - for (int32_t i = 0; i < MAX_ARGV_NUM; i++) { - tmpData[i] = tmpArgvString; - } - int32_t tmpValue = *(reinterpret_cast(data)); - SoftBusDumpDispatch(tmpValue, tmpValue, tmpData); -} +private: + volatile bool isInited_; +}; +} // anonymous namespace -void SoftBusHiDumperInterfaceFuzzTest(const uint8_t* data, size_t size) -{ - char tmpArgvString[TEST_ARGV_STRING_MAX_LEN] = {0}; - if (memcpy_s(tmpArgvString, sizeof(tmpArgvString) - 1, data, size) != EOK) { - return; - } - const char *tmpData[MAX_ARGV_NUM] = {nullptr}; - for (int32_t i = 0; i < MAX_ARGV_NUM; i++) { - tmpData[i] = tmpArgvString; - } - int32_t tmpValue = *(reinterpret_cast(data)); - SoftBusDumpProcess(tmpValue, tmpValue, tmpData); -} - -void SoftBusHiDumperNstackFuzzTest(const uint8_t* data, size_t size) -{ - (void)data; - (void)size; - SoftBusNStackHiDumperInit(); -} - -void SoftBusHiDumperTransFuzzTest(const uint8_t* data, size_t size) -{ - char tmpDumpVar[SOFTBUS_DUMP_VAR_NAME_LEN] = {0}; - if (memcpy_s(tmpDumpVar, sizeof(tmpDumpVar) - 1, data, size) != EOK) { - return; - } - SoftBusRegTransVarDump(tmpDumpVar, TransSessionShowInfoFunc); - SoftBusTransDumpHandlerInit(); - int32_t tmpValue = *(reinterpret_cast(data)); - char tmpPkgName[TEST_PKG_NAME_MAX_LEN] = {0}; - if (memcpy_s(tmpPkgName, sizeof(tmpPkgName) - 1, data, size) != EOK) { - return; - } - char tmpSessionName[TEST_SESSION_NAME_MAX_LEN] = {0}; - if (memcpy_s(tmpSessionName, sizeof(tmpSessionName) - 1, data, size) != EOK) { - return; - } - SoftBusTransDumpRegisterSession(tmpValue, tmpPkgName, tmpSessionName, tmpValue, tmpValue); - - if (size < sizeof(AppInfo)) { - return; - } - AppInfo testAppInfo; - if (memcpy_s(&testAppInfo, sizeof(AppInfo), data, sizeof(AppInfo)) != EOK) { - return; - } - TransDumpLaneLinkType laneLinkType = *(reinterpret_cast(data)); - SoftBusTransDumpRunningSession(tmpValue, laneLinkType, &testAppInfo); -} -} // namespace OHOS - -/* Fuzzer entry point */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { - if (data == nullptr || size < sizeof(int32_t)) { + static TestEnv env; + if (!env.IsInited()) { return 0; } - int32_t ret = SoftBusHiDumperInit(); - if (ret != SOFTBUS_OK) { - return 0; - } - OHOS::SoftBusHiDumperFuzzTest(data, size); - OHOS::SoftBusHiDumperBusCenterFuzzTest(data, size); - OHOS::SoftBusHiDumperConnFuzzTest(data, size); - OHOS::SoftBusHiDumperDiscFuzzTest(data, size); - OHOS::SoftBusHiDumperInterfaceFuzzTest(data, size); - OHOS::SoftBusHiDumperNstackFuzzTest(data, size); - OHOS::SoftBusHiDumperTransFuzzTest(data, size); - SoftBusHiDumperModuleDeInit(); + + DataGenerator::Write(data, size); + DoDump(); + DataGenerator::Clear(); return 0; } \ No newline at end of file diff --git a/tests/core/connection/fuzztest/BUILD.gn b/tests/core/connection/fuzztest/BUILD.gn index 3958368ae..d30c2ce1d 100644 --- a/tests/core/connection/fuzztest/BUILD.gn +++ b/tests/core/connection/fuzztest/BUILD.gn @@ -11,7 +11,16 @@ # See the License for the specific language governing permissions and # limitations under the License. +import("//build/test.gni") +import("../../../../dsoftbus.gni") + group("fuzztest") { testonly = true - deps = [ "softbusnegotiatemessage_fuzzer:SoftBusNegotiateMessageFuzzTest" ] + if (dsoftbus_feature_conn_p2p == true && + softbus_communication_wifi_feature == true) { + deps = [ + "softbusnegotiatemessage_fuzzer:SoftBusNegotiateMessageFuzzTest", + "wifidirectprotocol_fuzzer:WifiDirectProtocolFuzzTest", + ] + } } diff --git a/tests/core/connection/fuzztest/wifidirectprotocol_fuzzer/BUILD.gn b/tests/core/connection/fuzztest/wifidirectprotocol_fuzzer/BUILD.gn new file mode 100644 index 000000000..df04b8a11 --- /dev/null +++ b/tests/core/connection/fuzztest/wifidirectprotocol_fuzzer/BUILD.gn @@ -0,0 +1,48 @@ +# Copyright (c) 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 +# +# 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/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("../../../../../dsoftbus.gni") + +##############################fuzztest########################################## + +ohos_fuzztest("WifiDirectProtocolFuzzTest") { + module_out_path = dsoftbus_fuzz_out_path + fuzz_config_file = "$dsoftbus_root_path/tests/core/connection/fuzztest/wifidirectprotocol_fuzzer" + + include_dirs = [ "$dsoftbus_root_path/core/connection/wifi_direct_cpp" ] + + sources = [ "protocol_fuzzer.cpp" ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + deps = [ + "$dsoftbus_root_path/adapter:softbus_adapter", + "$dsoftbus_root_path/core/common:softbus_utils", + "$dsoftbus_root_path/core/frame:softbus_server", + "$dsoftbus_root_path/tests/sdk/common:softbus_access_token_test", + ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + ] +} diff --git a/tests/core/connection/fuzztest/wifidirectprotocol_fuzzer/corpus/init b/tests/core/connection/fuzztest/wifidirectprotocol_fuzzer/corpus/init new file mode 100644 index 000000000..6198079a2 --- /dev/null +++ b/tests/core/connection/fuzztest/wifidirectprotocol_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * Copyright (c) 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 + * + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/tests/core/connection/fuzztest/wifidirectprotocol_fuzzer/project.xml b/tests/core/connection/fuzztest/wifidirectprotocol_fuzzer/project.xml new file mode 100644 index 000000000..7133b2b92 --- /dev/null +++ b/tests/core/connection/fuzztest/wifidirectprotocol_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/tests/core/connection/fuzztest/wifidirectprotocol_fuzzer/protocol_fuzzer.cpp b/tests/core/connection/fuzztest/wifidirectprotocol_fuzzer/protocol_fuzzer.cpp new file mode 100644 index 000000000..1fdeeb446 --- /dev/null +++ b/tests/core/connection/fuzztest/wifidirectprotocol_fuzzer/protocol_fuzzer.cpp @@ -0,0 +1,89 @@ +/* + * Copyright (c) 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 + * + * 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 "protocol_fuzzer.h" + +#include +#include + +#include "conn_log.h" +#include "softbus_utils.h" + +#include "data/negotiate_message.h" +#include "protocol/wifi_direct_protocol_factory.h" + +namespace OHOS::SoftBus { +static void JsonProtocolParseFuzzTest(const uint8_t *data, size_t size) +{ + (void)data; + (void)size; + std::string raw[] = { + R"({"KEY_BRIDGE_SUPPORTED":false,"KEY_COMMAND_TYPE":8,"KEY_CONTENT_TYPE":2,"KEY_EXPECTED_ROLE":1,"KEY_GC_CHANNEL_LIST":"36##40##44##48##149##153##157##161##165","KEY_GC_MAC":"42:dc:a5:f3:4c:14","KEY_GO_MAC":"","KEY_MAC":"42:dc:a5:f3:4c:14","KEY_ROLE":5,"KEY_SELF_WIFI_CONFIG":"","KEY_STATION_FREQUENCY":5180,"KEY_VERSION":2,"KEY_WIDE_BAND_SUPPORTED":false})", + R"({"KEY_COMMAND_TYPE":9,"KEY_CONTENT_TYPE":2,"KEY_GC_CHANNEL_LIST":"36##40##44##48##149##153##157##161##165","KEY_GC_MAC":"a6:3b:0e:78:29:dd","KEY_GO_MAC":"42:dc:a5:f3:4c:14","KEY_IP":"","KEY_MAC":"a6:3b:0e:78:29:dd","KEY_SELF_WIFI_CONFIG":"","KEY_STATION_FREQUENCY":5180,"KEY_VERSION":2,"KEY_WIDE_BAND_SUPPORTED":false})", + R"({"KEY_BRIDGE_SUPPORTED":false,"KEY_COMMAND_TYPE":8,"KEY_CONTENT_TYPE":1,"KEY_EXPECTED_ROLE":2,"KEY_GC_IP":"192.168.49.3","KEY_GC_MAC":"a6:3b:0e:78:29:dd","KEY_GO_IP":"192.168.49.1","KEY_GO_MAC":"42:dc:a5:f3:4c:14","KEY_GO_PORT":43267,"KEY_GROUP_CONFIG":"DIRECT-ja-OHOS_0u31\n4e:e8:d0:45:8f:10\nulKjGU9T\n5180","KEY_MAC":"42:dc:a5:f3:4c:14","KEY_ROLE":2,"KEY_SELF_WIFI_CONFIG":"","KEY_VERSION":2})", + R"({"KEY_COMMAND_TYPE":9,"KEY_CONTENT_TYPE":3,"KEY_IP":"192.168.49.3","KEY_MAC":"a6:3b:0e:78:29:dd","KEY_RESULT":0,"KEY_VERSION":2})", + R"({"KEY_COMMAND_TYPE":13,"KEY_IP":"192.168.49.3","KEY_MAC":"a6:3b:0e:78:29:dd"})", + R"({"KEY_COMMAND_TYPE":5,"KEY_MAC":"42:dc:a5:f3:4c:14"})", + }; + for (auto s : raw) { + std::vector input; + input.insert(input.end(), s.begin(), s.end()); + auto protocol = WifiDirectProtocolFactory::CreateProtocol(ProtocolType::JSON); + NegotiateMessage msg; + msg.Unmarshalling(*protocol, input); + } +} + +static void StringToBytes(const std::string &s, std::vector output) +{ + auto size = UN_HEXIFY_LEN(s.length()); + uint8_t *buf = new uint8_t[size]; + auto ret = ConvertHexStringToBytes(buf, size, s.c_str(), s.size()); + if (ret != SOFTBUS_OK) { + CONN_LOGE(CONN_TEST, "convert hex to bytes failed, error=%{public}d", ret); + delete[] buf; + return; + } + CONN_LOGE(CONN_TEST, "success, '%{public}s'", s.c_str()); + output.insert(output.end(), buf, buf + size); + delete[] buf; +} + +static void TlvProtocolParseFuzzTest(const uint8_t *data, size_t size) +{ + (void)data; + (void)size; + std::string raw[] = { + R"(000400320000000d48007b2242616e645769647468223a332c224343223a34373735332c224368616e6e656c4964223a3135372c22576966694d6163223a2236383a31313a30353a38653a62363a3066227d)", + R"(00040037000000)", + R"(0004001b0000000104000100000008320000050063686261300105006368626130020400100000000304001000000013110036383a31313a30353a38653a62363a3066)", + }; + for (auto s : raw) { + std::vector input; + StringToBytes(s, input); + auto protocol = WifiDirectProtocolFactory::CreateProtocol(ProtocolType::TLV); + NegotiateMessage msg; + msg.Unmarshalling(*protocol, input); + } +} + +} // namespace OHOS::SoftBus + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + OHOS::SoftBus::JsonProtocolParseFuzzTest(data, size); + OHOS::SoftBus::TlvProtocolParseFuzzTest(data, size); + return 0; +} diff --git a/tests/core/connection/fuzztest/wifidirectprotocol_fuzzer/protocol_fuzzer.h b/tests/core/connection/fuzztest/wifidirectprotocol_fuzzer/protocol_fuzzer.h new file mode 100644 index 000000000..b07f3b928 --- /dev/null +++ b/tests/core/connection/fuzztest/wifidirectprotocol_fuzzer/protocol_fuzzer.h @@ -0,0 +1,24 @@ +/* + * Copyright (c) 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 + * + * 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 PROTOCOL_FUZZER_H +#define PROTOCOL_FUZZER_H + +#define FUZZ_PROJECT_NAME "protocol_fuzzer" + +namespace OHOS::SoftBus { +} + +#endif // PROTOCOL_FUZZER_H diff --git a/tests/core/connection/wifi_direct_cpp/BUILD.gn b/tests/core/connection/wifi_direct_cpp/BUILD.gn index efa39dbbf..4b0b0c24e 100644 --- a/tests/core/connection/wifi_direct_cpp/BUILD.gn +++ b/tests/core/connection/wifi_direct_cpp/BUILD.gn @@ -229,6 +229,7 @@ group("unittest") { ":WifiDirectIpManagerTest", ":WifiDirectManagerCppTest", ":WifiDirectRoleOptionTest", + "adapter:unittest", "data:unittest", "entity:unittest", "processor:unittest", diff --git a/tests/core/connection/wifi_direct_cpp/adapter/BUILD.gn b/tests/core/connection/wifi_direct_cpp/adapter/BUILD.gn new file mode 100644 index 000000000..12a6a1d76 --- /dev/null +++ b/tests/core/connection/wifi_direct_cpp/adapter/BUILD.gn @@ -0,0 +1,135 @@ +# Copyright (c) 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 +# +# 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") +ut_out_path = "dsoftbus/connection/wifi_direct_cpp/adapter" +wifi_direct_cpp_path = "$dsoftbus_root_path/core/connection/wifi_direct_cpp" +wifi_direct_cpp_unit_path = + "$dsoftbus_root_path/tests/core/connection/wifi_direct_cpp" +ohos_unittest("P2pAdapterTest") { + module_out_path = ut_out_path + include_dirs = [ + "//third_party/cJSON", + "//third_party/json/include", + "//third_party/googletest/googletest/include", + "//third_party/googletest/googletest/src", + "//third_party/bounds_checking_function/include", + "$dsoftbus_root_path/core/authentication/include", + "$dsoftbus_root_path/core/authentication/interface", + "$dsoftbus_root_path/core/common/dfx/hisysevent_adapter/include", + "$dsoftbus_root_path/core/common/dfx/interface/include", + "$dsoftbus_root_path/core/adapter/authentication/include", + "$dsoftbus_root_path/core/bus_center/lnn/lane_hub/heartbeat/include", + "$dsoftbus_root_path/core/adapter/bus_center/include", + "$dsoftbus_root_path/core/bus_center/utils/include", + "$dsoftbus_root_path/core/bus_center/lnn/net_builder/include", + "$dsoftbus_root_path/core/bus_center/lnn/net_ledger/common/include", + "$dsoftbus_root_path/core/bus_center/interface", + "$dsoftbus_root_path/core/bus_center/lnn/net_ledger/distributed_ledger/include", + "$dsoftbus_root_path/core/connection/interface", + "$dsoftbus_root_path/core/common/include", + "$dsoftbus_root_path/core/discovery/manager/include", + "$dsoftbus_root_path/core/discovery/interface", + "$dsoftbus_root_path/adapter/common/include", + "$dsoftbus_root_path/interfaces/inner_kits/lnn", + "$dsoftbus_root_path/interfaces/kits/common", + "$dsoftbus_root_path/interfaces/kits/discovery", + "$dsoftbus_root_path/interfaces/kits/bus_center", + "$dsoftbus_root_path/core/transmission/trans_channel/proxy/include", + "$dsoftbus_root_path/core/bus_center/lnn/lane_hub/lane_manager/include", + "$dsoftbus_root_path/core/bus_center/lnn/net_ledger/distributed_ledger/include", + "$wifi_direct_cpp_path", + "$wifi_direct_cpp_unit_path", + "$dsoftbus_root_path/adapter/common/include/OS_adapter_define/linux", + ] + + remove_configs = [ + "//build/config/compiler:no_rtti", + "//build/config/compiler:no_exceptions", + ] + configs = [ + "//build/config/compiler:rtti", + "//build/config/compiler:exceptions", + ] + cflags = [ + "-fexceptions", + "-frtti", + ] + + deps = [ + "$dsoftbus_root_path/adapter:softbus_adapter", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gmock_rtti", + "//third_party/googletest:gtest_main", + "//third_party/googletest:gtest_rtti", + ] + + sources = [ + "$wifi_direct_cpp_path/adapter/p2p_adapter.cpp", + "$wifi_direct_cpp_path/channel/auth_negotiate_channel.cpp", + "$wifi_direct_cpp_path/channel/dummy_negotiate_channel.cpp", + "$wifi_direct_cpp_path/channel/proxy_negotiate_channel.cpp", + "$wifi_direct_cpp_path/command/command_factory.cpp", + "$wifi_direct_cpp_path/command/connect_command.cpp", + "$wifi_direct_cpp_path/command/disconnect_command.cpp", + "$wifi_direct_cpp_path/command/negotiate_command.cpp", + "$wifi_direct_cpp_path/command/processor_selector_factory.cpp", + "$wifi_direct_cpp_path/command/simple_processor_selector.cpp", + "$wifi_direct_cpp_path/data/inner_link.cpp", + "$wifi_direct_cpp_path/data/interface_info.cpp", + "$wifi_direct_cpp_path/data/interface_manager.cpp", + "$wifi_direct_cpp_path/data/ipv4_info.cpp", + "$wifi_direct_cpp_path/data/link_info.cpp", + "$wifi_direct_cpp_path/data/link_manager.cpp", + "$wifi_direct_cpp_path/data/negotiate_message.cpp", + "$wifi_direct_cpp_path/entity/p2p_available_state.cpp", + "$wifi_direct_cpp_path/entity/p2p_broadcast_receiver.cpp", + "$wifi_direct_cpp_path/entity/p2p_connect_state.cpp", + "$wifi_direct_cpp_path/entity/p2p_create_group_state.cpp", + "$wifi_direct_cpp_path/entity/p2p_destroy_group_state.cpp", + "$wifi_direct_cpp_path/entity/p2p_entity.cpp", + "$wifi_direct_cpp_path/entity/p2p_entity_state.cpp", + "$wifi_direct_cpp_path/entity/p2p_unavailable_state.cpp", + "$wifi_direct_cpp_path/event/wifi_direct_event_dispatcher.cpp", + "$wifi_direct_cpp_path/processor/p2p_v1_processor.cpp", + "$wifi_direct_cpp_path/protocol/json_protocol.cpp", + "$wifi_direct_cpp_path/protocol/tlv_protocol.cpp", + "$wifi_direct_cpp_path/utils/duration_statistic.cpp", + "$wifi_direct_cpp_path/utils/wifi_direct_anonymous.cpp", + "$wifi_direct_cpp_path/utils/wifi_direct_dfx.cpp", + "$wifi_direct_cpp_path/utils/wifi_direct_trace.cpp", + "$wifi_direct_cpp_path/utils/wifi_direct_utils.cpp", + "$wifi_direct_cpp_path/wifi_direct_executor.cpp", + "$wifi_direct_cpp_path/wifi_direct_initiator.cpp", + "$wifi_direct_cpp_path/wifi_direct_ip_manager.cpp", + "$wifi_direct_cpp_path/wifi_direct_manager.cpp", + "$wifi_direct_cpp_path/wifi_direct_role_option.cpp", + "$wifi_direct_cpp_path/wifi_direct_scheduler.cpp", + "$wifi_direct_cpp_unit_path/net_conn_client.cpp", + "$wifi_direct_cpp_unit_path/wifi_direct_mock.cpp", + "p2p_adapter_test.cpp", + ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "hitrace:libhitracechain", + "init:libbegetutil", + "wifi:wifi_sdk", + ] +} +group("unittest") { + testonly = true + deps = [ ":P2pAdapterTest" ] +} diff --git a/tests/core/connection/wifi_direct_cpp/adapter/p2p_adapter_test.cpp b/tests/core/connection/wifi_direct_cpp/adapter/p2p_adapter_test.cpp new file mode 100644 index 000000000..491f34232 --- /dev/null +++ b/tests/core/connection/wifi_direct_cpp/adapter/p2p_adapter_test.cpp @@ -0,0 +1,396 @@ +/* + * Copyright (c) 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 + * + * 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 +#include "conn_log.h" + +#include "softbus_error_code.h" +#include "data/interface_info.h" +#include "data/interface_manager.h" +#include "entity/p2p_connect_state.h" +#include "entity/p2p_entity.h" +#include "utils/wifi_direct_utils.h" +#include "wifi_direct_mock.h" + +using namespace testing::ext; +using namespace testing; +using ::testing::_; +using ::testing::Invoke; +namespace OHOS::SoftBus { +static constexpr int CHANNEL_ARRAY_NUM_MAX = 256; +class P2pAdapterTest : public testing::Test { +public: + static void SetUpTestCase() + { + P2pEntity::Init(); + } + static void TearDownTestCase() {} + void SetUp() override {} + void TearDown() override {} +}; + +/* +* @tc.name: IsWifiEnableTest +* @tc.desc: is wifi enable +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(P2pAdapterTest, IsWifiEnableTest, TestSize.Level1) +{ + bool flag = P2pAdapter::IsWifiEnable(); + EXPECT_FALSE(flag); +} + +/* +* @tc.name: IsWifiConnectedTest +* @tc.desc: is wifi connected +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(P2pAdapterTest, IsWifiConnectedTest, TestSize.Level1) +{ + WifiLinkedInfo linkedInfo; + linkedInfo.connState = WIFI_CONNECTED; + WifiDirectInterfaceMock mock; + EXPECT_CALL(mock, GetLinkedInfo).WillOnce(Return(WIFI_SUCCESS)) + .WillOnce(DoAll(SetArgPointee<0>(linkedInfo), Return(WIFI_SUCCESS))); + bool flag = P2pAdapter::IsWifiConnected(); + EXPECT_FALSE(flag); + flag = P2pAdapter::IsWifiConnected(); + EXPECT_TRUE(flag); +} + +/* +* @tc.name: P2pConnectGroupTest +* @tc.desc: p2p connect group +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(P2pAdapterTest, P2pConnectGroupTest, TestSize.Level1) +{ + WifiDirectInterfaceMock mock; + P2pConnectParam param{"123\n01:02:03:04:05:06\n555\n16\n1", true, false}; + EXPECT_CALL(mock, Hid2dConnect(_)).WillOnce(Return(WIFI_SUCCESS)); + int32_t ret = P2pAdapter::P2pConnectGroup(param); + EXPECT_EQ(ret, SOFTBUS_OK); +} + +/* +* @tc.name: DestroyGroupTest +* @tc.desc: p2p destroy group +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(P2pAdapterTest, DestroyGroupTest, TestSize.Level1) +{ + InterfaceManager::GetInstance().UpdateInterface( + InterfaceInfo::InterfaceType::P2P, [](InterfaceInfo &info) { + info.SetRole(LinkInfo::LinkMode::INVALID); + return SOFTBUS_OK; + }); + P2pDestroyGroupParam param; + int32_t ret = P2pAdapter::DestroyGroup(param); + EXPECT_EQ(ret, SOFTBUS_CONN_UNKNOWN_ROLE); +} + +/* +* @tc.name: GetStationFrequencyWithFilterTest +* @tc.desc: get station frequence with filter +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(P2pAdapterTest, GetStationFrequencyWithFilterTest, TestSize.Level1) +{ + WifiDirectInterfaceMock mock; + WifiLinkedInfo info; + info.frequency = 5170; + EXPECT_CALL(mock, GetLinkedInfo) + .WillRepeatedly(DoAll(SetArgPointee<0>(info), Return(WIFI_SUCCESS))); + EXPECT_CALL(mock, Hid2dGetChannelListFor5G).WillOnce(Return(ERROR_WIFI_UNKNOWN)); + int32_t result = P2pAdapter::GetStationFrequencyWithFilter(); + EXPECT_EQ(result, ToSoftBusErrorCode(ERROR_WIFI_UNKNOWN)); + int size = CHANNEL_ARRAY_NUM_MAX; + std::vector array(CHANNEL_ARRAY_NUM_MAX, 34); + EXPECT_CALL(mock, Hid2dGetChannelListFor5G(_, _)).WillOnce( + [&array, size](int *chanList, int len) { + array[0] = 34; + chanList[0] = array[0]; + len = size; + return WIFI_SUCCESS; + }); + result = P2pAdapter::GetStationFrequencyWithFilter(); + EXPECT_EQ(result, info.frequency); + + EXPECT_CALL(mock, Hid2dGetChannelListFor5G).WillOnce(Return(WIFI_SUCCESS)); + result = P2pAdapter::GetStationFrequencyWithFilter(); + EXPECT_EQ(result, FREQUENCY_INVALID); + + info.frequency = 2412; + EXPECT_CALL(mock, GetLinkedInfo) + .WillRepeatedly(DoAll(SetArgPointee<0>(info), Return(WIFI_SUCCESS))); + result = P2pAdapter::GetStationFrequencyWithFilter(); + EXPECT_EQ(result, info.frequency); + info.frequency = 1; + EXPECT_CALL(mock, GetLinkedInfo) + .WillRepeatedly(DoAll(SetArgPointee<0>(info), Return(WIFI_SUCCESS))); + result = P2pAdapter::GetStationFrequencyWithFilter(); + EXPECT_EQ(result, FREQUENCY_INVALID); +} + +/* +* @tc.name: GetRecommendChannelTest +* @tc.desc: get recommend channel +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(P2pAdapterTest, GetRecommendChannelTest, TestSize.Level1) +{ + WifiDirectInterfaceMock mock; + EXPECT_CALL(mock, Hid2dGetRecommendChannel).WillRepeatedly(Return(ERROR_WIFI_UNKNOWN)); + int32_t ret = P2pAdapter::GetRecommendChannel(); + EXPECT_EQ(ret, ToSoftBusErrorCode(ERROR_WIFI_UNKNOWN)); +} + +/* +* @tc.name: GetInterfaceCoexistCapTest +* @tc.desc: get interface coexistCap +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(P2pAdapterTest, GetInterfaceCoexistCapTest, TestSize.Level1) +{ + std::string result = P2pAdapter::GetInterfaceCoexistCap(); + + EXPECT_TRUE(result.empty()); +} +/* +* @tc.name: GetRecommendChannelTest002 +* @tc.desc: get recommend channel +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(P2pAdapterTest, GetRecommendChannelTest002, TestSize.Level1) +{ + WifiDirectInterfaceMock mock; + RecommendChannelResponse response; + response.centerFreq = 0; + response.centerFreq1 = 1; + EXPECT_CALL(mock, Hid2dGetRecommendChannel).WillOnce(DoAll(SetArgPointee<1>(response), + Return(WIFI_SUCCESS))); + + int32_t ret = P2pAdapter::GetRecommendChannel(); + EXPECT_EQ(ret, CHANNEL_INVALID); + + response.centerFreq1 = 0; + EXPECT_CALL(mock, Hid2dGetRecommendChannel).WillOnce(Return(WIFI_SUCCESS)); + ret = P2pAdapter::GetRecommendChannel(); + EXPECT_EQ(ret, CHANNEL_INVALID); +} + +/* +* @tc.name: GetSelfWifiConfigInfoTest001 +* @tc.desc: get self wifi config info +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(P2pAdapterTest, GetSelfWifiConfigInfoTest001, TestSize.Level1) +{ + WifiDirectInterfaceMock mock; + int32_t wifiConfigSize = 0; + std::string config; + EXPECT_CALL(mock, Hid2dGetSelfWifiCfgInfo).WillOnce(DoAll(SetArgPointee<2>(wifiConfigSize), Return(WIFI_SUCCESS))); + int32_t ret = P2pAdapter::GetSelfWifiConfigInfo(config); + EXPECT_EQ(ret, SOFTBUS_OK); + + wifiConfigSize = 1; + EXPECT_CALL(mock, Hid2dGetSelfWifiCfgInfo).WillOnce(DoAll(SetArgPointee<2>(wifiConfigSize), Return(WIFI_SUCCESS))); + EXPECT_CALL(mock, SoftBusBase64Encode).WillOnce(Return(WIFI_SUCCESS)); + ret = P2pAdapter::GetSelfWifiConfigInfo(config); + EXPECT_EQ(ret, SOFTBUS_OK); +} + +/* +* @tc.name: SetPeerWifiConfigInfoTest001 +* @tc.desc: get self wifi config info +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(P2pAdapterTest, SetPeerWifiConfigInfoTest001, TestSize.Level1) +{ + WifiDirectInterfaceMock mock; + std::string config = "ssss8888123456"; + EXPECT_CALL(mock, SoftBusBase64Decode).WillOnce(Return(SOFTBUS_INVALID_PARAM)).WillOnce(Return(WIFI_SUCCESS)); + int32_t ret =P2pAdapter::SetPeerWifiConfigInfo(config); + EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); + + EXPECT_CALL(mock, Hid2dSetPeerWifiCfgInfo).WillOnce(Return(WIFI_SUCCESS)); + ret = P2pAdapter::SetPeerWifiConfigInfo(config); + EXPECT_EQ(ret, SOFTBUS_OK); +} + +/* +* @tc.name: SetPeerWifiConfigInfoV2Test001 +* @tc.desc: check create group +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(P2pAdapterTest, SetPeerWifiConfigInfoV2Test001, TestSize.Level1) +{ + const uint8_t cfg[] = {0, 0, 0, 0, 0}; + int32_t ret = P2pAdapter::SetPeerWifiConfigInfoV2(cfg, sizeof(cfg)); + EXPECT_EQ(ret, SOFTBUS_ERR); +} + +/* +* @tc.name: IsWideBandSupportedTest001 +* @tc.desc: check create group +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(P2pAdapterTest, IsWideBandSupportedTest001, TestSize.Level1) +{ + WifiDirectInterfaceMock mock; + std::string config = "ssss8888123456"; + EXPECT_CALL(mock, Hid2dIsWideBandwidthSupported).WillOnce(Return(true)); + bool result = P2pAdapter::IsWideBandSupported(); + EXPECT_EQ(result, true); +} + +/* +* @tc.name: GetGroupInfoTest001 +* @tc.desc: get group info +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(P2pAdapterTest, GetGroupInfoTest001, TestSize.Level1) +{ + WifiDirectInterfaceMock mock; + WifiP2pGroupInfo info {}; + P2pAdapter::WifiDirectP2pGroupInfo groupInfoOut {}; + info.clientDevicesSize = 1; + EXPECT_CALL(mock, GetCurrentGroup).WillOnce(DoAll(SetArgPointee<0>(info), Return(WIFI_SUCCESS))); + int32_t ret = P2pAdapter::GetGroupInfo(groupInfoOut); + EXPECT_EQ(ret, SOFTBUS_OK); +} + +/* +* @tc.name: GetGroupInfoTest002 +* @tc.desc: get group info +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(P2pAdapterTest, GetGroupInfoTest002, TestSize.Level1) +{ + WifiDirectInterfaceMock mock; + P2pAdapter::WifiDirectP2pGroupInfo p2pGroupInfo; + WifiP2pGroupInfo info {}; + info.clientDevicesSize = 1; + EXPECT_CALL(mock, GetCurrentGroup).WillOnce(DoAll(SetArgPointee<0>(info), Return(WIFI_SUCCESS))); + int32_t ret = P2pAdapter::GetGroupInfo(p2pGroupInfo); + EXPECT_EQ(ret, SOFTBUS_OK); +} + +/* +* @tc.name: GetGroupConfigTest001 +* @tc.desc: get group config +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(P2pAdapterTest, GetGroupConfigTest001, TestSize.Level1) +{ + WifiDirectInterfaceMock mock; + WifiP2pGroupInfo info {}; + std::string groupConfigString; + EXPECT_CALL(mock, GetCurrentGroup) + .WillOnce(Return(ERROR_WIFI_UNKNOWN)) + .WillOnce(DoAll(SetArgPointee<0>(info), Return(WIFI_SUCCESS))); + int32_t ret =P2pAdapter::GetGroupConfig(groupConfigString); + + EXPECT_EQ(ret, ToSoftBusErrorCode(static_cast(ERROR_WIFI_UNKNOWN))); + ret =P2pAdapter::GetGroupConfig(groupConfigString); + EXPECT_EQ(ret, SOFTBUS_OK); +} + + +/* +* @tc.name: GetIpAddressTest001 +* @tc.desc: get ip address +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(P2pAdapterTest, GetIpAddressTest001, TestSize.Level1) +{ + WifiDirectInterfaceMock mock; + std::string ipString = "127.0.0.X"; + WifiP2pGroupInfo info; + if (strcpy_s(info.interface, sizeof(info.interface), "wlan0") != EOK) { + CONN_LOGE(CONN_WIFI_DIRECT, "strcpy interfaceName fail"); + return; + } + EXPECT_CALL(mock, GetCurrentGroup) + .WillOnce(Return(ERROR_WIFI_UNKNOWN)) + .WillOnce(DoAll(SetArgPointee<0>(info), Return(WIFI_SUCCESS))); + int32_t ret = P2pAdapter::GetIpAddress(ipString); + EXPECT_EQ(ret, ToSoftBusErrorCode(static_cast(ERROR_WIFI_UNKNOWN))); + ret = P2pAdapter::GetIpAddress(ipString); + EXPECT_TRUE((ret != SOFTBUS_OK)); +} + +/* +* @tc.name: GetDynamicMacAddressTest001 +* @tc.desc: get dynamic mac adress +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(P2pAdapterTest, GetDynamicMacAddressTest001, TestSize.Level1) +{ + WifiDirectInterfaceMock mock; + std::string macString; + WifiP2pGroupInfo info; + if (strcpy_s(info.interface, sizeof(info.interface), "wlan0") != EOK) { + CONN_LOGE(CONN_WIFI_DIRECT, "strcpy interfaceName fail"); + return; + } + EXPECT_CALL(mock, GetCurrentGroup).WillOnce(Return(ERROR_WIFI_UNKNOWN)); + int32_t ret = P2pAdapter::GetDynamicMacAddress(macString); + EXPECT_EQ(ret, ToSoftBusErrorCode(ERROR_WIFI_UNKNOWN)); +} + +/* +* @tc.name: DestroyGroupTest002 +* @tc.desc: check destroy group +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(P2pAdapterTest, DestroyGroupTest002, TestSize.Level1) +{ + WifiDirectInterfaceMock mock; + std::string macString = ""; + std::string ipString; + int32_t ret = P2pAdapter::RequestGcIp(macString, ipString); + EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); + EXPECT_CALL(mock, Hid2dRequestGcIp) + .WillOnce(Return(ERROR_WIFI_UNKNOWN)) + .WillOnce(Return(WIFI_SUCCESS)); + macString = "11:22:33:44:55:66"; + ret = P2pAdapter::RequestGcIp(macString, ipString); + EXPECT_EQ(ret, ToSoftBusErrorCode(ERROR_WIFI_UNKNOWN)); + + ret = P2pAdapter::RequestGcIp(macString, ipString); + EXPECT_EQ(ret, WIFI_SUCCESS); +} +} \ No newline at end of file diff --git a/tests/core/connection/wifi_direct_cpp/processor/BUILD.gn b/tests/core/connection/wifi_direct_cpp/processor/BUILD.gn index 21664c7d7..e6fdbe9e3 100644 --- a/tests/core/connection/wifi_direct_cpp/processor/BUILD.gn +++ b/tests/core/connection/wifi_direct_cpp/processor/BUILD.gn @@ -13,6 +13,7 @@ import("//build/test.gni") import("../../../../../dsoftbus.gni") +import("./p2pv1_unittest.gni") wifi_direct_path = "$dsoftbus_root_path/core/connection/wifi_direct_cpp" wifi_direct_unit_path = @@ -21,83 +22,12 @@ ut_out_path = "dsoftbus/connection/wifi_direct_cpp/processor" ohos_unittest("P2pv1ProcessorTest") { module_out_path = ut_out_path - include_dirs = [ - ".", - "//third_party/cJSON", - "//third_party/json/include", - "//third_party/googletest/googletest/include", - "//third_party/googletest/googletest/src", - "//third_party/bounds_checking_function/include", + include_dirs = processorv1_ut_include_dirs - "$dsoftbus_root_path/core/bus_center/utils/include", - "$dsoftbus_root_path/core/authentication/include", - "$dsoftbus_root_path/core/authentication/interface", - "$dsoftbus_root_path/core/bus_center/lnn/net_builder/include", - "$dsoftbus_root_path/core/bus_center/lnn/net_ledger/common/include", - "$dsoftbus_root_path/core/bus_center/lnn/net_ledger/common/include", - "$dsoftbus_root_path/core/bus_center/lnn/net_ledger/distributed_ledger/include", - "$dsoftbus_root_path/core/bus_center/lnn/lane_hub/lane_manager/include", - "$dsoftbus_root_path/core/bus_center/interface", - "$dsoftbus_root_path/core/common/dfx/hisysevent_adapter/include", - "$dsoftbus_root_path/core/common/dfx/interface/include", - "$dsoftbus_root_path/core/connection/interface", - "$dsoftbus_root_path/core/common/include", - "$dsoftbus_root_path/core/discovery/manager/include", - "$dsoftbus_root_path/core/discovery/interface", - "$dsoftbus_root_path/adapter/common/include", - "$dsoftbus_root_path/interfaces/kits/common", - "$dsoftbus_root_path/interfaces/kits/discovery", - "$dsoftbus_root_path/interfaces/kits/bus_center", - "$dsoftbus_root_path/interfaces/inner_kits/lnn", - "$dsoftbus_root_path/core/transmission/trans_channel/proxy/include", - "$dsoftbus_root_path/adapter/common/include/OS_adapter_define/linux", - "$dsoftbus_root_path/core/transmission/trans_channel/proxy/include", - "$wifi_direct_path", - "$wifi_direct_unit_path", - ] - sources = [ - "$wifi_direct_path/adapter/p2p_adapter.cpp", - "$wifi_direct_path/channel/auth_negotiate_channel.cpp", - "$wifi_direct_path/channel/dummy_negotiate_channel.cpp", + sources = processorv1_ut_sources - # proxy_negotiate_channel is mocked - "$wifi_direct_path/command/command_factory.cpp", - "$wifi_direct_path/command/connect_command.cpp", - "$wifi_direct_path/command/disconnect_command.cpp", - "$wifi_direct_path/command/negotiate_command.cpp", - "$wifi_direct_path/command/processor_selector_factory.cpp", - "$wifi_direct_path/command/simple_processor_selector.cpp", - "$wifi_direct_path/data/inner_link.cpp", - "$wifi_direct_path/data/interface_info.cpp", - "$wifi_direct_path/data/interface_manager.cpp", - "$wifi_direct_path/data/ipv4_info.cpp", - "$wifi_direct_path/data/link_info.cpp", - "$wifi_direct_path/data/link_manager.cpp", - "$wifi_direct_path/data/negotiate_message.cpp", - "$wifi_direct_path/data/wifi_config_info.cpp", - - # entity is mocked by p2p_entity.h in current directory - "$wifi_direct_path/event/wifi_direct_event_dispatcher.cpp", - "$wifi_direct_path/processor/p2p_v1_processor.cpp", - "$wifi_direct_path/protocol/json_protocol.cpp", - "$wifi_direct_path/protocol/tlv_protocol.cpp", - "$wifi_direct_path/utils/duration_statistic.cpp", - "$wifi_direct_path/utils/wifi_direct_anonymous.cpp", - "$wifi_direct_path/utils/wifi_direct_dfx.cpp", - "$wifi_direct_path/utils/wifi_direct_trace.cpp", - "$wifi_direct_path/utils/wifi_direct_utils.cpp", - "$wifi_direct_path/wifi_direct_executor.cpp", - "$wifi_direct_path/wifi_direct_initiator.cpp", - "$wifi_direct_path/wifi_direct_ip_manager.cpp", - "$wifi_direct_path/wifi_direct_manager.cpp", - "$wifi_direct_path/wifi_direct_role_option.cpp", - "$wifi_direct_path/wifi_direct_scheduler.cpp", - "$wifi_direct_unit_path/net_conn_client.cpp", - "$wifi_direct_unit_path/wifi_direct_mock.cpp", - "channel/proxy_negotiate_channel.h", - "p2p_v1_processor_test.cpp", - ] + defines += processorv1_ut_defines remove_configs = [ "//build/config/compiler:no_rtti", diff --git a/tests/core/connection/wifi_direct_cpp/processor/p2p_v1_fuzz_helper.h b/tests/core/connection/wifi_direct_cpp/processor/p2p_v1_fuzz_helper.h new file mode 100644 index 000000000..dda223646 --- /dev/null +++ b/tests/core/connection/wifi_direct_cpp/processor/p2p_v1_fuzz_helper.h @@ -0,0 +1,114 @@ +/* + * Copyright (c) 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 + * + * 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 P2P_V1_FUZZ_HELPER_H +#define P2P_V1_FUZZ_HELPER_H + +#include "data/negotiate_message.h" + +#include "fuzz_data_generator.h" + +namespace OHOS::SoftBus { + +class P2pV1FuzzHelper { +public: + using FuzzInjector = void (*)(NegotiateMessage &message); + static int FuzzCommonEnum(int max, int overflow) + { + int32_t value = 0; + GenerateInt32(value); + return value % (max + overflow); + } + + static void FuzzCommandType(NegotiateMessage &message) + { + auto value = static_cast( + FuzzCommonEnum(static_cast(LegacyCommandType::CMD_PC_GET_INTERFACE_INFO_RESP), 3)); + message.SetLegacyP2pCommandType(value); + } + + static void FuzzContentType(NegotiateMessage &message) + { + auto value = static_cast(FuzzCommonEnum(static_cast(LegacyContentType::RESULT), 3)); + message.SetLegacyP2pContentType(value); + } + + static void FuzzGcChannelList(NegotiateMessage &message) + { + std::string value; + GenerateString(value); + message.SetLegacyP2pGcChannelList(value); + } + + static void FuzzGcMac(NegotiateMessage &message) + { + std::string value; + GenerateString(value); + message.SetLegacyP2pGcMac(value); + } + + static void FuzzGoMac(NegotiateMessage &message) + { + std::string value; + GenerateString(value); + message.SetLegacyP2pGoMac(value); + } + + static void FuzzIP(NegotiateMessage &message) + { + std::string value; + GenerateString(value); + message.SetLegacyP2pIp(value); + } + + static void FuzzMac(NegotiateMessage &message) + { + std::string value; + GenerateString(value); + message.SetLegacyP2pMac(value); + } + + static void FuzzSelfWifiCfg(NegotiateMessage &message) + { + std::string value; + GenerateString(value); + message.SetLegacyP2pWifiConfigInfo(value); + } + + static void FuzzStationFrequency(NegotiateMessage &message) + { + int value; + GenerateInt32(value); + message.SetLegacyP2pStationFrequency(value); + } + + static void FuzzVersion(NegotiateMessage &message) + { + int value; + GenerateInt32(value); + message.SetLegacyP2pVersion(value); + } + + static void FuzzWideBandSupport(NegotiateMessage &message) + { + bool value; + GenerateBool(value); + message.SetLegacyP2pWideBandSupported(value); + } +}; + +} // namespace OHOS::SoftBus + +#endif // P2P_V1_FUZZ_HELPER_H diff --git a/tests/core/connection/wifi_direct_cpp/processor/p2p_v1_processor_test.cpp b/tests/core/connection/wifi_direct_cpp/processor/p2p_v1_processor_test.cpp index 7dca7ff1b..b609cf580 100644 --- a/tests/core/connection/wifi_direct_cpp/processor/p2p_v1_processor_test.cpp +++ b/tests/core/connection/wifi_direct_cpp/processor/p2p_v1_processor_test.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#define private public +#define private public #define protected public #include "processor/p2p_v1_processor.h" #undef protected @@ -36,10 +36,15 @@ #include "wifi_direct_scheduler_factory.h" #include "entity/p2p_entity.h" -#include "wifi_direct_mock.h" #include "net_conn_client.h" +#include "wifi_direct_mock.h" #include "wifi_direct_test_context.h" +// for fuzz test +#include "fuzz_data_generator.h" +#include "fuzz_environment.h" +#include "p2p_v1_fuzz_helper.h" + using namespace testing::ext; using namespace testing; using ::testing::_; @@ -200,6 +205,7 @@ void P2pV1ProcessorTest::InjectEntityMock(P2pEntity &mock) return result; }); EXPECT_CALL(mock, NotifyNewClientJoining(_)).WillRepeatedly([](const std::string &remoteMac) {}); + EXPECT_CALL(mock, CancelNewClientJoining(_)).WillRepeatedly([](const std::string &remoteMac) {}); } void P2pV1ProcessorTest::InjectCommonMock(WifiDirectInterfaceMock &mock) @@ -240,6 +246,19 @@ void P2pV1ProcessorTest::InjectCommonMock(WifiDirectInterfaceMock &mock) EXPECT_CALL( mock, ProxyNegotiateChannelGetRemoteDeviceId(context_.Get(TestContextKey::CONNECT_NEGO_CHANNEL_ID, int32_t(0)))) .WillRepeatedly(Return(context_.Get(TestContextKey::REMOTE_UUID, std::string("")))); + EXPECT_CALL(mock, LnnSetLocalNumInfo(_, _)).WillRepeatedly(Return(SOFTBUS_OK)); + EXPECT_CALL(mock, LnnSetLocalStrInfo(_, _)).WillRepeatedly(Return(SOFTBUS_OK)); + EXPECT_CALL(mock, LnnSyncP2pInfo()).WillRepeatedly(Return(SOFTBUS_OK)); + EXPECT_CALL(mock, AuthGenRequestId()).WillRepeatedly(Return(0)); + EXPECT_CALL(mock, AuthGetDeviceUuid(_, _, _)).WillRepeatedly([this](int64_t authId, char *uuid, uint16_t size) { + auto id = context_.Get(TestContextKey::REMOTE_UUID, std::string("")); + (void)strcpy_s(uuid, size, id.c_str()); + return SOFTBUS_OK; + }); + EXPECT_CALL(mock, AuthPostTransData(_, _)).WillRepeatedly(Return(SOFTBUS_OK)); + EXPECT_CALL(mock, IsFeatureSupport(_, _)).WillRepeatedly([](uint64_t feature, FeatureCapability capaBit) { + return ((feature & (1 << (uint64_t)capaBit)) != 0); + }); } void P2pV1ProcessorTest::PrepareConnectParameter(WifiDirectConnectInfo &info, WifiDirectConnectCallback &callback) @@ -618,4 +637,200 @@ HWTEST_F(P2pV1ProcessorTest, ReuseRemoteLinkTimeout, TestSize.Level1) // ugly way (sleep 1s) to wait processor terminate, as mock environment will be cleanup before processor terminate. sleep(1); } + +static bool InspectProcessorState(const std::string &remoteDeviceId, uint32_t timeoutMs, uint32_t deltaMs) +{ + WifiDirectScheduler &scheduler = WifiDirectSchedulerFactory::GetInstance().GetScheduler(); + // expect executor run and terminate + bool expected[] = { true, false }; + int index = 0; + auto times = timeoutMs / deltaMs; + for (auto i = 0; i < times && index < ARRAY_SIZE(expected); i++) { + auto status = scheduler.CheckExecutorRunning(remoteDeviceId); + if (status == expected[index]) { + index += 1; + continue; + } + SoftBusSleepMs(deltaMs); + } + return index == ARRAY_SIZE(expected); +} + +/* + * @tc.name: PassiveConnectTimeout + * @tc.desc: passive connect timeout + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(P2pV1ProcessorTest, PassiveConnectTimeoutWhenNone, TestSize.Level1) +{ + context_.Set(TestContextKey::REMOTE_MAC, std::string("42:dc:a5:f3:4c:14")); + context_.Set(TestContextKey::WIFI_STA_FREQUENCY, int(5180)); + context_.Set(TestContextKey::WIFI_RECOMMEND_FREQUENCY, int(5180)); + context_.Set(TestContextKey::WIFI_REQUEST_GC_IP, + std::pair>(WIFI_SUCCESS, std::vector { 192, 168, 49, 3 })); + + WifiDirectInterfaceMock mock; + InjectCommonMock(mock); + InjectData(mock); + P2pEntity entityMock; + InjectEntityMock(entityMock); + InjectChannel(mock); + + auto channelId = context_.Get(TestContextKey::CONNECT_NEGO_CHANNEL_ID, int32_t(0)); + std::string message = + R"({"KEY_BRIDGE_SUPPORTED":false,"KEY_COMMAND_TYPE":8,"KEY_CONTENT_TYPE":2,"KEY_EXPECTED_ROLE":1,"KEY_GC_CHANNEL_LIST":"36##40##44##48##149##153##157##161##165","KEY_GC_MAC":"42:dc:a5:f3:4c:14","KEY_GO_MAC":"","KEY_MAC":"42:dc:a5:f3:4c:14","KEY_ROLE":5,"KEY_SELF_WIFI_CONFIG":"","KEY_STATION_FREQUENCY":5180,"KEY_VERSION":2,"KEY_WIDE_BAND_SUPPORTED":false})"; + CoCProxyNegotiateChannel::InjectReceiveData(channelId, message); + + auto deviceId = context_.Get(TestContextKey::REMOTE_UUID, std::string("")); + ASSERT_TRUE(InspectProcessorState(deviceId, P2pV1Processor::P2P_V1_WAITING_REQUEST_TIME_MS + 1000, 200)); +} + +/* + * @tc.name: PassiveConnectSuccessWhenNone + * @tc.desc: passive connect success + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(P2pV1ProcessorTest, PassiveConnectSuccessWhenNone, TestSize.Level1) +{ + context_.Set(TestContextKey::REMOTE_MAC, std::string("42:dc:a5:f3:4c:14")); + context_.Set(TestContextKey::WIFI_STA_FREQUENCY, int(5180)); + context_.Set(TestContextKey::WIFI_RECOMMEND_FREQUENCY, int(5180)); + context_.Set(TestContextKey::WIFI_REQUEST_GC_IP, + std::pair>(WIFI_SUCCESS, std::vector { 192, 168, 49, 3 })); + + WifiDirectInterfaceMock mock; + InjectCommonMock(mock); + InjectData(mock); + P2pEntity entityMock; + InjectEntityMock(entityMock); + InjectChannel(mock); + + auto channelId = context_.Get(TestContextKey::CONNECT_NEGO_CHANNEL_ID, int32_t(0)); + EXPECT_CALL(mock, ProxyNegotiateChannelSendMessage(channelId, _)) + .WillOnce([](int32_t channelId, const NegotiateMessage &msg) { + std::string message = + R"({"KEY_BRIDGE_SUPPORTED":false,"KEY_COMMAND_TYPE":8,"KEY_CONTENT_TYPE":1,"KEY_EXPECTED_ROLE":2,"KEY_GC_IP":"192.168.49.3","KEY_GC_MAC":"a6:3b:0e:78:29:dd","KEY_GO_IP":"192.168.49.1","KEY_GO_MAC":"42:dc:a5:f3:4c:14","KEY_GO_PORT":43267,"KEY_GROUP_CONFIG":"DIRECT-ja-OHOS_0u31\n4e:e8:d0:45:8f:10\nulKjGU9T\n5180","KEY_MAC":"42:dc:a5:f3:4c:14","KEY_ROLE":2,"KEY_SELF_WIFI_CONFIG":"","KEY_VERSION":2})"; + CoCProxyNegotiateChannel::InjectReceiveData(channelId, message); + return SOFTBUS_OK; + }) + .WillRepeatedly(Return(context_.Get(TestContextKey::CHANNEL_SEND_MESSAGE, int(0)))); + EXPECT_CALL(mock, AuthOpenConn(_, _, _, _)) + .WillOnce([](const AuthConnInfo *info, uint32_t requestId, const AuthConnCallback *callback, bool isMeta) { + // sleep 100s to make sure processor state can be inspected by InspectProcessorState + SoftBusSleepMs(100); + AuthHandle handle = { 0 }; + callback->onConnOpened(requestId, handle); + return SOFTBUS_OK; + }); + + std::string message = + R"({"KEY_BRIDGE_SUPPORTED":false,"KEY_COMMAND_TYPE":8,"KEY_CONTENT_TYPE":2,"KEY_EXPECTED_ROLE":1,"KEY_GC_CHANNEL_LIST":"36##40##44##48##149##153##157##161##165","KEY_GC_MAC":"42:dc:a5:f3:4c:14","KEY_GO_MAC":"","KEY_MAC":"42:dc:a5:f3:4c:14","KEY_ROLE":5,"KEY_SELF_WIFI_CONFIG":"","KEY_STATION_FREQUENCY":5180,"KEY_VERSION":2,"KEY_WIDE_BAND_SUPPORTED":false})"; + CoCProxyNegotiateChannel::InjectReceiveData(channelId, message); + + auto deviceId = context_.Get(TestContextKey::REMOTE_UUID, std::string("")); + ASSERT_TRUE(InspectProcessorState(deviceId, 2000, 10)); + + auto remoteMac = context_.Get(TestContextKey::REMOTE_MAC, std::string("")); + InnerLink::LinkState state = InnerLink::LinkState::INVALID_STATE; + LinkManager::GetInstance().ProcessIfPresent(remoteMac, [&state](InnerLink &link) { + state = link.GetState(); + }); + ASSERT_EQ(state, InnerLink::LinkState::CONNECTED); +} + +static P2pV1FuzzHelper::FuzzInjector g_fuzzInjectorTable[] = { + P2pV1FuzzHelper::FuzzContentType, + P2pV1FuzzHelper::FuzzGcChannelList, + P2pV1FuzzHelper::FuzzGcMac, + P2pV1FuzzHelper::FuzzGoMac, + P2pV1FuzzHelper::FuzzIP, + P2pV1FuzzHelper::FuzzMac, + P2pV1FuzzHelper::FuzzSelfWifiCfg, + P2pV1FuzzHelper::FuzzStationFrequency, + P2pV1FuzzHelper::FuzzVersion, + P2pV1FuzzHelper::FuzzWideBandSupport, +}; +static std::string GenerateCmdConnV1Req() +{ + static uint32_t counter = 0; + counter += 1; + + std::string raw = + R"({"KEY_COMMAND_TYPE":9,"KEY_CONTENT_TYPE":2,"KEY_GC_CHANNEL_LIST":"36##40##44##48##149##153##157##161##165","KEY_GC_MAC":"a6:3b:0e:78:29:dd","KEY_GO_MAC":"42:dc:a5:f3:4c:14","KEY_IP":"","KEY_MAC":"a6:3b:0e:78:29:dd","KEY_SELF_WIFI_CONFIG":"","KEY_STATION_FREQUENCY":5180,"KEY_VERSION":2,"KEY_WIDE_BAND_SUPPORTED":false})"; + std::vector input; + input.insert(input.end(), raw.c_str(), raw.c_str() + raw.size()); + auto unmarshalProtocol = WifiDirectProtocolFactory::CreateProtocol(ProtocolType::JSON); + NegotiateMessage message; + message.Unmarshalling(*unmarshalProtocol, input); + + auto index = counter % ARRAY_SIZE(g_fuzzInjectorTable); + g_fuzzInjectorTable[index](message); + + std::vector output; + auto marshalProtocol = WifiDirectProtocolFactory::CreateProtocol(ProtocolType::JSON); + message.Marshalling(*marshalProtocol, output); + return std::string((char *)output.data(), output.size()); +} + +/* + * @tc.name: ReuseRemoteLinkTimeout + * @tc.desc: reuse remote link timeout + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(P2pV1ProcessorTest, FuzzTestChannelData, TestSize.Level1) +{ + if (!FuzzEnvironment::IsFuzzEnable()) { + GTEST_SKIP() << "only support in fuzz test"; + } + + context_.Set(TestContextKey::REMOTE_MAC, std::string("a6:3b:0e:78:29:dd")); + context_.Set(TestContextKey::WIFI_STA_FREQUENCY, int(5180)); + context_.Set(TestContextKey::WIFI_RECOMMEND_FREQUENCY, int(5180)); + context_.Set(TestContextKey::WIFI_REQUEST_GC_IP, + std::pair>(WIFI_SUCCESS, std::vector { 192, 168, 49, 3 })); + + WifiDirectInterfaceMock mock; + InjectCommonMock(mock); + InjectData(mock); + P2pEntity entityMock; + InjectEntityMock(entityMock); + InjectChannel(mock); + + auto channelId = context_.Get(TestContextKey::CONNECT_NEGO_CHANNEL_ID, int32_t(0)); + EXPECT_CALL(mock, ProxyNegotiateChannelSendMessage(channelId, _)) + .WillOnce([](int32_t channelId, const NegotiateMessage &msg) { + auto message = GenerateCmdConnV1Req(); + CoCProxyNegotiateChannel::InjectReceiveData(channelId, message); + return SOFTBUS_OK; + }) + .WillRepeatedly([](int32_t channelId, const NegotiateMessage &msg) { + return SOFTBUS_NOT_IMPLEMENT; + }); + + WifiDirectConnectInfo info = { 0 }; + WifiDirectConnectCallback callback { 0 }; + PrepareConnectParameter(info, callback); + std::promise result; + EXPECT_CALL(mock, OnConnectFailure(context_.Get(TestContextKey::CONNECT_REQUEST_ID, uint32_t(0)), _)) + .Times(1) + .WillOnce<>([&result](uint32_t requestId, int32_t reason) { + result.set_value(reason); + }); + + WifiDirectScheduler &scheduler = WifiDirectSchedulerFactory::GetInstance().GetScheduler(); + auto ret = scheduler.ConnectDevice(info, callback); + ASSERT_EQ(ret, SOFTBUS_OK); + + auto future = result.get_future(); + auto status = future.wait_for(std::chrono::milliseconds(P2pV1Processor::P2P_V1_WAITING_RESPONSE_TIME_MS + 1000)); + ASSERT_EQ(status, std::future_status::ready); + auto value = future.get(); + ASSERT_NE(value, SOFTBUS_OK); + + // ugly way (sleep 1s) to wait processor terminate, as mock environment will be cleanup before processor terminate. + sleep(1); +} } // namespace OHOS::SoftBus diff --git a/tests/core/connection/wifi_direct_cpp/processor/p2pv1_unittest.gni b/tests/core/connection/wifi_direct_cpp/processor/p2pv1_unittest.gni new file mode 100644 index 000000000..8463422f1 --- /dev/null +++ b/tests/core/connection/wifi_direct_cpp/processor/p2pv1_unittest.gni @@ -0,0 +1,103 @@ +# Copyright (c) 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 +# +# 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("../../../../../dsoftbus.gni") + +wifi_direct_path = "$dsoftbus_root_path/core/connection/wifi_direct_cpp" +wifi_direct_unit_path = + "$dsoftbus_root_path/tests/core/connection/wifi_direct_cpp" +current_path = rebase_path(".") + +processorv1_ut_include_dirs = [ + "$current_path", + + "//third_party/cJSON", + "//third_party/json/include", + "//third_party/googletest/googletest/include", + "//third_party/googletest/googletest/src", + "//third_party/bounds_checking_function/include", + + "$dsoftbus_root_path/core/bus_center/utils/include", + "$dsoftbus_root_path/core/authentication/include", + "$dsoftbus_root_path/core/authentication/interface", + "$dsoftbus_root_path/core/bus_center/lnn/net_builder/include", + "$dsoftbus_root_path/core/bus_center/lnn/net_ledger/common/include", + "$dsoftbus_root_path/core/bus_center/lnn/net_ledger/common/include", + "$dsoftbus_root_path/core/bus_center/lnn/net_ledger/distributed_ledger/include", + "$dsoftbus_root_path/core/bus_center/lnn/lane_hub/lane_manager/include", + "$dsoftbus_root_path/core/bus_center/interface", + "$dsoftbus_root_path/core/common/dfx/hisysevent_adapter/include", + "$dsoftbus_root_path/core/common/dfx/interface/include", + "$dsoftbus_root_path/core/connection/interface", + "$dsoftbus_root_path/core/common/include", + "$dsoftbus_root_path/core/discovery/manager/include", + "$dsoftbus_root_path/core/discovery/interface", + "$dsoftbus_root_path/adapter/common/include", + "$dsoftbus_root_path/interfaces/kits/common", + "$dsoftbus_root_path/interfaces/kits/discovery", + "$dsoftbus_root_path/interfaces/kits/bus_center", + "$dsoftbus_root_path/interfaces/inner_kits/lnn", + "$dsoftbus_root_path/core/transmission/trans_channel/proxy/include", + "$dsoftbus_root_path/adapter/common/include/OS_adapter_define/linux", + "$dsoftbus_root_path/core/transmission/trans_channel/proxy/include", + + "$dsoftbus_root_path/tests/common/include", + + "$wifi_direct_path", + "$wifi_direct_unit_path", +] + +processorv1_ut_sources = [ + "$wifi_direct_path/adapter/p2p_adapter.cpp", + "$wifi_direct_path/channel/auth_negotiate_channel.cpp", + "$wifi_direct_path/channel/dummy_negotiate_channel.cpp", + + # proxy_negotiate_channel is mocked + "$wifi_direct_path/command/command_factory.cpp", + "$wifi_direct_path/command/connect_command.cpp", + "$wifi_direct_path/command/disconnect_command.cpp", + "$wifi_direct_path/command/negotiate_command.cpp", + "$wifi_direct_path/command/processor_selector_factory.cpp", + "$wifi_direct_path/command/simple_processor_selector.cpp", + "$wifi_direct_path/data/inner_link.cpp", + "$wifi_direct_path/data/interface_info.cpp", + "$wifi_direct_path/data/interface_manager.cpp", + "$wifi_direct_path/data/ipv4_info.cpp", + "$wifi_direct_path/data/link_info.cpp", + "$wifi_direct_path/data/link_manager.cpp", + "$wifi_direct_path/data/negotiate_message.cpp", + "$wifi_direct_path/data/wifi_config_info.cpp", + + # entity is mocked by p2p_entity.h in current directory + "$current_path/channel/proxy_negotiate_channel.h", + "$current_path/p2p_v1_processor_test.cpp", + "$wifi_direct_path/event/wifi_direct_event_dispatcher.cpp", + "$wifi_direct_path/processor/p2p_v1_processor.cpp", + "$wifi_direct_path/protocol/json_protocol.cpp", + "$wifi_direct_path/protocol/tlv_protocol.cpp", + "$wifi_direct_path/utils/duration_statistic.cpp", + "$wifi_direct_path/utils/wifi_direct_anonymous.cpp", + "$wifi_direct_path/utils/wifi_direct_dfx.cpp", + "$wifi_direct_path/utils/wifi_direct_trace.cpp", + "$wifi_direct_path/utils/wifi_direct_utils.cpp", + "$wifi_direct_path/wifi_direct_executor.cpp", + "$wifi_direct_path/wifi_direct_initiator.cpp", + "$wifi_direct_path/wifi_direct_ip_manager.cpp", + "$wifi_direct_path/wifi_direct_manager.cpp", + "$wifi_direct_path/wifi_direct_role_option.cpp", + "$wifi_direct_path/wifi_direct_scheduler.cpp", + "$wifi_direct_unit_path/net_conn_client.cpp", + "$wifi_direct_unit_path/wifi_direct_mock.cpp", +] + +processorv1_ut_defines = [ "P2P_V1_WAITING_TIMEOUT_MS_OVERWRITE=1000" ] diff --git a/tests/core/connection/wifi_direct_cpp/wifi_direct_mock.cpp b/tests/core/connection/wifi_direct_cpp/wifi_direct_mock.cpp index dd5e46bf8..92226fba4 100644 --- a/tests/core/connection/wifi_direct_cpp/wifi_direct_mock.cpp +++ b/tests/core/connection/wifi_direct_cpp/wifi_direct_mock.cpp @@ -162,6 +162,11 @@ int32_t LnnGetRemoteDefaultPtkByUuid(const char *uuid, char *remotePtk, uint32_t return OHOS::SoftBus::WifiDirectInterfaceMock::GetMock()->LnnGetRemoteDefaultPtkByUuid(uuid, remotePtk, len); } +int32_t SoftBusBase64Encode(unsigned char *dst, size_t dlen, size_t *olen, const unsigned char *src, size_t slen) +{ + return OHOS::SoftBus::WifiDirectInterfaceMock::GetMock()->SoftBusBase64Encode(dst, dlen, olen, src, slen); +} + WifiErrorCode GetLinkedInfo(WifiLinkedInfo *info) { return OHOS::SoftBus::WifiDirectInterfaceMock::GetMock()->GetLinkedInfo(info); diff --git a/tests/core/connection/wifi_direct_cpp/wifi_direct_mock.h b/tests/core/connection/wifi_direct_cpp/wifi_direct_mock.h index c1c4f9282..c06370b5f 100644 --- a/tests/core/connection/wifi_direct_cpp/wifi_direct_mock.h +++ b/tests/core/connection/wifi_direct_cpp/wifi_direct_mock.h @@ -65,6 +65,8 @@ public: const AuthConnCallback *callback, bool isMeta) = 0; virtual int32_t LnnGetLocalNumInfo(InfoKey key, int32_t *info) = 0; virtual int32_t LnnGetRemoteNumInfo(const char *netWorkId, InfoKey key, int32_t *info) = 0; + virtual int32_t SoftBusBase64Encode(unsigned char *dst, size_t dlen, size_t *olen, + const unsigned char *src, size_t slen) = 0; virtual int32_t LnnGetLocalPtkByUuid(const char *uuid, char *localPtk, uint32_t len) = 0; virtual int32_t LnnGetLocalDefaultPtkByUuid(const char *uuid, char *localPtk, uint32_t len) = 0; virtual int32_t LnnGetRemoteByteInfo(const char *networkId, InfoKey key, uint8_t *info, uint32_t len) = 0; @@ -139,6 +141,8 @@ public: MOCK_METHOD4(AuthOpenConn, int32_t (const AuthConnInfo*, uint32_t, const AuthConnCallback*, bool)); MOCK_METHOD2(LnnGetLocalNumInfo, int32_t (InfoKey, int32_t*)); MOCK_METHOD3(LnnGetRemoteNumInfo, int32_t (const char*, InfoKey, int32_t*)); + MOCK_METHOD(int32_t, SoftBusBase64Encode, (unsigned char *, size_t, size_t *, + const unsigned char *, size_t), (override)); MOCK_METHOD3(LnnGetLocalPtkByUuid, int32_t (const char *uuid, char *localPtk, uint32_t len)); MOCK_METHOD3(LnnGetLocalDefaultPtkByUuid, int32_t (const char *uuid, char *localPtk, uint32_t len)); MOCK_METHOD4(LnnGetRemoteByteInfo, int32_t (const char *networkId, InfoKey key, uint8_t *info, uint32_t len)); diff --git a/tests/core/discovery/BUILD.gn b/tests/core/discovery/BUILD.gn index 72e29ad89..0e71f9a35 100644 --- a/tests/core/discovery/BUILD.gn +++ b/tests/core/discovery/BUILD.gn @@ -45,6 +45,7 @@ group("unittest") { deps += [ "$dsoftbus_root_path/dsoftbus_enhance/test/core/connection:unittest", "$dsoftbus_root_path/dsoftbus_enhance/test/core/discovery:unittest", + "$dsoftbus_root_path/tests/core/broadcast:unittest", ] } } diff --git a/tests/core/frame/fuzztest/softbusserverstub_fuzzer/softbusserverstub_fuzzer.cpp b/tests/core/frame/fuzztest/softbusserverstub_fuzzer/softbusserverstub_fuzzer.cpp index c5a110a2a..6bf019436 100644 --- a/tests/core/frame/fuzztest/softbusserverstub_fuzzer/softbusserverstub_fuzzer.cpp +++ b/tests/core/frame/fuzztest/softbusserverstub_fuzzer/softbusserverstub_fuzzer.cpp @@ -28,17 +28,20 @@ #include "system_ability_definition.h" #include "securec.h" #define private public +#include "softbus_def.h" #include "softbus_server_stub.h" #include "softbus_server.h" #define TYPE_NUM 10 #define QOS_NUM 8 -#define INPUT_NAME_SIZE_MAX 20 +#define INPUT_NAME_SIZE_MAX 70 #define NETWORKID_SIZE_MAX 20 +#define SIZE_NUM_THREE 3 +#define SIZE_NUM_FOUR 4 +#define SIZE_NUM_FIVE 5 + namespace OHOS { -constexpr int32_t SOFTBUS_FUZZ_TEST_UID = 1; -constexpr int32_t SOFTBUS_FUZZ_TEST_PID = 1; constexpr int32_t SOFTBUS_FUZZ_TEST_START_DISCOVERY_SUB_SCRIBE_ID = 5; constexpr int32_t SOFTBUS_FUZZ_TEST_START_DISCOVERY_MODE = 6; constexpr int32_t SOFTBUS_FUZZ_TEST_START_DISCOVERY_MEDIUM = 7; @@ -97,7 +100,7 @@ static sptr GetRemoteObject(void) return nullptr; } -static bool SendRequestByCommand(const uint8_t* data, size_t size, uint32_t command) +static bool SendRequestByCommand(const uint8_t *data, size_t size, uint32_t command) { sptr object = GetRemoteObject(); if (object == nullptr) { @@ -113,9 +116,65 @@ static bool SendRequestByCommand(const uint8_t* data, size_t size, uint32_t comm return object->SendRequest(command, datas, reply, option) == ERR_NONE; } -bool PublishServiceFuzzTest(const uint8_t* data, size_t size) +static void PublishInfoProc(const uint8_t *data, MessageParcel &datas) { - return SendRequestByCommand(data, size, SERVER_PUBLISH_SERVICE); + uint32_t offset = 0; + char pkgName[INPUT_NAME_SIZE_MAX] = "distribdata_test"; + if (memcpy_s(pkgName, INPUT_NAME_SIZE_MAX, reinterpret_cast(data), INPUT_NAME_SIZE_MAX - 1) != EOK) { + return; + } + pkgName[INPUT_NAME_SIZE_MAX - 1] = '\0'; + offset = INPUT_NAME_SIZE_MAX; + int32_t publishId = *reinterpret_cast(data + offset); + offset += sizeof(int32_t); + int32_t mode = *reinterpret_cast(data + offset); + offset += sizeof(int32_t); + int32_t medium = *reinterpret_cast(data + offset); + offset += sizeof(int32_t); + int32_t freq = *reinterpret_cast(data + offset); + offset += sizeof(int32_t); + + char capability[INPUT_NAME_SIZE_MAX] = ""; + if (memcpy_s(capability, INPUT_NAME_SIZE_MAX, reinterpret_cast(data), + INPUT_NAME_SIZE_MAX - 1) != EOK) { + return; + } + capability[INPUT_NAME_SIZE_MAX - 1] = '\0'; + uint32_t dataLen = *reinterpret_cast(data + offset); + offset += sizeof(uint32_t); + char capabilityData[INPUT_NAME_SIZE_MAX] = ""; + if (memcpy_s(capabilityData, INPUT_NAME_SIZE_MAX, reinterpret_cast(data), + INPUT_NAME_SIZE_MAX) != EOK) { + return; + } + capabilityData[INPUT_NAME_SIZE_MAX - 1] = '\0'; + datas.WriteCString(pkgName); + datas.WriteInt32(publishId); + datas.WriteInt32(mode); + datas.WriteInt32(medium); + datas.WriteInt32(freq); + datas.WriteCString(capability); + datas.WriteUint32(dataLen); + datas.WriteCString(capabilityData); +} + +bool PublishServiceFuzzTest(const uint8_t *data, size_t size) +{ + sptr object = GetRemoteObject(); + if (object == nullptr || data == nullptr || size < INPUT_NAME_SIZE_MAX * SIZE_NUM_THREE + + sizeof(int32_t) * SIZE_NUM_FOUR + sizeof(uint32_t)) { + return false; + } + + MessageParcel datas; + PublishInfoProc(data, datas); + MessageParcel reply; + sptr SoftBusServer = new OHOS::SoftBusServer(SOFTBUS_SERVER_SA_ID, true); + if (SoftBusServer == nullptr) { + return false; + } + SoftBusServer->PublishServiceInner(datas, reply); + return true; } bool UnPublishServiceFuzzTest(const uint8_t *data, size_t size) @@ -125,16 +184,16 @@ bool UnPublishServiceFuzzTest(const uint8_t *data, size_t size) return false; } uint32_t offset = 0; - char pkgname[INPUT_NAME_SIZE_MAX] = "distribdata_test"; - if (memcpy_s(pkgname, INPUT_NAME_SIZE_MAX, reinterpret_cast(data), INPUT_NAME_SIZE_MAX - 1) != EOK) { + char pkgName[INPUT_NAME_SIZE_MAX] = "distribdata_test"; + if (memcpy_s(pkgName, INPUT_NAME_SIZE_MAX, reinterpret_cast(data), INPUT_NAME_SIZE_MAX - 1) != EOK) { return false; } - pkgname[INPUT_NAME_SIZE_MAX - 1] = '\0'; + pkgName[INPUT_NAME_SIZE_MAX - 1] = '\0'; offset = INPUT_NAME_SIZE_MAX; int32_t publishId = *reinterpret_cast(data + offset); MessageParcel datas; - datas.WriteCString(pkgname); + datas.WriteCString(pkgName); datas.WriteInt32(publishId); MessageParcel reply; sptr SoftBusServer = new OHOS::SoftBusServer(SOFTBUS_SERVER_SA_ID, true); @@ -145,14 +204,68 @@ bool UnPublishServiceFuzzTest(const uint8_t *data, size_t size) return true; } -bool CreateSessionServerFuzzTest(const uint8_t* data, size_t size) +bool CreateSessionServerFuzzTest(const uint8_t *data, size_t size) { - return SendRequestByCommand(data, size, SERVER_CREATE_SESSION_SERVER); + sptr object = GetRemoteObject(); + if (object == nullptr || data == nullptr || size < INPUT_NAME_SIZE_MAX + INPUT_NAME_SIZE_MAX) { + return false; + } + uint32_t offset = 0; + char pkgName[INPUT_NAME_SIZE_MAX] = "distribdata_test"; + if (memcpy_s(pkgName, INPUT_NAME_SIZE_MAX, reinterpret_cast(data), INPUT_NAME_SIZE_MAX - 1) != EOK) { + return false; + } + pkgName[INPUT_NAME_SIZE_MAX - 1] = '\0'; + offset = INPUT_NAME_SIZE_MAX; + char sessionName[INPUT_NAME_SIZE_MAX] = "distribdata_test"; + if (memcpy_s(sessionName, INPUT_NAME_SIZE_MAX, reinterpret_cast(data + offset), + INPUT_NAME_SIZE_MAX - 1) != EOK) { + return false; + } + sessionName[INPUT_NAME_SIZE_MAX - 1] = '\0'; + + MessageParcel datas; + datas.WriteCString(pkgName); + datas.WriteCString(sessionName); + MessageParcel reply; + sptr SoftBusServer = new OHOS::SoftBusServer(SOFTBUS_SERVER_SA_ID, true); + if (SoftBusServer == nullptr) { + return false; + } + SoftBusServer->CreateSessionServerInner(datas, reply); + return true; } -bool RemoveSessionServerFuzzTest(const uint8_t* data, size_t size) +bool RemoveSessionServerFuzzTest(const uint8_t *data, size_t size) { - return SendRequestByCommand(data, size, SERVER_REMOVE_SESSION_SERVER); + sptr object = GetRemoteObject(); + if (object == nullptr || data == nullptr || size < INPUT_NAME_SIZE_MAX + INPUT_NAME_SIZE_MAX) { + return false; + } + uint32_t offset = 0; + char pkgName[INPUT_NAME_SIZE_MAX] = "distribdata_test"; + if (memcpy_s(pkgName, INPUT_NAME_SIZE_MAX, reinterpret_cast(data), INPUT_NAME_SIZE_MAX - 1) != EOK) { + return false; + } + pkgName[INPUT_NAME_SIZE_MAX - 1] = '\0'; + offset = INPUT_NAME_SIZE_MAX; + char sessionName[INPUT_NAME_SIZE_MAX] = "distribdata_test"; + if (memcpy_s(sessionName, INPUT_NAME_SIZE_MAX, reinterpret_cast(data + offset), + INPUT_NAME_SIZE_MAX - 1) != EOK) { + return false; + } + sessionName[INPUT_NAME_SIZE_MAX - 1] = '\0'; + + MessageParcel datas; + datas.WriteCString(pkgName); + datas.WriteCString(sessionName); + MessageParcel reply; + sptr SoftBusServer = new OHOS::SoftBusServer(SOFTBUS_SERVER_SA_ID, true); + if (SoftBusServer == nullptr) { + return false; + } + SoftBusServer->RemoveSessionServerInner(datas, reply); + return true; } bool OpenSessionFuzzTest(const uint8_t *data, size_t size) @@ -206,57 +319,223 @@ bool OpenSessionFuzzTest(const uint8_t *data, size_t size) return true; } -bool OpenAuthSessionFuzzTest(const uint8_t* data, size_t size) -{ - return SendRequestByCommand(data, size, SERVER_OPEN_AUTH_SESSION); -} - -bool NotifyAuthSuccessFuzzTest(const uint8_t* data, size_t size) -{ - return SendRequestByCommand(data, size, SERVER_NOTIFY_AUTH_SUCCESS); -} - -bool CloseChannelFuzzTest(const uint8_t* data, size_t size) -{ - return SendRequestByCommand(data, size, SERVER_CLOSE_CHANNEL); -} - -bool SendMessageFuzzTest(const uint8_t* data, size_t size) -{ - return SendRequestByCommand(data, size, SERVER_SESSION_SENDMSG); -} - -bool QosReportFuzzTest(const uint8_t* data, size_t size) -{ - return SendRequestByCommand(data, size, SERVER_QOS_REPORT); -} - -bool GrantPermissionFuzzTest(const uint8_t* data, size_t size) +bool OpenAuthSessionFuzzTest(const uint8_t *data, size_t size) { sptr object = GetRemoteObject(); - if (object == nullptr) { + if (object == nullptr || data == nullptr || size < sizeof(ConnectionAddr) + INPUT_NAME_SIZE_MAX) { + return false; + } + uint32_t offset = 0; + char sessionName[INPUT_NAME_SIZE_MAX] = { 0 }; + if (memcpy_s(sessionName, INPUT_NAME_SIZE_MAX, reinterpret_cast(data), + INPUT_NAME_SIZE_MAX - 1) != EOK) { + return false; + } + sessionName[INPUT_NAME_SIZE_MAX - 1] = '\0'; + offset += INPUT_NAME_SIZE_MAX; + ConnectionAddr addrInfo; + memset_s(&addrInfo, sizeof(ConnectionAddr), 0, sizeof(ConnectionAddr)); + if (memcpy_s(&addrInfo, sizeof(ConnectionAddr), data + offset, sizeof(ConnectionAddr)) != EOK) { return false; } - int32_t uid = SOFTBUS_FUZZ_TEST_UID; - int32_t pid = SOFTBUS_FUZZ_TEST_PID; MessageParcel datas; - datas.WriteInterfaceToken(SOFTBUS_SERVER_STUB_INTERFACE_TOKEN); + datas.WriteCString(sessionName); + datas.WriteRawData(&addrInfo, sizeof(ConnectionAddr)); + MessageParcel reply; + sptr SoftBusServer = new OHOS::SoftBusServer(SOFTBUS_SERVER_SA_ID, true); + if (SoftBusServer == nullptr) { + return false; + } + SoftBusServer->OpenAuthSessionInner(datas, reply); + return true; +} + +bool NotifyAuthSuccessFuzzTest(const uint8_t *data, size_t size) +{ + sptr object = GetRemoteObject(); + if (object == nullptr || data == nullptr || size < sizeof(int32_t) + sizeof(int32_t)) { + return false; + } + uint32_t offset = 0; + int32_t channelId = *reinterpret_cast(data); + offset += sizeof(int32_t); + int32_t channelType = *reinterpret_cast(data + offset); + + MessageParcel datas; + datas.WriteInt32(channelId); + datas.WriteInt32(channelType); + MessageParcel reply; + sptr SoftBusServer = new OHOS::SoftBusServer(SOFTBUS_SERVER_SA_ID, true); + if (SoftBusServer == nullptr) { + return false; + } + SoftBusServer->NotifyAuthSuccessInner(datas, reply); + return true; +} + +bool CloseChannelFuzzTest(const uint8_t *data, size_t size) +{ + sptr object = GetRemoteObject(); + if (object == nullptr || data == nullptr || size < sizeof(int32_t) + sizeof(int32_t) + INPUT_NAME_SIZE_MAX) { + return false; + } + uint32_t offset = 0; + int32_t channelId = *reinterpret_cast(data); + offset += sizeof(int32_t); + int32_t channelType = *reinterpret_cast(data + offset); + offset += sizeof(int32_t); + char sessionName[INPUT_NAME_SIZE_MAX] = ""; + if (memcpy_s(sessionName, INPUT_NAME_SIZE_MAX, data + offset, INPUT_NAME_SIZE_MAX - 1) != EOK) { + return false; + } + sessionName[INPUT_NAME_SIZE_MAX - 1] = '\0'; + + MessageParcel datas; + datas.WriteInt32(channelId); + datas.WriteInt32(channelType); + if (channelType == CHANNEL_TYPE_UNDEFINED) { + datas.WriteCString(sessionName); + } + MessageParcel reply; + sptr SoftBusServer = new OHOS::SoftBusServer(SOFTBUS_SERVER_SA_ID, true); + if (SoftBusServer == nullptr) { + return false; + } + SoftBusServer->CloseChannelInner(datas, reply); + return true; +} + +bool SendMessageFuzzTest(const uint8_t *data, size_t size) +{ + sptr object = GetRemoteObject(); + if (object == nullptr || data == nullptr || size < sizeof(int32_t) * SIZE_NUM_THREE + + INPUT_NAME_SIZE_MAX + sizeof(uint32_t)) { + return false; + } + uint32_t offset = 0; + int32_t channelId = *reinterpret_cast(data); + offset += sizeof(int32_t); + int32_t channelType = *reinterpret_cast(data + offset); + offset += sizeof(int32_t); + uint32_t len = INPUT_NAME_SIZE_MAX; + char sessionName[INPUT_NAME_SIZE_MAX] = ""; + if (memcpy_s(sessionName, INPUT_NAME_SIZE_MAX, data + offset, INPUT_NAME_SIZE_MAX - 1) != EOK) { + return false; + } + sessionName[INPUT_NAME_SIZE_MAX - 1] = '\0'; + offset += INPUT_NAME_SIZE_MAX; + char msg[INPUT_NAME_SIZE_MAX] = ""; + if (memcpy_s(msg, INPUT_NAME_SIZE_MAX, data + offset, INPUT_NAME_SIZE_MAX - 1) != EOK) { + return false; + } + msg[INPUT_NAME_SIZE_MAX - 1] = '\0'; + offset += INPUT_NAME_SIZE_MAX; + int32_t msgType = *reinterpret_cast(data + offset); + MessageParcel datas; + datas.WriteInt32(channelId); + datas.WriteInt32(channelType); + datas.WriteUint32(len); + datas.WriteRawData(msg, INPUT_NAME_SIZE_MAX); + datas.WriteInt32(msgType); + MessageParcel reply; + sptr SoftBusServer = new OHOS::SoftBusServer(SOFTBUS_SERVER_SA_ID, true); + if (SoftBusServer == nullptr) { + return false; + } + SoftBusServer->SendMessageInner(datas, reply); + return true; +} + +bool QosReportFuzzTest(const uint8_t *data, size_t size) +{ + sptr object = GetRemoteObject(); + if (object == nullptr || data == nullptr || size < sizeof(int32_t) * SIZE_NUM_THREE + + sizeof(uint32_t)) { + return false; + } + uint32_t offset = 0; + int32_t channelId = *reinterpret_cast(data); + offset += sizeof(int32_t); + int32_t channelType = *reinterpret_cast(data + offset); + offset += sizeof(int32_t); + int32_t appType = *reinterpret_cast(data + offset); + offset += sizeof(int32_t); + int32_t quality = *reinterpret_cast(data + offset); + MessageParcel datas; + datas.WriteInt32(channelId); + datas.WriteInt32(channelType); + datas.WriteInt32(appType); + datas.WriteInt32(quality); + MessageParcel reply; + sptr SoftBusServer = new OHOS::SoftBusServer(SOFTBUS_SERVER_SA_ID, true); + if (SoftBusServer == nullptr) { + return false; + } + SoftBusServer->QosReportInner(datas, reply); + return true; +} + +bool GrantPermissionFuzzTest(const uint8_t *data, size_t size) +{ + sptr object = GetRemoteObject(); + if (object == nullptr || data == nullptr || size < sizeof(int32_t) + sizeof(int32_t) + + INPUT_NAME_SIZE_MAX + sizeof(int32_t)) { + return false; + } + uint32_t offset = 0; + int32_t uid = *reinterpret_cast(data); + offset += sizeof(int32_t); + int32_t pid = *reinterpret_cast(data + offset); + offset += sizeof(int32_t); + char sessionName[INPUT_NAME_SIZE_MAX] = ""; + if (memcpy_s(sessionName, INPUT_NAME_SIZE_MAX, data, INPUT_NAME_SIZE_MAX - 1) != EOK) { + return false; + } + sessionName[INPUT_NAME_SIZE_MAX - 1] = '\0'; + offset += INPUT_NAME_SIZE_MAX; + char msg[INPUT_NAME_SIZE_MAX] = ""; + if (memcpy_s(msg, INPUT_NAME_SIZE_MAX, reinterpret_cast(data + offset), + INPUT_NAME_SIZE_MAX - 1) != EOK) { + return false; + } + msg[INPUT_NAME_SIZE_MAX - 1] = '\0'; + offset += INPUT_NAME_SIZE_MAX; + int32_t msgType = *reinterpret_cast(data + offset); + MessageParcel datas; datas.WriteInt32(uid); datas.WriteInt32(pid); - datas.WriteBuffer(data, size); - datas.RewindRead(0); + datas.WriteCString(sessionName); + datas.WriteInt32(msgType); MessageParcel reply; - MessageOption option; - SetAceessTokenPermission("SoftBusServerStubTest"); - if (object->SendRequest(SERVER_GRANT_PERMISSION, datas, reply, option) != ERR_NONE) { + sptr SoftBusServer = new OHOS::SoftBusServer(SOFTBUS_SERVER_SA_ID, true); + if (SoftBusServer == nullptr) { return false; } + SoftBusServer->SendMessageInner(datas, reply); return true; } bool RemovePermissionFuzzTest(const uint8_t *data, size_t size) { - return SendRequestByCommand(data, size, SERVER_REMOVE_PERMISSION); + sptr object = GetRemoteObject(); + if (object == nullptr || data == nullptr || size < INPUT_NAME_SIZE_MAX) { + return false; + } + char sessionName[INPUT_NAME_SIZE_MAX] = ""; + if (memcpy_s(sessionName, INPUT_NAME_SIZE_MAX, reinterpret_cast(data), + INPUT_NAME_SIZE_MAX - 1) != EOK) { + return false; + } + sessionName[INPUT_NAME_SIZE_MAX - 1] = '\0'; + MessageParcel datas; + datas.WriteCString(sessionName); + MessageParcel reply; + sptr SoftBusServer = new OHOS::SoftBusServer(SOFTBUS_SERVER_SA_ID, true); + if (SoftBusServer == nullptr) { + return false; + } + SoftBusServer->RemovePermissionInner(datas, reply); + return true; } bool StreamStatsFuzzTest(const uint8_t *data, size_t size) @@ -284,12 +563,12 @@ bool StreamStatsFuzzTest(const uint8_t *data, size_t size) return true; } -bool GetSoftbusSpecObjectFuzzTest(const uint8_t* data, size_t size) +bool GetSoftbusSpecObjectFuzzTest(const uint8_t *data, size_t size) { return SendRequestByCommand(data, size, SERVER_GET_SOFTBUS_SPEC_OBJECT); } -bool StartDiscoveryFuzzTest(const uint8_t* data, size_t size) +bool StartDiscoveryFuzzTest(const uint8_t *data, size_t size) { sptr object = GetRemoteObject(); if (object == nullptr) { @@ -301,7 +580,6 @@ bool StartDiscoveryFuzzTest(const uint8_t* data, size_t size) int32_t freq = SOFTBUS_FUZZ_TEST_START_DISCOVERY_FREQ; bool boolNum = true; MessageParcel datas; - datas.WriteInterfaceToken(SOFTBUS_SERVER_STUB_INTERFACE_TOKEN); datas.WriteBuffer(data, size); datas.WriteInt32(subscribeId); datas.WriteInt32(mode); @@ -311,17 +589,39 @@ bool StartDiscoveryFuzzTest(const uint8_t* data, size_t size) datas.WriteInt32(freq); datas.RewindRead(0); MessageParcel reply; - MessageOption option; - SetAceessTokenPermission("SoftBusServerStubTest"); - if (object->SendRequest(SERVER_START_DISCOVERY, datas, reply, option) != ERR_NONE) { + sptr SoftBusServer = new OHOS::SoftBusServer(SOFTBUS_SERVER_SA_ID, true); + if (SoftBusServer == nullptr) { return false; } + SoftBusServer->StartDiscoveryInner(datas, reply); return true; } -bool StopDiscoveryFuzzTest(const uint8_t* data, size_t size) +bool StopDiscoveryFuzzTest(const uint8_t *data, size_t size) { - return SendRequestByCommand(data, size, SERVER_STOP_DISCOVERY); + sptr object = GetRemoteObject(); + if (object == nullptr) { + return false; + } + char pkgName[INPUT_NAME_SIZE_MAX] = ""; + uint32_t offset = 0; + if (memcpy_s(pkgName, INPUT_NAME_SIZE_MAX, reinterpret_cast(data), + INPUT_NAME_SIZE_MAX - 1) != EOK) { + return false; + } + pkgName[INPUT_NAME_SIZE_MAX - 1] = '\0'; + offset += INPUT_NAME_SIZE_MAX; + int32_t publishId = *reinterpret_cast(data + offset); + MessageParcel datas; + datas.WriteCString(pkgName); + datas.WriteInt32(publishId); + MessageParcel reply; + sptr SoftBusServer = new OHOS::SoftBusServer(SOFTBUS_SERVER_SA_ID, true); + if (SoftBusServer == nullptr) { + return false; + } + SoftBusServer->StopDiscoveryInner(datas, reply); + return true; } bool JoinLNNFuzzTest(const uint8_t *data, size_t size) @@ -342,8 +642,8 @@ bool JoinLNNFuzzTest(const uint8_t *data, size_t size) if (addr == nullptr) { return false; } - if (memcpy_s(addr, sizeof(ConnectionAddr), reinterpret_cast(data + offset), sizeof(ConnectionAddr)) != - EOK) { + if (memcpy_s(addr, sizeof(ConnectionAddr), reinterpret_cast(data + offset), + sizeof(ConnectionAddr)) != EOK) { SoftBusFree(addr); return false; } @@ -363,7 +663,7 @@ bool JoinLNNFuzzTest(const uint8_t *data, size_t size) return true; } -bool JoinMetaNodeFuzzTest(const uint8_t* data, size_t size) +bool JoinMetaNodeFuzzTest(const uint8_t *data, size_t size) { sptr object = GetRemoteObject(); if (object == nullptr) { @@ -418,7 +718,7 @@ bool LeaveLNNFuzzTest(const uint8_t *data, size_t size) return true; } -bool LeaveMetaNodeFuzzTest(const uint8_t* data, size_t size) +bool LeaveMetaNodeFuzzTest(const uint8_t *data, size_t size) { return SendRequestByCommand(data, size, SERVER_LEAVE_METANODE); } @@ -452,7 +752,7 @@ bool GetAllOnlineNodeInfoFuzzTest(const uint8_t *data, size_t size) return true; } -bool GetLocalDeviceInfoFuzzTest(const uint8_t* data, size_t size) +bool GetLocalDeviceInfoFuzzTest(const uint8_t *data, size_t size) { sptr object = GetRemoteObject(); if (object == nullptr || data == nullptr || size < INPUT_NAME_SIZE_MAX + sizeof(uint32_t)) { @@ -559,69 +859,393 @@ bool SetNodeDataChangeFlagFuzzTest(const uint8_t *data, size_t size) return true; } -bool StartTimeSyncFuzzTest(const uint8_t* data, size_t size) -{ - return SendRequestByCommand(data, size, SERVER_START_TIME_SYNC); -} - -bool StopTimeSyncFuzzTest(const uint8_t* data, size_t size) -{ - return SendRequestByCommand(data, size, SERVER_STOP_TIME_SYNC); -} - -bool PublishLNNFuzzTest(const uint8_t* data, size_t size) -{ - return SendRequestByCommand(data, size, SERVER_PUBLISH_LNN); -} - -bool StopPublishLNNFuzzTest(const uint8_t* data, size_t size) -{ - return SendRequestByCommand(data, size, SERVER_STOP_PUBLISH_LNN); -} - -bool RefreshLNNFuzzTest(const uint8_t* data, size_t size) -{ - return SendRequestByCommand(data, size, SERVER_REFRESH_LNN); -} - -bool StopRefreshLNNFuzzTest(const uint8_t* data, size_t size) -{ - return SendRequestByCommand(data, size, SERVER_STOP_REFRESH_LNN); -} - -bool ActiveMetaNodeFuzzTest(const uint8_t* data, size_t size) -{ - return SendRequestByCommand(data, size, SERVER_ACTIVE_META_NODE); -} - -bool DeactiveMetaNodeFuzzTest(const uint8_t* data, size_t size) -{ - return SendRequestByCommand(data, size, SERVER_DEACTIVE_META_NODE); -} - -bool GetAllMetaNodeInfoFuzzTest(const uint8_t* data, size_t size) -{ - return SendRequestByCommand(data, size, SERVER_GET_ALL_META_NODE_INFO); -} - -bool ShiftLNNGearFuzzTest(const uint8_t* data, size_t size) +bool StartTimeSyncFuzzTest(const uint8_t *data, size_t size) { sptr object = GetRemoteObject(); - if (object == nullptr) { + if (object == nullptr || data == nullptr || size < INPUT_NAME_SIZE_MAX + NETWORKID_SIZE_MAX + + sizeof(int32_t) + sizeof(int32_t)) { return false; } - bool boolNum = true; + uint32_t offset = 0; + char clientName[INPUT_NAME_SIZE_MAX] = ""; + char networkId[NETWORKID_SIZE_MAX] = ""; + + if (memcpy_s(clientName, INPUT_NAME_SIZE_MAX, reinterpret_cast(data), INPUT_NAME_SIZE_MAX - 1) != + EOK) { + return false; + } + clientName[INPUT_NAME_SIZE_MAX - 1] = '\0'; + offset += INPUT_NAME_SIZE_MAX; + if (memcpy_s(networkId, NETWORKID_SIZE_MAX, reinterpret_cast(data + offset), + NETWORKID_SIZE_MAX - 1) != EOK) { + return false; + } + networkId[NETWORKID_SIZE_MAX - 1] = '\0'; + offset += NETWORKID_SIZE_MAX; + int32_t accuracy = *reinterpret_cast(data + offset); + offset += sizeof(int32_t); + int32_t period = *reinterpret_cast(data + offset); + MessageParcel datas; - datas.WriteInterfaceToken(SOFTBUS_SERVER_STUB_INTERFACE_TOKEN); - datas.WriteBuffer(data, size); - datas.WriteBool(boolNum); - datas.RewindRead(0); + datas.WriteCString(clientName); + datas.WriteCString(networkId); + datas.WriteInt32(accuracy); + datas.WriteInt32(period); MessageParcel reply; - MessageOption option; - SetAceessTokenPermission("SoftBusServerStubTest"); - if (object->SendRequest(SERVER_SHIFT_LNN_GEAR, datas, reply, option) != ERR_NONE) { + sptr SoftBusServer = new OHOS::SoftBusServer(SOFTBUS_SERVER_SA_ID, true); + if (SoftBusServer == nullptr) { return false; } + SoftBusServer->StartTimeSyncInner(datas, reply); + return true; +} + +bool StopTimeSyncFuzzTest(const uint8_t *data, size_t size) +{ + sptr object = GetRemoteObject(); + if (object == nullptr || data == nullptr || size < INPUT_NAME_SIZE_MAX + NETWORKID_SIZE_MAX + + sizeof(int32_t) + sizeof(int32_t)) { + return false; + } + uint32_t offset = 0; + char clientName[INPUT_NAME_SIZE_MAX] = ""; + char networkId[NETWORKID_SIZE_MAX] = ""; + + if (memcpy_s(clientName, INPUT_NAME_SIZE_MAX, reinterpret_cast(data), INPUT_NAME_SIZE_MAX - 1) != + EOK) { + return false; + } + clientName[INPUT_NAME_SIZE_MAX - 1] = '\0'; + offset += INPUT_NAME_SIZE_MAX; + if (memcpy_s(networkId, NETWORKID_SIZE_MAX, reinterpret_cast(data + offset), + NETWORKID_SIZE_MAX - 1) != EOK) { + return false; + } + networkId[NETWORKID_SIZE_MAX - 1] = '\0'; + + MessageParcel datas; + datas.WriteCString(clientName); + datas.WriteCString(networkId); + MessageParcel reply; + sptr SoftBusServer = new OHOS::SoftBusServer(SOFTBUS_SERVER_SA_ID, true); + if (SoftBusServer == nullptr) { + return false; + } + SoftBusServer->StartTimeSyncInner(datas, reply); + return true; +} + +static void DiscInfoProc(const uint8_t *data, MessageParcel &datas) +{ + uint32_t offset = 0; + char clientName[INPUT_NAME_SIZE_MAX] = ""; + if (memcpy_s(clientName, INPUT_NAME_SIZE_MAX, reinterpret_cast(data), INPUT_NAME_SIZE_MAX - 1) != + EOK) { + return; + } + clientName[INPUT_NAME_SIZE_MAX - 1] = '\0'; + offset += INPUT_NAME_SIZE_MAX; + char capability[INPUT_NAME_SIZE_MAX] = ""; + if (memcpy_s(capability, INPUT_NAME_SIZE_MAX, reinterpret_cast(data + offset), + INPUT_NAME_SIZE_MAX - 1) != EOK) { + return; + } + capability[INPUT_NAME_SIZE_MAX - 1] = '\0'; + offset += INPUT_NAME_SIZE_MAX; + int32_t publishId = *reinterpret_cast(data + offset); + offset += sizeof(int32_t); + int32_t mode = *reinterpret_cast(data + offset); + offset += sizeof(int32_t); + int32_t medium = *reinterpret_cast(data + offset); + offset += sizeof(int32_t); + int32_t freq = *reinterpret_cast(data + offset); + offset += sizeof(int32_t); + int32_t dataLen = *reinterpret_cast(data + offset); + offset += sizeof(int32_t); + char capabilityData[INPUT_NAME_SIZE_MAX] = ""; + if (memcpy_s(capabilityData, INPUT_NAME_SIZE_MAX, reinterpret_cast(data + offset), + INPUT_NAME_SIZE_MAX - 1) != EOK) { + return; + } + capabilityData[INPUT_NAME_SIZE_MAX - 1] = '\0'; + offset += INPUT_NAME_SIZE_MAX; + bool ranging = *reinterpret_cast(data + offset); + + datas.WriteCString(clientName); + datas.WriteInt32(publishId); + datas.WriteInt32(mode); + datas.WriteInt32(medium); + datas.WriteInt32(freq); + datas.WriteCString(capability); + datas.WriteInt32(dataLen); + datas.WriteCString(capabilityData); + datas.WriteBool(ranging); +} + +bool PublishLNNFuzzTest(const uint8_t *data, size_t size) +{ + sptr object = GetRemoteObject(); + if (object == nullptr || data == nullptr || size < (INPUT_NAME_SIZE_MAX * SIZE_NUM_THREE) + + (sizeof(int32_t) * SIZE_NUM_FIVE)) { + return false; + } + MessageParcel datas; + DiscInfoProc(data, datas); + MessageParcel reply; + sptr SoftBusServer = new OHOS::SoftBusServer(SOFTBUS_SERVER_SA_ID, true); + if (SoftBusServer == nullptr) { + return false; + } + SoftBusServer->PublishLNNInner(datas, reply); + return true; +} + +bool StopPublishLNNFuzzTest(const uint8_t *data, size_t size) +{ + sptr object = GetRemoteObject(); + if (object == nullptr || data == nullptr || size < (INPUT_NAME_SIZE_MAX * SIZE_NUM_THREE) + + (sizeof(int32_t) * SIZE_NUM_FIVE)) { + return false; + } + uint32_t offset = 0; + char clientName[INPUT_NAME_SIZE_MAX] = ""; + if (memcpy_s(clientName, INPUT_NAME_SIZE_MAX, reinterpret_cast(data), + INPUT_NAME_SIZE_MAX - 1) != EOK) { + return false; + } + clientName[INPUT_NAME_SIZE_MAX - 1] = '\0'; + offset += INPUT_NAME_SIZE_MAX; + int32_t publishId = *reinterpret_cast(data + offset); + MessageParcel datas; + datas.WriteCString(clientName); + datas.WriteInt32(publishId); + MessageParcel reply; + sptr SoftBusServer = new OHOS::SoftBusServer(SOFTBUS_SERVER_SA_ID, true); + if (SoftBusServer == nullptr) { + return false; + } + SoftBusServer->StopPublishLNNInner(datas, reply); + return true; +} + +static void RefreshInfoProc(const uint8_t *data, MessageParcel &datas) +{ + uint32_t offset = 0; + char clientName[INPUT_NAME_SIZE_MAX] = ""; + if (memcpy_s(clientName, INPUT_NAME_SIZE_MAX, reinterpret_cast(data), INPUT_NAME_SIZE_MAX - 1) != + EOK) { + return; + } + clientName[INPUT_NAME_SIZE_MAX - 1] = '\0'; + offset += INPUT_NAME_SIZE_MAX; + char capability[INPUT_NAME_SIZE_MAX] = ""; + if (memcpy_s(capability, INPUT_NAME_SIZE_MAX, reinterpret_cast(data + offset), + INPUT_NAME_SIZE_MAX - 1) != EOK) { + return; + } + capability[INPUT_NAME_SIZE_MAX - 1] = '\0'; + offset += INPUT_NAME_SIZE_MAX; + int32_t publishId = *reinterpret_cast(data + offset); + offset += sizeof(int32_t); + int32_t mode = *reinterpret_cast(data + offset); + offset += sizeof(int32_t); + int32_t medium = *reinterpret_cast(data + offset); + offset += sizeof(int32_t); + int32_t freq = *reinterpret_cast(data + offset); + offset += sizeof(int32_t); + int32_t dataLen = *reinterpret_cast(data + offset); + offset += sizeof(int32_t); + bool isSameAccount = *reinterpret_cast(data + offset); + offset += sizeof(bool); + bool isWakeRemote = *reinterpret_cast(data + offset); + offset += sizeof(bool); + char capabilityData[INPUT_NAME_SIZE_MAX] = ""; + if (memcpy_s(capabilityData, INPUT_NAME_SIZE_MAX, reinterpret_cast(data + offset), + INPUT_NAME_SIZE_MAX - 1) != EOK) { + return; + } + capabilityData[INPUT_NAME_SIZE_MAX - 1] = '\0'; + offset += INPUT_NAME_SIZE_MAX; + + datas.WriteCString(clientName); + datas.WriteInt32(publishId); + datas.WriteInt32(mode); + datas.WriteInt32(medium); + datas.WriteInt32(freq); + datas.WriteBool(isSameAccount); + datas.WriteBool(isWakeRemote); + datas.WriteCString(capability); + datas.WriteInt32(dataLen); + datas.WriteCString(capabilityData); +} + +bool RefreshLNNFuzzTest(const uint8_t *data, size_t size) +{ + sptr object = GetRemoteObject(); + if (object == nullptr || data == nullptr || size < (INPUT_NAME_SIZE_MAX * SIZE_NUM_THREE) + + (sizeof(int32_t) * SIZE_NUM_FIVE) + sizeof(bool) + sizeof(bool)) { + return false; + } + MessageParcel datas; + RefreshInfoProc(data, datas); + MessageParcel reply; + sptr SoftBusServer = new OHOS::SoftBusServer(SOFTBUS_SERVER_SA_ID, true); + if (SoftBusServer == nullptr) { + return false; + } + SoftBusServer->RefreshLNNInner(datas, reply); + return true; +} + +bool StopRefreshLNNFuzzTest(const uint8_t *data, size_t size) +{ + sptr object = GetRemoteObject(); + if (object == nullptr || data == nullptr || size < INPUT_NAME_SIZE_MAX + sizeof(int32_t)) { + return false; + } + uint32_t offset = 0; + char clientName[INPUT_NAME_SIZE_MAX] = ""; + if (memcpy_s(clientName, INPUT_NAME_SIZE_MAX, reinterpret_cast(data), + INPUT_NAME_SIZE_MAX - 1) != EOK) { + return false; + } + clientName[INPUT_NAME_SIZE_MAX - 1] = '\0'; + offset += INPUT_NAME_SIZE_MAX; + int32_t refreshId = *reinterpret_cast(data + offset); + MessageParcel datas; + datas.WriteCString(clientName); + datas.WriteInt32(refreshId); + MessageParcel reply; + sptr SoftBusServer = new OHOS::SoftBusServer(SOFTBUS_SERVER_SA_ID, true); + if (SoftBusServer == nullptr) { + return false; + } + SoftBusServer->StopRefreshLNNInner(datas, reply); + return true; +} + +bool ActiveMetaNodeFuzzTest(const uint8_t *data, size_t size) +{ + sptr object = GetRemoteObject(); + if (object == nullptr || data == nullptr || size < sizeof(MetaNodeConfigInfo)) { + return false; + } + MetaNodeConfigInfo info; + if (memset_s(&info, sizeof(MetaNodeConfigInfo), 0, sizeof(MetaNodeConfigInfo)) != EOK) { + return false; + } + if (memcpy_s(&info, sizeof(MetaNodeConfigInfo), reinterpret_cast(data), + sizeof(MetaNodeConfigInfo)) != EOK) { + return false; + } + MessageParcel datas; + datas.WriteRawData(&info, sizeof(MetaNodeConfigInfo)); + MessageParcel reply; + sptr SoftBusServer = new OHOS::SoftBusServer(SOFTBUS_SERVER_SA_ID, true); + if (SoftBusServer == nullptr) { + return false; + } + SoftBusServer->ActiveMetaNodeInner(datas, reply); + return true; +} + +bool DeactiveMetaNodeFuzzTest(const uint8_t *data, size_t size) +{ + sptr object = GetRemoteObject(); + if (object == nullptr || data == nullptr || size < INPUT_NAME_SIZE_MAX) { + return false; + } + char metaNodeId[INPUT_NAME_SIZE_MAX] = ""; + if (memcpy_s(metaNodeId, INPUT_NAME_SIZE_MAX, reinterpret_cast(data), + INPUT_NAME_SIZE_MAX - 1) != EOK) { + return false; + } + metaNodeId[INPUT_NAME_SIZE_MAX - 1] = '\0'; + MessageParcel datas; + datas.WriteCString(metaNodeId); + MessageParcel reply; + sptr SoftBusServer = new OHOS::SoftBusServer(SOFTBUS_SERVER_SA_ID, true); + if (SoftBusServer == nullptr) { + return false; + } + SoftBusServer->DeactiveMetaNodeInner(datas, reply); + return true; +} + +bool GetAllMetaNodeInfoFuzzTest(const uint8_t *data, size_t size) +{ + sptr object = GetRemoteObject(); + if (object == nullptr || data == nullptr || size < sizeof(int32_t)) { + return false; + } + int32_t infoNum = *reinterpret_cast(data); + MessageParcel datas; + datas.WriteInt32(infoNum); + MessageParcel reply; + sptr SoftBusServer = new OHOS::SoftBusServer(SOFTBUS_SERVER_SA_ID, true); + if (SoftBusServer == nullptr) { + return false; + } + SoftBusServer->GetAllMetaNodeInfoInner(datas, reply); + return true; +} + +static void ShiftLNNGearInfoProc(const uint8_t *data, MessageParcel &datas) +{ + uint32_t offset = 0; + char pkgName[INPUT_NAME_SIZE_MAX] = ""; + if (memcpy_s(pkgName, INPUT_NAME_SIZE_MAX, reinterpret_cast(data), + INPUT_NAME_SIZE_MAX - 1) != EOK) { + return; + } + pkgName[INPUT_NAME_SIZE_MAX - 1] = '\0'; + offset += INPUT_NAME_SIZE_MAX; + datas.WriteCString(pkgName); + char callerId[INPUT_NAME_SIZE_MAX] = ""; + if (memcpy_s(callerId, INPUT_NAME_SIZE_MAX, reinterpret_cast(data + offset), + INPUT_NAME_SIZE_MAX - 1) != EOK) { + return; + } + callerId[INPUT_NAME_SIZE_MAX - 1] = '\0'; + offset += INPUT_NAME_SIZE_MAX; + datas.WriteCString(callerId); + bool hasNetworkId = *reinterpret_cast(data + offset); + datas.WriteBool(hasNetworkId); + offset += sizeof(bool); + if (!hasNetworkId) { + char networkId[INPUT_NAME_SIZE_MAX] = ""; + if (memcpy_s(networkId, INPUT_NAME_SIZE_MAX, reinterpret_cast(data + offset), + INPUT_NAME_SIZE_MAX - 1) != EOK) { + return; + } + networkId[INPUT_NAME_SIZE_MAX - 1] = '\0'; + offset += INPUT_NAME_SIZE_MAX; + datas.WriteCString(networkId); + } + GearMode mode; + memset_s(&mode, sizeof(GearMode), 0, sizeof(GearMode)); + if (memcpy_s(&mode, sizeof(GearMode), reinterpret_cast(data + offset), + sizeof(GearMode)) != EOK) { + return; + } + datas.WriteRawData(&mode, sizeof(GearMode)); +} + +bool ShiftLNNGearFuzzTest(const uint8_t *data, size_t size) +{ + sptr object = GetRemoteObject(); + if (object == nullptr || data == nullptr || size < sizeof(bool) + INPUT_NAME_SIZE_MAX * SIZE_NUM_THREE + + sizeof(GearMode)) { + return false; + } + MessageParcel datas; + ShiftLNNGearInfoProc(data, datas); + MessageParcel reply; + sptr SoftBusServer = new OHOS::SoftBusServer(SOFTBUS_SERVER_SA_ID, true); + if (SoftBusServer == nullptr) { + return false; + } + SoftBusServer->ShiftLNNGearInner(datas, reply); return true; } @@ -650,18 +1274,46 @@ bool RippleStatsFuzzTest(const uint8_t *data, size_t size) return true; } -bool SoftbusRegisterServiceFuzzTest(const uint8_t* data, size_t size) +bool SoftbusRegisterServiceFuzzTest(const uint8_t *data, size_t size) { - return SendRequestByCommand(data, size, MANAGE_REGISTER_SERVICE); + sptr object = GetRemoteObject(); + if (object == nullptr || data == nullptr || size < sizeof(int32_t) + sizeof(int32_t) + sizeof(IRemoteObject)) { + return false; + } + uint32_t offset = 0; + sptr obj; + memset_s(obj, sizeof(IRemoteObject), 0, sizeof(IRemoteObject)); + if (memcpy_s(obj, sizeof(IRemoteObject), reinterpret_cast(data), + sizeof(IRemoteObject)) != EOK) { + return false; + } + offset += sizeof(IRemoteObject); + char pkgName[INPUT_NAME_SIZE_MAX] = ""; + if (memcpy_s(pkgName, INPUT_NAME_SIZE_MAX, reinterpret_cast(data + offset), + INPUT_NAME_SIZE_MAX - 1) != EOK) { + return false; + } + pkgName[INPUT_NAME_SIZE_MAX - 1] = '\0'; + offset += INPUT_NAME_SIZE_MAX; + MessageParcel datas; + datas.WriteRemoteObject(obj); + datas.WriteCString(pkgName); + MessageParcel reply; + sptr SoftBusServer = new OHOS::SoftBusServer(SOFTBUS_SERVER_SA_ID, true); + if (SoftBusServer == nullptr) { + return false; + } + SoftBusServer->SoftbusRegisterServiceInner(datas, reply); + return true; } bool CheckOpenSessionPermissionFuzzTest(const uint8_t *data, size_t size) { #define SESSION_NAME_SIZE_MAX 256 -#define DEVICE_ID_SIZE_MAX 50 -#define GROUP_ID_SIZE_MAX 50 +#define DEVICE_ID_SIZE_TEST_MAX 50 +#define GROUP_ID_SIZE_TEST_MAX 50 sptr object = GetRemoteObject(); - if (object == nullptr || data == nullptr || size < DEVICE_ID_SIZE_MAX + GROUP_ID_SIZE_MAX) { + if (object == nullptr || data == nullptr || size < DEVICE_ID_SIZE_TEST_MAX + GROUP_ID_SIZE_TEST_MAX) { return false; } SetAceessTokenPermission("SoftBusServerStubTest"); @@ -699,7 +1351,7 @@ bool CheckOpenSessionPermissionFuzzTest(const uint8_t *data, size_t size) return true; } -bool EvaLuateQosInnerFuzzTest(const uint8_t* data, size_t size) +bool EvaLuateQosInnerFuzzTest(const uint8_t *data, size_t size) { sptr object = GetRemoteObject(); if (object == nullptr) { @@ -724,7 +1376,7 @@ bool EvaLuateQosInnerFuzzTest(const uint8_t* data, size_t size) return true; } -bool EvaLuateQosInnerNetworkIdFuzzTest(const uint8_t* data, size_t size) +bool EvaLuateQosInnerNetworkIdFuzzTest(const uint8_t *data, size_t size) { sptr object = GetRemoteObject(); if (object == nullptr) { @@ -749,7 +1401,7 @@ bool EvaLuateQosInnerNetworkIdFuzzTest(const uint8_t* data, size_t size) return true; } -bool EvaLuateQosInnerDataTypeFuzzTest(const uint8_t* data, size_t size) +bool EvaLuateQosInnerDataTypeFuzzTest(const uint8_t *data, size_t size) { sptr object = GetRemoteObject(); if (object == nullptr) { @@ -773,7 +1425,7 @@ bool EvaLuateQosInnerDataTypeFuzzTest(const uint8_t* data, size_t size) return true; } -bool EvaLuateQosInnerQosCountFuzzTest(const uint8_t* data, size_t size) +bool EvaLuateQosInnerQosCountFuzzTest(const uint8_t *data, size_t size) { sptr object = GetRemoteObject(); if (object == nullptr) { @@ -796,7 +1448,7 @@ bool EvaLuateQosInnerQosCountFuzzTest(const uint8_t* data, size_t size) return true; } -bool RunFuzzTestCase(const uint8_t* data, size_t size) +bool RunFuzzTestCase(const uint8_t *data, size_t size) { OHOS::EvaLuateQosInnerDataTypeFuzzTest(data, size); OHOS::EvaLuateQosInnerQosCountFuzzTest(data, size); diff --git a/tests/core/transmission/fuzztest/BUILD.gn b/tests/core/transmission/fuzztest/BUILD.gn index a8c2b94ae..5dba594df 100644 --- a/tests/core/transmission/fuzztest/BUILD.gn +++ b/tests/core/transmission/fuzztest/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2023 Huawei Device Co., Ltd. +# Copyright (c) 2023-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 @@ -15,6 +15,7 @@ group("fuzztest") { testonly = true deps = [ "softbusproxychannellistener_fuzzer:fuzztest", + "softbusproxychannelmanager_fuzzer:fuzztest", "softbusproxychannelnetwork_fuzzer:fuzztest", "transproxyonmessagereceived_fuzzer:fuzztest", ] diff --git a/tests/core/transmission/fuzztest/softbusproxychannelmanager_fuzzer/BUILD.gn b/tests/core/transmission/fuzztest/softbusproxychannelmanager_fuzzer/BUILD.gn new file mode 100644 index 000000000..a5135b0c5 --- /dev/null +++ b/tests/core/transmission/fuzztest/softbusproxychannelmanager_fuzzer/BUILD.gn @@ -0,0 +1,99 @@ +# Copyright (c) 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 +# +# 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/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("../../../../../dsoftbus.gni") + +##############################fuzztest########################################## + +dsoftbus_root_path = "../../../../.." +softbus_adapter_common = "${dsoftbus_root_path}/adapter/common" + +ohos_fuzztest("SoftbusProxyChannelManagerFuzzTest") { + module_out_path = dsoftbus_fuzz_out_path + + fuzz_config_file = "$dsoftbus_root_path/tests/core/transmission/fuzztest/softbusproxychannelmanager_fuzzer" + + include_dirs = [ + "$softbus_adapter_common/include", + + "$dsoftbus_root_path/core/adapter/bus_center/include", + "$dsoftbus_root_path/core/authentication/interface", + + "$dsoftbus_root_path/core/bus_center/interface", + "$dsoftbus_root_path/core/bus_center/lnn/net_ledger/common/include", + "$dsoftbus_root_path/core/bus_center/lnn/lane_hub/lane_manager/include", + + "$dsoftbus_root_path/core/common/include", + "$dsoftbus_root_path/core/common/message_handler/include", + + "$dsoftbus_root_path/core/connection/interface", + "$dsoftbus_root_path/core/connection/p2p/interface", + "$dsoftbus_root_path/core/connection/p2p/common/include", + + "$dsoftbus_root_path/core/discovery/interface", + "$dsoftbus_root_path/core/discovery/manager/include", + + "$dsoftbus_root_path/core/transmission/common/include", + "$dsoftbus_root_path/core/transmission/trans_channel/common/include", + "$dsoftbus_root_path/core/transmission/trans_channel/proxy/include", + + "$dsoftbus_root_path/core/transmission/session/include", + "$dsoftbus_root_path/core/transmission/trans_channel/manager/include", + "$dsoftbus_root_path/core/transmission/pending_packet/include", + + "$dsoftbus_root_path/interfaces/kits", + "$dsoftbus_root_path/interfaces/kits/bus_center", + "$dsoftbus_root_path/interfaces/kits/common", + "$dsoftbus_root_path/interfaces/kits/discovery", + "$dsoftbus_root_path/interfaces/kits/transport", + + "//third_party/cJSON", + "unittest/common/", + + "$dsoftbus_root_path/core/bus_center/lnn/net_buscenter/include", + "$dsoftbus_root_path/core/transmission/trans_channel/proxy/src", + "$dsoftbus_root_path/core/transmission/interface", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "softbusproxychannelmanager_fuzzer.cpp" ] + + deps = [ + "$dsoftbus_root_path/adapter:softbus_adapter", + "$dsoftbus_root_path/core/common:softbus_utils", + "$dsoftbus_root_path/core/frame:softbus_server", + ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + ] +} + +group("fuzztest") { + testonly = true + deps = [ + # deps file + ":SoftbusProxyChannelManagerFuzzTest", + ] +} diff --git a/tests/core/transmission/fuzztest/softbusproxychannelmanager_fuzzer/corpus/init b/tests/core/transmission/fuzztest/softbusproxychannelmanager_fuzzer/corpus/init new file mode 100644 index 000000000..00647f8d8 --- /dev/null +++ b/tests/core/transmission/fuzztest/softbusproxychannelmanager_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * Copyright (c) 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 + * + * 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. + */ + +FUZZ diff --git a/tests/core/transmission/fuzztest/softbusproxychannelmanager_fuzzer/project.xml b/tests/core/transmission/fuzztest/softbusproxychannelmanager_fuzzer/project.xml new file mode 100644 index 000000000..7133b2b92 --- /dev/null +++ b/tests/core/transmission/fuzztest/softbusproxychannelmanager_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/tests/core/transmission/fuzztest/softbusproxychannelmanager_fuzzer/softbusproxychannelmanager_fuzzer.cpp b/tests/core/transmission/fuzztest/softbusproxychannelmanager_fuzzer/softbusproxychannelmanager_fuzzer.cpp new file mode 100644 index 000000000..fb6bdc95e --- /dev/null +++ b/tests/core/transmission/fuzztest/softbusproxychannelmanager_fuzzer/softbusproxychannelmanager_fuzzer.cpp @@ -0,0 +1,390 @@ +/* + * Copyright (c) 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 + * + * 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 "softbusproxychannelmanager_fuzzer.h" +#include "softbus_proxychannel_manager.h" + +namespace OHOS { +class TestEnv { +public: + TestEnv() + { + isInited_ = false; + (void)TransProxyManagerInit(TransServerGetChannelCb()); + isInited_ = true; + } + + ~TestEnv() + { + isInited_ = false; + TransProxyManagerDeinit(); + } + + bool IsInited(void) + { + return isInited_; + } +private: + volatile bool isInited_; +}; + +static void FillAppInfoPart(const uint8_t *data, size_t size, AppInfo *appInfo) +{ + appInfo->fileProtocol = *(reinterpret_cast(data)); + appInfo->autoCloseTime = *(reinterpret_cast(data)); + appInfo->myHandleId = *(reinterpret_cast(data)); + appInfo->peerHandleId = *(reinterpret_cast(data)); + appInfo->transFlag = *(reinterpret_cast(data)); + appInfo->authSeq = *(reinterpret_cast(data)); + appInfo->linkType = *(reinterpret_cast(data)); + appInfo->connectType = *(reinterpret_cast(data)); + appInfo->channelType = *(reinterpret_cast(data)); + appInfo->errorCode = *(reinterpret_cast(data)); + appInfo->timeStart = *(reinterpret_cast(data)); + appInfo->connectedStart = *(reinterpret_cast(data)); + appInfo->fastTransData = (reinterpret_cast(data)); + appInfo->fastTransDataSize = *(reinterpret_cast(data)); + appInfo->callingTokenId = *(reinterpret_cast(data)); + appInfo->isClient = *(reinterpret_cast(data)); + appInfo->osType = *(reinterpret_cast(data)); +} + +static void FillAppInfo(const uint8_t *data, size_t size, AppInfo *appInfo) +{ + appInfo->routeType = static_cast(*(reinterpret_cast(data))); + appInfo->businessType = static_cast(*(reinterpret_cast(data))); + appInfo->streamType = static_cast(*(reinterpret_cast(data))); + appInfo->udpConnType = static_cast(*(reinterpret_cast(data))); + appInfo->udpChannelOptType = static_cast(*(reinterpret_cast(data))); + appInfo->fd = *(reinterpret_cast(data)); + appInfo->appType = static_cast(*(reinterpret_cast(data))); + appInfo->myData = *(reinterpret_cast(data)); + appInfo->peerData = *(reinterpret_cast(data)); + appInfo->protocol = *(reinterpret_cast(data)); + appInfo->encrypt = *(reinterpret_cast(data)); + appInfo->algorithm = *(reinterpret_cast(data)); + appInfo->crc = *(reinterpret_cast(data)); + FillAppInfoPart(data, size, appInfo); +} + +static void FillConnectOption(const uint8_t *data, size_t size, ConnectOption *connInfo) +{ + connInfo->type = static_cast(*(reinterpret_cast(data))); +} + +void TransProxyGetNewChanSeqTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + int32_t channelId = *(reinterpret_cast(data)); + TransProxyGetNewChanSeq(channelId); +} + +void TransProxyOpenProxyChannelTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(AppInfo))) { + return; + } + int32_t channelId; + AppInfo appInfo; + FillAppInfo(data, size, &appInfo); + ConnectOption connectOption; + FillConnectOption(data, size, &connectOption); + TransProxyOpenProxyChannel(&appInfo, &connectOption, &channelId); +} + +void TransProxyCloseProxyChannelTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + int32_t channelId = *(reinterpret_cast(data)); + TransProxyCloseProxyChannel(channelId); +} + +void TransProxyDelByConnIdTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(uint32_t))) { + return; + } + uint32_t connId = *(reinterpret_cast(data)); + TransProxyDelByConnId(connId); +} + +void TransProxyDelChanByReqIdTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + int32_t reqId = *(reinterpret_cast(data)); + int32_t errCode = *(reinterpret_cast(data)); + TransProxyDelChanByReqId(reqId, errCode); +} + +void TransProxyDelChanByChanIdTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + int32_t chanId = *(reinterpret_cast(data)); + TransProxyDelChanByChanId(chanId); +} + +void TransProxyGetChanByChanIdTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + int32_t chanId = *(reinterpret_cast(data)); + ProxyChannelInfo chan; + TransProxyGetChanByChanId(chanId, &chan); +} + +void TransProxyGetChanByReqIdTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + int32_t reqId = *(reinterpret_cast(data)); + ProxyChannelInfo chan; + TransProxyGetChanByReqId(reqId, &chan); +} + +void TransProxyOpenProxyChannelSuccessTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + int32_t channelId = *(reinterpret_cast(data)); + TransProxyOpenProxyChannelSuccess(channelId); +} + +void TransProxyOpenProxyChannelFailTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(AppInfo))) { + return; + } + int32_t channelId = *(reinterpret_cast(data)); + int32_t errCode = *(reinterpret_cast(data)); + AppInfo appInfo; + FillAppInfo(data, size, &appInfo); + TransProxyOpenProxyChannelFail(channelId, &appInfo, errCode); +} + +void TransProxyGetSessionKeyByChanIdTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + int32_t channelId = *(reinterpret_cast(data)); + char sessionKey[SESSION_KEY_LENGTH] = { 0 }; + uint32_t sessionKeySize = SESSION_KEY_LENGTH; + TransProxyGetSessionKeyByChanId(channelId, sessionKey, sessionKeySize); +} + +void TransProxyGetSendMsgChanInfoTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + int32_t channelId = *(reinterpret_cast(data)); + ProxyChannelInfo chan; + TransProxyGetSendMsgChanInfo(channelId, &chan); +} + +void TransProxyCreateChanInfoTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(AppInfo))) { + return; + } + int32_t channelId = *(reinterpret_cast(data)); + AppInfo appInfo; + FillAppInfo(data, size, &appInfo); + ProxyChannelInfo chan; + TransProxyCreateChanInfo(&chan, channelId, &appInfo); +} + +void TransProxyChanProcessByReqIdTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + int32_t reqId = *(reinterpret_cast(data)); + uint32_t connId = *(reinterpret_cast(data)); + TransProxyChanProcessByReqId(reqId, connId); +} + +void TransProxyGetAuthIdTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + int32_t channelId = *(reinterpret_cast(data)); + AuthHandle authHandle; + TransProxyGetAuthId(channelId, &authHandle); +} + +void TransProxyGetNameByChanIdTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + int32_t chanId = *(reinterpret_cast(data)); + uint16_t pkgLen = *(reinterpret_cast(data)); + uint16_t sessionLen = *(reinterpret_cast(data)); + char pkgName[MAX_PACKAGE_NAME_LEN]; + char sessionName[SESSION_NAME_SIZE_MAX]; + TransProxyGetNameByChanId(chanId, pkgName, sessionName, pkgLen, sessionLen); +} + +void TransRefreshProxyTimesNativeTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + int32_t channelId = *(reinterpret_cast(data)); + TransRefreshProxyTimesNative(channelId); +} + +void TransProxyDeathCallbackTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < MAX_PACKAGE_NAME_LEN)) { + return; + } + char *pkgName = const_cast(reinterpret_cast(data)); + int32_t pid = *(reinterpret_cast(data)); + TransProxyDeathCallback(pkgName, pid); +} + +void TransProxyGetAppInfoByChanIdTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + int32_t chanId = *(reinterpret_cast(data)); + AppInfo appInfo; + TransProxyGetAppInfoByChanId(chanId, &appInfo); +} + +void TransProxyGetConnIdByChanIdTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + int32_t channelId = *(reinterpret_cast(data)); + int32_t connId; + TransProxyGetConnIdByChanId(channelId, &connId); +} + +void TransProxyGetConnOptionByChanIdTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + int32_t channelId = *(reinterpret_cast(data)); + ConnectOption connOpt; + TransProxyGetConnOptionByChanId(channelId, &connOpt); +} + +void TransProxyGetAppInfoTypeTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int16_t))) { + return; + } + const char *identity = "test"; + int16_t myId = *(reinterpret_cast(data)); + AppType appType; + TransProxyGetAppInfoType(myId, identity, &appType); +} + +void TransProxySpecialUpdateChanInfoTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(ProxyChannelInfo))) { + return; + } + ProxyChannelInfo channelInfo; + channelInfo.channelId = *(reinterpret_cast(data)); + TransProxySpecialUpdateChanInfo(&channelInfo); +} + +void TransProxySetAuthHandleByChanIdTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(AuthHandle))) { + return; + } + int32_t channelId = *(reinterpret_cast(data)); + AuthHandle authHandle; + authHandle.authId = *(reinterpret_cast(data)); + authHandle.type = *(reinterpret_cast(data)); + TransProxySetAuthHandleByChanId(channelId, authHandle); +} + +void TransProxyNegoSessionKeySuccTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + int32_t channelId = *(reinterpret_cast(data)); + TransProxyNegoSessionKeySucc(channelId); +} + +void TransProxyNegoSessionKeyFailTest(const uint8_t *data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + int32_t channelId = *(reinterpret_cast(data)); + int32_t errCode = *(reinterpret_cast(data)); + TransProxyNegoSessionKeyFail(channelId, errCode); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + static OHOS::TestEnv env; + if (!env.IsInited()) { + return 0; + } + /* Run your code on data */ + OHOS::TransProxyGetNewChanSeqTest(data, size); + OHOS::TransProxyOpenProxyChannelTest(data, size); + OHOS::TransProxyCloseProxyChannelTest(data, size); + OHOS::TransProxyDelByConnIdTest(data, size); + OHOS::TransProxyDelChanByReqIdTest(data, size); + OHOS::TransProxyDelChanByChanIdTest(data, size); + OHOS::TransProxyGetChanByChanIdTest(data, size); + OHOS::TransProxyGetChanByReqIdTest(data, size); + OHOS::TransProxyOpenProxyChannelSuccessTest(data, size); + OHOS::TransProxyOpenProxyChannelFailTest(data, size); + OHOS::TransProxyGetSessionKeyByChanIdTest(data, size); + OHOS::TransProxyGetSendMsgChanInfoTest(data, size); + OHOS::TransProxyCreateChanInfoTest(data, size); + OHOS::TransProxyChanProcessByReqIdTest(data, size); + OHOS::TransProxyGetAuthIdTest(data, size); + OHOS::TransProxyGetNameByChanIdTest(data, size); + OHOS::TransRefreshProxyTimesNativeTest(data, size); + OHOS::TransProxyDeathCallbackTest(data, size); + OHOS::TransProxyGetAppInfoByChanIdTest(data, size); + OHOS::TransProxyGetConnIdByChanIdTest(data, size); + OHOS::TransProxyGetConnOptionByChanIdTest(data, size); + OHOS::TransProxyGetAppInfoTypeTest(data, size); + OHOS::TransProxySpecialUpdateChanInfoTest(data, size); + OHOS::TransProxySetAuthHandleByChanIdTest(data, size); + OHOS::TransProxyNegoSessionKeySuccTest(data, size); + OHOS::TransProxyNegoSessionKeyFailTest(data, size); + return 0; +} \ No newline at end of file diff --git a/tests/core/transmission/fuzztest/softbusproxychannelmanager_fuzzer/softbusproxychannelmanager_fuzzer.h b/tests/core/transmission/fuzztest/softbusproxychannelmanager_fuzzer/softbusproxychannelmanager_fuzzer.h new file mode 100644 index 000000000..fef2967df --- /dev/null +++ b/tests/core/transmission/fuzztest/softbusproxychannelmanager_fuzzer/softbusproxychannelmanager_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 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 + * + * 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 SOFTBUSPROXYCHANNELMANAGER_FUZZER_H +#define SOFTBUSPROXYCHANNELMANAGER_FUZZER_H + +#define FUZZ_PROJECT_NAME "softbusproxychannelmanager_fuzzer" + +#endif diff --git a/tests/core/transmission/fuzztest/transproxyonmessagereceived_fuzzer/BUILD.gn b/tests/core/transmission/fuzztest/transproxyonmessagereceived_fuzzer/BUILD.gn index 963d341df..6c352ae9f 100644 --- a/tests/core/transmission/fuzztest/transproxyonmessagereceived_fuzzer/BUILD.gn +++ b/tests/core/transmission/fuzztest/transproxyonmessagereceived_fuzzer/BUILD.gn @@ -21,7 +21,7 @@ import("../../../../../dsoftbus.gni") dsoftbus_root_path = "../../../../.." -ohos_fuzztest("TransProxyonMessagereceivedFuzzTest") { +ohos_fuzztest("TransProxyOnMessageReceivedFuzzTest") { module_out_path = dsoftbus_fuzz_out_path fuzz_config_file = "$dsoftbus_root_path/tests/core/transmission/fuzztest/transproxyonmessagereceived_fuzzer" @@ -64,7 +64,7 @@ group("fuzztest") { deps = [] deps += [ # deps file - ":TransProxyonMessagereceivedFuzzTest", + ":TransProxyOnMessageReceivedFuzzTest", ] } ############################################################################### diff --git a/tests/core/transmission/fuzztest/transproxyonmessagereceived_fuzzer/transproxyonmessagereceived_fuzzer.cpp b/tests/core/transmission/fuzztest/transproxyonmessagereceived_fuzzer/transproxyonmessagereceived_fuzzer.cpp index 6d47b16ae..d98963f17 100644 --- a/tests/core/transmission/fuzztest/transproxyonmessagereceived_fuzzer/transproxyonmessagereceived_fuzzer.cpp +++ b/tests/core/transmission/fuzztest/transproxyonmessagereceived_fuzzer/transproxyonmessagereceived_fuzzer.cpp @@ -15,40 +15,87 @@ #include "transproxyonmessagereceived_fuzzer.h" -#include "softbus_adapter_thread.h" #include #include #include -#include "softbus_proxychannel_message.h" + +#include "softbus_adapter_thread.h" #include "softbus_proxychannel_manager.h" +#include "softbus_proxychannel_message.h" namespace OHOS { +class TransProxyOnMessageReceivedTestEvent { +public: + TransProxyOnMessageReceivedTestEvent() + { + isInited_ = false; + (void)TransProxyManagerInit(TransServerGetChannelCb()); + isInited_ = true; + } + + ~TransProxyOnMessageReceivedTestEvent() + { + isInited_ = false; + TransProxyManagerDeinit(); + } + + bool IsInited(void) + { + return isInited_; + } +private: + volatile bool isInited_; +}; + +static void InitProxyMessageHead(const uint8_t *data, size_t size, ProxyMessageHead *proxyMessageHead) +{ + proxyMessageHead->type = *(reinterpret_cast(data)); + proxyMessageHead->cipher = *(reinterpret_cast(data)); + proxyMessageHead->myId = *(reinterpret_cast(data)); + proxyMessageHead->peerId = *(reinterpret_cast(data)); + proxyMessageHead->reserved = *(reinterpret_cast(data)); +} + +static void InitAuthHandle(const uint8_t *data, size_t size, AuthHandle *authHandle) +{ + authHandle->authId = *(reinterpret_cast(data)); + authHandle->type = *(reinterpret_cast(data)); +} + +static void InitProxyMessage(const uint8_t *data, size_t size, ProxyMessage *proxyMessage) +{ + InitProxyMessageHead(data, size, &proxyMessage->msgHead); + proxyMessage->dateLen = *(reinterpret_cast(data)); + proxyMessage->data = const_cast(reinterpret_cast(data)); + proxyMessage->connId = *(reinterpret_cast(data)); + InitAuthHandle(data, size, &proxyMessage->authHandle); + proxyMessage->keyIndex = *(reinterpret_cast(data)); +} void TransProxyOnMessageReceivedTest(const uint8_t *data, size_t size) { if ((data == nullptr) || (size < sizeof(ProxyMessage))) { return; } - ProxyMessage msg; - ProxyMessageHead mad; - msg.authHandle.authId = *(reinterpret_cast(data)); - msg.authHandle.type = *(reinterpret_cast(data)); - msg.connId = *(reinterpret_cast(data)); - msg.dateLen = *(reinterpret_cast(data)); - mad.type = *(reinterpret_cast(data)); - mad.cipher = *(reinterpret_cast(data)); - mad.myId = *(reinterpret_cast(data)); - mad.peerId = *(reinterpret_cast(data)); - mad.reserved = *(reinterpret_cast(data)); - msg.data = const_cast(reinterpret_cast(data)); - TransProxyOnMessageReceived(&msg); -} + + ProxyMessage proxyMessage; + InitProxyMessage(data, size, &proxyMessage); + + TransProxyOnMessageReceived(&proxyMessage); + TransProxyOnMessageReceived(nullptr); } +} // namespace OHOS /* Fuzzer entry point */ extern "C" int32_t LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { + static OHOS::TransProxyOnMessageReceivedTestEvent testEvent; + if (!testEvent.IsInited()) { + return 0; + } + /* Run your code on data */ OHOS::TransProxyOnMessageReceivedTest(data, size); + return 0; } diff --git a/tests/core/transmission/session/trans_session_manager_test.cpp b/tests/core/transmission/session/trans_session_manager_test.cpp index e67690c96..1da60756a 100644 --- a/tests/core/transmission/session/trans_session_manager_test.cpp +++ b/tests/core/transmission/session/trans_session_manager_test.cpp @@ -346,6 +346,7 @@ HWTEST_F(TransSessionManagerTest, TransSessionManagerTest13, TestSize.Level1) TransSessionMgrDeinit(); TransOnLinkDown(g_networkid, NULL, NULL, NULL, WIFI_P2P); } + /** * @tc.name: TransSessionManagerTest14 * @tc.desc: Transmission session manager onLink down with wrong parameters. diff --git a/tests/core/transmission/trans_channel/auth_channel/trans_auth_channel_test.cpp b/tests/core/transmission/trans_channel/auth_channel/trans_auth_channel_test.cpp index 38a314482..5a5750945 100644 --- a/tests/core/transmission/trans_channel/auth_channel/trans_auth_channel_test.cpp +++ b/tests/core/transmission/trans_channel/auth_channel/trans_auth_channel_test.cpp @@ -63,7 +63,7 @@ const char *g_authSessionName = "com.huawei.devicegroupmanage"; const char *g_deviceId = "ABCDEF00ABCDEF00ABCDEF00"; const char *g_groupid = "TEST_GROUP_ID"; const char *g_errMsg = "error"; -static IServerChannelCallBack *callback = NULL; +static IServerChannelCallBack *callback = nullptr; class TransAuthChannelTest : public testing::Test { public: TransAuthChannelTest() @@ -87,7 +87,6 @@ void TransAuthChannelTest::SetUpTestCase(void) BusCenterServerInit(); TransServerInit(); DiscEventManagerInit(); - TransChannelInit(); callback = TransServerGetChannelCb(); } @@ -98,12 +97,11 @@ void TransAuthChannelTest::TearDownTestCase(void) AuthDeinit(); TransServerDeinit(); DiscEventManagerDeinit(); - TransChannelDeinit(); } static int32_t TestGenerateAppInfo(AppInfo *appInfo) { - if (appInfo == NULL) { + if (appInfo == nullptr) { return SOFTBUS_INVALID_PARAM; } @@ -182,7 +180,7 @@ HWTEST_F(TransAuthChannelTest, OperateAuthChannelInfoTest001, TestSize.Level1) HWTEST_F(TransAuthChannelTest, GetAppInfoTest001, TestSize.Level1) { AppInfo *appInfo = (AppInfo*)SoftBusCalloc(sizeof(AppInfo)); - ASSERT_TRUE(appInfo != NULL); + ASSERT_TRUE(appInfo != nullptr); int32_t ret = TransSessionMgrInit(); ASSERT_EQ(ret, SOFTBUS_OK); ret = TransAuthInit(callback); @@ -328,7 +326,7 @@ HWTEST_F(TransAuthChannelTest, OnAuthChannelDataRecvTest001, TestSize.Level1) { int32_t authId = TRANS_TEST_AUTH_ID; AuthChannelData *data = (AuthChannelData*)SoftBusCalloc(sizeof(AuthChannelData)); - ASSERT_TRUE(data != NULL); + ASSERT_TRUE(data != nullptr); OnAuthChannelDataRecv(authId, NULL); @@ -431,11 +429,11 @@ HWTEST_F(TransAuthChannelTest, OperateAuthChannelInfoTest002, TestSize.Level1) DelAuthChannelInfoByChanId(TRANS_TEST_CHANNEL_ID); bool isClient = true; AuthChannelInfo *info = CreateAuthChannelInfo(g_sessionName, isClient); - EXPECT_TRUE(info != NULL); + EXPECT_TRUE(info != nullptr); ret = AddAuthChannelInfo(info); ASSERT_EQ(ret, SOFTBUS_OK); AuthChannelInfo *newInfo = (AuthChannelInfo*)SoftBusCalloc(sizeof(AuthChannelInfo)); - ASSERT_TRUE(newInfo != NULL); + ASSERT_TRUE(newInfo != nullptr); int32_t channelId = info->appInfo.myData.channelId; ret = GetAuthChannelInfoByChanId(channelId, newInfo); EXPECT_EQ(ret, SOFTBUS_OK); @@ -464,7 +462,7 @@ HWTEST_F(TransAuthChannelTest, OperateAuthChannelInfoTest003, TestSize.Level1) DelAuthChannelInfoByAuthId(TRANS_TEST_AUTH_ID); bool isClient = true; AuthChannelInfo *info = CreateAuthChannelInfo(g_sessionName, isClient); - ASSERT_TRUE(info != NULL); + ASSERT_TRUE(info != nullptr); info->authId = TRANS_TEST_AUTH_ID; ret = AddAuthChannelInfo(info); ASSERT_EQ(ret, SOFTBUS_OK); @@ -494,12 +492,12 @@ HWTEST_F(TransAuthChannelTest, OperateAuthChannelInfoTest004, TestSize.Level1) ASSERT_EQ(ret, SOFTBUS_OK); bool isClient = true; AuthChannelInfo *info = CreateAuthChannelInfo(g_sessionName, isClient); - ASSERT_TRUE(info != NULL); + ASSERT_TRUE(info != nullptr); info->authId = TRANS_TEST_AUTH_ID; ret = AddAuthChannelInfo(info); ASSERT_EQ(ret, SOFTBUS_OK); AuthChannelInfo *newInfo = (AuthChannelInfo*)SoftBusCalloc(sizeof(AuthChannelInfo)); - ASSERT_TRUE(newInfo != NULL); + ASSERT_TRUE(newInfo != nullptr); ret = GetChannelInfoByAuthId(TRANS_TEST_AUTH_ID, newInfo); EXPECT_EQ(ret, SOFTBUS_OK); ret = memcmp(info, newInfo, sizeof(AuthChannelInfo)); @@ -525,7 +523,7 @@ HWTEST_F(TransAuthChannelTest, NotifyOpenAuthChannelSuccessTest001, TestSize.Lev int32_t ret = TransAuthInit(callback); ASSERT_EQ(ret, SOFTBUS_OK); AppInfo* appInfo = (AppInfo*)SoftBusCalloc(sizeof(AppInfo)); - ASSERT_TRUE(appInfo != NULL); + ASSERT_TRUE(appInfo != nullptr); ret = TestGenerateAppInfo(appInfo); ASSERT_EQ(ret, SOFTBUS_OK); ret = NotifyOpenAuthChannelSuccess(appInfo, isServer); @@ -595,7 +593,7 @@ HWTEST_F(TransAuthChannelTest, NotifyOnDataReceivedTest001, TestSize.Level1) ASSERT_EQ(ret, SOFTBUS_OK); bool isClient = true; AuthChannelInfo *info = CreateAuthChannelInfo(g_sessionName, isClient); - ASSERT_TRUE(info != NULL); + ASSERT_TRUE(info != nullptr); info->authId = TRANS_TEST_AUTH_ID; ret = AddAuthChannelInfo(info); ASSERT_EQ(ret, SOFTBUS_OK); @@ -615,11 +613,11 @@ HWTEST_F(TransAuthChannelTest, NotifyOnDataReceivedTest001, TestSize.Level1) HWTEST_F(TransAuthChannelTest, CopyPeerAppInfoTest001, TestSize.Level1) { AppInfo *recvAppInfo = (AppInfo*)SoftBusCalloc(sizeof(AppInfo)); - ASSERT_TRUE(recvAppInfo != NULL); + ASSERT_TRUE(recvAppInfo != nullptr); int32_t ret = TestGenerateAppInfo(recvAppInfo); ASSERT_EQ(ret, SOFTBUS_OK); AppInfo *channelAppInfo = (AppInfo*)SoftBusCalloc(sizeof(AppInfo)); - ASSERT_TRUE(channelAppInfo != NULL); + ASSERT_TRUE(channelAppInfo != nullptr); ret = CopyPeerAppInfo(recvAppInfo, channelAppInfo); EXPECT_EQ(ret, SOFTBUS_OK); SoftBusFree(recvAppInfo); @@ -641,16 +639,23 @@ HWTEST_F(TransAuthChannelTest, OnRequsetUpdateAuthChannelTest001, TestSize.Level ret = TransAuthInit(callback); ASSERT_EQ(ret, SOFTBUS_OK); AppInfo *appInfo = (AppInfo*)SoftBusCalloc(sizeof(AppInfo)); - ASSERT_TRUE(appInfo != NULL); + ASSERT_TRUE(appInfo != nullptr); ret = TestGenerateAppInfo(appInfo); ASSERT_EQ(ret, SOFTBUS_OK); - ret = OnRequsetUpdateAuthChannel(TRANS_TEST_AUTH_ID, appInfo); - EXPECT_NE(ret, SOFTBUS_OK); + bool isClient = true; ret = TransCreateSessionServer(g_pkgName, g_sessionName, TRANS_TEST_UID, TRANS_TEST_PID); ASSERT_EQ(ret, SOFTBUS_OK); - bool isClient = true; + AuthChannelInfo *testinfo = CreateAuthChannelInfo(g_sessionName, isClient); + ASSERT_TRUE(testinfo != nullptr); + testinfo->authId = TRANS_TEST_AUTH_ID + TRANS_TEST_SESSION_ID; + ret = AddAuthChannelInfo(testinfo); + ASSERT_EQ(ret, SOFTBUS_OK); + ret = OnRequsetUpdateAuthChannel(TRANS_TEST_AUTH_ID, appInfo); + EXPECT_EQ(ret, SOFTBUS_OK); + ret = TransCreateSessionServer(g_pkgName, g_sessionName, TRANS_TEST_UID, TRANS_TEST_PID); + ASSERT_EQ(ret, SOFTBUS_SERVER_NAME_REPEATED); AuthChannelInfo *info = CreateAuthChannelInfo(g_sessionName, isClient); - ASSERT_TRUE(info != NULL); + ASSERT_TRUE(info != nullptr); info->authId = TRANS_TEST_AUTH_ID; ret = AddAuthChannelInfo(info); ASSERT_EQ(ret, SOFTBUS_OK); @@ -658,13 +663,13 @@ HWTEST_F(TransAuthChannelTest, OnRequsetUpdateAuthChannelTest001, TestSize.Level EXPECT_EQ(ret, SOFTBUS_OK); DelAuthChannelInfoByAuthId(TRANS_TEST_AUTH_ID); AuthChannelInfo *newinfo = CreateAuthChannelInfo(g_sessionName, isClient); - ASSERT_TRUE(newinfo != NULL); + ASSERT_TRUE(newinfo != nullptr); newinfo->authId = TRANS_TEST_AUTH_ID + 1; newinfo->appInfo.myData.channelId++; ret = AddAuthChannelInfo(newinfo); ASSERT_EQ(ret, SOFTBUS_OK); ret = OnRequsetUpdateAuthChannel(TRANS_TEST_AUTH_ID, appInfo); - EXPECT_EQ(ret, SOFTBUS_TRANS_INVALID_CHANNEL_ID); + EXPECT_EQ(ret, SOFTBUS_OK); DelAuthChannelInfoByAuthId(TRANS_TEST_AUTH_ID + 1); SoftBusFree(appInfo); TransSessionMgrDeinit(); @@ -686,13 +691,21 @@ HWTEST_F(TransAuthChannelTest, OnRequsetUpdateAuthChannelTest002, TestSize.Level ret = TransAuthInit(callback); ASSERT_EQ(ret, SOFTBUS_OK); AppInfo *appInfo = (AppInfo*)SoftBusCalloc(sizeof(AppInfo)); - ASSERT_TRUE(appInfo != NULL); + ASSERT_TRUE(appInfo != nullptr); ret = TestGenerateAppInfo(appInfo); ASSERT_EQ(ret, SOFTBUS_OK); - ret = OnRequsetUpdateAuthChannel(TRANS_TEST_AUTH_ID, appInfo); - EXPECT_NE(ret, SOFTBUS_OK); + bool isClient = true; ret = TransCreateSessionServer(g_pkgName, g_sessionName, TRANS_TEST_UID, TRANS_TEST_PID); ASSERT_EQ(ret, SOFTBUS_OK); + AuthChannelInfo *testinfo = CreateAuthChannelInfo(g_sessionName, isClient); + ASSERT_TRUE(testinfo != nullptr); + testinfo->authId = TRANS_TEST_AUTH_ID + 1; + ret = AddAuthChannelInfo(testinfo); + ASSERT_EQ(ret, SOFTBUS_OK); + ret = OnRequsetUpdateAuthChannel(TRANS_TEST_AUTH_ID, appInfo); + EXPECT_NE(ret, SOFTBUS_TRANS_INVALID_CHANNEL_ID); + ret = TransCreateSessionServer(g_pkgName, g_sessionName, TRANS_TEST_UID, TRANS_TEST_PID); + ASSERT_EQ(ret, SOFTBUS_SERVER_NAME_REPEATED); DelAuthChannelInfoByAuthId(TRANS_TEST_AUTH_ID); SoftBusFree(appInfo); TransSessionMgrDeinit(); @@ -709,13 +722,13 @@ HWTEST_F(TransAuthChannelTest, OnRecvAuthChannelRequestTest001, TestSize.Level1) { cJSON *msg = cJSON_CreateObject(); AppInfo *appInfo = (AppInfo*)SoftBusCalloc(sizeof(AppInfo)); - ASSERT_TRUE(appInfo != NULL); + ASSERT_TRUE(appInfo != nullptr); int32_t ret = TestGenerateAppInfo(appInfo); ASSERT_EQ(ret, SOFTBUS_OK); ret = TransAuthChannelMsgPack(msg, appInfo); ASSERT_EQ(ret, SOFTBUS_OK); char *data = cJSON_PrintUnformatted(msg); - ASSERT_TRUE(data != NULL); + ASSERT_TRUE(data != nullptr); OnRecvAuthChannelRequest(TRANS_TEST_AUTH_ID, NULL, strlen(data)); OnRecvAuthChannelRequest(TRANS_TEST_AUTH_ID, data, 0); SoftBusFree(appInfo); @@ -737,7 +750,7 @@ HWTEST_F(TransAuthChannelTest, OnRecvAuthChannelRequestTest002, TestSize.Level1) EXPECT_CALL(AuthChannelMock, LnnGetSettingDeviceName(_, _)).WillRepeatedly(Return(SOFTBUS_INVALID_PARAM)); cJSON *msg = cJSON_CreateObject(); AppInfo *appInfo = (AppInfo*)SoftBusCalloc(sizeof(AppInfo)); - ASSERT_TRUE(appInfo != NULL); + ASSERT_TRUE(appInfo != nullptr); int32_t ret = TestGenerateAppInfo(appInfo); ASSERT_EQ(ret, SOFTBUS_OK); char cJsonStr[ERR_MSG_MAX_LEN] = {0}; @@ -750,7 +763,7 @@ HWTEST_F(TransAuthChannelTest, OnRecvAuthChannelRequestTest002, TestSize.Level1) ret = TransAuthChannelMsgPack(msg, appInfo); ASSERT_EQ(ret, SOFTBUS_OK); char *data = cJSON_PrintUnformatted(msg); - ASSERT_TRUE(data != NULL); + ASSERT_TRUE(data != nullptr); OnRecvAuthChannelRequest(TRANS_TEST_AUTH_ID, data, strlen(data)); bool res = strcpy_s(appInfo->myData.sessionName, sizeof(appInfo->myData.sessionName), g_authSessionName); ASSERT_EQ(res, EOK); @@ -760,7 +773,7 @@ HWTEST_F(TransAuthChannelTest, OnRecvAuthChannelRequestTest002, TestSize.Level1) ret = TransAuthChannelMsgPack(msg, appInfo); ASSERT_EQ(ret, SOFTBUS_OK); data = cJSON_PrintUnformatted(msg); - ASSERT_TRUE(data != NULL); + ASSERT_TRUE(data != nullptr); OnRecvAuthChannelRequest(TRANS_TEST_AUTH_ID, data, strlen(data)); SoftBusFree(appInfo); cJSON_free(data); @@ -787,7 +800,7 @@ HWTEST_F(TransAuthChannelTest, OnRecvAuthChannelRequestTest003, TestSize.Level1) ASSERT_EQ(ret, SOFTBUS_OK); cJSON *msg = cJSON_CreateObject(); AppInfo *appInfo = (AppInfo*)SoftBusCalloc(sizeof(AppInfo)); - ASSERT_TRUE(appInfo != NULL); + ASSERT_TRUE(appInfo != nullptr); ret = TestGenerateAppInfo(appInfo); ASSERT_EQ(ret, SOFTBUS_OK); ret = strcpy_s(appInfo->myData.sessionName, sizeof(appInfo->myData.sessionName), g_authSessionName); @@ -795,11 +808,11 @@ HWTEST_F(TransAuthChannelTest, OnRecvAuthChannelRequestTest003, TestSize.Level1) ret = TransAuthChannelMsgPack(msg, appInfo); ASSERT_EQ(ret, SOFTBUS_OK); char *data = cJSON_PrintUnformatted(msg); - ASSERT_TRUE(data != NULL); + ASSERT_TRUE(data != nullptr); OnRecvAuthChannelRequest(TRANS_TEST_AUTH_ID, data, strlen(data)); bool isClient = true; AuthChannelInfo *info = CreateAuthChannelInfo(g_authSessionName, isClient); - ASSERT_TRUE(info != NULL); + ASSERT_TRUE(info != nullptr); info->authId = TRANS_TEST_AUTH_ID + 1; info->appInfo.myData.channelId++; ret = AddAuthChannelInfo(info); @@ -835,7 +848,7 @@ HWTEST_F(TransAuthChannelTest, OnDisconnectTest001, TestSize.Level1) ASSERT_EQ(ret, SOFTBUS_OK); bool isClient = true; AuthChannelInfo *info = CreateAuthChannelInfo(g_authSessionName, isClient); - ASSERT_TRUE(info != NULL); + ASSERT_TRUE(info != nullptr); info->authId = TRANS_TEST_AUTH_ID; ret = AddAuthChannelInfo(info); ASSERT_EQ(ret, SOFTBUS_OK); @@ -871,7 +884,7 @@ HWTEST_F(TransAuthChannelTest, TransAuthGetNameByChanIdTest001, TestSize.Level1) ASSERT_EQ(ret, SOFTBUS_OK); bool isClient = true; AuthChannelInfo *info = CreateAuthChannelInfo(g_sessionName, isClient); - ASSERT_TRUE(info != NULL); + ASSERT_TRUE(info != nullptr); info->appInfo.myData.channelId = TRANS_TEST_CHANNEL_ID; info->authId = TRANS_TEST_AUTH_ID; ret = AddAuthChannelInfo(info); @@ -893,7 +906,7 @@ HWTEST_F(TransAuthChannelTest, TransAuthGetNameByChanIdTest001, TestSize.Level1) HWTEST_F(TransAuthChannelTest, TransPostAuthChannelMsgTest002, TestSize.Level1) { AppInfo *appInfo = (AppInfo*)SoftBusCalloc(sizeof(AppInfo)); - ASSERT_TRUE(appInfo != NULL); + ASSERT_TRUE(appInfo != nullptr); int32_t ret = TestGenerateAppInfo(appInfo); ASSERT_EQ(ret, SOFTBUS_OK); ret =TransPostAuthChannelMsg(appInfo, TRANS_TEST_AUTH_ID, AUTH_CHANNEL_REQ); @@ -913,7 +926,7 @@ HWTEST_F(TransAuthChannelTest, TransSendAuthMsgTest002, TestSize.Level1) ASSERT_EQ(ret, SOFTBUS_OK); bool isClient = true; AuthChannelInfo *info = CreateAuthChannelInfo(g_sessionName, isClient); - ASSERT_TRUE(info != NULL); + ASSERT_TRUE(info != nullptr); info->appInfo.myData.channelId = TRANS_TEST_CHANNEL_ID; info->authId = TRANS_TEST_AUTH_ID; ret = AddAuthChannelInfo(info); @@ -940,14 +953,14 @@ HWTEST_F(TransAuthChannelTest, TransAuthGetConnOptionByChanIdTest002, TestSize.L ret = TransAuthInit(callback); ASSERT_EQ(ret, SOFTBUS_OK); ConnectOption *connOpt = (ConnectOption*)SoftBusCalloc(sizeof(ConnectOption)); - ASSERT_TRUE(connOpt != NULL); + ASSERT_TRUE(connOpt != nullptr); ret = TransAuthGetConnOptionByChanId(TRANS_TEST_CHANNEL_ID, connOpt); EXPECT_NE(ret, SOFTBUS_OK); ret = TransCreateSessionServer(g_pkgName, g_sessionName, TRANS_TEST_UID, TRANS_TEST_PID); ASSERT_EQ(ret, SOFTBUS_OK); bool isClient = true; AuthChannelInfo *info = CreateAuthChannelInfo(g_sessionName, isClient); - ASSERT_TRUE(info != NULL); + ASSERT_TRUE(info != nullptr); info->appInfo.myData.channelId = TRANS_TEST_CHANNEL_ID; info->authId = TRANS_TEST_AUTH_ID; info->isClient = false; @@ -957,7 +970,7 @@ HWTEST_F(TransAuthChannelTest, TransAuthGetConnOptionByChanIdTest002, TestSize.L EXPECT_NE(ret, SOFTBUS_OK); DelAuthChannelInfoByAuthId(TRANS_TEST_AUTH_ID); info = CreateAuthChannelInfo(g_sessionName, isClient); - ASSERT_TRUE(info != NULL); + ASSERT_TRUE(info != nullptr); info->appInfo.myData.channelId = TRANS_TEST_CHANNEL_ID; info->authId = TRANS_TEST_AUTH_ID; info->isClient = true; @@ -980,7 +993,7 @@ HWTEST_F(TransAuthChannelTest, TransAuthGetConnOptionByChanIdTest002, TestSize.L HWTEST_F(TransAuthChannelTest, TransAuthGetAppInfoByChanIdTest001, TestSize.Level1) { AppInfo *appInfo = (AppInfo*)SoftBusCalloc(sizeof(AppInfo)); - ASSERT_TRUE(appInfo != NULL); + ASSERT_TRUE(appInfo != nullptr); int32_t ret = TransAuthGetAppInfoByChanId(TRANS_TEST_CHANNEL_ID, NULL); EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); SoftBusFree(appInfo); @@ -1000,13 +1013,13 @@ HWTEST_F(TransAuthChannelTest, TransAuthGetAppInfoByChanIdTest002, TestSize.Leve ASSERT_EQ(ret, SOFTBUS_OK); bool isClient = true; AuthChannelInfo *info = CreateAuthChannelInfo(g_sessionName, isClient); - ASSERT_TRUE(info != NULL); + ASSERT_TRUE(info != nullptr); info->appInfo.myData.channelId = TRANS_TEST_CHANNEL_ID; info->authId = TRANS_TEST_AUTH_ID; ret = AddAuthChannelInfo(info); ASSERT_EQ(ret, SOFTBUS_OK); AppInfo *appInfo = (AppInfo*)SoftBusCalloc(sizeof(AppInfo)); - ASSERT_TRUE(appInfo != NULL); + ASSERT_TRUE(appInfo != nullptr); ret = TransAuthGetAppInfoByChanId(TRANS_TEST_CHANNEL_ID, appInfo); EXPECT_EQ(ret, SOFTBUS_OK); DelAuthChannelInfoByAuthId(TRANS_TEST_AUTH_ID); @@ -1024,7 +1037,7 @@ HWTEST_F(TransAuthChannelTest, TransAuthGetAppInfoByChanIdTest002, TestSize.Leve HWTEST_F(TransAuthChannelTest, TransNotifyAuthDataSuccessTest001, TestSize.Level1) { ConnectOption *connOpt = (ConnectOption*)SoftBusCalloc(sizeof(ConnectOption)); - ASSERT_TRUE(connOpt != NULL); + ASSERT_TRUE(connOpt != nullptr); int32_t ret = TransNotifyAuthDataSuccess(TRANS_TEST_CHANNEL_ID, NULL); EXPECT_NE(ret, SOFTBUS_OK); connOpt->type = CONNECT_TYPE_MAX; @@ -1052,7 +1065,7 @@ HWTEST_F(TransAuthChannelTest, OnRecvAuthChannelReply001, TestSize.Level1) OnRecvAuthChannelReply(TRANS_TEST_AUTH_ID, NULL, DEVICE_ID_SIZE_MAX); cJSON *msg = cJSON_CreateObject(); AppInfo *appInfo = (AppInfo*)SoftBusCalloc(sizeof(AppInfo)); - ASSERT_TRUE(appInfo != NULL); + ASSERT_TRUE(appInfo != nullptr); ret = TestGenerateAppInfo(appInfo); ASSERT_EQ(ret, SOFTBUS_OK); char cJsonStr[ERR_MSG_MAX_LEN] = {0}; @@ -1062,7 +1075,7 @@ HWTEST_F(TransAuthChannelTest, OnRecvAuthChannelReply001, TestSize.Level1) OnRecvAuthChannelReply(TRANS_TEST_AUTH_ID, cJsonStr, strlen(cJsonStr)); bool isClient = true; AuthChannelInfo *info = CreateAuthChannelInfo(g_sessionName, isClient); - ASSERT_TRUE(info != NULL); + ASSERT_TRUE(info != nullptr); info->authId = TRANS_TEST_AUTH_ID; OnRecvAuthChannelReply(TRANS_TEST_AUTH_ID, cJsonStr, strlen(cJsonStr)); ret = AddAuthChannelInfo(info); @@ -1071,7 +1084,7 @@ HWTEST_F(TransAuthChannelTest, OnRecvAuthChannelReply001, TestSize.Level1) ret = TransAuthChannelMsgPack(msg, appInfo); ASSERT_EQ(ret, SOFTBUS_OK); char *data = cJSON_PrintUnformatted(msg); - ASSERT_TRUE(data != NULL); + ASSERT_TRUE(data != nullptr); OnRecvAuthChannelReply(TRANS_TEST_AUTH_ID, data, strlen(data)); DelAuthChannelInfoByAuthId(TRANS_TEST_AUTH_ID); SoftBusFree(appInfo); @@ -1093,7 +1106,7 @@ HWTEST_F(TransAuthChannelTest, TransCloseAuthChannel001, TestSize.Level1) ASSERT_EQ(ret, SOFTBUS_OK); bool isClient = true; AuthChannelInfo *info = CreateAuthChannelInfo(g_sessionName, isClient); - ASSERT_TRUE(info != NULL); + ASSERT_TRUE(info != nullptr); info->authId = TRANS_TEST_AUTH_ID; ret = AddAuthChannelInfo(info); ASSERT_EQ(ret, SOFTBUS_OK); @@ -1120,14 +1133,14 @@ HWTEST_F(TransAuthChannelTest, TransAuthGetChannelInfo001, TestSize.Level1) ASSERT_EQ(ret, SOFTBUS_OK); bool isClient = true; AuthChannelInfo *info = CreateAuthChannelInfo(g_sessionName, isClient); - ASSERT_TRUE(info != NULL); + ASSERT_TRUE(info != nullptr); int32_t channelId = info->appInfo.myData.channelId; info->authId = TRANS_TEST_AUTH_ID; ret = AddAuthChannelInfo(info); ASSERT_EQ(ret, SOFTBUS_OK); AuthChannelInfo *newInfo = CreateAuthChannelInfo(g_sessionName, isClient); - ASSERT_TRUE(newInfo != NULL); + ASSERT_TRUE(newInfo != nullptr); int32_t newChannelId = newInfo->appInfo.myData.channelId; newInfo->authId = TRANS_TEST_AUTH_ID + 1; ret = AddAuthChannelInfo(newInfo); @@ -1138,7 +1151,7 @@ HWTEST_F(TransAuthChannelTest, TransAuthGetChannelInfo001, TestSize.Level1) ret = GetAuthIdByChannelId(newChannelId); EXPECT_EQ(ret, TRANS_TEST_AUTH_ID + 1); AuthChannelInfo *destInfo = (AuthChannelInfo*)SoftBusCalloc(sizeof(AuthChannelInfo)); - ASSERT_TRUE(destInfo != NULL); + ASSERT_TRUE(destInfo != nullptr); ret = GetChannelInfoByAuthId(TRANS_TEST_AUTH_ID, destInfo); EXPECT_EQ(ret, SOFTBUS_OK); ret = memcmp(info, destInfo, sizeof(AuthChannelInfo)); @@ -1189,7 +1202,7 @@ HWTEST_F(TransAuthChannelTest, TransOpenAuthMsgChannelTest003, TestSize.Level1) ASSERT_EQ(ret, SOFTBUS_OK); ret = TransOpenAuthMsgChannel(g_sessionName, &connInfo, &channelId, NULL); - EXPECT_EQ(ret, SOFTBUS_STRCPY_ERR); + EXPECT_NE(ret, SOFTBUS_OK); TransSessionMgrDeinit(); TransAuthDeinit(); diff --git a/tests/core/transmission/trans_channel/manager/trans_channel_callback_test/trans_channel_callback_test.cpp b/tests/core/transmission/trans_channel/manager/trans_channel_callback_test/trans_channel_callback_test.cpp index 0447727c4..b08c60b7f 100644 --- a/tests/core/transmission/trans_channel/manager/trans_channel_callback_test/trans_channel_callback_test.cpp +++ b/tests/core/transmission/trans_channel/manager/trans_channel_callback_test/trans_channel_callback_test.cpp @@ -78,7 +78,7 @@ HWTEST_F(TransChannelCallbackTest, TransServerOnChannelOpened001, TestSize.Level channel->isServer = false; channel->channelType = CHANNEL_TYPE_UDP; ret = TransServerGetChannelCb()->OnChannelOpened(pkgName, pid, sessionName, channel); - EXPECT_EQ(SOFTBUS_TRANS_PROXY_REMOTE_NULL, ret); + EXPECT_NE(SOFTBUS_OK, ret); channel->isServer = true; channel->channelType = (CHANNEL_TYPE_UDP - 1); 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 a2e2d9b97..f7a0820dc 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 @@ -88,7 +88,6 @@ void TransChannelManagerTest::SetUpTestCase(void) BusCenterServerInit(); TransServerInit(); DiscEventManagerInit(); - TransChannelInit(); } void TransChannelManagerTest::TearDownTestCase(void) @@ -297,9 +296,6 @@ HWTEST_F(TransChannelManagerTest, TransOpenChannelProc001, TestSize.Level1) ret = TransOpenChannelProc(CHANNEL_TYPE_UDP, appInfo, connOpt, &channelId); EXPECT_NE(SOFTBUS_OK, ret); - ret = TransOpenChannelProc(CHANNEL_TYPE_PROXY, appInfo, connOpt, &channelId); - EXPECT_NE(SOFTBUS_OK, ret); - ret = TransOpenChannelProc(CHANNEL_TYPE_TCP_DIRECT, appInfo, connOpt, &channelId); EXPECT_NE(SOFTBUS_OK, ret); diff --git a/tests/core/transmission/trans_channel/proxy_channel/softbus_proxychannel_listener_test.cpp b/tests/core/transmission/trans_channel/proxy_channel/softbus_proxychannel_listener_test.cpp index ae7146e7c..ce82f43bb 100644 --- a/tests/core/transmission/trans_channel/proxy_channel/softbus_proxychannel_listener_test.cpp +++ b/tests/core/transmission/trans_channel/proxy_channel/softbus_proxychannel_listener_test.cpp @@ -191,9 +191,7 @@ HWTEST_F(SoftbusProxyChannelListenerTest, NotifyNormalChannelOpenedTest001, Test strcpy_s(pkgName, SESSIONKEYSIZE, TEST_CHANNEL_INDENTITY); AppInfo *appInfo = (AppInfo *)SoftBusCalloc(sizeof(AppInfo)); - if (appInfo == NULL) { - return; - } + EXPECT_NE(NULL, appInfo); appInfo->appType = APP_TYPE_AUTH; int32_t ret = NotifyNormalChannelOpened(TEST_NUMBER_25, appInfo, 0); EXPECT_EQ(SOFTBUS_OK, ret); @@ -212,9 +210,7 @@ HWTEST_F(SoftbusProxyChannelListenerTest, NotifyNormalChannelOpenedTest001, Test HWTEST_F(SoftbusProxyChannelListenerTest, OnProxyChannelOpenedTest001, TestSize.Level1) { AppInfo *appInfo = (AppInfo *)SoftBusCalloc(sizeof(AppInfo)); - if (appInfo == NULL) { - return; - } + EXPECT_NE(NULL, appInfo); strcpy_s(appInfo->myData.sessionName, SESSIONKEYSIZE, VALID_SESSIONNAME); appInfo->appType = APP_TYPE_AUTH; int32_t ret = OnProxyChannelOpened(TEST_NUMBER_25, appInfo, 0); @@ -231,9 +227,7 @@ HWTEST_F(SoftbusProxyChannelListenerTest, OnProxyChannelOpenedTest001, TestSize. HWTEST_F(SoftbusProxyChannelListenerTest, OnProxyChannelOpenFailedTest001, TestSize.Level1) { AppInfo *appInfo = (AppInfo *)SoftBusCalloc(sizeof(AppInfo)); - if (appInfo == NULL) { - return; - } + EXPECT_NE(NULL, appInfo); strcpy_s(appInfo->myData.pkgName, SESSIONKEYSIZE, TEST_PKG_NAME); appInfo->myData.pid = TEST_NUMBER_25; strcpy_s(appInfo->myData.sessionName, SESSIONKEYSIZE, VALID_SESSIONNAME); @@ -254,9 +248,7 @@ HWTEST_F(SoftbusProxyChannelListenerTest, OnProxyChannelOpenFailedTest001, TestS HWTEST_F(SoftbusProxyChannelListenerTest, OnProxyChannelClosedTest001, TestSize.Level1) { AppInfo *appInfo = (AppInfo *)SoftBusCalloc(sizeof(AppInfo)); - if (appInfo == NULL) { - return; - } + EXPECT_NE(NULL, appInfo); strcpy_s(appInfo->myData.pkgName, SESSIONKEYSIZE, TEST_PKG_NAME); appInfo->myData.pid = TEST_NUMBER_25; strcpy_s(appInfo->myData.sessionName, SESSIONKEYSIZE, VALID_SESSIONNAME); @@ -276,9 +268,7 @@ HWTEST_F(SoftbusProxyChannelListenerTest, OnProxyChannelClosedTest001, TestSize. HWTEST_F(SoftbusProxyChannelListenerTest, OnProxyChannelMsgReceivedTest001, TestSize.Level1) { AppInfo *appInfo = (AppInfo *)SoftBusCalloc(sizeof(AppInfo)); - if (appInfo == NULL) { - return; - } + EXPECT_NE(NULL, appInfo); strcpy_s(appInfo->myData.pkgName, SESSIONKEYSIZE, TEST_PKG_NAME); appInfo->myData.pid = TEST_NUMBER_25; strcpy_s(appInfo->myData.sessionName, SESSIONKEYSIZE, VALID_SESSIONNAME); @@ -300,9 +290,7 @@ HWTEST_F(SoftbusProxyChannelListenerTest, OnProxyChannelMsgReceivedTest001, Test HWTEST_F(SoftbusProxyChannelListenerTest, TransProxyGetAppInfoTest001, TestSize.Level1) { AppInfo *appInfo = (AppInfo *)SoftBusCalloc(sizeof(AppInfo)); - if (appInfo == NULL) { - return; - } + EXPECT_NE(NULL, appInfo); char sessionName[SESSIONKEYSIZE] = {0}; strcpy_s(sessionName, SESSIONKEYSIZE, VALID_SESSIONNAME); char peerNetworkId[SESSIONKEYSIZE] = {0}; diff --git a/tests/core/transmission/trans_channel/proxy_channel/softbus_proxychannel_message_test.cpp b/tests/core/transmission/trans_channel/proxy_channel/softbus_proxychannel_message_test.cpp index c3daaab84..69202801f 100644 --- a/tests/core/transmission/trans_channel/proxy_channel/softbus_proxychannel_message_test.cpp +++ b/tests/core/transmission/trans_channel/proxy_channel/softbus_proxychannel_message_test.cpp @@ -230,7 +230,7 @@ HWTEST_F(SoftbusProxyChannelMessageTest, TransProxyHandshakeErrMsgTest001, TestS int32_t errCode = SOFTBUS_OK; ret = TransProxyUnPackHandshakeErrMsg(msg, &errCode, sizeof(msg)); - EXPECT_EQ(SOFTBUS_INVALID_PARAM, ret); + EXPECT_EQ(SOFTBUS_CREATE_JSON_ERR, ret); cJSON_free(msg); } diff --git a/tests/core/transmission/trans_channel/tcp_direct/unittest/mock/trans_tcp_direct_message_test_mock.cpp b/tests/core/transmission/trans_channel/tcp_direct/unittest/mock/trans_tcp_direct_message_test_mock.cpp index eaa09802a..a46cf701d 100644 --- a/tests/core/transmission/trans_channel/tcp_direct/unittest/mock/trans_tcp_direct_message_test_mock.cpp +++ b/tests/core/transmission/trans_channel/tcp_direct/unittest/mock/trans_tcp_direct_message_test_mock.cpp @@ -156,15 +156,5 @@ cJSON* cJSON_Parse(const char *value) { return GetTransTcpDirectMessageInterface()->cJSON_Parse(value); } - -static struct WifiDirectManager g_manager = { - .getLocalIpByRemoteIp = GetLocalIpByRemoteIp, - .getRemoteUuidByIp = GetRemoteUuidByIp, -}; - -struct WifiDirectManager* GetWifiDirectManager(void) -{ - return &g_manager; -} } } diff --git a/tests/core/transmission/trans_channel/tcp_direct/unittest/mock/trans_tcp_direct_message_test_mock.h b/tests/core/transmission/trans_channel/tcp_direct/unittest/mock/trans_tcp_direct_message_test_mock.h index e005457d3..d2d93aa38 100644 --- a/tests/core/transmission/trans_channel/tcp_direct/unittest/mock/trans_tcp_direct_message_test_mock.h +++ b/tests/core/transmission/trans_channel/tcp_direct/unittest/mock/trans_tcp_direct_message_test_mock.h @@ -19,7 +19,6 @@ #include #include "auth_interface.h" -#include "bus_center_manager.h" #include "softbus_feature_config.h" #include "softbus_message_open_channel.h" #include "softbus_socket.h" diff --git a/tests/core/transmission/trans_channel/tcp_direct/unittest/trans_core_tcp_direct_test.cpp b/tests/core/transmission/trans_channel/tcp_direct/unittest/trans_core_tcp_direct_test.cpp index c9d76725b..4963a0b1c 100644 --- a/tests/core/transmission/trans_channel/tcp_direct/unittest/trans_core_tcp_direct_test.cpp +++ b/tests/core/transmission/trans_channel/tcp_direct/unittest/trans_core_tcp_direct_test.cpp @@ -60,7 +60,6 @@ void TransCoreTcpDirectTest::SetUpTestCase(void) BusCenterServerInit(); TransServerInit(); DiscEventManagerInit(); - TransChannelInit(); } void TransCoreTcpDirectTest::TearDownTestCase(void) @@ -70,7 +69,6 @@ void TransCoreTcpDirectTest::TearDownTestCase(void) AuthDeinit(); TransServerDeinit(); DiscEventManagerDeinit(); - TransChannelDeinit(); } SessionServer *TestSetPack() diff --git a/tests/core/transmission/trans_channel/tcp_direct/unittest/trans_server_tcp_direct_test.cpp b/tests/core/transmission/trans_channel/tcp_direct/unittest/trans_server_tcp_direct_test.cpp index 5494563d4..9163618ec 100644 --- a/tests/core/transmission/trans_channel/tcp_direct/unittest/trans_server_tcp_direct_test.cpp +++ b/tests/core/transmission/trans_channel/tcp_direct/unittest/trans_server_tcp_direct_test.cpp @@ -128,7 +128,6 @@ void TransServerTcpDirectTest::SetUpTestCase(void) BusCenterServerInit(); TransServerInit(); DiscEventManagerInit(); - TransChannelInit(); CreatSessionConnList(); ret = AuthCommonInit(); EXPECT_EQ(ret, SOFTBUS_OK); @@ -147,7 +146,6 @@ void TransServerTcpDirectTest::TearDownTestCase(void) AuthDeinit(); TransServerDeinit(); DiscEventManagerDeinit(); - TransChannelDeinit(); AuthCommonDeinit(); TransTcpDirectDeinit(); LnnDeinitLocalLedger(); diff --git a/tests/core/transmission/trans_channel/tcp_direct/unittest/trans_tcp_direct_listener_test.cpp b/tests/core/transmission/trans_channel/tcp_direct/unittest/trans_tcp_direct_listener_test.cpp index cedae6691..43774113f 100644 --- a/tests/core/transmission/trans_channel/tcp_direct/unittest/trans_tcp_direct_listener_test.cpp +++ b/tests/core/transmission/trans_channel/tcp_direct/unittest/trans_tcp_direct_listener_test.cpp @@ -138,7 +138,7 @@ HWTEST_F(TransTcpDirectListenerTest, TdcOnConnectEventTest001, TestSize.Level1) int cfd = NORMAL_FD; int32_t ret = TdcOnConnectEvent(module, cfd, clientAddr); - EXPECT_EQ(SOFTBUS_LOCK_ERR, ret); + EXPECT_NE(SOFTBUS_OK, ret); } /** diff --git a/tests/core/transmission/trans_channel/tcp_direct/unittest/trans_tcp_direct_message_append_test.cpp b/tests/core/transmission/trans_channel/tcp_direct/unittest/trans_tcp_direct_message_append_test.cpp index 2f7f7a8ba..dd7b1b20a 100644 --- a/tests/core/transmission/trans_channel/tcp_direct/unittest/trans_tcp_direct_message_append_test.cpp +++ b/tests/core/transmission/trans_channel/tcp_direct/unittest/trans_tcp_direct_message_append_test.cpp @@ -946,7 +946,7 @@ HWTEST_F(TransTcpDirectMessageAppendTest, GetAuthIdByChannelInfoTest004, TestSiz NiceMock TcpMessageMock; EXPECT_CALL(TcpMessageMock, GetAuthHandleByChanId).WillOnce(Return(SOFTBUS_NOT_FIND)); EXPECT_CALL(TcpMessageMock, GetAppInfoById).WillOnce(Return(SOFTBUS_OK)); - EXPECT_CALL(TcpMessageMock, GetRemoteUuidByIp).WillOnce(Return(SOFTBUS_NOT_FIND)); + EXPECT_CALL(TcpMessageMock, GetRemoteUuidByIp).WillRepeatedly(Return(SOFTBUS_NOT_FIND)); AuthHandle authHandle = { .authId = AUTH_INVALID_ID }; (void)GetAuthIdByChannelInfo(channelId, seq, cipherFlag, &authHandle); EXPECT_EQ(authHandle.authId, AUTH_INVALID_ID); diff --git a/tests/core/transmission/trans_channel/tcp_direct/unittest/trans_tcp_direct_message_static_test.cpp b/tests/core/transmission/trans_channel/tcp_direct/unittest/trans_tcp_direct_message_static_test.cpp index c98eaee67..9e1955426 100644 --- a/tests/core/transmission/trans_channel/tcp_direct/unittest/trans_tcp_direct_message_static_test.cpp +++ b/tests/core/transmission/trans_channel/tcp_direct/unittest/trans_tcp_direct_message_static_test.cpp @@ -65,7 +65,6 @@ void TransTcpDirectMessageStaticTest::SetUpTestCase(void) BusCenterServerInit(); TransServerInit(); DiscEventManagerInit(); - TransChannelInit(); const IServerChannelCallBack *cb = TransServerGetChannelCb(); int32_t ret = TransTdcSetCallBack(cb); EXPECT_EQ(ret, SOFTBUS_OK); @@ -78,7 +77,6 @@ void TransTcpDirectMessageStaticTest::TearDownTestCase(void) AuthDeinit(); TransServerDeinit(); DiscEventManagerDeinit(); - TransChannelDeinit(); } SessionConn *TestSetSessionConn() @@ -128,7 +126,7 @@ AppInfo *TestSetAppInfo() HWTEST_F(TransTcpDirectMessageStaticTest, SwitchCipherTypeToAuthLinkType0001, TestSize.Level1) { SessionConn *conn = (SessionConn *)SoftBusCalloc(sizeof(SessionConn)); - if (conn == NULL) { + if (conn == nullptr) { return; } @@ -180,7 +178,7 @@ HWTEST_F(TransTcpDirectMessageStaticTest, TransTdcPostFisrtData0003, TestSize.Le { int32_t ret; SessionConn *conn = (SessionConn *)SoftBusCalloc(sizeof(SessionConn)); - if (conn == NULL) { + if (conn == nullptr) { return; } diff --git a/tests/core/transmission/trans_channel/tcp_direct/unittest/trans_tcp_direct_p2p_test.cpp b/tests/core/transmission/trans_channel/tcp_direct/unittest/trans_tcp_direct_p2p_test.cpp index 0af8b2333..438b2c806 100644 --- a/tests/core/transmission/trans_channel/tcp_direct/unittest/trans_tcp_direct_p2p_test.cpp +++ b/tests/core/transmission/trans_channel/tcp_direct/unittest/trans_tcp_direct_p2p_test.cpp @@ -51,7 +51,7 @@ static int32_t g_port = 6000; static const char *g_sessionName = "com.test.trans.auth.demo"; static const char *g_pkgName = "dms"; static const char *g_udid = "ABCDEF00ABCDEF00ABCDEF00ABCDEF00ABCDEF00ABCDEF00ABCDEF00ABCDEF00"; -static IServerChannelCallBack g_channelCallBack; +static IServerChannelCallBack g_testChannelCallBack; class TransTcpDirectP2pTest : public testing::Test { public: TransTcpDirectP2pTest() @@ -97,47 +97,47 @@ SessionConn *TestSetSessionConn() return conn; } -static int32_t TransServerOnChannelOpened(const char *pkgName, int32_t pid, const char *sessionName, +static int32_t TestTransServerOnChannelOpened(const char *pkgName, int32_t pid, const char *sessionName, const ChannelInfo *channel) { TRANS_LOGE(TRANS_QOS, "TransServerOnChannelOpened"); return SOFTBUS_OK; } -static int32_t TransServerOnChannelClosed( +static int32_t TestTransServerOnChannelClosed( const char *pkgName, int32_t pid, int32_t channelId, int32_t channelType, int32_t messageType) { TRANS_LOGE(TRANS_QOS, "TransServerOnChannelClosed"); return SOFTBUS_OK; } -static int32_t TransServerOnChannelOpenFailed(const char *pkgName, int32_t pid, int32_t channelId, +static int32_t TestTransServerOnChannelOpenFailed(const char *pkgName, int32_t pid, int32_t channelId, int32_t channelType, int32_t errCode) { TRANS_LOGE(TRANS_QOS, "TransServerOnChannelOpenFailed"); return SOFTBUS_OK; } -static int32_t TransServerOnMsgReceived(const char *pkgName, int32_t pid, int32_t channelId, int32_t channelType, +static int32_t TestTransServerOnMsgReceived(const char *pkgName, int32_t pid, int32_t channelId, int32_t channelType, TransReceiveData *receiveData) { TRANS_LOGE(TRANS_QOS, "TransServerOnChannelOpenFailed"); return SOFTBUS_OK; } -static int32_t TransServerOnQosEvent(const char *pkgName, const QosParam *param) +static int32_t TestTransServerOnQosEvent(const char *pkgName, const QosParam *param) { TRANS_LOGE(TRANS_QOS, "TransServerOnChannelOpenFailed"); return SOFTBUS_OK; } -static int32_t TransGetPkgNameBySessionName(const char *sessionName, char *pkgName, uint16_t len) +static int32_t TestTransGetPkgNameBySessionName(const char *sessionName, char *pkgName, uint16_t len) { TRANS_LOGE(TRANS_QOS, "TransGetPkgNameBySessionName"); return SOFTBUS_OK; } -static int32_t TransGetUidAndPid(const char *sessionName, int32_t *uid, int32_t *pid) +static int32_t TestTransGetUidAndPid(const char *sessionName, int32_t *uid, int32_t *pid) { TRANS_LOGE(TRANS_QOS, "TransGetUidAndPid"); return SOFTBUS_OK; @@ -145,14 +145,14 @@ static int32_t TransGetUidAndPid(const char *sessionName, int32_t *uid, int32_t IServerChannelCallBack *TestTransServerGetChannelCb(void) { - g_channelCallBack.OnChannelOpened = TransServerOnChannelOpened; - g_channelCallBack.OnChannelClosed = TransServerOnChannelClosed; - g_channelCallBack.OnChannelOpenFailed = TransServerOnChannelOpenFailed; - g_channelCallBack.OnDataReceived = TransServerOnMsgReceived; - g_channelCallBack.OnQosEvent = TransServerOnQosEvent; - g_channelCallBack.GetPkgNameBySessionName = TransGetPkgNameBySessionName; - g_channelCallBack.GetUidAndPidBySessionName = TransGetUidAndPid; - return &g_channelCallBack; + g_testChannelCallBack.OnChannelOpened = TestTransServerOnChannelOpened; + g_testChannelCallBack.OnChannelClosed = TestTransServerOnChannelClosed; + g_testChannelCallBack.OnChannelOpenFailed = TestTransServerOnChannelOpenFailed; + g_testChannelCallBack.OnDataReceived = TestTransServerOnMsgReceived; + g_testChannelCallBack.OnQosEvent = TestTransServerOnQosEvent; + g_testChannelCallBack.GetPkgNameBySessionName = TestTransGetPkgNameBySessionName; + g_testChannelCallBack.GetUidAndPidBySessionName = TestTransGetUidAndPid; + return &g_testChannelCallBack; } string TestGetMsgPack() diff --git a/tests/core/transmission/trans_channel/udp_negotiation/trans_udp_nego_test.cpp b/tests/core/transmission/trans_channel/udp_negotiation/trans_udp_nego_test.cpp index da95d2b4b..e663ae778 100644 --- a/tests/core/transmission/trans_channel/udp_negotiation/trans_udp_nego_test.cpp +++ b/tests/core/transmission/trans_channel/udp_negotiation/trans_udp_nego_test.cpp @@ -290,7 +290,7 @@ HWTEST_F(TransUdpNegoTest, TransOnExchangeUdpInfoReply001, TestSize.Level1) int32_t ret = TransAddUdpChannel(newChannel); EXPECT_EQ(ret, SOFTBUS_OK); ret = InitQos(); - EXPECT_EQ(ret, SOFTBUS_OK); + EXPECT_NE(ret, SOFTBUS_INVALID_PARAM); TransOnExchangeUdpInfoReply(authId, INVALID_SEQ, msg); @@ -551,7 +551,7 @@ HWTEST_F(TransUdpNegoTest, UdpOpenAuthConn001, TestSize.Level1) uint32_t requestId = 1; bool isMeta = false; int32_t ret = UdpOpenAuthConn(peerUdid.c_str(), requestId, isMeta, 0); - EXPECT_EQ(ret, SOFTBUS_NOT_IMPLEMENT); + EXPECT_NE(ret, SOFTBUS_OK); isMeta = true; ret = UdpOpenAuthConn(peerUdid.c_str(), requestId, isMeta, 0); diff --git a/tests/core/transmission/trans_channel/udp_negotiation/trans_udp_negotiation_test.cpp b/tests/core/transmission/trans_channel/udp_negotiation/trans_udp_negotiation_test.cpp index a63c3a716..d11383da5 100644 --- a/tests/core/transmission/trans_channel/udp_negotiation/trans_udp_negotiation_test.cpp +++ b/tests/core/transmission/trans_channel/udp_negotiation/trans_udp_negotiation_test.cpp @@ -63,34 +63,6 @@ public: {} }; -static int OnSessionOpened(int sessionId, int result) -{ - TRANS_LOGI(TRANS_TEST, "session opened, sessionId=%{public}d", sessionId); - return SOFTBUS_OK; -} - -static void OnSessionClosed(int sessionId) -{ - TRANS_LOGI(TRANS_TEST, "session closed, sessionId=%{public}d", sessionId); -} - -static void OnBytesReceived(int sessionId, const void *data, unsigned int len) -{ - TRANS_LOGI(TRANS_TEST, "session bytes received, sessionId=%{public}d", sessionId); -} - -static void OnMessageReceived(int sessionId, const void *data, unsigned int len) -{ - TRANS_LOGI(TRANS_TEST, "session msg received, sessionId=%{public}d", sessionId); -} - -static ISessionListener g_sessionlistener = { - .OnSessionOpened = OnSessionOpened, - .OnSessionClosed = OnSessionClosed, - .OnBytesReceived = OnBytesReceived, - .OnMessageReceived = OnMessageReceived, -}; - void TransUdpNegotiationTest::SetUpTestCase(void) { SoftbusConfigInit(); @@ -100,7 +72,6 @@ void TransUdpNegotiationTest::SetUpTestCase(void) BusCenterServerInit(); TransServerInit(); DiscEventManagerInit(); - TransChannelInit(); SetAceessTokenPermission("dsoftbusTransTest"); } @@ -111,7 +82,6 @@ void TransUdpNegotiationTest::TearDownTestCase(void) AuthDeinit(); TransServerDeinit(); DiscEventManagerDeinit(); - TransChannelDeinit(); } /** @@ -290,12 +260,10 @@ HWTEST_F(TransUdpNegotiationTest, TransUdpNegotiationTest07, TestSize.Level1) */ HWTEST_F(TransUdpNegotiationTest, TransUdpNegotiationTest08, TestSize.Level1) { - int res = CreateSessionServer(g_pkgName, g_sessionName, &g_sessionlistener); - EXPECT_EQ(res, SOFTBUS_OK); AppInfo* appInfo = (AppInfo*)SoftBusMalloc(sizeof(AppInfo)); EXPECT_TRUE(appInfo != NULL); memset_s(appInfo, sizeof(AppInfo), 0, sizeof(AppInfo)); - res = strcpy_s(appInfo->myData.sessionName, sizeof(appInfo->myData.sessionName), + int res = strcpy_s(appInfo->myData.sessionName, sizeof(appInfo->myData.sessionName), g_sessionName); EXPECT_EQ(res, EOK); appInfo->myData.channelId = TEST_CHANNEL_ID; @@ -332,12 +300,10 @@ HWTEST_F(TransUdpNegotiationTest, TransUdpNegotiationTest09, TestSize.Level1) */ HWTEST_F(TransUdpNegotiationTest, TransUdpNegotiationTest10, TestSize.Level1) { - int res = CreateSessionServer(g_pkgName, g_sessionName, &g_sessionlistener); - EXPECT_EQ(res, SOFTBUS_OK); AppInfo* appInfo = (AppInfo*)SoftBusMalloc(sizeof(AppInfo)); EXPECT_TRUE(appInfo != NULL); memset_s(appInfo, sizeof(AppInfo), 0, sizeof(AppInfo)); - res = strcpy_s(appInfo->myData.sessionName, sizeof(appInfo->myData.sessionName), + int res = strcpy_s(appInfo->myData.sessionName, sizeof(appInfo->myData.sessionName), g_sessionName); EXPECT_EQ(res, EOK); int32_t ret = NotifyUdpQosEvent(appInfo, INVALID_EVENT_ID, 0, NULL); @@ -387,5 +353,7 @@ HWTEST_F(TransUdpNegotiationTest, TransUdpNegotiationTest12, TestSize.Level1) EXPECT_EQ(ret, SOFTBUS_OK); TransUdpDeathCallback(g_pkgName, INVALID_PID); EXPECT_EQ(ret, SOFTBUS_OK); + ret = TransUdpChannelMgrInit(); + EXPECT_EQ(ret, SOFTBUS_OK); } } \ No newline at end of file diff --git a/tests/sdk/discovery/unittest/BUILD.gn b/tests/sdk/discovery/unittest/BUILD.gn index 81f0e8bb0..22fb0408a 100644 --- a/tests/sdk/discovery/unittest/BUILD.gn +++ b/tests/sdk/discovery/unittest/BUILD.gn @@ -134,10 +134,34 @@ if (defined(ohos_lite)) { } } + ohos_unittest("DiscSdkManagerTest") { + module_out_path = module_output_path + sources = [ "disc_sdk_manager_test.cpp" ] + include_dirs = [ + "$dsoftbus_root_path/core/common/include", + "$dsoftbus_root_path/interfaces/kits/common", + "$dsoftbus_root_path/interfaces/kits/discovery", + "$dsoftbus_root_path/sdk/discovery/ipc/include", + "$dsoftbus_root_path/sdk/discovery/ipc/standard/include", + "$dsoftbus_root_path/sdk/discovery/manager/include", + "$dsoftbus_root_path/tests/sdk/common/include", + ] + deps = [ + "$dsoftbus_root_path/sdk:softbus_client", + "$dsoftbus_root_path/tests/sdk/common:softbus_access_token_test", + ] + external_deps = [ + "c_utils:utils", + "googletest:gtest_main", + "hilog:libhilog", + ] + } + group("unittest") { testonly = true deps = [ ":DiscSdkAutoTest", + ":DiscSdkManagerTest", ":DiscSdkOnlyL2Test", ":DiscSdkTest", ] diff --git a/tests/sdk/discovery/unittest/disc_sdk_manager_test.cpp b/tests/sdk/discovery/unittest/disc_sdk_manager_test.cpp new file mode 100644 index 000000000..6f4aa8a56 --- /dev/null +++ b/tests/sdk/discovery/unittest/disc_sdk_manager_test.cpp @@ -0,0 +1,366 @@ +/* + * Copyright (c) 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 + * + * 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 "client_disc_manager.h" +#include "disc_server_proxy.h" +#include "softbus_errcode.h" + +using namespace testing::ext; + +namespace OHOS { +static int32_t g_subscribeId = 0; +static int32_t g_publishId = 0; +static char g_pkgName[] = "Softbus_Kits"; +static bool g_isFound = false; +static bool g_discSuccessFlag = false; +static bool g_discFailedFlag = false; +static bool g_pubSuccessFlag = false; +static bool g_pubFailedFlag = false; + +class DiscSdkManagerTest : public testing::Test { +public: + DiscSdkManagerTest() + {} + ~DiscSdkManagerTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp() override + {} + void TearDown() override + {} +}; + +void DiscSdkManagerTest::SetUpTestCase(void) +{} + +void DiscSdkManagerTest::TearDownTestCase(void) +{} + +static SubscribeInfo g_subscribeInfo = { + .subscribeId = 1, + .mode = DISCOVER_MODE_PASSIVE, + .medium = COAP, + .freq = MID, + .isSameAccount = true, + .isWakeRemote = false, + .capability = "dvKit", + .capabilityData = (unsigned char *)"capdata", + .dataLen = strlen("capdata") +}; + +static PublishInfo g_publishInfo = { + .publishId = 1, + .mode = DISCOVER_MODE_PASSIVE, + .medium = COAP, + .freq = MID, + .capability = "dvKit", + .capabilityData = (unsigned char *)"capdata", + .dataLen = strlen("capdata") +}; + +static void TestDeviceFound(const DeviceInfo *device) +{ + printf("[client]TestDeviceFound\n"); + g_isFound = true; +} + +static void TestDiscoverFailed(int32_t subscribeId, DiscoveryFailReason failReason) +{ + printf("[client]TestDiscoverFailed\n"); + g_discFailedFlag = true; +} + +static void TestDiscoverySuccess(int32_t subscribeId) +{ + printf("[client]TestDiscoverySuccess\n"); + g_discSuccessFlag = true; +} + +static void TestPublishSuccess(int32_t publishId) +{ + printf("[client]TestPublishSuccess\n"); + g_pubSuccessFlag = true; +} + +static void TestPublishFail(int32_t publishId, PublishFailReason reason) +{ + printf("[client]TestPublishFail\n"); + g_pubFailedFlag = true; +} + +static IDiscoveryCallback g_subscribeCb = { + .OnDeviceFound = TestDeviceFound, + .OnDiscoverFailed = TestDiscoverFailed, + .OnDiscoverySuccess = TestDiscoverySuccess +}; + +static IPublishCallback g_publishCb = { + .OnPublishSuccess = TestPublishSuccess, + .OnPublishFail = TestPublishFail +}; + +/** + * @tc.name: PublishServiceInnerTest001 + * @tc.desc: Test PublishServiceInner when ServerIpcPublishService failed. + * @tc.in: Test Moudle, Test Number, Test Levels. + * @tc.out: NonZero + * @tc.type: FUNC + * @tc.require: The g_serverProxy is not initialized and return SOFTBUS_NO_INIT. + */ +HWTEST_F(DiscSdkManagerTest, PublishServiceInnerTest001, TestSize.Level1) +{ + int32_t ret = DiscClientInit(); + EXPECT_EQ(ret, SOFTBUS_OK); + DiscServerProxyDeInit(); + ret = PublishServiceInner(g_pkgName, &g_publishInfo, &g_publishCb); + EXPECT_EQ(ret, SOFTBUS_NO_INIT); + DiscClientDeinit(); +} + +/** + * @tc.name: UnpublishServiceInnerTest001 + * @tc.desc: Test UnpublishServiceInner when ServerIpcUnPublishService failed. + * @tc.in: Test Moudle, Test Number, Test Levels. + * @tc.out: NonZero + * @tc.type: FUNC + * @tc.require: The g_serverProxy is not initialized and return SOFTBUS_NO_INIT. + */ +HWTEST_F(DiscSdkManagerTest, UnpublishServiceInnerTest001, TestSize.Level1) +{ + int32_t ret = UnpublishServiceInner(g_pkgName, g_publishId); + EXPECT_EQ(ret, SOFTBUS_NO_INIT); +} + +/** + * @tc.name: StartDiscoveryInnerTest001 + * @tc.desc: Test StartDiscoveryInner when ServerIpcStartDiscovery failed. + * @tc.in: Test Moudle, Test Number, Test Levels. + * @tc.out: NonZero + * @tc.type: FUNC + * @tc.require: The g_serverProxy is not initialized and return SOFTBUS_NO_INIT. + */ +HWTEST_F(DiscSdkManagerTest, StartDiscoveryInnerTest001, TestSize.Level1) +{ + int32_t ret = DiscClientInit(); + EXPECT_EQ(ret, SOFTBUS_OK); + DiscServerProxyDeInit(); + ret = StartDiscoveryInner(g_pkgName, &g_subscribeInfo, &g_subscribeCb); + EXPECT_EQ(ret, SOFTBUS_NO_INIT); + DiscClientDeinit(); +} + +/** + * @tc.name: StopDiscoveryInnerTest001 + * @tc.desc: Test StopDiscoveryInner when ServerIpcStopDiscovery failed. + * @tc.in: Test Moudle, Test Number, Test Levels. + * @tc.out: NonZero + * @tc.type: FUNC + * @tc.require: The g_serverProxy is not initialized and return SOFTBUS_NO_INIT. + */ +HWTEST_F(DiscSdkManagerTest, StopDiscoveryInnerTest001, TestSize.Level1) +{ + int32_t ret = StopDiscoveryInner(g_pkgName, g_subscribeId); + EXPECT_EQ(ret, SOFTBUS_NO_INIT); +} + +/** + * @tc.name: DiscClientOnDeviceFoundTest001 + * @tc.desc: The first call to DiscClientOnDeviceFound parameter is null, the second call g_discInfo is not + * initialized, and the third call is normal. + * @tc.in: Test Moudle, Test Number, Test Levels. + * @tc.out: NonZero + * @tc.type: FUNC + * @tc.require: Test DiscClientOnDeviceFound when g_discInfo is null and normal. + */ +HWTEST_F(DiscSdkManagerTest, DiscClientOnDeviceFoundTest001, TestSize.Level1) +{ + DeviceInfo device; + DiscClientOnDeviceFound(nullptr); + EXPECT_FALSE(g_isFound); + DiscClientOnDeviceFound(&device); + EXPECT_FALSE(g_isFound); + int32_t ret = DiscClientInit(); + EXPECT_EQ(ret, SOFTBUS_OK); + DiscServerProxyDeInit(); + ret = StartDiscoveryInner(g_pkgName, &g_subscribeInfo, &g_subscribeCb); + EXPECT_EQ(ret, SOFTBUS_NO_INIT); + DiscClientOnDeviceFound(&device); + EXPECT_TRUE(g_isFound); + DiscClientDeinit(); +} + +/** + * @tc.name: DiscClientOnDiscoverySuccessTest001 + * @tc.desc: The first call to DiscClientOnDiscoverySuccess g_discInfo is null, the second call is normal. + * @tc.in: Test Moudle, Test Number, Test Levels. + * @tc.out: NonZero + * @tc.type: FUNC + * @tc.require: Test DiscClientOnDiscoverySuccess when g_discInfo is null and normal. + */ +HWTEST_F(DiscSdkManagerTest, DiscClientOnDiscoverySuccessTest001, TestSize.Level1) +{ + DiscClientOnDiscoverySuccess(g_subscribeId); + EXPECT_FALSE(g_discSuccessFlag); + int32_t ret = DiscClientInit(); + EXPECT_EQ(ret, SOFTBUS_OK); + DiscServerProxyDeInit(); + ret = StartDiscoveryInner(g_pkgName, &g_subscribeInfo, &g_subscribeCb); + EXPECT_EQ(ret, SOFTBUS_NO_INIT); + DiscClientOnDiscoverySuccess(g_subscribeId); + EXPECT_TRUE(g_discSuccessFlag); + DiscClientDeinit(); +} + +/** + * @tc.name: DiscClientOnDiscoverFailedTest001 + * @tc.desc: The first call to DiscClientOnDiscoverFailed g_discInfo is null, the second call is normal. + * @tc.in: Test Moudle, Test Number, Test Levels. + * @tc.out: NonZero + * @tc.type: FUNC + * @tc.require: Test DiscClientOnDiscoverFailed when g_discInfo is null and normal. + */ +HWTEST_F(DiscSdkManagerTest, DiscClientOnDiscoverFailedTest001, TestSize.Level1) +{ + DiscClientOnDiscoverFailed(g_subscribeId, DISCOVERY_FAIL_REASON_NOT_SUPPORT_MEDIUM); + EXPECT_FALSE(g_discFailedFlag); + int32_t ret = DiscClientInit(); + EXPECT_EQ(ret, SOFTBUS_OK); + DiscServerProxyDeInit(); + ret = StartDiscoveryInner(g_pkgName, &g_subscribeInfo, &g_subscribeCb); + EXPECT_EQ(ret, SOFTBUS_NO_INIT); + DiscClientOnDiscoverFailed(g_subscribeId, DISCOVERY_FAIL_REASON_NOT_SUPPORT_MEDIUM); + EXPECT_TRUE(g_discFailedFlag); + DiscClientDeinit(); +} + +/** + * @tc.name: DiscClientOnPublishSuccessTest001 + * @tc.desc: The first call to DiscClientOnPublishSuccess g_discInfo is null, the second call is normal. + * @tc.in: Test Moudle, Test Number, Test Levels. + * @tc.out: NonZero + * @tc.type: FUNC + * @tc.require: Test DiscClientOnPublishSuccess when g_discInfo is null and normal. + */ +HWTEST_F(DiscSdkManagerTest, DiscClientOnPublishSuccessTest001, TestSize.Level1) +{ + DiscClientOnPublishSuccess(g_publishId); + EXPECT_FALSE(g_pubSuccessFlag); + int32_t ret = DiscClientInit(); + EXPECT_EQ(ret, SOFTBUS_OK); + DiscServerProxyDeInit(); + ret = PublishServiceInner(g_pkgName, &g_publishInfo, &g_publishCb); + EXPECT_EQ(ret, SOFTBUS_NO_INIT); + DiscClientOnPublishSuccess(g_publishId); + EXPECT_TRUE(g_pubSuccessFlag); + DiscClientDeinit(); +} + +/** + * @tc.name: DiscClientOnPublishFailTest001 + * @tc.desc: The first call to DiscClientOnPublishFail g_discInfo is null, the second call is normal. + * @tc.in: Test Moudle, Test Number, Test Levels. + * @tc.out: NonZero + * @tc.type: FUNC + * @tc.require: Test DiscClientOnPublishFail when g_discInfo is null and normal. + */ +HWTEST_F(DiscSdkManagerTest, DiscClientOnPublishFailTest001, TestSize.Level1) +{ + DiscClientOnPublishFail(g_publishId, PUBLISH_FAIL_REASON_NOT_SUPPORT_MEDIUM); + EXPECT_FALSE(g_pubFailedFlag); + int32_t ret = DiscClientInit(); + EXPECT_EQ(ret, SOFTBUS_OK); + DiscServerProxyDeInit(); + ret = PublishServiceInner(g_pkgName, &g_publishInfo, &g_publishCb); + EXPECT_EQ(ret, SOFTBUS_NO_INIT); + DiscClientOnPublishFail(g_publishId, PUBLISH_FAIL_REASON_NOT_SUPPORT_MEDIUM); + EXPECT_TRUE(g_pubFailedFlag); + DiscClientDeinit(); +} + +/** + * @tc.name: DiscServerProxyInitTest001 + * @tc.desc: Test DiscServerProxyInit again. + * @tc.in: Test Moudle, Test Number, Test Levels. + * @tc.out: NonZero + * @tc.type: FUNC + * @tc.require: The g_serverProxy is initialized and return SOFTBUS_OK. + */ +HWTEST_F(DiscSdkManagerTest, DiscServerProxyInitTest001, TestSize.Level1) +{ + int32_t ret = DiscServerProxyInit(); + EXPECT_EQ(ret, SOFTBUS_OK); + ret = DiscServerProxyInit(); + EXPECT_EQ(ret, SOFTBUS_OK); + DiscServerProxyDeInit(); +} + +/** + * @tc.name: ServerIpcPublishServiceTest001 + * @tc.desc: Test the first call to ServerIpcPublishService. + * @tc.in: Test Moudle, Test Number, Test Levels. + * @tc.out: NonZero + * @tc.type: FUNC + * @tc.require: The g_serverProxy is not initialized and return SOFTBUS_NO_INIT. + */ +HWTEST_F(DiscSdkManagerTest, ServerIpcPublishServiceTest001, TestSize.Level1) +{ + int32_t ret = ServerIpcPublishService(g_pkgName, &g_publishInfo); + EXPECT_EQ(ret, SOFTBUS_NO_INIT); +} + +/** + * @tc.name: ServerIpcUnPublishServiceTest001 + * @tc.desc: Test the first call to ServerIpcUnPublishService. + * @tc.in: Test Moudle, Test Number, Test Levels. + * @tc.out: NonZero + * @tc.type: FUNC + * @tc.require: The g_serverProxy is not initialized and return SOFTBUS_NO_INIT. + */ +HWTEST_F(DiscSdkManagerTest, ServerIpcUnPublishServiceTest001, TestSize.Level1) +{ + int32_t ret = ServerIpcUnPublishService(g_pkgName, g_publishId); + EXPECT_EQ(ret, SOFTBUS_NO_INIT); +} + +/** + * @tc.name: ServerIpcStartDiscoveryTest001 + * @tc.desc: Test the first call to ServerIpcStartDiscovery. + * @tc.in: Test Moudle, Test Number, Test Levels. + * @tc.out: NonZero + * @tc.type: FUNC + * @tc.require: The g_serverProxy is not initialized and return SOFTBUS_NO_INIT. + */ +HWTEST_F(DiscSdkManagerTest, ServerIpcStartDiscoveryTest001, TestSize.Level1) +{ + int32_t ret = ServerIpcStartDiscovery(g_pkgName, &g_subscribeInfo); + EXPECT_EQ(ret, SOFTBUS_NO_INIT); +} + +/** + * @tc.name: ServerIpcStopDiscoveryTest001 + * @tc.desc: Test the first call to ServerIpcStopDiscovery. + * @tc.in: Test Moudle, Test Number, Test Levels. + * @tc.out: NonZero + * @tc.type: FUNC + * @tc.require: The g_serverProxy is not initialized and return SOFTBUS_NO_INIT. + */ +HWTEST_F(DiscSdkManagerTest, ServerIpcStopDiscoveryTest001, TestSize.Level1) +{ + int32_t ret = ServerIpcStopDiscovery(g_pkgName, g_subscribeId); + EXPECT_EQ(ret, SOFTBUS_NO_INIT); +} +} // namespace OHOS diff --git a/tests/sdk/frame/fuzztest/softbusclientstub_fuzzer/softbusclientstub_fuzzer.cpp b/tests/sdk/frame/fuzztest/softbusclientstub_fuzzer/softbusclientstub_fuzzer.cpp index e7fd8e428..a26a94077 100644 --- a/tests/sdk/frame/fuzztest/softbusclientstub_fuzzer/softbusclientstub_fuzzer.cpp +++ b/tests/sdk/frame/fuzztest/softbusclientstub_fuzzer/softbusclientstub_fuzzer.cpp @@ -29,6 +29,29 @@ namespace OHOS { constexpr size_t FOO_MAX_LEN = 1024; constexpr size_t U32_AT_SIZE = 4; +class TestEnv { +public: + TestEnv() + { + isInited_ = false; + ClientTransChannelInit(); + isInited_ = true; + } + + ~TestEnv() + { + isInited_ = false; + ClientTransChannelDeinit(); + } + + bool IsInited(void) + { + return isInited_; + } +private: + volatile bool isInited_; +}; + enum SoftBusFuncId { CLIENT_ON_CHANNEL_OPENED = 256, CLIENT_ON_CHANNEL_OPENFAILED, @@ -47,6 +70,7 @@ enum SoftBusFuncId { CLIENT_ON_JOIN_METANODE_RESULT, CLIENT_ON_LEAVE_RESULT, CLIENT_ON_LEAVE_METANODE_RESULT, + CLIENT_ON_NODE_DEVICE_NOT_TRUST, CLIENT_ON_NODE_ONLINE_STATE_CHANGED, CLIENT_ON_NODE_BASIC_INFO_CHANGED, CLIENT_ON_LOCAL_NETWORK_ID_CHANGED, @@ -359,6 +383,22 @@ bool OnLeaveMetaNodeResultInnerTest(const uint8_t* data, size_t size) return true; } +bool OnNodeDeviceNotTrustedInnerTest(const uint8_t* data, size_t size) +{ + MessageParcel datas; + datas.WriteInterfaceToken(SOFTBUS_CLIENT_STUB_INTERFACE_TOKEN); + datas.WriteBuffer(data, size); + datas.RewindRead(0); + MessageParcel reply; + MessageOption option; + sptr softBusClientStub = new OHOS::SoftBusClientStub(); + if (softBusClientStub == nullptr) { + return false; + } + softBusClientStub->OnRemoteRequest(CLIENT_ON_NODE_DEVICE_NOT_TRUST, datas, reply, option); + return true; +} + bool OnNodeOnlineStateChangedInnerTest(const uint8_t* data, size_t size) { constexpr uint32_t infoTypeLen = 10; @@ -618,7 +658,10 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) return 0; } - ClientTransChannelInit(); + static OHOS::TestEnv env; + if (!env.IsInited()) { + return 0; + } OHOS::OnChannelOpenedInnerTest(dataWithEndCharacter, size); OHOS::OnChannelOpenFailedInnerTest(data, size); OHOS::OnChannelLinkDownInnerTest(dataWithEndCharacter, size); @@ -644,7 +687,6 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) OHOS::OnClientTransLimitChangeInnerTest(data, size); OHOS::SetChannelInfoInnerTest(dataWithEndCharacter, size); OHOS::OnChannelBindInnerTest(data, size); - ClientTransChannelDeinit(); SoftBusFree(dataWithEndCharacter); return 0; diff --git a/tests/sdk/transmission/fuzztest/clienttranschannelcallback_fuzzer/clienttranschannelcallback_fuzzer.cpp b/tests/sdk/transmission/fuzztest/clienttranschannelcallback_fuzzer/clienttranschannelcallback_fuzzer.cpp index 342b8dcc6..f241c8daa 100644 --- a/tests/sdk/transmission/fuzztest/clienttranschannelcallback_fuzzer/clienttranschannelcallback_fuzzer.cpp +++ b/tests/sdk/transmission/fuzztest/clienttranschannelcallback_fuzzer/clienttranschannelcallback_fuzzer.cpp @@ -33,6 +33,35 @@ #include "softbus_utils.h" namespace OHOS { +class TestEnv { +public: + TestEnv() + { + isInited_ = false; + IClientSessionCallBack *cb = GetClientSessionCb(); + TransTdcManagerInit(cb); + ClientTransAuthInit(cb); + ClientTransProxyInit(cb); + ClientTransUdpMgrInit(cb); + isInited_ = true; + } + + ~TestEnv() + { + isInited_ = false; + TransTdcManagerDeinit(); + ClientTransUdpMgrDeinit(); + ClientTransProxyDeinit(); + } + + bool IsInited(void) + { + return isInited_; + } +private: + volatile bool isInited_; +}; + void ClientTransChannelCallbackTest(const uint8_t *data, size_t size) { #define TEST_DATA_LENGTH 1024 @@ -80,6 +109,10 @@ void ClientTransChannelCallbackTest(const uint8_t *data, size_t size) extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { /* Run your code on data */ + static OHOS::TestEnv env; + if (!env.IsInited()) { + return 0; + } OHOS::ClientTransChannelCallbackTest(data, size); return 0; } diff --git a/tests/sdk/transmission/fuzztest/sessionmock_fuzzer/sessionmock_fuzzer.cpp b/tests/sdk/transmission/fuzztest/sessionmock_fuzzer/sessionmock_fuzzer.cpp index 7d2c6678c..f3957a318 100755 --- a/tests/sdk/transmission/fuzztest/sessionmock_fuzzer/sessionmock_fuzzer.cpp +++ b/tests/sdk/transmission/fuzztest/sessionmock_fuzzer/sessionmock_fuzzer.cpp @@ -69,7 +69,7 @@ void CloseSessionInnerTest(const uint8_t *data, size_t size) void GrantPermissionInnerTest(const uint8_t *data, size_t size) { - if (data == nullptr || size == 0) { + if (data == nullptr || size < sizeof(int32_t)) { return; } diff --git a/tests/sdk/transmission/fuzztest/transserverproxyextern_fuzzer/transserverproxyextern_fuzzer.cpp b/tests/sdk/transmission/fuzztest/transserverproxyextern_fuzzer/transserverproxyextern_fuzzer.cpp index 8fd2d446f..146fc78b6 100644 --- a/tests/sdk/transmission/fuzztest/transserverproxyextern_fuzzer/transserverproxyextern_fuzzer.cpp +++ b/tests/sdk/transmission/fuzztest/transserverproxyextern_fuzzer/transserverproxyextern_fuzzer.cpp @@ -108,10 +108,13 @@ void ServerIpcOpenAuthSessionTest(const uint8_t *data, size_t size) } char *sessionName = const_cast(reinterpret_cast(data)); - ConnectionAddr *connectionAddr = const_cast(reinterpret_cast(data)); - - (void)ServerIpcOpenAuthSession(sessionName, connectionAddr); - (void)ServerIpcOpenAuthSession(nullptr, connectionAddr); + ConnectionAddr connectionAddr; + connectionAddr.type = CONNECTION_ADDR_SESSION; + connectionAddr.info.session.sessionId = *(reinterpret_cast(data)); + connectionAddr.info.session.channelId = *(reinterpret_cast(data)); + connectionAddr.info.session.type = *(reinterpret_cast(data)); + (void)ServerIpcOpenAuthSession(sessionName, &connectionAddr); + (void)ServerIpcOpenAuthSession(nullptr, &connectionAddr); (void)ServerIpcOpenAuthSession(sessionName, nullptr); (void)ServerIpcOpenAuthSession(nullptr, nullptr); } @@ -135,6 +138,9 @@ void ServerIpcCloseChannelTest(const uint8_t *data, size_t size) void ServerIpcCloseChannelWithStatisticsTest(const uint8_t *data, size_t size) { + if (size < sizeof(uint64_t)) { + return; + } int32_t channelId = *(reinterpret_cast(data)); uint64_t laneId = *(reinterpret_cast(data)); @@ -171,18 +177,20 @@ void ServerIpcStreamStatsTest(const uint8_t *data, size_t size) { int32_t channelId = *(reinterpret_cast(data)); int32_t channelType = *(reinterpret_cast(data)); - StreamSendStats *streamSendStats = const_cast(reinterpret_cast(data)); - - (void)ServerIpcStreamStats(channelId, channelType, streamSendStats); + StreamSendStats streamSendStats; + streamSendStats.costTimeStatsCnt[FRAME_COST_LT10MS] = *(reinterpret_cast(data)); + streamSendStats.sendBitRateStatsCnt[FRAME_BIT_RATE_LT3M] = *(reinterpret_cast(data)); + (void)ServerIpcStreamStats(channelId, channelType, &streamSendStats); } void ServerIpcRippleStatsTest(const uint8_t *data, size_t size) { int32_t channelId = *(reinterpret_cast(data)); int32_t channelType = *(reinterpret_cast(data)); - TrafficStats *trafficStats = const_cast(reinterpret_cast(data)); - - (void)ServerIpcRippleStats(channelId, channelType, trafficStats); + TrafficStats trafficStats; + trafficStats.stats[0] = 't'; + trafficStats.stats[1] = 'e'; + (void)ServerIpcRippleStats(channelId, channelType, &trafficStats); } void ServerIpcGrantPermissionTest(const uint8_t *data, size_t size) diff --git a/tests/sdk/transmission/trans_channel/BUILD.gn b/tests/sdk/transmission/trans_channel/BUILD.gn index 32e849942..a9ec0d813 100644 --- a/tests/sdk/transmission/trans_channel/BUILD.gn +++ b/tests/sdk/transmission/trans_channel/BUILD.gn @@ -70,7 +70,7 @@ if (defined(ohos_lite)) { "$dsoftbus_root_path/sdk/transmission/trans_channel/udp/file/include", ] - trans_sdk_proxy_test_deps = [ "$dsoftbus_root_path/sdk:softbus_client" ] + trans_sdk_proxy_test_deps = [ "$dsoftbus_root_path/tests/sdk/frame/fuzztest/softbusclientstub_fuzzer:softbus_client_static" ] module_output_path = "dsoftbus/transmission" ohos_unittest("TransSdkStreamTest") { @@ -216,6 +216,7 @@ if (defined(ohos_lite)) { "$dsoftbus_root_path/core/frame/common/include", "$dsoftbus_root_path/core/transmission/common/include", "$dsoftbus_root_path/core/bus_center/lnn/lane_hub/lane_manager/include", + "$dsoftbus_root_path/interfaces/inner_kits/lnn", ] deps = trans_sdk_test_common_deps deps += trans_sdk_proxy_test_deps diff --git a/tests/sdk/transmission/trans_channel/udp/file/BUILD.gn b/tests/sdk/transmission/trans_channel/udp/file/BUILD.gn index 975c5a917..5b63b77cb 100644 --- a/tests/sdk/transmission/trans_channel/udp/file/BUILD.gn +++ b/tests/sdk/transmission/trans_channel/udp/file/BUILD.gn @@ -103,7 +103,7 @@ if (defined(ohos_lite)) { deps = [ "$dsoftbus_root_path/core/common:softbus_utils", "$dsoftbus_root_path/core/frame:softbus_server", - "$dsoftbus_root_path/sdk:softbus_client", + "$dsoftbus_root_path/tests/sdk/frame/fuzztest/softbusclientstub_fuzzer:softbus_client_static", ] native_source_path = rebase_path("$dsoftbus_root_path") diff --git a/tests/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/vtp_stream_socket_test/BUILD.gn b/tests/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/vtp_stream_socket_test/BUILD.gn index 34d9cf039..1b9e67d48 100644 --- a/tests/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/vtp_stream_socket_test/BUILD.gn +++ b/tests/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/vtp_stream_socket_test/BUILD.gn @@ -1,4 +1,4 @@ -# 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 @@ -38,7 +38,7 @@ ohos_unittest("VtpStreamSocketTest") { deps = [ "$dsoftbus_root_path/core/common:softbus_utils", "$dsoftbus_root_path/core/frame:softbus_server", - "$dsoftbus_root_path/sdk:softbus_client", + "$dsoftbus_root_path/tests/sdk/frame/fuzztest/softbusclientstub_fuzzer:softbus_client_static", ] native_source_path = rebase_path("$dsoftbus_root_path")