diff --git a/adapter/BUILD.gn b/adapter/BUILD.gn index fc6e5604b..43fac7fd1 100644 --- a/adapter/BUILD.gn +++ b/adapter/BUILD.gn @@ -11,20 +11,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -import( - "//foundation/communication/dsoftbus/adapter/common/net/bluetooth/net_bluetooth.gni") import("//foundation/communication/dsoftbus/dsoftbus.gni") -if (enable_connection_ble == true || enable_discovery_ble == true) { - net_bluetooth_src = adapter_ble_src - net_bluetooth_inc = adapter_ble_inc - net_bluetooth_deps = adapter_ble_deps -} else { - net_bluetooth_src = [] - net_bluetooth_inc = [] - net_bluetooth_deps = [] -} - if (defined(ohos_lite)) { import("//build/lite/config/component/lite_component.gni") if (ohos_kernel_type == "liteos_m") { @@ -53,7 +41,7 @@ if (defined(ohos_lite)) { if (ohos_kernel_type == "liteos_m") { static_library("softbus_adapter") { - include_dirs = common_include + net_bluetooth_inc + include_dirs = common_include include_dirs += [ "//kernel/liteos_m/kal/cmsis" ] if (board_name == "hispark_pegasus") { include_dirs += @@ -73,14 +61,12 @@ if (defined(ohos_lite)) { "$softbus_adapter_common/mbedtls/softbus_adapter_crypto.c", "$softbus_adapter_config/spec_config/softbus_config_adapter.c", ] - sources += net_bluetooth_src deps = [ "//base/hiviewdfx/hilog_lite/frameworks/mini:hilog_lite" ] - deps += net_bluetooth_deps public_configs = [ ":dsoftbus_adapter_common_interface" ] } } else { shared_library("softbus_adapter") { - include_dirs = common_include + net_bluetooth_inc + include_dirs = common_include cflags = [ "-Wall", "-Werror", @@ -101,14 +87,12 @@ if (defined(ohos_lite)) { "$softbus_adapter_common/mbedtls/softbus_adapter_crypto.c", "$softbus_adapter_config/spec_config/softbus_config_adapter.c", ] - sources += net_bluetooth_src deps = [ "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", "//base/startup/syspara_lite/frameworks/parameter/src:sysparam", "//third_party/bounds_checking_function:libsec_shared", ] deps += [ "//third_party/mbedtls:mbedtls_shared" ] - deps += net_bluetooth_deps public_configs = [ ":dsoftbus_adapter_common_interface" ] } } @@ -129,7 +113,6 @@ if (defined(ohos_lite)) { "//third_party/mbedtls/include", "//utils/native/base/include", ] - include_dirs += net_bluetooth_inc sources = [ "$softbus_adapter_common/bus_center/platform/bus_center_adapter.c", "$softbus_adapter_common/kernel/liteos_a/lnn_ip_utils_adapter.c", @@ -142,8 +125,6 @@ if (defined(ohos_lite)) { "$softbus_adapter_common/mbedtls/softbus_adapter_crypto.c", "$softbus_adapter_config/spec_config/softbus_config_adapter.c", ] - sources += net_bluetooth_src - deps = net_bluetooth_deps public_deps = [ "//base/startup/syspara_lite/interfaces/innerkits/native/syspara:syspara", "//third_party/bounds_checking_function:libsec_static", diff --git a/adapter/common/include/softbus_adapter_cpu.h b/adapter/common/include/softbus_adapter_cpu.h index 249892f19..a8b870a15 100644 --- a/adapter/common/include/softbus_adapter_cpu.h +++ b/adapter/common/include/softbus_adapter_cpu.h @@ -29,7 +29,11 @@ extern "C" { #define RMB() BARRIER() #elif defined __linux__ || defined __LITEOS__ || defined __APPLE__ #define DSB() __asm__ volatile("dsb" ::: "memory") +#ifdef _ARM64_ +#define DMB() __asm__ volatile("DMB ISHLD" : : : "memory") +#else #define DMB() __asm__ volatile("dmb" ::: "memory") +#endif #define ISB() __asm__ volatile("isb" ::: "memory") #define BARRIER() __asm__ volatile("" ::: "memory") diff --git a/adapter/common/net/bluetooth/ble/softbus_adapter_ble_gatt.c b/adapter/common/net/bluetooth/ble/softbus_adapter_ble_gatt.c index 3656dd590..79cab9234 100755 --- a/adapter/common/net/bluetooth/ble/softbus_adapter_ble_gatt.c +++ b/adapter/common/net/bluetooth/ble/softbus_adapter_ble_gatt.c @@ -15,6 +15,7 @@ #include "softbus_adapter_ble_gatt.h" #include +#include "adapter_bt_utils.h" #include "ohos_bt_def.h" #include "ohos_bt_gap.h" #include "ohos_bt_gatt.h" diff --git a/adapter/common/net/bluetooth/ble/softbus_adapter_ble_gatt_client.c b/adapter/common/net/bluetooth/ble/softbus_adapter_ble_gatt_client.c new file mode 100644 index 000000000..3ece00c9f --- /dev/null +++ b/adapter/common/net/bluetooth/ble/softbus_adapter_ble_gatt_client.c @@ -0,0 +1,259 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "softbus_adapter_ble_gatt_client.h" + +#include +#include "securec.h" +#include "softbus_def.h" +#include "softbus_errcode.h" +#include "softbus_log.h" +#include "softbus_type_def.h" + +#include "ohos_bt_def.h" +#include "ohos_bt_gatt_client.h" + +#define APP_UUID_LEN 2 +#define INVALID_ID (-1) + +static BtGattClientCallbacks g_btGattClientCallbacks = { 0 }; +static SoftBusGattcCallback *g_softBusGattcCallback = NULL; + +static void GattcConnectionStateChangedCallback(int clientId, int connectionState, int status) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "StateChangedCallback id=%d,state=%d,status=%d", + clientId, connectionState, status); + if (connectionState != OHOS_STATE_CONNECTED && connectionState != OHOS_STATE_DISCONNECTED) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "GattcConnectionStateChangedCallback ignore"); + return; + } + g_softBusGattcCallback->ConnectionStateCallback(clientId, connectionState, status); +} + +static void GattcConnectParaUpdateCallback(int clientId, int interval, int latency, int timeout, int status) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ParaUpdateCallback"); +} + +static void GattcSearchServiceCompleteCallback(int clientId, int status) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "SearchServiceCompleteCallback, id=%d,status=%d", + clientId, status); + g_softBusGattcCallback->ServiceCompleteCallback(clientId, status); +} + +static void GattcReadCharacteristicCallback(int clientId, BtGattReadData *readData, int status) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ReadCharacteristicCallback,id=%d,status=%d", + clientId, status); +} + +static void GattcWriteCharacteristicCallback(int clientId, BtGattCharacteristic *characteristic, int status) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "WriteCharacteristicCallback, id=%d,status=%d", + clientId, status); +} + +static void GattcReadDescriptorCallback(int clientId, BtGattReadData *readData, int status) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ReadDescriptorCallback,id=%d,status=%d", clientId, status); +} + +static void GattcWriteDescriptorCallback(int clientId, BtGattDescriptor *descriptor, int status) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "WriteDescriptorCallback,id=%d,status=%d", clientId, status); +} + +static void GattcConfigureMtuSizeCallback(int clientId, int mtuSize, int status) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ConfigureMtuSizeCallback,id=%d,mtusize=%d,status=%d", + clientId, mtuSize, status); + g_softBusGattcCallback->ConfigureMtuSizeCallback(clientId, mtuSize, status); +} + +static void GattcRegisterNotificationCallback(int clientId, int status) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "RegisterNotificationCallback,id=%d,status=%d", clientId, status); + g_softBusGattcCallback->RegistNotificationCallback(clientId, status); +} + +static void GattcNotificationCallback(int clientId, BtGattReadData *notifyData, int status) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "GattcNotificationCallback,id=%d,status=%d", clientId, status); + SoftBusGattcNotify notify; + notify.dataLen = notifyData->dataLen; + notify.charaUuid.uuidLen = notifyData->attribute.characteristic.characteristicUuid.uuidLen; + notify.data = notifyData->data; + notify.charaUuid.uuid = notifyData->attribute.characteristic.characteristicUuid.uuid; + + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "GattcNotificationCallback,id=%d,status=%d", clientId, status); + g_softBusGattcCallback->NotificationReceiveCallback(clientId, ¬ify, status); +} + + +void SoftbusGattcRegisterCallback(SoftBusGattcCallback *cb) +{ + g_btGattClientCallbacks.ConnectionStateCb = GattcConnectionStateChangedCallback; + g_btGattClientCallbacks.connectParaUpdateCb = GattcConnectParaUpdateCallback; + g_btGattClientCallbacks.searchServiceCompleteCb = GattcSearchServiceCompleteCallback; + g_btGattClientCallbacks.readCharacteristicCb = GattcReadCharacteristicCallback; + g_btGattClientCallbacks.writeCharacteristicCb = GattcWriteCharacteristicCallback; + g_btGattClientCallbacks.readDescriptorCb = GattcReadDescriptorCallback; + g_btGattClientCallbacks.writeDescriptorCb = GattcWriteDescriptorCallback; + g_btGattClientCallbacks.configureMtuSizeCb = GattcConfigureMtuSizeCallback; + g_btGattClientCallbacks.registerNotificationCb = GattcRegisterNotificationCallback; + g_btGattClientCallbacks.notificationCb = GattcNotificationCallback; + g_softBusGattcCallback = cb; +} +int32_t SoftbusGattcRegister(void) +{ + BtUuid appId; + char uuid[APP_UUID_LEN] = {0xEE, 0xFD}; + appId.uuid = uuid; + appId.uuidLen = APP_UUID_LEN; + int32_t clientId = BleGattcRegister(appId); + if (clientId <= 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleGattcRegister error"); + return INVALID_ID; + } + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleGattcRegister %d", clientId); + return clientId; +} + +int32_t SoftbusGattcUnRegister(int32_t clientId) +{ + if (clientId <= 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftbusGattcUnRegister invalid param"); + return SOFTBUS_INVALID_PARAM; + } + + if (BleGattcUnRegister(clientId) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleGattcUnRegister error"); + return SOFTBUS_GATTC_INTERFACE_FAILED; + } + return SOFTBUS_OK; +} + +int32_t SoftbusGattcConnect(int32_t clientId, SoftBusBtAddr *addr) +{ + if (clientId <= 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftbusGattcConnect invalid param"); + return SOFTBUS_INVALID_PARAM; + } + BdAddr bdAddr; + if (memcpy_s(bdAddr.addr, OHOS_BD_ADDR_LEN, addr->addr, BT_ADDR_LEN) != EOK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftbusGattcConnect memcpy error"); + return SOFTBUS_INVALID_PARAM; + } + if (BleGattcConnect(clientId, &g_btGattClientCallbacks, &bdAddr, false, OHOS_BT_TRANSPORT_TYPE_LE) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleGattcConnect error"); + return SOFTBUS_GATTC_INTERFACE_FAILED; + } + return SOFTBUS_OK; +} + +int32_t SoftbusBleGattcDisconnect(int32_t clientId) +{ + if (clientId <= 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftbusBleGattcDisconnect invalid param"); + return SOFTBUS_INVALID_PARAM; + } + if (BleGattcDisconnect(clientId) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleGattcDisconnect error"); + return SOFTBUS_GATTC_INTERFACE_FAILED; + } + return SOFTBUS_OK; +} + +int32_t SoftbusGattcSearchServices(int32_t clientId) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftbusGattcSearchServices %d", clientId); + if (clientId <= 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftbusGattcSearchServices invalid param"); + return SOFTBUS_INVALID_PARAM; + } + int32_t ret = BleGattcSearchServices(clientId); + if (ret != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleGattcSearchServices error, ret = %d", ret); + return SOFTBUS_GATTC_INTERFACE_FAILED; + } + return SOFTBUS_OK; +} + +int32_t SoftbusGattcGetService(int32_t clientId, SoftBusBtUuid *serverUuid) +{ + if (clientId <= 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftbusGattcGetService invalid param"); + return SOFTBUS_INVALID_PARAM; + } + BtUuid btUuid; + btUuid.uuid = serverUuid->uuid; + btUuid.uuidLen = serverUuid->uuidLen; + if (BleGattcGetService(clientId, btUuid) == false) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleGattcGetService error"); + return SOFTBUS_GATTC_INTERFACE_FAILED; + } + return SOFTBUS_OK; +} + +int32_t SoftbusGattcRegisterNotification(int32_t clientId, SoftBusBtUuid *serverUuid, SoftBusBtUuid *charaUuid) +{ + if (clientId <= 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftbusGattcRegisterNotification invalid param"); + return SOFTBUS_INVALID_PARAM; + } + BtGattCharacteristic btCharaUuid; + btCharaUuid.serviceUuid.uuid = serverUuid->uuid; + btCharaUuid.serviceUuid.uuidLen = serverUuid->uuidLen; + btCharaUuid.characteristicUuid.uuid = charaUuid->uuid; + btCharaUuid.characteristicUuid.uuidLen = charaUuid->uuidLen; + if (BleGattcRegisterNotification(clientId, btCharaUuid, true) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleGattcRegisterNotification error"); + return SOFTBUS_GATTC_INTERFACE_FAILED; + } + return SOFTBUS_OK; +} + +int32_t SoftbusGattcConfigureMtuSize(int32_t clientId, int mtuSize) +{ + if (clientId <= 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftbusGattcConfigureMtuSize invalid param"); + return SOFTBUS_INVALID_PARAM; + } + if (BleGattcConfigureMtuSize(clientId, mtuSize) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleGattcConfigureMtuSize error"); + return SOFTBUS_GATTC_INTERFACE_FAILED; + } + return SOFTBUS_OK; +} + +int32_t SoftbusGattcWriteCharacteristic(int32_t clientId, SoftBusGattcData *clientData) +{ + if (clientId <= 0 || clientData == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftbusGattcWriteCharacteristic invalid param"); + return SOFTBUS_INVALID_PARAM; + } + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftbusGattcRegisterNotification clientId = %d", clientId); + BtGattCharacteristic characteristic; + characteristic.serviceUuid.uuid = clientData->serviceUuid.uuid; + characteristic.serviceUuid.uuidLen = clientData->serviceUuid.uuidLen; + characteristic.characteristicUuid.uuid = clientData->characterUuid.uuid; + characteristic.characteristicUuid.uuidLen = clientData->characterUuid.uuidLen; + if (BleGattcWriteCharacteristic(clientId, characteristic, OHOS_GATT_WRITE_NO_RSP, + clientData->valueLen, clientData->value) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftbusGattcWriteCharacteristic error"); + return SOFTBUS_GATTC_INTERFACE_FAILED; + } + return SOFTBUS_OK; +} \ No newline at end of file diff --git a/adapter/common/net/bluetooth/common/softbus_adapter_bt_common.c b/adapter/common/net/bluetooth/common/softbus_adapter_bt_common.c index 26e7af857..6e507ad37 100755 --- a/adapter/common/net/bluetooth/common/softbus_adapter_bt_common.c +++ b/adapter/common/net/bluetooth/common/softbus_adapter_bt_common.c @@ -26,7 +26,7 @@ #include "softbus_errcode.h" #include "softbus_log.h" -#define STATE_LISTENER_MAX_NUM 2 +#define STATE_LISTENER_MAX_NUM 3 typedef struct { bool isUsed; diff --git a/adapter/common/net/bluetooth/common/adapter_bt_utils.h b/adapter/common/net/bluetooth/include/adapter_bt_utils.h old mode 100755 new mode 100644 similarity index 96% rename from adapter/common/net/bluetooth/common/adapter_bt_utils.h rename to adapter/common/net/bluetooth/include/adapter_bt_utils.h index 5a61cfe9a..8bf09004a --- a/adapter/common/net/bluetooth/common/adapter_bt_utils.h +++ b/adapter/common/net/bluetooth/include/adapter_bt_utils.h @@ -1,27 +1,27 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef ADAPTER_BT_UTILS_H -#define ADAPTER_BT_UTILS_H - -#include "ohos_bt_def.h" -#include "ohos_bt_gap.h" -#include "ohos_bt_gatt.h" -#include "softbus_adapter_ble_gatt.h" -#include "softbus_adapter_bt_common.h" - -int BleOhosStatusToSoftBus(BtStatus status); - +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ADAPTER_BT_UTILS_H +#define ADAPTER_BT_UTILS_H + +#include "ohos_bt_def.h" +#include "ohos_bt_gap.h" +#include "ohos_bt_gatt.h" +#include "softbus_adapter_ble_gatt.h" +#include "softbus_adapter_bt_common.h" + +int BleOhosStatusToSoftBus(BtStatus status); + #endif \ No newline at end of file diff --git a/adapter/common/net/bluetooth/include/softbus_adapter_ble_gatt.h b/adapter/common/net/bluetooth/include/softbus_adapter_ble_gatt.h index f9913db88..c248cb1a6 100755 --- a/adapter/common/net/bluetooth/include/softbus_adapter_ble_gatt.h +++ b/adapter/common/net/bluetooth/include/softbus_adapter_ble_gatt.h @@ -110,7 +110,7 @@ typedef struct { typedef struct { void (*OnScanStart)(int listenerId, int status); void (*OnScanStop)(int listenerId, int status); - void (*OnScanResult)(int listenerId, SoftBusBleScanResult *scanResultdata); + void (*OnScanResult)(int listenerId, const SoftBusBleScanResult *scanResultdata); } SoftBusScanListener; typedef struct { diff --git a/adapter/common/net/bluetooth/include/softbus_adapter_ble_gatt_client.h b/adapter/common/net/bluetooth/include/softbus_adapter_ble_gatt_client.h new file mode 100644 index 000000000..28aba6d1d --- /dev/null +++ b/adapter/common/net/bluetooth/include/softbus_adapter_ble_gatt_client.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SOFTBUS_ADAPTER_BLE_GATT_CLIENT_H +#define SOFTBUS_ADAPTER_BLE_GATT_CLIENT_H + +#include "stdbool.h" +#include "stdint.h" +#include "softbus_adapter_bt_common.h" + +typedef struct { + SoftBusBtUuid charaUuid; + uint16_t dataLen; + uint8_t *data; +} SoftBusGattcNotify; + +typedef struct { + SoftBusBtUuid serviceUuid; + SoftBusBtUuid characterUuid; + int32_t valueLen; + char *value; +} SoftBusGattcData; + +typedef struct { + void (*ConnectionStateCallback)(int32_t clientId, int32_t connState, int32_t status); + void (*ServiceCompleteCallback)(int32_t clientId, int32_t status); + void (*RegistNotificationCallback)(int32_t clientId, int status); + void (*NotificationReceiveCallback)(int32_t clientId, SoftBusGattcNotify *param, int32_t status); + void (*ConfigureMtuSizeCallback)(int clientId, int mtuSize, int status); +} SoftBusGattcCallback; + +void SoftbusGattcRegisterCallback(SoftBusGattcCallback *cb); +int32_t SoftbusGattcRegister(void); +int32_t SoftbusGattcUnRegister(int32_t clientId); +int32_t SoftbusGattcConnect(int32_t clientId, SoftBusBtAddr *addr); +int32_t SoftbusBleGattcDisconnect(int32_t clientId); +int32_t SoftbusGattcSearchServices(int32_t clientId); +int32_t SoftbusGattcGetService(int32_t clientId, SoftBusBtUuid *serverUuid); +int32_t SoftbusGattcRegisterNotification(int32_t clientId, SoftBusBtUuid *serverUuid, SoftBusBtUuid *charaUuid); +int32_t SoftbusGattcWriteCharacteristic(int32_t clientId, SoftBusGattcData *clientData); +int32_t SoftbusGattcConfigureMtuSize(int32_t clientId, int mtuSize); + +#endif /* SOFTBUS_ADAPTER_BLE_GATT_CLIENT_H */ diff --git a/adapter/common/net/bluetooth/include/softbus_adapter_bt_common.h b/adapter/common/net/bluetooth/include/softbus_adapter_bt_common.h index 6e5d65141..eea986e29 100644 --- a/adapter/common/net/bluetooth/include/softbus_adapter_bt_common.h +++ b/adapter/common/net/bluetooth/include/softbus_adapter_bt_common.h @@ -58,6 +58,11 @@ typedef struct { char *uuid; } SoftBusBtUuid; +typedef enum { + SOFTBUS_BT_CONNECT = 0x01, + SOFTBUS_BT_DISCONNECT = 0x03 +} SoftBusBtConnectState; + typedef struct { void (*OnBtStateChanged)(int listenerId, int state); } SoftBusBtStateListener; diff --git a/adapter/common/net/bluetooth/net_bluetooth.gni b/adapter/common/net/bluetooth/net_bluetooth.gni index 0a4fa3c87..33589fa6b 100755 --- a/adapter/common/net/bluetooth/net_bluetooth.gni +++ b/adapter/common/net/bluetooth/net_bluetooth.gni @@ -21,8 +21,10 @@ adapter_ble_inc = [ ] adapter_ble_src = [ "$dsoftbus_root_path/adapter/common/net/bluetooth/ble/softbus_adapter_ble_gatt.c", + "$dsoftbus_root_path/adapter/common/net/bluetooth/ble/softbus_adapter_ble_gatt_client.c", "$dsoftbus_root_path/adapter/common/net/bluetooth/ble/softbus_adapter_ble_gatt_server.c", "$dsoftbus_root_path/adapter/common/net/bluetooth/common/adapter_bt_utils.c", "$dsoftbus_root_path/adapter/common/net/bluetooth/common/softbus_adapter_bt_common.c", ] +adapter_net_br_src = [ "$dsoftbus_root_path/adapter/common/net/bluetooth/common/softbus_adapter_bt_common.c" ] adapter_ble_deps = [ "//foundation/communication/bluetooth/interfaces/innerkits/native_cpp/framework:btframework" ] diff --git a/adapter/default_config/spec_config/softbus_config_type.h b/adapter/default_config/spec_config/softbus_config_type.h index ba84bc2d1..e07394583 100644 --- a/adapter/default_config/spec_config/softbus_config_type.h +++ b/adapter/default_config/spec_config/softbus_config_type.h @@ -44,6 +44,8 @@ typedef enum { SOFTBUS_INT_LNN_UDID_INIT_DELAY_LEN, /* the default val is 0 */ SOFTBUS_STR_LNN_NET_IF_NAME, /* the default val is 0:eth0,1:wlan0 */ SOFTBUS_INT_LNN_MAX_CONCURENT_NUM, /* the default val is 0 */ + SOFTBUS_INT_AUTH_MAX_BYTES_LENGTH, /* L1: 4K, L2: 64K */ + SOFTBUS_INT_AUTH_MAX_MESSAGE_LENGTH, /* L1: 1K, L2: 4K */ SOFTBUS_CONFIG_TYPE_MAX, } ConfigType; diff --git a/core/adapter/br/include/wrapper_br_interface.h b/core/adapter/br/include/wrapper_br_interface.h index f0d05f30f..877059f0a 100644 --- a/core/adapter/br/include/wrapper_br_interface.h +++ b/core/adapter/br/include/wrapper_br_interface.h @@ -16,8 +16,10 @@ #ifndef WRAPPER_BR_INTERFACE_H #define WRAPPER_BR_INTERFACE_H +#include #include -#include "ohos_types.h" + +#include "softbus_adapter_bt_common.h" #ifdef __cplusplus extern "C" { @@ -30,18 +32,8 @@ extern "C" { typedef uint8_t BT_UUIDL[BT_UUID_LEN]; typedef uint8_t BT_ADDR[BT_ADDR_LEN]; -enum SppEventType { - SPP_EVENT_TYPE_ACCEPT = 1, - SPP_EVENT_TYPE_DISCONNECTED, - SPP_EVENT_TYPE_CONNECTED, - SPP_EVENT_TYPE_CONGEST -}; - -typedef struct { - // 0:read, 1:accept, 2:disconnected, 3:congest, 4:connteced - void (*OnEvent)(int32_t type, int32_t socketFd, int32_t value); - void (*OnDataReceived)(int32_t socketFd, const char* buf, int32_t len); -} SppSocketEventCallback; +#define BR_READ_SOCKET_CLOSED 0 +#define BR_READ_FAILED -1 typedef struct { BT_UUIDL uuid; @@ -51,18 +43,19 @@ typedef struct { typedef struct tagSppSocketDriver { void (*Init)(const struct tagSppSocketDriver* this_p); - int32_t (*OpenSppServer)(const BT_ADDR mac, const BT_UUIDL uuid, int32_t isSecure); - int32_t (*OpenSppClient)(const BT_ADDR mac, const BT_UUIDL uuid, int32_t isSecure); - int32_t (*CloseClient)(int32_t clientFd); - void (*CloseServer)(int32_t serverFd); - int32_t (*Connect)(int32_t clientFd, const SppSocketEventCallback* callback); - int32_t (*GetRemoteDeviceInfo)(int32_t clientFd, const BluetoothRemoteDevice* device); - int32_t (*IsConnected)(int32_t clientFd); - int32_t (*Accept)(int32_t serverFd, const SppSocketEventCallback* callback); + int32_t (*OpenSppServer)(const char *name, int32_t nameLen, const char *uuid, int32_t isSecure); + void (*CloseSppServer)(int32_t serverFd); + int32_t (*Connect)(const char *uuid, const BT_ADDR mac); + int32_t (*DisConnect)(int32_t clientFd); + bool (*IsConnected)(int32_t clientFd); + int32_t (*Accept)(int32_t serverFd); int32_t (*Write)(int32_t clientFd, const char* buf, const int32_t length); + int32_t (*Read)(int32_t clientFd, char* buf, const int32_t length); + int32_t (*GetRemoteDeviceInfo)(int32_t clientFd, const BluetoothRemoteDevice* device); } SppSocketDriver; SppSocketDriver* InitSppSocketDriver(); +int32_t SppGattsRegisterHalCallback(const SoftBusBtStateListener *lister); #ifdef __cplusplus } diff --git a/core/adapter/br/mock/wrapper_br_interface.c b/core/adapter/br/mock/wrapper_br_interface.c index d73e39f58..3cb7c1cdd 100644 --- a/core/adapter/br/mock/wrapper_br_interface.c +++ b/core/adapter/br/mock/wrapper_br_interface.c @@ -14,137 +14,144 @@ */ #include "wrapper_br_interface.h" -#include "bt_rfcom.h" #include "message_handler.h" +#include "ohos_bt_def.h" +#include "ohos_bt_gap.h" +#include "ohos_bt_spp.h" +#include "securec.h" +#include "softbus_adapter_mem.h" +#include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_log.h" +#include "string.h" -static SppSocketEventCallback *g_connectCallback = NULL; -static SppSocketEventCallback *g_connectServiceCallback = NULL; - -static void OnEventRfcom(uint8 type, uint8 handle, int value) -{ - g_connectCallback->OnEvent((int32_t)type, (int32_t)handle, value); -} - -static void OnDataReceivedRfcom(uint8 handle, const uint8 *buf, uint16 len) -{ - g_connectCallback->OnDataReceived((int32_t)handle, (char*)buf, (int32_t)len); -} - -static BtRfcomEventCallback g_rfcomEventcb = { - .OnEvent = OnEventRfcom, - .OnDataReceived = OnDataReceivedRfcom -}; - -static void OnEventServiceRfcom(uint8 type, uint8 handle, int value) -{ - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_INFO, - "[Client event call back form bt, and socketid = %u, tpye = %u]", handle, type); - if (g_connectServiceCallback == NULL) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_INFO, "[g_connectServiceCallback is NULL]"); - return; - } - g_connectServiceCallback->OnEvent((int32_t)type, (int32_t)handle, value); -} - -static void OnDataReceivedServiceRfcom(uint8 handle, const uint8 *buf, uint16 len) -{ - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_INFO, - "[Client received call back form bt, and socketid = %u, len = %u]", handle, len); - if (g_connectServiceCallback == NULL) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_INFO, "[g_connectServiceCallback is NULL]"); - return; - } - g_connectServiceCallback->OnDataReceived((int32_t)handle, (char*)buf, (int32_t)len); -} - -static BtRfcomEventCallback g_rfcomServiceEventcb = { - .OnEvent = OnEventServiceRfcom, - .OnDataReceived = OnDataReceivedServiceRfcom -}; - -static int32_t Connect(int32_t clientFd, const SppSocketEventCallback *callback) -{ - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_INFO, "[mock clientFd = %d]", clientFd); - g_connectCallback = (SppSocketEventCallback*)callback; - int ret = BtRfcomClientConnect((uint8)clientFd, &g_rfcomEventcb); - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_INFO, "[BtRfcom return = %d]", ret); - ret = (ret == BT_RFCOM_STATUS_OK) ? SOFTBUS_OK : SOFTBUS_ERR; - return ret; -} +#define IS_BR_ENCRYPT true static void Init(const struct tagSppSocketDriver *sppDriver) { (void)sppDriver; } -static int32_t OpenSppServer(const BT_ADDR mac, const BT_UUIDL uuid, int32_t isSecure) +static int32_t OpenSppServer(const char *name, int32_t nameLen, const char *uuid, int32_t isSecure) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_INFO, "[OpenSppServer connect]"); - return SOFTBUS_ERR; + if (name == NULL || nameLen <= 0) { + SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "OpenSppServer invalid param"); + return SOFTBUS_ERR; + } + (void)isSecure; + + BtCreateSocketPara socketPara; + (void)memset_s((char *)&socketPara, sizeof(socketPara), 0, sizeof(socketPara)); + socketPara.uuid.uuid = (char *)uuid; + socketPara.uuid.uuidLen = strlen(uuid); + socketPara.socketType = OHOS_SPP_SOCKET_RFCOMM; + socketPara.isEncrypt = IS_BR_ENCRYPT; + return SppServerCreate(&socketPara, name, nameLen); } -static int32_t OpenSppClient(const BT_ADDR mac, const BT_UUIDL uuid, int32_t isSecure) +static void CloseSppServer(int32_t serverFd) { - (void)isSecure; - int ret = BtRfcomClientCreate(mac, uuid); - if (ret == BT_RFCOM_CLIENT_INVALID_HANDLE) { + SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_INFO, "[CloseServer Connect, and serverFd = %d]", serverFd); + SppServerClose(serverFd); +} + +static int32_t Connect(const char *uuid, const BT_ADDR mac) +{ + if (mac == NULL) { + return SOFTBUS_ERR; + } + BtCreateSocketPara socketPara; + (void)memset_s((char *)&socketPara, sizeof(socketPara), 0, sizeof(socketPara)); + socketPara.uuid.uuid = (char *)uuid; + socketPara.uuid.uuidLen = strlen(uuid); + socketPara.socketType = OHOS_SPP_SOCKET_RFCOMM; + socketPara.isEncrypt = IS_BR_ENCRYPT; + + BdAddr bdAddr; + (void)memset_s((char *)&bdAddr, sizeof(bdAddr), 0, sizeof(bdAddr)); + if (memcpy_s((char *)bdAddr.addr, OHOS_BD_ADDR_LEN, mac, BT_ADDR_LEN) != EOK) { + SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "Connect memcpy_s failed"); + return SOFTBUS_ERR; + } + int ret = SppConnect(&socketPara, &bdAddr); + if (ret == BT_SPP_INVALID_ID) { + SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "[BT_SPP_INVALID_ID]"); + return SOFTBUS_ERR; + } + SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "SppConnect ok clientId: %d", ret); + return ret; +} + +static int32_t DisConnect(int32_t clientFd) +{ + SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_INFO, "[DisConnect, and clientFd = %d]", clientFd); + return SppDisconnect(clientFd); +} + +static bool IsConnected(int32_t clientFd) +{ + SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_INFO, "[get connected state from bt, clientFd = %d]", clientFd); + return IsSppConnected(clientFd); +} + +static int32_t Accept(int32_t serverFd) +{ + SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_INFO, "[Accept remote device to connect, and serverFd = %d]", serverFd); + int32_t ret = SppServerAccept(serverFd); + if (ret == BT_SPP_INVALID_ID) { return SOFTBUS_ERR; } return ret; } -static int32_t CloseClient(int32_t clientFd) +static int32_t Write(int32_t clientFd, const char *buf, const int32_t len) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_INFO, "[CloseClient connect, and serverFd = %d]", clientFd); - return BtRfcomClientDisconnect((uint8)clientFd); + return SppWrite(clientFd, buf, len); } -static void CloseServer(int32_t serverFd) +static int32_t Read(int32_t clientFd, char *buf, const int32_t len) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_INFO, "[CloseServer Connect, and serverFd = %d]", serverFd); + int32_t ret = SppRead(clientFd, buf, len); + if (ret == BT_SPP_READ_SOCKET_CLOSED) { + return BR_READ_SOCKET_CLOSED; + } else if (ret == BT_SPP_READ_FAILED) { + return BR_READ_FAILED; + } + return ret; } - static int32_t GetRemoteDeviceInfo(int32_t clientFd, const BluetoothRemoteDevice *device) { SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_INFO, "[to get remotedeviceinfo, clientFd = %d]", clientFd); - return 0; -} + BdAddr bdAddr; + (void)memset_s((char *)&bdAddr, sizeof(bdAddr), 0, sizeof(bdAddr)); + (void)SppGetRemoteAddr(clientFd, &bdAddr); + if (memcpy_s((char *)device->mac, BT_ADDR_LEN, (char *)bdAddr.addr, OHOS_BD_ADDR_LEN) != EOK) { + SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "GetRemoteDeviceInfo memcpy_s failed"); + return SOFTBUS_ERR; + } -static int32_t IsConnected(int32_t clientFd) -{ - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_INFO, "[to get connected state from bt, clientFd = %d]", clientFd); - return true; -} - -static int32_t Accept(int32_t serverFd, const SppSocketEventCallback *callback) -{ - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_INFO, "[Accept remote device to connect, and serverFd = %d]", serverFd); - g_connectServiceCallback = (SppSocketEventCallback*)callback; - return 0; -} - -static int32_t Write(int32_t g_clientFd, const char *buf, const int32_t length) -{ - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_INFO, "[mock Write] g_clientFd=%d,len=%d", g_clientFd, length); - return BtRfcomClientWrite((uint8)g_clientFd, (uint8 *)buf, (uint16)length); + return SOFTBUS_OK; } static SppSocketDriver g_sppSocketDriver = { .Init = Init, .OpenSppServer = OpenSppServer, - .OpenSppClient = OpenSppClient, - .CloseClient = CloseClient, - .CloseServer = CloseServer, + .CloseSppServer = CloseSppServer, .Connect = Connect, - .GetRemoteDeviceInfo = GetRemoteDeviceInfo, + .DisConnect = DisConnect, .IsConnected = IsConnected, .Accept = Accept, - .Write = Write + .Write = Write, + .Read = Read, + .GetRemoteDeviceInfo = GetRemoteDeviceInfo }; +int32_t SppGattsRegisterHalCallback(const SoftBusBtStateListener *lister) +{ + return SoftBusAddBtStateListener(lister); +} + SppSocketDriver *InitSppSocketDriver() { SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_INFO, "[InitSppSocketDriver]"); diff --git a/core/adapter/core_adapter.gni b/core/adapter/core_adapter.gni index 2ebe0f776..8f66aa409 100644 --- a/core/adapter/core_adapter.gni +++ b/core/adapter/core_adapter.gni @@ -10,8 +10,14 @@ # 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( + "//foundation/communication/dsoftbus/adapter/common/net/bluetooth/net_bluetooth.gni") import("//foundation/communication/dsoftbus/dsoftbus.gni") + br_adapter_src = [ "$dsoftbus_root_path/core/adapter/br/mock/wrapper_br_interface.c" ] -br_adapter_inc = [ "$dsoftbus_root_path/core/adapter/br/include" ] +br_adapter_inc = [ + "$dsoftbus_root_path/core/adapter/br/include", + "//foundation/communication/bluetooth/interfaces/innerkits/native_c/include", +] diff --git a/core/common/BUILD.gn b/core/common/BUILD.gn index 81a9f7bb4..456337fb4 100644 --- a/core/common/BUILD.gn +++ b/core/common/BUILD.gn @@ -18,6 +18,7 @@ import( import("//foundation/communication/dsoftbus/dsoftbus.gni") common_utils_src = [ + "bitmap/softbus_bitmap.c", "network/softbus_network_utils.c", "json_utils/softbus_json_utils.c", "log/softbus_log.c", diff --git a/core/common/bitmap/softbus_bitmap.c b/core/common/bitmap/softbus_bitmap.c new file mode 100644 index 000000000..63ec8c36b --- /dev/null +++ b/core/common/bitmap/softbus_bitmap.c @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "softbus_bitmap.h" +#include + +#define UINT32_BITNUM 32 + +void SoftbusBitmapSet(uint32_t *bitmap, const uint8_t pos) +{ + if (bitmap == NULL || pos >= UINT32_BITNUM) { + return; + } + *bitmap |= 1U << pos; +} + +void SoftbusBitmapClr(uint32_t *bitmap, const uint8_t pos) +{ + if (bitmap == NULL || pos >= UINT32_BITNUM) { + return; + } + *bitmap &= ~(1U << pos); +} + +void SoftbusBitmapSetBits(uint32_t *bitmap, const uint8_t start, const uint8_t nums) +{ + if (bitmap == NULL || (start + nums) > UINT32_BITNUM || start < 0 || nums < 0) { + return; + } + *bitmap |= (UINT32_MAX - ((((1U << ((start + nums - 1U))) - 1U)) & (~((1U << ((start - 1U))) - 1U)))); +} + +void SoftbusBitmapClrBits(uint32_t *bitmap, const uint8_t start, const uint8_t nums) +{ + if (bitmap == NULL || (start + nums) > UINT32_BITNUM || start < 0 || nums < 0) { + return; + } + *bitmap &= ((((1U << ((start + nums - 1U))) - 1U)) & (~((1U << ((start - 1U))) - 1U))); +} + +uint8_t SoftbusLowBitGet(uint32_t bitmap) +{ + uint8_t pos = 0; + while (bitmap > 0) { + pos++; + if (bitmap & 0X1) { + return pos; + } + bitmap = bitmap >> 1; + } + return 0; +} + +uint8_t SoftbusHighBitGet(uint32_t bitmap) +{ + uint8_t pos = 0; + while (bitmap > 0) { + bitmap = bitmap >> 1U; + pos++; + } + return pos; +} + +bool SoftbusIsBitmapSet(const uint32_t *bitmap, const uint8_t pos) +{ + if (bitmap == NULL || pos >= UINT32_BITNUM) { + return false; + } + bool flag = ((1U << pos) & (*bitmap)) ? true : false; + return flag; +} \ No newline at end of file diff --git a/core/common/include/softbus_bitmap.h b/core/common/include/softbus_bitmap.h new file mode 100644 index 000000000..daad5c4ef --- /dev/null +++ b/core/common/include/softbus_bitmap.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef SOFTBUS_BITMAP_H +#define SOFTBUS_BITMAP_H + +#include +#include + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + + +#define DATA_ONE(y) (1 + ((y) - (y))) +#define SOFTBUS_BIT(n) (1U << (n)) +#define SOFTBUS_BITGET(x, bit) ((x) & (DATA_ONE(x) << (bit))) +#define SOFTBUS_BITSHIFT (x, bit) (((x) >> (bit)) & 1) +#define SOFTBUS_BITSGET(x, high, low) ((x) & (((DATA_ONE(x) << ((high) + 1)) - 1) & ~((DATA_ONE(x) << (low)) - 1))) +#define SOFTBUS_BITSSHIFT(x, high, low) (((x) >> (low)) & ((DATA_ONE(x) << ((high) - (low) + 1)) - 1)) +#define SOFTBUS_BITISSET (x, bit) (((x) & (DATA_ONE(x) << (bit))) ? 1 : 0) + +void SoftbusBitmapSet(uint32_t *bitmap, const uint8_t pos); +void SoftbusBitmapClr(uint32_t *bitmap, const uint8_t pos); +void SoftbusBitmapSetBits(uint32_t *bitmap, const uint8_t start, const uint8_t nums); +void SoftbusBitmapClrBits(uint32_t *bitmap, const uint8_t start, const uint8_t nums); +uint8_t SoftbusLowBitGet(uint32_t bitmap); +uint8_t SoftbusHighBitGet(uint32_t bitmap); +bool SoftbusIsBitmapSet(const uint32_t *bitMap, const uint8_t pos); + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ +#endif /* SOFTBUS_BITMAP_H */ \ No newline at end of file diff --git a/core/common/include/softbus_errcode.h b/core/common/include/softbus_errcode.h index 6ededaa99..ef1428c66 100644 --- a/core/common/include/softbus_errcode.h +++ b/core/common/include/softbus_errcode.h @@ -122,6 +122,12 @@ enum SoftBusErrNo { SOFTBUS_BLECONNECTION_MTU_OVERFLOW_ERROR, SOFTBUS_BLECONNECTION_MUTEX_LOCK_ERROR, SOFTBUS_BLECONNECTION_GATT_CLIENT_NOT_SUPPORT, + SOFTBUS_GATTC_INTERFACE_FAILED, + SOFTBUS_BLEGATTC_NONT_INIT, + SOFTBUS_BLEGATTC_NOT_READY, + SOFTBUS_GATTC_DUPLICATE_PARAM, + SOFTBUS_GATTC_NONE_PARAM, + SOFTBUS_BLEGATTC_NODE_NOT_EXIST, SOFTBUS_DISCOVER_ERR_BASE = (-3000), diff --git a/core/common/include/softbus_json_utils.h b/core/common/include/softbus_json_utils.h index 12bca5ab5..179b7fb7b 100644 --- a/core/common/include/softbus_json_utils.h +++ b/core/common/include/softbus_json_utils.h @@ -32,6 +32,8 @@ bool GetJsonObjectStringItem(const cJSON *json, const char * const string, char bool GetJsonObjectNumberItem(const cJSON *json, const char * const string, int *target); +bool GetJsonObjectSignedNumberItem(const cJSON *json, const char * const string, int *target); + bool GetJsonObjectNumber64Item(const cJSON *json, const char * const string, int64_t *target); bool GetJsonObjectDoubleItem(const cJSON *json, const char * const string, double *target); @@ -44,6 +46,8 @@ bool AddNumberToJsonObject(cJSON *json, const char * const string, int num); bool AddNumber64ToJsonObject(cJSON *json, const char * const string, int64_t num); +bool AddBoolToJsonObject(cJSON *json, const char * const string, bool value); + #ifdef __cplusplus #if __cplusplus } diff --git a/core/common/include/softbus_log.h b/core/common/include/softbus_log.h index 9e4ac6b09..ae058b91c 100644 --- a/core/common/include/softbus_log.h +++ b/core/common/include/softbus_log.h @@ -16,6 +16,7 @@ #ifndef SOFTBUS_LOG_H #define SOFTBUS_LOG_H +#include #include "softbus_adapter_log.h" #ifdef __cplusplus @@ -36,6 +37,27 @@ typedef enum { void SoftBusLog(SoftBusLogModule module, SoftBusLogLevel level, const char *fmt, ...); +#define UUID_ANONYMIZED_LENGTH 4 +#define NETWORKID_ANONYMIZED_LENGTH 4 +#define UDID_ANONYMIZED_LENGTH 4 + +const char *Anonymizes(const char *target, const uint8_t expectAnonymizedLength); + +inline const char *AnonymizesUUID(const char *input) +{ + return Anonymizes(input, UUID_ANONYMIZED_LENGTH); +} + +inline const char *AnonymizesNetworkID(const char *input) +{ + return Anonymizes(input, NETWORKID_ANONYMIZED_LENGTH); +} + +inline const char *AnonymizesUDID(const char *input) +{ + return Anonymizes(input, UDID_ANONYMIZED_LENGTH); +} + #ifdef __cplusplus #if __cplusplus } diff --git a/core/common/json_utils/softbus_json_utils.c b/core/common/json_utils/softbus_json_utils.c index 97ce61f5c..a6d34ecbe 100644 --- a/core/common/json_utils/softbus_json_utils.c +++ b/core/common/json_utils/softbus_json_utils.c @@ -54,6 +54,20 @@ bool GetJsonObjectNumberItem(const cJSON *json, const char * const string, int * return true; } +bool GetJsonObjectSignedNumberItem(const cJSON *json, const char * const string, int *target) +{ + if (json == NULL || string == NULL || target == NULL) { + return false; + } + cJSON *item = cJSON_GetObjectItemCaseSensitive(json, string); + if (item == NULL || !cJSON_IsNumber(item)) { + SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "Cannot find or invalid [%s]", string); + return false; + } + *target = (int)item->valuedouble; + return true; +} + bool GetJsonObjectDoubleItem(const cJSON *json, const char * const string, double *target) { if (json == NULL || string == NULL || target == NULL) { @@ -145,4 +159,21 @@ bool AddNumber64ToJsonObject(cJSON *json, const char * const string, int64_t num return false; } return true; +} + +bool AddBoolToJsonObject(cJSON *json, const char * const string, bool value) +{ + if (json == NULL || string == NULL) { + return false; + } + cJSON *item = cJSON_CreateBool(value); + if (item == NULL) { + SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "Cannot create cJSON bool object [%s]", string); + return false; + } + if (!cJSON_AddItemToObject(json, string, item)) { + cJSON_Delete(item); + return false; + } + return true; } \ No newline at end of file diff --git a/core/common/log/softbus_log.c b/core/common/log/softbus_log.c index d5e3659d6..98e9a4630 100644 --- a/core/common/log/softbus_log.c +++ b/core/common/log/softbus_log.c @@ -22,6 +22,9 @@ #define LOG_NAME_MAX_LEN 5 #define LOG_PRINT_MAX_LEN 256 +// anonymize should mask more than half of the string +#define EXPECTED_ANONYMIZED_TIMES 2 + static int32_t g_logLevel; typedef struct { @@ -50,7 +53,7 @@ void SoftBusLog(SoftBusLogModule module, SoftBusLogLevel level, const char *fmt, return; } - SoftbusGetConfig(SOFTBUS_INT_ADAPTER_LOG_LEVEL, (unsigned char*)&g_logLevel, sizeof(g_logLevel)); + SoftbusGetConfig(SOFTBUS_INT_ADAPTER_LOG_LEVEL, (unsigned char *)&g_logLevel, sizeof(g_logLevel)); if ((int32_t)level < g_logLevel) { return; } @@ -73,3 +76,19 @@ void SoftBusLog(SoftBusLogModule module, SoftBusLogLevel level, const char *fmt, return; } + +const char *Anonymizes(const char *target, const uint8_t expectAnonymizedLength) +{ + if (target == NULL) { + return "NULL"; + } + if (expectAnonymizedLength == 0) { + return "BADLENGTH"; + } + size_t targetLen = strlen(target); + if (targetLen / expectAnonymizedLength < EXPECTED_ANONYMIZED_TIMES) { + return "TOOSHORT"; + } + + return target + (targetLen - expectAnonymizedLength); +} diff --git a/core/common/softbus_property/softbus_feature_config.c b/core/common/softbus_property/softbus_feature_config.c index 646e71bae..9c536300a 100644 --- a/core/common/softbus_property/softbus_feature_config.c +++ b/core/common/softbus_property/softbus_feature_config.c @@ -25,7 +25,13 @@ #define MAX_BYTES_LENGTH 4194304 #define MAX_MESSAGE_LENGTH 4096 + +#ifdef SOFTBUS_STANDARD_SYSTEM +#define CONN_BR_MAX_DATA_LENGTH (40 * 1000) +#else #define CONN_BR_MAX_DATA_LENGTH 4096 +#endif + #define CONN_RFCOM_SEND_MAX_LEN 990 #define CONN_BR_RECEIVE_MAX_LEN 10 #define CONN_TCP_MAX_LENGTH 3072 @@ -52,14 +58,20 @@ #ifdef SOFTBUS_STANDARD_SYSTEM #define DEFAULT_MAX_BYTES_LEN (4 * 1024 * 1024) #define DEFAULT_MAX_MESSAGE_LEN (4 * 1024) +#define DEFAULT_AUTH_MAX_BYTES_LEN (40000 - 8) +#define DEFAULT_AUTH_MAX_MESSAGE_LEN (4 * 1024) #define DEFAULT_IS_SUPPORT_TCP_PROXY 1 #elif defined SOFTBUS_SMALL_SYSTEM #define DEFAULT_MAX_BYTES_LEN (1 * 1024 * 1024) #define DEFAULT_MAX_MESSAGE_LEN (4 * 1024) +#define DEFAULT_AUTH_MAX_BYTES_LEN (4 * 1024) +#define DEFAULT_AUTH_MAX_MESSAGE_LEN (1 * 1024) #define DEFAULT_IS_SUPPORT_TCP_PROXY 1 #else #define DEFAULT_MAX_BYTES_LEN (2 * 1024) #define DEFAULT_MAX_MESSAGE_LEN (1 * 1024) +#define DEFAULT_AUTH_MAX_BYTES_LEN (2 * 1024) +#define DEFAULT_AUTH_MAX_MESSAGE_LEN (1 * 1024) #define DEFAULT_IS_SUPPORT_TCP_PROXY 0 #endif @@ -110,6 +122,8 @@ typedef struct { int32_t selectInterval; int32_t maxBytesLen; int32_t maxMessageLen; + int32_t maxAuthBytesLen; + int32_t maxAuthMessageLen; } TransConfigItem; static TransConfigItem g_tranConfig = {0}; @@ -210,6 +224,16 @@ ConfigVal g_configItems[SOFTBUS_CONFIG_TYPE_MAX] = { (unsigned char*)&(g_config.lnnMaxConcurentNum), sizeof(g_config.lnnMaxConcurentNum) }, + { + SOFTBUS_INT_AUTH_MAX_BYTES_LENGTH, + (unsigned char*)&(g_tranConfig.maxAuthBytesLen), + sizeof(g_tranConfig.maxAuthBytesLen) + }, + { + SOFTBUS_INT_AUTH_MAX_MESSAGE_LENGTH, + (unsigned char*)&(g_tranConfig.maxAuthMessageLen), + sizeof(g_tranConfig.maxAuthMessageLen) + }, }; int SoftbusSetConfig(ConfigType type, const unsigned char *val, int32_t len) @@ -246,6 +270,8 @@ static void SoftbusConfigSetTransDefaultVal(void) g_tranConfig.selectInterval = DEFAULT_SELECT_INTERVAL; g_tranConfig.maxBytesLen = DEFAULT_MAX_BYTES_LEN; g_tranConfig.maxMessageLen = DEFAULT_MAX_MESSAGE_LEN; + g_tranConfig.maxAuthBytesLen = DEFAULT_AUTH_MAX_BYTES_LEN; + g_tranConfig.maxAuthMessageLen = DEFAULT_AUTH_MAX_MESSAGE_LEN; } static void SoftbusConfigSetDefaultVal(void) diff --git a/core/connection/ble/conn_ble.gni b/core/connection/ble/conn_ble.gni index 033046a2b..d97c11850 100644 --- a/core/connection/ble/conn_ble.gni +++ b/core/connection/ble/conn_ble.gni @@ -11,19 +11,32 @@ # See the License for the specific language governing permissions and # limitations under the License. +import( + "//foundation/communication/dsoftbus/adapter/common/net/bluetooth/net_bluetooth.gni") import("//foundation/communication/dsoftbus/dsoftbus.gni") ble_connection_deps = [] if (enable_connection_ble == false) { ble_connection_src = [ "$dsoftbus_root_path/core/connection/ble/src/softbus_ble_connection_virtual.c" ] ble_connection_inc = [ "$dsoftbus_root_path/core/connection/ble/include" ] + if (enable_connection_br == true) { + ble_connection_src += adapter_net_br_src + ble_connection_inc += adapter_ble_inc + ble_connection_deps += adapter_ble_deps + } } else { ble_connection_src = [ "$dsoftbus_root_path/core/connection/ble/src/softbus_ble_connection.c", + "$dsoftbus_root_path/core/connection/ble/src/softbus_ble_gatt_client.c", + "$dsoftbus_root_path/core/connection/ble/src/softbus_ble_gatt_server.c", + "$dsoftbus_root_path/core/connection/ble/src/softbus_ble_queue.c", "$dsoftbus_root_path/core/connection/ble/src/softbus_ble_trans_manager.c", ] ble_connection_inc = [ "$dsoftbus_root_path/core/connection/ble/include", "$dsoftbus_root_path/core/connection/ble/src", ] + ble_connection_src += adapter_ble_src + ble_connection_inc += adapter_ble_inc + ble_connection_deps += adapter_ble_deps } diff --git a/core/connection/ble/src/softbus_ble_connection_inner.h b/core/connection/ble/include/softbus_ble_connection_inner.h similarity index 59% rename from core/connection/ble/src/softbus_ble_connection_inner.h rename to core/connection/ble/include/softbus_ble_connection_inner.h index 8fc50f339..829c1466e 100644 --- a/core/connection/ble/src/softbus_ble_connection_inner.h +++ b/core/connection/ble/include/softbus_ble_connection_inner.h @@ -21,6 +21,12 @@ #include "softbus_conn_manager.h" #define MAX_CACHE_NUM_PER_CONN 3 +#define BLE_CLIENT_TYPE 0 +#define BLE_SERVER_TYPE 1 +#define SOFTBUS_SERVICE_UUID "11C8B310-80E4-4276-AFC0-F81590B2177F" +#define SOFTBUS_CHARA_BLENET_UUID "00002B00-0000-1000-8000-00805F9B34FB" +#define SOFTBUS_CHARA_BLECONN_UUID "00002B01-0000-1000-8000-00805F9B34FB" +#define SOFTBUS_DESCRIPTOR_CONFIGURE_UUID "00002902-0000-1000-8000-00805F9B34FB" typedef struct { int32_t isUsed; @@ -30,6 +36,12 @@ typedef struct { char *cache; } BleRecvCache; +typedef struct { + ListNode node; + int32_t requestId; + ConnectResult callback; +} BleRequestInfo; + typedef struct { ListNode node; int32_t halConnId; @@ -40,11 +52,16 @@ typedef struct { int32_t refCount; int32_t mtu; int32_t peerType; + ListNode requestList; char peerDevId[UDID_BUF_LEN]; BleRecvCache recvCache[MAX_CACHE_NUM_PER_CONN]; } BleConnectionInfo; -BleConnectionInfo* GetBleConnInfoByHalConnId(int32_t halConnectionId); -int32_t GetBleAttrHandle(int32_t module); +typedef struct { + void (*BleOnDataReceived)(bool isBleConn, int32_t halConnId, uint32_t len, const char *value); + void (*BleDisconnectCallback)(int32_t halConnId, int32_t isServer); + void (*BleConnectCallback)(int32_t halConnId, const char *bleStrMac, const SoftBusBtAddr *btAddr); + BleConnectionInfo* (*GetBleConnInfoByHalConnId)(int32_t halConnectionId); +} SoftBusBleConnCalback; #endif \ No newline at end of file diff --git a/core/connection/ble/include/softbus_ble_gatt_client.h b/core/connection/ble/include/softbus_ble_gatt_client.h new file mode 100644 index 000000000..b972c8d57 --- /dev/null +++ b/core/connection/ble/include/softbus_ble_gatt_client.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BLE_GATT_CLIENT_H +#define BLE_GATT_CLIENT_H + +#include "common_list.h" +#include "softbus_adapter_ble_gatt_client.h" +#include "softbus_ble_connection_inner.h" +#include "softbus_conn_manager.h" + +int32_t SoftBusGattClientInit(SoftBusBleConnCalback *cb); +int32_t SoftBusGattClientConnect(SoftBusBtAddr *bleAddr); +int32_t SoftBusGattClientDisconnect(int32_t clientId); +int32_t SoftBusGattClientSend(const int32_t clientId, const char *data, int32_t len, int32_t module); + +#endif /* BLE_GATT_CLIENT_H */ \ No newline at end of file diff --git a/core/connection/ble/include/softbus_ble_gatt_server.h b/core/connection/ble/include/softbus_ble_gatt_server.h new file mode 100644 index 000000000..3ca36e454 --- /dev/null +++ b/core/connection/ble/include/softbus_ble_gatt_server.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BLE_GATT_SERVER_H +#define BLE_GATT_SERVER_H + +#include "common_list.h" +#include "softbus_adapter_ble_gatt_server.h" +#include "softbus_ble_connection_inner.h" +#include "softbus_conn_manager.h" + +int32_t SoftBusGattServerInit(SoftBusBleConnCalback *cb); +int32_t SoftBusGattServerStartService(void); +int32_t SoftBusGattServerStopService(void); +void SoftBusGattServerOnBtStateChanged(int state); +int32_t SoftBusGattServerSend(int32_t halConnId, const char *data, int32_t len, int32_t module); + +#endif \ No newline at end of file diff --git a/core/connection/ble/include/softbus_ble_queue.h b/core/connection/ble/include/softbus_ble_queue.h new file mode 100644 index 000000000..c69251685 --- /dev/null +++ b/core/connection/ble/include/softbus_ble_queue.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SOFTBUS_BLE_QUEUE_H +#define SOFTBUS_BLE_QUEUE_H + +#include + +typedef struct { + uint32_t halConnId; + uint32_t connectionId; + int32_t pid; + int32_t flag; + int32_t isServer; + int32_t isInner; + int32_t module; + int32_t seq; + int32_t len; + const char *data; +} SendQueueNode; + +int BleInnerQueueInit(void); +void BleInnerQueueDeinit(void); +int BleEnqueueNonBlock(const void *msg); +int BleDequeueNonBlock(void **msg); +#endif \ No newline at end of file diff --git a/core/connection/ble/src/softbus_ble_trans_manager.h b/core/connection/ble/include/softbus_ble_trans_manager.h similarity index 85% rename from core/connection/ble/src/softbus_ble_trans_manager.h rename to core/connection/ble/include/softbus_ble_trans_manager.h index f63e24c2b..a2877071f 100644 --- a/core/connection/ble/src/softbus_ble_trans_manager.h +++ b/core/connection/ble/include/softbus_ble_trans_manager.h @@ -20,6 +20,11 @@ #define MAX_DATA_LEN 4096 +typedef struct { + BleConnectionInfo* (*GetBleConnInfoByHalConnId)(int32_t halConnectionId); +} SoftBusBleTransCalback; + +int32_t BleTransInit(SoftBusBleTransCalback *cb); int32_t BleTransSend(BleConnectionInfo *connInfo, const char *data, int32_t len, int32_t seq, int32_t module); char *BleTransRecv(int32_t halConnId, char *value, uint32_t len, uint32_t *outLen, int32_t *index); void BleTransCacheFree(int32_t halConnId, int32_t index); diff --git a/core/connection/ble/src/softbus_ble_connection.c b/core/connection/ble/src/softbus_ble_connection.c index 133e4c1b7..1229b2d22 100644 --- a/core/connection/ble/src/softbus_ble_connection.c +++ b/core/connection/ble/src/softbus_ble_connection.c @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include "softbus_ble_connection.h" #include #include @@ -23,10 +24,13 @@ #include "bus_center_manager.h" #include "cJSON.h" #include "common_list.h" -#include "message_handler.h" #include "securec.h" #include "softbus_adapter_ble_gatt_server.h" #include "softbus_adapter_mem.h" +#include "softbus_adapter_timer.h" +#include "softbus_ble_gatt_client.h" +#include "softbus_ble_gatt_server.h" +#include "softbus_ble_queue.h" #include "softbus_ble_trans_manager.h" #include "softbus_conn_manager.h" #include "softbus_def.h" @@ -36,7 +40,6 @@ #include "softbus_queue.h" #include "softbus_type_def.h" #include "softbus_utils.h" -#include "softbus_adapter_thread.h" #define SEND_QUEUE_UNIT_NUM 128 #define CONNECT_REF_INCRESE 1 @@ -47,33 +50,9 @@ #define CONN_MAGIC_NUMBER 0xBABEFACE #define KEY_METHOD "KEY_METHOD" #define KEY_DELTA "KEY_DELTA" -#define KEY_REFERENCE_NUM "KEY_REFERENCE_NUM" +#define KEY_REF_NUM "KEY_REF_NUM" #define TYPE_HEADER_SIZE 4 -#define SOFTBUS_SERVICE_UUID "11C8B310-80E4-4276-AFC0-F81590B2177F" -#define SOFTBUS_CHARA_BLENET_UUID "00002B00-0000-1000-8000-00805F9B34FB" -#define SOFTBUS_CHARA_BLECONN_UUID "00002B01-0000-1000-8000-00805F9B34FB" -#define SOFTBUS_DESCRIPTOR_CONFIGURE_UUID "00002902-0000-1000-8000-00805F9B34FB" - -typedef enum { - BLE_GATT_SERVICE_INITIAL = 0, - BLE_GATT_SERVICE_ADDING, - BLE_GATT_SERVICE_ADDED, - BLE_GATT_SERVICE_STARTING, - BLE_GATT_SERVICE_STARTED, - BLE_GATT_SERVICE_STOPPING, - BLE_GATT_SERVICE_DELETING, - BLE_GATT_SERVICE_INVALID -} GattServiceState; - -typedef struct { - GattServiceState state; - int32_t svcId; - int32_t bleConnCharaId; - int32_t bleConnDesId; - int32_t bleNetCharaId; - int32_t bleNetDesId; -} SoftBusGattService; - +#define INVALID_CLIENID (-1) typedef enum { BLE_CONNECTION_STATE_CONNECTING = 0, BLE_CONNECTION_STATE_CONNECTED, @@ -82,31 +61,6 @@ typedef enum { BLE_CONNECTION_STATE_CLOSED } BleConnectionState; -typedef enum { - ADD_SERVICE_MSG, - ADD_CHARA_MSG, - ADD_DESCRIPTOR_MSG, -} BleConnLoopMsg; - -typedef struct { - SoftBusMutex lock; - SoftBusCond cond; - LockFreeQueue *queue; -} BleQueue; - -typedef struct { - uint32_t halConnId; - uint32_t connectionId; - int32_t pid; - int32_t flag; - int32_t isServer; - int32_t isInner; - int32_t module; - int32_t seq; - int32_t len; - const char *data; -} SendQueueNode; - typedef enum { TYPE_UNKNOW = -1, TYPE_AUTH = 0, @@ -118,54 +72,24 @@ typedef struct { int32_t type; } BleBasicInfo; -static const int MAX_SERVICE_CHAR_NUM = 8; -static const int BLE_GATT_ATT_MTU_DEFAULT = 23; static const int BLE_GATT_ATT_MTU_DEFAULT_PAYLOAD = 21; -static const int MTU_HEADER_SIZE = 3; static const int BLE_GATT_ATT_MTU_MAX = 512; static const int BLE_ROLE_CLIENT = 1; static const int BLE_ROLE_SERVER = 2; static LIST_HEAD(g_conection_list); static ConnectCallback *g_connectCallback = NULL; -static SoftBusHandler g_bleAsyncHandler = { - .name ="g_bleAsyncHandler" -}; static ConnectFuncInterface g_bleInterface = { 0 }; -static SoftBusGattsCallback g_bleGattsCallback = { 0 }; -static SoftBusMutex g_connectionLock; -static SoftBusGattService g_gattService = { - .state = BLE_GATT_SERVICE_INITIAL, - .svcId = -1, - .bleConnCharaId = -1, - .bleConnDesId = -1, - .bleNetCharaId = -1, - .bleNetDesId = -1 -}; -static BleQueue g_sendQueue; +static pthread_mutex_t g_connectionLock; -static SoftBusMessage *BleConnCreateLoopMsg(int32_t what, uint64_t arg1, uint64_t arg2, const char *data) -{ - SoftBusMessage *msg = NULL; - msg = SoftBusCalloc(sizeof(SoftBusMessage)); - if (msg == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleConnCreateLoopMsg SoftBusCalloc failed"); - return NULL; - } - msg->what = what; - msg->arg1 = arg1; - msg->arg2 = arg2; - msg->handler = &g_bleAsyncHandler; - msg->FreeMessage = NULL; - msg->obj = (void *)data; - return msg; -} +static void PackRequest(int32_t delta, uint32_t connectionId); +static int32_t SendSelfBasicInfo(uint32_t connId, int32_t roleType); static int32_t AllocBleConnectionIdLocked() { static int16_t nextConnectionId = 0; uint32_t tempId; - if (SoftBusThreadMutexLock(&g_connectionLock) != 0) { + if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return 0; } @@ -182,7 +106,7 @@ static int32_t AllocBleConnectionIdLocked() } break; } - (void)SoftBusThreadMutexUnlock(&g_connectionLock); + (void)pthread_mutex_unlock(&g_connectionLock); return tempId; } @@ -194,6 +118,7 @@ static BleConnectionInfo* CreateBleConnectionNode(void) return NULL; } ListInit(&newConnectionInfo->node); + ListInit(&newConnectionInfo->requestList); newConnectionInfo->connId = AllocBleConnectionIdLocked(); newConnectionInfo->mtu = BLE_GATT_ATT_MTU_DEFAULT_PAYLOAD; newConnectionInfo->refCount = 1; @@ -202,6 +127,27 @@ static BleConnectionInfo* CreateBleConnectionNode(void) return newConnectionInfo; } +static void ReleaseBleconnectionNode(BleConnectionInfo *newConnectionInfo) +{ + if (newConnectionInfo == NULL) { + return; + } + + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "ReleaseBleconnectionNode"); + BleRequestInfo *requestInfo = NULL; + ListNode *item = NULL; + ListNode *itemNext = NULL; + if (IsListEmpty(&newConnectionInfo->requestList) != true) { + LIST_FOR_EACH_SAFE(item, itemNext, &newConnectionInfo->requestList) { + requestInfo = LIST_ENTRY(item, BleRequestInfo, node); + ListDelete(&requestInfo->node); + SoftBusFree(requestInfo); + } + } + SoftBusFree(newConnectionInfo); + return; +} + void DeleteBleConnectionNode(BleConnectionInfo* node) { if (node == NULL) { @@ -220,7 +166,7 @@ static BleConnectionInfo* GetBleConnInfoByConnId(uint32_t connectionId) { ListNode *item = NULL; BleConnectionInfo *itemNode = NULL; - if (SoftBusThreadMutexLock(&g_connectionLock) != 0) { + if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return NULL; } @@ -230,7 +176,7 @@ static BleConnectionInfo* GetBleConnInfoByConnId(uint32_t connectionId) break; } } - (void)SoftBusThreadMutexUnlock(&g_connectionLock); + (void)pthread_mutex_unlock(&g_connectionLock); return itemNode; } @@ -238,7 +184,7 @@ BleConnectionInfo* GetBleConnInfoByHalConnId(int32_t halConnectionId) { ListNode *item = NULL; BleConnectionInfo *itemNode = NULL; - if (SoftBusThreadMutexLock(&g_connectionLock) != 0) { + if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return NULL; } @@ -248,7 +194,7 @@ BleConnectionInfo* GetBleConnInfoByHalConnId(int32_t halConnectionId) break; } } - (void)SoftBusThreadMutexUnlock(&g_connectionLock); + (void)pthread_mutex_unlock(&g_connectionLock); return itemNode; } @@ -258,7 +204,7 @@ static int32_t GetBleConnInfoByAddr(const char *strAddr, BleConnectionInfo **ser BleConnectionInfo *itemNode = NULL; bool findServer = false; bool findClient = false; - if (SoftBusThreadMutexLock(&g_connectionLock) != 0) { + if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return SOFTBUS_BLECONNECTION_MUTEX_LOCK_ERROR; } @@ -277,41 +223,122 @@ static int32_t GetBleConnInfoByAddr(const char *strAddr, BleConnectionInfo **ser } } } - (void)SoftBusThreadMutexUnlock(&g_connectionLock); + (void)pthread_mutex_unlock(&g_connectionLock); return SOFTBUS_OK; } -int32_t GetBleAttrHandle(int32_t module) +static void BleDeviceConnected(const BleConnectionInfo *itemNode, uint32_t requestId, const ConnectResult *result) { - return (module == MODULE_BLE_NET) ? g_gattService.bleNetCharaId : g_gattService.bleConnCharaId; + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ble mac has connected"); + ConnectionInfo connectionInfo; + connectionInfo.isAvailable = 1; + connectionInfo.isServer = itemNode->info.isServer; + connectionInfo.type = CONNECT_BLE; + if (strcpy_s(connectionInfo.info.bleInfo.bleMac, BT_MAC_LEN, itemNode->info.info.bleInfo.bleMac) != EOK) { + return; + } + int connectionId = itemNode->connId; + + (void)pthread_mutex_unlock(&g_connectionLock); + if (result->OnConnectSuccessed != NULL) { + result->OnConnectSuccessed( + requestId, connectionId, &connectionInfo); + } + + (void)PackRequest(CONNECT_REF_INCRESE, connectionId); +} + +static int32_t BleConnectDeviceFristTime(const ConnectOption *option, uint32_t requestId, const ConnectResult *result) +{ + BleConnectionInfo *newConnectionInfo = CreateBleConnectionNode(); + if (newConnectionInfo == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "ble client node create fail"); + return SOFTBUS_ERR; + } + BleRequestInfo *requestInfo = SoftBusCalloc(sizeof(BleRequestInfo)); + if (requestInfo == NULL) { + ReleaseBleconnectionNode(newConnectionInfo); + return SOFTBUS_ERR; + } + newConnectionInfo->mtu = BLE_GATT_ATT_MTU_MAX; + ListInit(&requestInfo->node); + ListAdd(&newConnectionInfo->requestList, &requestInfo->node); + if (strcpy_s(newConnectionInfo->info.info.bleInfo.bleMac, sizeof(newConnectionInfo->info.info.bleInfo.bleMac), + option->info.bleOption.bleMac) != EOK) { + ReleaseBleconnectionNode(newConnectionInfo); + return SOFTBUS_ERR; + } + + requestInfo->requestId = requestId; + (void)memcpy_s(&requestInfo->callback, sizeof(requestInfo->callback), result, sizeof(*result)); + newConnectionInfo->state = BLE_CONNECTION_STATE_CONNECTING; + newConnectionInfo->info.isServer = BLE_CLIENT_TYPE; + int32_t clientId = INVALID_CLIENID; + if (ConvertBtMacToBinary(newConnectionInfo->info.info.bleInfo.bleMac, BT_MAC_LEN, + newConnectionInfo->btBinaryAddr.addr, BT_ADDR_LEN) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "convert bt mac to binary fail."); + ReleaseBleconnectionNode(newConnectionInfo); + return SOFTBUS_ERR; + } + clientId = SoftBusGattClientConnect(&(newConnectionInfo->btBinaryAddr)); + if (clientId < 0) { + ReleaseBleconnectionNode(newConnectionInfo); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusGattClientConnect fail ret=%d", clientId); + return SOFTBUS_ERR; + } + newConnectionInfo->halConnId = clientId; + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "new connection %d,clientId=%d", + newConnectionInfo->connId, clientId); + ListAdd(&g_conection_list, &newConnectionInfo->node); + return SOFTBUS_OK; } static int32_t BleConnectDevice(const ConnectOption *option, uint32_t requestId, const ConnectResult *result) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, - "ConnectDevice failed, reason:gatt client is not currently supported"); - return SOFTBUS_BLECONNECTION_GATT_CLIENT_NOT_SUPPORT; -} - -static int BleEnqueueNonBlock(const void *msg) -{ - if (msg == NULL) { + "BleConnectDevice, requestId=%d", requestId); + if (pthread_mutex_lock(&g_connectionLock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return SOFTBUS_ERR; } - return QueueMultiProducerEnqueue(g_sendQueue.queue, msg); -} - -static int BleDequeueBlock(void **msg) -{ - if (msg == NULL) { - return SOFTBUS_ERR; + int32_t ret = SOFTBUS_OK; + ListNode *item = NULL; + BleConnectionInfo *targetConnectionInfo = NULL; + LIST_FOR_EACH(item, &g_conection_list) { + BleConnectionInfo *itemNode = LIST_ENTRY(item, BleConnectionInfo, node); + if (itemNode->info.isServer != BLE_CLIENT_TYPE) { + continue; + } + if (strncmp(itemNode->info.info.bleInfo.bleMac, option->info.bleOption.bleMac, BT_MAC_LEN) == 0) { + targetConnectionInfo = itemNode; + if (itemNode->state == BLE_CONNECTION_STATE_CONNECTED) { + BleDeviceConnected(itemNode, requestId, result); + (void)pthread_mutex_unlock(&g_connectionLock); + return SOFTBUS_OK; + } else if (itemNode->state == BLE_CONNECTION_STATE_CONNECTING) { + BleRequestInfo *requestInfo = SoftBusMalloc(sizeof(BleRequestInfo)); + if (requestInfo == NULL) { + (void)pthread_mutex_unlock(&g_connectionLock); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, + "[ConnectDevice fail and state is BLE_CONNECTION_STATE_CONNECTING.]"); + return SOFTBUS_ERR; + } + (void)memset_s(requestInfo, sizeof(BleRequestInfo), 0, sizeof(BleRequestInfo)); + ListInit(&requestInfo->node); + requestInfo->requestId = requestId; + (void)memcpy_s(&requestInfo->callback, sizeof(requestInfo->callback), result, sizeof(*result)); + ListAdd(&itemNode->requestList, &requestInfo->node); + } else if (itemNode->state == BLE_CONNECTION_STATE_CLOSING) { + result->OnConnectFailed(requestId, 0); + } + } } - (void)SoftBusThreadMutexLock(&g_sendQueue.lock); - if (QueueIsEmpty(g_sendQueue.queue) == 0) { - SoftBusCondWait(&g_sendQueue.cond, &g_sendQueue.lock, NULL); - (void)SoftBusThreadMutexUnlock(&g_sendQueue.lock); + if (targetConnectionInfo == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[targetConnectionInfo == NULL]"); + ret = BleConnectDeviceFristTime(option, requestId, result); } - return QueueSingleConsumerDequeue(g_sendQueue.queue, msg); + (void)pthread_mutex_unlock(&g_connectionLock); + return ret; } static int32_t BlePostBytes(uint32_t connectionId, const char *data, int32_t len, int32_t pid, int32_t flag) @@ -337,14 +364,13 @@ static int32_t BlePostBytes(uint32_t connectionId, const char *data, int32_t len node->flag = flag; node->len = len; node->data = data; + node->isInner = 0; int ret = BleEnqueueNonBlock((const void *)node); if (ret != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BlePostBytes enqueue failed"); + SoftBusFree(node); return ret; } - (void)SoftBusThreadMutexLock(&g_sendQueue.lock); - SoftBusCondSignal(&g_sendQueue.cond); - (void)SoftBusThreadMutexUnlock(&g_sendQueue.lock); return SOFTBUS_OK; } @@ -370,15 +396,13 @@ static int32_t BlePostBytesInner(uint32_t connectionId, ConnPostData *data) node->data = data->buf; node->isInner = 1; node->module = data->module; - node->isInner = data->seq; + node->seq = data->seq; int ret = BleEnqueueNonBlock((const void *)node); if (ret != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BlePostBytes enqueue failed"); + SoftBusFree(node); return ret; } - (void)SoftBusThreadMutexLock(&g_sendQueue.lock); - SoftBusCondSignal(&g_sendQueue.cond); - (void)SoftBusThreadMutexUnlock(&g_sendQueue.lock); return SOFTBUS_OK; } @@ -387,12 +411,12 @@ static int AddNumToJson(cJSON *json, int32_t requestOrResponse, int32_t delta, i if (requestOrResponse == METHOD_NOTIFY_REQUEST) { if (!AddNumberToJsonObject(json, KEY_METHOD, METHOD_NOTIFY_REQUEST) || !AddNumberToJsonObject(json, KEY_DELTA, delta) || - !AddNumberToJsonObject(json, KEY_REFERENCE_NUM, count)) { + !AddNumberToJsonObject(json, KEY_REF_NUM, count)) { return SOFTBUS_BRCONNECTION_PACKJSON_ERROR; } } else { if (!AddNumberToJsonObject(json, KEY_METHOD, METHOD_NOTIFY_RESPONSE) || - !AddNumberToJsonObject(json, KEY_REFERENCE_NUM, count)) { + !AddNumberToJsonObject(json, KEY_REF_NUM, count)) { return SOFTBUS_BRCONNECTION_PACKJSON_ERROR; } } @@ -401,7 +425,7 @@ static int AddNumToJson(cJSON *json, int32_t requestOrResponse, int32_t delta, i static void SendRefMessage(int32_t delta, int32_t connectionId, int32_t count, int32_t requestOrResponse) { - cJSON *json = cJSON_CreateObject(); + cJSON *json = cJSON_CreateObject(); if (json == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Cannot create cJSON object"); return; @@ -411,14 +435,13 @@ static void SendRefMessage(int32_t delta, int32_t connectionId, int32_t count, i SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Cannot AddNumToJson"); return; } - char *data = cJSON_PrintUnformatted(json); cJSON_Delete(json); if (data == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "cJSON_PrintUnformatted failed"); return; } - + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SendRefMessage:%s", data); int32_t headSize = sizeof(ConnPktHead); int32_t dataLen = strlen(data) + 1 + headSize; char *buf = (char *)SoftBusCalloc(dataLen); @@ -432,7 +455,6 @@ static void SendRefMessage(int32_t delta, int32_t connectionId, int32_t count, i head.seq = 1; head.flag = 0; head.len = strlen(data) + 1; - if (memcpy_s(buf, dataLen, (void *)&head, headSize)) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "memcpy_s head error"); cJSON_free(data); @@ -446,7 +468,11 @@ static void SendRefMessage(int32_t delta, int32_t connectionId, int32_t count, i return; } cJSON_free(data); - (void)BlePostBytes(connectionId, buf, dataLen, 0, 0); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "SendRefMessage BlePostBytes"); + if (BlePostBytes(connectionId, buf, dataLen, 0, 0) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SendRefMessage BlePostBytes failed"); + SoftBusFree(buf); + } return; } @@ -457,7 +483,7 @@ static void PackRequest(int32_t delta, uint32_t connectionId) ListNode *item = NULL; BleConnectionInfo *targetNode = NULL; int refCount; - if (SoftBusThreadMutexLock(&g_connectionLock) != 0) { + if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return; } @@ -470,7 +496,7 @@ static void PackRequest(int32_t delta, uint32_t connectionId) break; } } - (void)SoftBusThreadMutexUnlock(&g_connectionLock); + (void)pthread_mutex_unlock(&g_connectionLock); if (targetNode == NULL) { return; } @@ -478,6 +504,14 @@ static void PackRequest(int32_t delta, uint32_t connectionId) SendRefMessage(delta, connectionId, refCount, METHOD_NOTIFY_REQUEST); } +static void AbortConnection(SoftBusBtAddr btAddr, int32_t halConnId, int32_t isServer) +{ + if (isServer == BLE_CLIENT_TYPE) { + SoftBusGattClientDisconnect(halConnId); + } + SoftBusGattsDisconnect(btAddr, halConnId); +} + static void OnPackResponse(int32_t delta, int32_t peerRef, uint32_t connectionId) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, @@ -485,7 +519,7 @@ static void OnPackResponse(int32_t delta, int32_t peerRef, uint32_t connectionId ListNode *item = NULL; BleConnectionInfo *targetNode = NULL; int myRefCount; - if (SoftBusThreadMutexLock(&g_connectionLock) != 0) { + if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return; } @@ -500,10 +534,10 @@ static void OnPackResponse(int32_t delta, int32_t peerRef, uint32_t connectionId } if (targetNode == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Not find OnPackResponse device"); - (void)SoftBusThreadMutexUnlock(&g_connectionLock); + (void)pthread_mutex_unlock(&g_connectionLock); return; } - (void)SoftBusThreadMutexUnlock(&g_connectionLock); + (void)pthread_mutex_unlock(&g_connectionLock); SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[onPackRequest: myRefCount=%d]", myRefCount); if (peerRef > 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[remote device Ref is > 0, do not reply]"); @@ -511,7 +545,8 @@ static void OnPackResponse(int32_t delta, int32_t peerRef, uint32_t connectionId } if (myRefCount <= 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[local device Ref <= 0, close connection now]"); - SoftBusGattsDisconnect(targetNode->btBinaryAddr, targetNode->halConnId); + targetNode->state = BLE_CONNECTION_STATE_CLOSING; + AbortConnection(targetNode->btBinaryAddr, targetNode->halConnId, targetNode->info.isServer); return; } SendRefMessage(delta, connectionId, myRefCount, METHOD_NOTIFY_RESPONSE); @@ -524,13 +559,20 @@ static void RecvConnectedComd(uint32_t connectionId, const cJSON *data) int32_t keyRefernceNum = 0; SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "RecvConnectedComd ID=%u", connectionId); + char *payload123 = cJSON_PrintUnformatted(data); + if (data == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "123cJSON_PrintUnformatted failed"); + return; + } + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "RecvConnectedComd:%s", payload123); + if (!GetJsonObjectNumberItem(data, KEY_METHOD, &keyMethod)) { return; } if (keyMethod == METHOD_NOTIFY_REQUEST) { if (!GetJsonObjectNumberItem(data, KEY_METHOD, &keyMethod) || - !GetJsonObjectNumberItem(data, KEY_DELTA, &keyDelta) || - !GetJsonObjectNumberItem(data, KEY_REFERENCE_NUM, &keyRefernceNum)) { + !GetJsonObjectSignedNumberItem(data, KEY_DELTA, &keyDelta) || + !GetJsonObjectNumberItem(data, KEY_REF_NUM, &keyRefernceNum)) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "REQUEST fail"); return; } @@ -539,11 +581,11 @@ static void RecvConnectedComd(uint32_t connectionId, const cJSON *data) if (keyMethod == METHOD_NOTIFY_RESPONSE) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "NOTIFY_RESPONSE"); if (!GetJsonObjectNumberItem(data, KEY_METHOD, &keyMethod) || - !GetJsonObjectNumberItem(data, KEY_REFERENCE_NUM, &keyRefernceNum)) { + !GetJsonObjectNumberItem(data, KEY_REF_NUM, &keyRefernceNum)) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "RESPONSE fail"); return; } - (void)SoftBusThreadMutexLock(&g_connectionLock); + (void)pthread_mutex_lock(&g_connectionLock); ListNode *item = NULL; LIST_FOR_EACH(item, &g_conection_list) { BleConnectionInfo *itemNode = LIST_ENTRY(item, BleConnectionInfo, node); @@ -555,7 +597,7 @@ static void RecvConnectedComd(uint32_t connectionId, const cJSON *data) break; } } - (void)SoftBusThreadMutexUnlock(&g_connectionLock); + (void)pthread_mutex_unlock(&g_connectionLock); } } @@ -583,19 +625,12 @@ static int32_t BleDisconnectDeviceNow(const ConnectOption *option) SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleDisconnectDevice GetBleConnInfo failed"); return SOFTBUS_BLECONNECTION_GETCONNINFO_ERROR; } - SoftBusBtAddr btAddr; if (server != NULL) { - ret = ConvertBtMacToBinary((const char *)server->info.info.bleInfo.bleMac, - BT_MAC_LEN, btAddr.addr, BT_ADDR_LEN); - if (ret != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Convert ble addr to binary failed:%d", ret); - return ret; - } - ret = SoftBusGattsDisconnect(btAddr, server->halConnId); + server->state = BLE_CONNECTION_STATE_CLOSING; + SoftBusGattsDisconnect(server->btBinaryAddr, server->halConnId); } else { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, - "BleDisconnectDeviceNow failed, reason:gatt client not support"); - return SOFTBUS_BLECONNECTION_GATT_CLIENT_NOT_SUPPORT; + client->state = BLE_CONNECTION_STATE_CLOSING; + SoftBusGattClientDisconnect(client->halConnId); } return ret; } @@ -603,7 +638,7 @@ static int32_t BleDisconnectDeviceNow(const ConnectOption *option) static int32_t BleGetConnectionInfo(uint32_t connectionId, ConnectionInfo *info) { int32_t result = SOFTBUS_ERR; - if (SoftBusThreadMutexLock(&g_connectionLock) != 0) { + if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return SOFTBUS_ERR; } @@ -613,420 +648,203 @@ static int32_t BleGetConnectionInfo(uint32_t connectionId, ConnectionInfo *info) if (itemNode->connId == connectionId) { if (memcpy_s(info, sizeof(ConnectionInfo), &(itemNode->info), sizeof(ConnectionInfo)) != EOK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleGetConnInfo scpy error"); - (void)SoftBusThreadMutexUnlock(&g_connectionLock); + (void)pthread_mutex_unlock(&g_connectionLock); return SOFTBUS_BLECONNECTION_GETCONNINFO_ERROR; } result = SOFTBUS_OK; break; } } - (void)SoftBusThreadMutexUnlock(&g_connectionLock); + (void)pthread_mutex_unlock(&g_connectionLock); return result; } static int32_t BleStartLocalListening(const LocalListenerInfo *info) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "BleGattsStartService enter"); - if (SoftBusThreadMutexLock(&g_connectionLock) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); - return SOFTBUS_BLECONNECTION_MUTEX_LOCK_ERROR; - } - if ((g_gattService.state == BLE_GATT_SERVICE_STARTED) || - (g_gattService.state == BLE_GATT_SERVICE_STARTING)) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, - "BleStartLocalListening service already started or is starting"); - (void)SoftBusThreadMutexUnlock(&g_connectionLock); - return SOFTBUS_OK; - } - if (g_gattService.state == BLE_GATT_SERVICE_ADDED) { - g_gattService.state = BLE_GATT_SERVICE_STARTING; - int ret = SoftBusGattsStartService(g_gattService.svcId); - if (ret != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusGattsStartService failed"); - g_gattService.state = BLE_GATT_SERVICE_ADDED; - } - (void)SoftBusThreadMutexUnlock(&g_connectionLock); - return (ret == SOFTBUS_OK) ? ret : SOFTBUS_ERR; - } - (void)SoftBusThreadMutexUnlock(&g_connectionLock); - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, - "BleStartLocalListening wrong service state:%d", g_gattService.state); - return SOFTBUS_ERR; + return SoftBusGattServerStartService(); } static int32_t BleStopLocalListening(const LocalListenerInfo *info) { - if (SoftBusThreadMutexLock(&g_connectionLock) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); - return SOFTBUS_BLECONNECTION_MUTEX_LOCK_ERROR; - } - if ((g_gattService.state == BLE_GATT_SERVICE_ADDED) || - (g_gattService.state == BLE_GATT_SERVICE_STOPPING)) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, - "BleStopLocalListening service already stopped or is stopping"); - (void)SoftBusThreadMutexUnlock(&g_connectionLock); - return SOFTBUS_OK; - } - if (g_gattService.state == BLE_GATT_SERVICE_STARTED) { - g_gattService.state = BLE_GATT_SERVICE_STOPPING; - int ret = SoftBusGattsStopService(g_gattService.svcId); - if (ret != SOFTBUS_OK) { - g_gattService.state = BLE_GATT_SERVICE_STARTED; - } - (void)SoftBusThreadMutexUnlock(&g_connectionLock); - return (ret == SOFTBUS_OK) ? ret : SOFTBUS_ERR; - } - (void)SoftBusThreadMutexUnlock(&g_connectionLock); - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, - "BleStopLocalListening wrong service state:%d", g_gattService.state); - return SOFTBUS_ERR; + return SoftBusGattServerStopService(); } -static void UpdateGattService(SoftBusGattService *service, int status) +static void BleDeviceConnectPackRequest(int32_t value, int32_t connId) { - if (service == NULL) { - return; - } - if (SoftBusThreadMutexLock(&g_connectionLock) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); - return; - } - switch (service->state) { - case BLE_GATT_SERVICE_ADDING: - if ((service->svcId != -1) && - (service->bleConnCharaId != -1) && - (service->bleNetCharaId != -1) && - (service->bleConnDesId != -1) && - (service->bleNetDesId != -1)) { - service->state = BLE_GATT_SERVICE_ADDED; - if (BleStartLocalListening(NULL) != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleStartLocalListening failed"); - } - break; - } - if (service->svcId != -1) { - service->state = BLE_GATT_SERVICE_DELETING; - int ret = SoftBusGattsDeleteService(service->svcId); - if (ret != SOFTBUS_OK) { - service->state = BLE_GATT_SERVICE_INVALID; - } - } else { - service->state = BLE_GATT_SERVICE_INITIAL; - } - break; - case BLE_GATT_SERVICE_STARTING: - service->state = (status == SOFTBUS_OK) ? BLE_GATT_SERVICE_STARTED : - BLE_GATT_SERVICE_ADDED; - break; - case BLE_GATT_SERVICE_STOPPING: - service->state = (status == SOFTBUS_OK) ? BLE_GATT_SERVICE_ADDED : - BLE_GATT_SERVICE_STARTED; - break; - case BLE_GATT_SERVICE_DELETING: - service->state = (status == SOFTBUS_OK) ? BLE_GATT_SERVICE_INITIAL : - BLE_GATT_SERVICE_INVALID; - break; - default: - break; - } - (void)SoftBusThreadMutexUnlock(&g_connectionLock); -} - -static void ResetGattService(SoftBusGattService *service) -{ - if (service == NULL) { - return; - } - if (SoftBusThreadMutexLock(&g_connectionLock) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); - return; - } - if (service->svcId != -1) { - service->state = BLE_GATT_SERVICE_DELETING; - int ret = SoftBusGattsDeleteService(service->svcId); - if (ret != SOFTBUS_OK) { - service->state = BLE_GATT_SERVICE_INVALID; - } - } else { - service->state = BLE_GATT_SERVICE_INITIAL; - } - service->svcId = -1; - service->bleConnCharaId = -1; - service->bleConnDesId = -1; - service->bleNetCharaId = -1; - service->bleNetDesId = -1; - (void)SoftBusThreadMutexUnlock(&g_connectionLock); -} - -static void BleServiceAddCallback(int status, SoftBusBtUuid *uuid, int srvcHandle) -{ - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ServiceAddCallback srvcHandle=%d\n", srvcHandle); - if ((uuid == NULL) || (uuid->uuid == NULL)) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleServiceAddCallback appUuid is null"); - return; - } - - if (memcmp(uuid->uuid, SOFTBUS_SERVICE_UUID, uuid->uuidLen) == 0) { - if (status != SOFTBUS_OK) { - ResetGattService(&g_gattService); - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleRegisterServerCallback failed, status=%d", status); - return; - } - if (SoftBusThreadMutexLock(&g_connectionLock) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); - return; - } - if (g_gattService.state != BLE_GATT_SERVICE_ADDING) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, - "g_gattService wrong state, should be BLE_GATT_SERVICE_ADDING"); - (void)SoftBusThreadMutexUnlock(&g_connectionLock); - return; - } - g_gattService.svcId = srvcHandle; - (void)SoftBusThreadMutexUnlock(&g_connectionLock); - SoftBusMessage *msg = BleConnCreateLoopMsg(ADD_CHARA_MSG, - SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_READ | SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_WRITE_NO_RSP | - SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_WRITE | SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_NOTIFY | - SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_INDICATE, SOFTBUS_GATT_PERMISSION_READ | - SOFTBUS_GATT_PERMISSION_WRITE, SOFTBUS_CHARA_BLENET_UUID); - if (msg == NULL) { - return; - } - g_bleAsyncHandler.looper->PostMessage(g_bleAsyncHandler.looper, msg); - - msg = BleConnCreateLoopMsg(ADD_DESCRIPTOR_MSG, 0, - SOFTBUS_GATT_PERMISSION_READ | SOFTBUS_GATT_PERMISSION_WRITE, SOFTBUS_DESCRIPTOR_CONFIGURE_UUID); - if (msg == NULL) { - return; - } - g_bleAsyncHandler.looper->PostMessage(g_bleAsyncHandler.looper, msg); - - msg = BleConnCreateLoopMsg(ADD_CHARA_MSG, - SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_READ | SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_WRITE_NO_RSP | - SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_WRITE | SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_NOTIFY | - SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_INDICATE, SOFTBUS_GATT_PERMISSION_READ | - SOFTBUS_GATT_PERMISSION_WRITE, SOFTBUS_CHARA_BLECONN_UUID); - if (msg == NULL) { - return; - } - g_bleAsyncHandler.looper->PostMessage(g_bleAsyncHandler.looper, msg); - } else { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleServiceAddCallback unknown uuid"); + while (--value > 0) { + (void)PackRequest(CONNECT_REF_INCRESE, connId); } } -static void BleCharacteristicAddCallback(int status, SoftBusBtUuid *uuid, int srvcHandle, - int characteristicHandle) +static void BleClientConnectCallback(int32_t halConnId, const char *bleStrMac, const SoftBusBtAddr *btAddr) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, - "CharacteristicAddCallback srvcHandle=%d,charHandle=%d\n", srvcHandle, characteristicHandle); - if ((uuid == NULL) || (uuid->uuid == NULL)) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleServiceAddCallback appUuid is null"); - return; + ListNode *bleItem = NULL; + (void)pthread_mutex_lock(&g_connectionLock); + int32_t connId = 0; + LIST_FOR_EACH(bleItem, &g_conection_list) { + BleConnectionInfo *itemNode = LIST_ENTRY(bleItem, BleConnectionInfo, node); + if (itemNode->halConnId != halConnId) { + continue; + } + connId = itemNode->connId; + itemNode->state = BLE_CONNECTION_STATE_CONNECTED; } - if ((srvcHandle == g_gattService.svcId) && (memcmp(uuid->uuid, SOFTBUS_CHARA_BLENET_UUID, uuid->uuidLen) == 0)) { - if (status != SOFTBUS_OK) { - ResetGattService(&g_gattService); - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleRegisterServerCallback failed, status=%d", status); - return; - } - if (SoftBusThreadMutexLock(&g_connectionLock) != 0) { - return; - } - if (g_gattService.state != BLE_GATT_SERVICE_ADDING) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "g_gattService state not equal BLE_GATT_SERVICE_ADDING"); - (void)SoftBusThreadMutexUnlock(&g_connectionLock); - return; - } - g_gattService.bleNetCharaId = characteristicHandle; - (void)SoftBusThreadMutexUnlock(&g_connectionLock); - return; - } - if ((srvcHandle == g_gattService.svcId) && (memcmp(uuid->uuid, SOFTBUS_CHARA_BLECONN_UUID, uuid->uuidLen) == 0)) { - if (status != SOFTBUS_OK) { - ResetGattService(&g_gattService); - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleRegisterServerCallback failed, status=%d", status); - return; - } - if (SoftBusThreadMutexLock(&g_connectionLock) != 0) { - return; - } - if (g_gattService.state != BLE_GATT_SERVICE_ADDING) { - (void)SoftBusThreadMutexUnlock(&g_connectionLock); - return; - } - g_gattService.bleConnCharaId = characteristicHandle; - (void)SoftBusThreadMutexUnlock(&g_connectionLock); - SoftBusMessage *msg = BleConnCreateLoopMsg(ADD_DESCRIPTOR_MSG, 0, - SOFTBUS_GATT_PERMISSION_READ | SOFTBUS_GATT_PERMISSION_WRITE, SOFTBUS_DESCRIPTOR_CONFIGURE_UUID); - if (msg == NULL) { - return; - } - g_bleAsyncHandler.looper->PostMessage(g_bleAsyncHandler.looper, msg); + (void)pthread_mutex_unlock(&g_connectionLock); + if (SendSelfBasicInfo(connId, BLE_ROLE_CLIENT) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SendSelfBasicInfo error"); } } -static void BleDescriptorAddCallback(int status, SoftBusBtUuid *uuid, - int srvcHandle, int descriptorHandle) +static void BleClientDoneConnect(BleConnectionInfo *targetNode) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "DescriptorAddCallback srvcHandle=%d,descriptorHandle=%d\n", - srvcHandle, descriptorHandle); - if ((uuid == NULL) || (uuid->uuid == NULL)) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleServiceAddCallback appUuid is null"); + ListNode notifyList; + ListNode *item = NULL; + ListNode *itemNext = NULL; + BleRequestInfo *requestInfo = NULL; + int32_t packRequestFlag = 0; + ListInit(¬ifyList); + LIST_FOR_EACH_SAFE(item, itemNext, &targetNode->requestList) { + requestInfo = LIST_ENTRY(item, BleRequestInfo, node); + ListDelete(&requestInfo->node); + ListAdd(¬ifyList, &requestInfo->node); + packRequestFlag++; + } + if (packRequestFlag == 0) { return; } - - if ((srvcHandle == g_gattService.svcId) && - (memcmp(uuid->uuid, SOFTBUS_DESCRIPTOR_CONFIGURE_UUID, uuid->uuidLen) == 0)) { - if (status != SOFTBUS_OK) { - ResetGattService(&g_gattService); - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleRegisterServerCallback failed, status=%d", status); - return; + BleDeviceConnectPackRequest(packRequestFlag, targetNode->connId); + LIST_FOR_EACH_SAFE(item, itemNext, ¬ifyList) { + requestInfo = LIST_ENTRY(item, BleRequestInfo, node); + if (requestInfo->callback.OnConnectSuccessed != NULL) { + requestInfo->callback.OnConnectSuccessed( + requestInfo->requestId, targetNode->connId, &targetNode->info); } - if (SoftBusThreadMutexLock(&g_connectionLock) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); - return; - } - if (g_gattService.state != BLE_GATT_SERVICE_ADDING) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, - "g_gattService wrong state, should be BLE_GATT_SERVICE_ADDING"); - (void)SoftBusThreadMutexUnlock(&g_connectionLock); - return; - } - if (g_gattService.bleNetDesId == -1) { - g_gattService.bleNetDesId = descriptorHandle; - } else { - g_gattService.bleConnDesId = descriptorHandle; - UpdateGattService(&g_gattService, 0); - } - (void)SoftBusThreadMutexUnlock(&g_connectionLock); - } else { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleDescriptorAddCallback unknown srvcHandle or uuid"); + ListDelete(&requestInfo->node); + SoftBusFree(requestInfo); } } -static void BleServiceStartCallback(int status, int srvcHandle) +static void BleServerConnectCallback(int32_t halConnId, const char *bleStrMac, const SoftBusBtAddr *btAddr) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "ServiceStartCallback srvcHandle=%d\n", srvcHandle); - if (srvcHandle != g_gattService.svcId) { - return; - } - if (status != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleServiceStartCallback start failed"); - } - UpdateGattService(&g_gattService, status); - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleServiceStartCallback start success"); -} - -static void BleServiceStopCallback(int status, int srvcHandle) -{ - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ServiceStopCallback srvcHandle=%d\n", srvcHandle); - if (srvcHandle != g_gattService.svcId) { - return; - } - if (status != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleServiceStopCallback stop failed"); - } - UpdateGattService(&g_gattService, status); -} - -static void BleServiceDeleteCallback(int status, int srvcHandle) -{ - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ServiceDeleteCallback srvcHandle=%d\n", srvcHandle); - if (srvcHandle != g_gattService.svcId) { - return; - } - if (status != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleServiceStopCallback stop failed"); - } - UpdateGattService(&g_gattService, status); -} - -static void BleConnectServerCallback(int connId, const SoftBusBtAddr *btAddr) -{ - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ConnectServerCallback is coming, halConnId=%d\n", connId); - char bleMac[BT_MAC_LEN]; - int ret = ConvertBtMacToStr(bleMac, BT_MAC_LEN, btAddr->addr, BT_ADDR_LEN); - if (ret != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Convert ble addr failed:%d", ret); - return; - } - if (SoftBusThreadMutexLock(&g_connectionLock) != 0) { + if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return; } ListNode *item = NULL; LIST_FOR_EACH(item, &g_conection_list) { BleConnectionInfo *itemNode = LIST_ENTRY(item, BleConnectionInfo, node); - if (itemNode->halConnId == connId) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleConnectServerCallback exist same connId, exit"); - (void)SoftBusThreadMutexUnlock(&g_connectionLock); + if (itemNode->halConnId == halConnId) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleConnectCallback exist same connId, exit"); + (void)pthread_mutex_unlock(&g_connectionLock); return; } } BleConnectionInfo *newNode = CreateBleConnectionNode(); - newNode->halConnId = connId; + if (newNode == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "ble client node create fail"); + (void)pthread_mutex_unlock(&g_connectionLock); + return; + } + newNode->halConnId = halConnId; if (memcpy_s(newNode->btBinaryAddr.addr, BT_ADDR_LEN, btAddr->addr, BT_ADDR_LEN) != EOK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleConnectServerCallback memcpy_s error"); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleConnectCallback memcpy_s error"); SoftBusFree(newNode); - (void)SoftBusThreadMutexUnlock(&g_connectionLock); + (void)pthread_mutex_unlock(&g_connectionLock); return; } - if (memcpy_s(newNode->info.info.bleInfo.bleMac, BT_MAC_LEN, bleMac, BT_MAC_LEN) != EOK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleConnectServerCallback memcpy_s error"); + if (memcpy_s(newNode->info.info.bleInfo.bleMac, BT_MAC_LEN, bleStrMac, BT_MAC_LEN) != EOK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleConnectCallback memcpy_s error"); SoftBusFree(newNode); - (void)SoftBusThreadMutexUnlock(&g_connectionLock); + (void)pthread_mutex_unlock(&g_connectionLock); return; } - newNode->info.isServer = 1; + newNode->info.isServer = BLE_SERVER_TYPE; newNode->state = BLE_CONNECTION_STATE_CONNECTED; ListTailInsert(&g_conection_list, &(newNode->node)); - (void)SoftBusThreadMutexUnlock(&g_connectionLock); - g_connectCallback->OnConnected(newNode->connId, &(newNode->info)); + (void)pthread_mutex_unlock(&g_connectionLock); } -static void BleDisconnectServerCallback(int connId, const SoftBusBtAddr *btAddr) +static void ReleaseBleConnectionInfo(BleConnectionInfo *info) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "DisconnectServerCallback is coming, halconnId=%d", connId); - char bleMac[BT_MAC_LEN]; - int ret = ConvertBtMacToStr(bleMac, BT_MAC_LEN, btAddr->addr, BT_ADDR_LEN); - if (ret != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Convert ble addr failed:%d", ret); - return; - } - if (SoftBusThreadMutexLock(&g_connectionLock) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); - return; - } ListNode *item = NULL; ListNode *nextItem = NULL; - BleConnectionInfo *targetNode = NULL; - LIST_FOR_EACH_SAFE(item, nextItem, &g_conection_list) { - BleConnectionInfo *itemNode = LIST_ENTRY(item, BleConnectionInfo, node); - if (itemNode->halConnId == connId) { - targetNode = itemNode; + ListDelete(&info->node); + LIST_FOR_EACH_SAFE(item, nextItem, &info->requestList) { + BleRequestInfo *requestInfo = LIST_ENTRY(item, BleRequestInfo, node); + ListDelete(&(requestInfo->node)); + SoftBusFree(requestInfo); + } + SoftBusFree(info); +} + +static void BleNotifyDisconnect(const ListNode *notifyList, int32_t connectionId, + ConnectionInfo connectionInfo, int32_t value) +{ + ListNode *item = NULL; + ListNode *itemNext = NULL; + if (IsListEmpty(notifyList) != true) { + LIST_FOR_EACH_SAFE(item, itemNext, notifyList) { + BleRequestInfo *requestInfo = LIST_ENTRY(item, BleRequestInfo, node); + if (requestInfo->callback.OnConnectFailed != NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[BleNotifyDisconnect]connectionId=%d", connectionId); + requestInfo->callback.OnConnectFailed(requestInfo->requestId, value); + } + ListDelete(&requestInfo->node); + SoftBusFree(requestInfo); + } + } + + if (g_connectCallback != NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[BleNotifyDisconnect] disconn connectionId=%d", connectionId); + g_connectCallback->OnDisconnected(connectionId, &connectionInfo); + } +} + +static void BleDisconnectCallback(int32_t halConnId, int32_t isServer) +{ + ListNode *bleItem = NULL; + ListNode *item = NULL; + ListNode *itemNext = NULL; + int32_t connectionId = -1; + ListNode notifyList; + ListInit(¬ifyList); + ConnectionInfo connectionInfo; + BleConnectionInfo *bleNode = NULL; + if (pthread_mutex_lock(&g_connectionLock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleDisconnectCallback mutex failed"); + return; + } + LIST_FOR_EACH(bleItem, &g_conection_list) { + BleConnectionInfo *itemNode = LIST_ENTRY(bleItem, BleConnectionInfo, node); + if (itemNode->halConnId == halConnId) { + bleNode = itemNode; itemNode->state = BLE_CONNECTION_STATE_CLOSED; - ListDelete(&(itemNode->node)); - DeleteBleConnectionNode(itemNode); + (void)memcpy_s(&connectionInfo, sizeof(ConnectionInfo), &(itemNode->info), sizeof(ConnectionInfo)); + connectionId = itemNode->connId; + connectionInfo.isAvailable = 0; + LIST_FOR_EACH_SAFE(item, itemNext, &itemNode->requestList) { + BleRequestInfo *requestInfo = LIST_ENTRY(item, BleRequestInfo, node); + ListDelete(&requestInfo->node); + ListAdd(¬ifyList, &requestInfo->node); + } break; } } - (void)SoftBusThreadMutexUnlock(&g_connectionLock); - if (targetNode == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleDisconnectServerCallback unknown halconnId:%d", connId); - return; + ReleaseBleConnectionInfo(bleNode); + (void)pthread_mutex_unlock(&g_connectionLock); + if (connectionId != -1) { + BleNotifyDisconnect(¬ifyList, connectionId, connectionInfo, isServer); } - g_connectCallback->OnDisconnected(targetNode->connId, &(targetNode->info)); } -static cJSON *GetLocalInfoJson(void) +static cJSON *GetLocalInfoJson(int32_t roleType) { cJSON *json = cJSON_CreateObject(); if (json == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Cannot create cJSON object"); return NULL; } - char devId[UUID_BUF_LEN] = {0}; + char devId[UDID_BUF_LEN] = {0}; if (LnnGetLocalStrInfo(STRING_KEY_DEV_UDID, devId, UDID_BUF_LEN) != SOFTBUS_OK) { cJSON_Delete(json); SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SendSelfBasicInfo Get local dev Id failed."); @@ -1037,7 +855,7 @@ static cJSON *GetLocalInfoJson(void) SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SendSelfBasicInfo Cannot add devid to jsonobj"); return NULL; } - if (!AddNumberToJsonObject(json, "type", BLE_ROLE_SERVER)) { + if (!AddNumberToJsonObject(json, "type", roleType)) { cJSON_Delete(json); SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SendSelfBasicInfo Cannot add type to jsonobj"); return NULL; @@ -1045,9 +863,9 @@ static cJSON *GetLocalInfoJson(void) return json; } -int SendSelfBasicInfo(uint32_t connId) +static int32_t SendSelfBasicInfo(uint32_t connId, int32_t roleType) { - cJSON *json = GetLocalInfoJson(); + cJSON *json = GetLocalInfoJson(roleType); if (json == NULL) { return SOFTBUS_ERR; } @@ -1080,46 +898,71 @@ int SendSelfBasicInfo(uint32_t connId) .len = dataLen, .buf = (char*)buf }; - BlePostBytesInner(connId, &postData); - return SOFTBUS_OK; + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "SendSelfBasicInfo BlePostBytesInner module:%d", postData.module); + int ret = BlePostBytesInner(connId, &postData); + if (ret != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SendSelfBasicInfo BlePostBytesInner failed"); + SoftBusFree(buf); + } + return ret; } -int PeerBasicInfoParse(BleConnectionInfo *connInfo, const char *value, int32_t len) +static int32_t PeerBasicInfoParse(BleConnectionInfo *connInfo, const char *value, int32_t len) { cJSON *data = NULL; data = cJSON_Parse(value + TYPE_HEADER_SIZE); - if (!GetJsonObjectStringItem(data, "devid", connInfo->peerDevId, UUID_BUF_LEN) || - !GetJsonObjectNumberItem(data, "type", &connInfo->peerType)) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "PeerBasicInfoParse failed"); + if (data == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "PeerBasicInfoParse cJSON_Parse failed"); return SOFTBUS_ERR; } + if (!GetJsonObjectStringItem(data, "devid", connInfo->peerDevId, UUID_BUF_LEN) || + !GetJsonObjectNumberItem(data, "type", &connInfo->peerType)) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "PeerBasicInfoParse get info failed"); + cJSON_Delete(data); + return SOFTBUS_ERR; + } + cJSON_Delete(data); return SOFTBUS_OK; } -static void BleOnDataReceived(int32_t handle, int32_t halConnId, uint32_t len, const char *value) +static int32_t BleOnDataUpdate(BleConnectionInfo *targetNode) { - if (value == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleOnDataReceived invalid data"); - return; + if (targetNode->peerType != BLE_ROLE_CLIENT && targetNode->peerType != BLE_ROLE_SERVER) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleOnDataUpdate invalid role type"); + return SOFTBUS_ERR; } - if (SoftBusThreadMutexLock(&g_connectionLock) != 0) { + if (targetNode->peerType == BLE_ROLE_SERVER) { + BleClientDoneConnect(targetNode); + return SOFTBUS_OK; + } + if (SendSelfBasicInfo(targetNode->connId, BLE_ROLE_SERVER) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SendSelfBasicInfo error"); + return SOFTBUS_ERR; + } + g_connectCallback->OnConnected(targetNode->connId, &(targetNode->info)); + return SOFTBUS_OK; +} + +static void BleOnDataReceived(bool isBleConn, int32_t halConnId, uint32_t len, const char *value) +{ + if (pthread_mutex_lock(&g_connectionLock) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); return; } BleConnectionInfo *targetNode = GetBleConnInfoByHalConnId(halConnId); if (targetNode == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleOnDataReceived unknown device"); - (void)SoftBusThreadMutexUnlock(&g_connectionLock); + (void)pthread_mutex_unlock(&g_connectionLock); return; } - if (handle == g_gattService.bleConnCharaId) { + if (isBleConn) { ConnPktHead *head = (ConnPktHead *)value; if (head->module == MODULE_CONNECTION) { cJSON *data = NULL; data = cJSON_Parse(value + sizeof(ConnPktHead)); if (data == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[receive data invalid]"); - (void)SoftBusThreadMutexUnlock(&g_connectionLock); + (void)pthread_mutex_unlock(&g_connectionLock); return; } RecvConnectedComd(targetNode->connId, (const cJSON*)data); @@ -1139,87 +982,17 @@ static void BleOnDataReceived(int32_t handle, int32_t halConnId, uint32_t len, c g_connectCallback->OnDataReceived(targetNode->connId, MODULE_BLE_NET, 0, (char *)value, len); } else { if (PeerBasicInfoParse(targetNode, value, len) != SOFTBUS_OK) { - (void)SoftBusThreadMutexUnlock(&g_connectionLock); + (void)pthread_mutex_unlock(&g_connectionLock); return; } targetNode->state = BLE_CONNECTION_STATE_BASIC_INFO_EXCHANGED; - SendSelfBasicInfo(targetNode->connId); + if (BleOnDataUpdate(targetNode) != SOFTBUS_OK) { + (void)pthread_mutex_unlock(&g_connectionLock); + return; + } } } - (void)SoftBusThreadMutexUnlock(&g_connectionLock); -} - -static void BleRequestReadCallback(SoftBusGattReadRequest readCbPara) -{ - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "RequestReadCallback transId=%d, attrHandle=%d\n", - readCbPara.transId, readCbPara.attrHandle); - SoftBusGattsResponse response = { - .connectId = readCbPara.connId, - .status = SOFTBUS_BT_STATUS_SUCCESS, - .attrHandle = readCbPara.transId, - .valueLen = strlen("not support!") + 1, - .value = "not support!" - }; - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleRequestReadCallback sendresponse"); - SoftBusGattsSendResponse(&response); -} - -static void BleRequestWriteCallback(SoftBusGattWriteRequest writeCbPara) -{ - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "RequestWriteCallback halconnId=%d, transId=%d, attrHandle=%d\n", - writeCbPara.connId, writeCbPara.transId, writeCbPara.attrHandle); - if (writeCbPara.attrHandle != g_gattService.bleConnCharaId && - writeCbPara.attrHandle != g_gattService.bleNetCharaId) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleOnDataReceived not support handle :%d expect:%d", - writeCbPara.attrHandle, g_gattService.bleConnCharaId); - return; - } - if (writeCbPara.needRsp) { - SoftBusGattsResponse response = { - .connectId = writeCbPara.connId, - .status = SOFTBUS_BT_STATUS_SUCCESS, - .attrHandle = writeCbPara.transId, - .valueLen = writeCbPara.length, - .value = (char *)writeCbPara.value - }; - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleRequestWriteCallback sendresponse"); - SoftBusGattsSendResponse(&response); - } - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, - "BLEINFOPRTINT:BleRequestWriteCallback valuelen:%d value:)", writeCbPara.length); - uint32_t len; - int32_t index = -1; - char *value = BleTransRecv(writeCbPara.connId, (char *)writeCbPara.value, - (uint32_t)writeCbPara.length, &len, &index); - if (value == NULL) { - return; - } - BleOnDataReceived(writeCbPara.attrHandle, writeCbPara.connId, len, (const char *)value); - if (index != -1) { - BleTransCacheFree(writeCbPara.connId, index); - } -} - -static void BleResponseConfirmationCallback(int status, int handle) -{ - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, - "ResponseConfirmationCallback status=%d, handle=%d\n", status, handle); -} - -static void BleNotifySentCallback(int connId, int status) -{ - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "IndicationSentCallback status=%d, connId=%d\n", status, connId); -} - -static void BleMtuChangeCallback(int connId, int mtu) -{ - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "MtuChangeCallback connId=%d, mtu=%d\n", connId, mtu); - BleConnectionInfo *connInfo = GetBleConnInfoByConnId(connId); - if (connInfo == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleMtuChangeCallback GetBleConnInfo failed"); - return; - } - connInfo->mtu = mtu; + (void)pthread_mutex_unlock(&g_connectionLock); } static int32_t SendBleData(SendQueueNode *node) @@ -1227,10 +1000,7 @@ static int32_t SendBleData(SendQueueNode *node) if (node->len > MAX_DATA_LEN) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "SendBleData big msg, len:%d\n", node->len); } - if (node->isServer == 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SendBleData ble gatt client not support"); - return SOFTBUS_ERR; - } + BleConnectionInfo *connInfo = GetBleConnInfoByConnId(node->connectionId); if (connInfo == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleMtuChangeCallback GetBleConnInfo failed"); @@ -1257,11 +1027,12 @@ static void FreeSendNode(SendQueueNode *node) void *BleSendTask(void *arg) { +#define WAIT_TIME 10 + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "BleSendTask enter"); while (1) { SendQueueNode *node = NULL; - BleDequeueBlock((void **)(&node)); - if (node == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "get sendItem failed"); + if (BleDequeueNonBlock((void **)(&node)) != SOFTBUS_OK) { + SoftBusSleepMs(WAIT_TIME); continue; } if (SendBleData(node) != SOFTBUS_OK) { @@ -1271,24 +1042,6 @@ void *BleSendTask(void *arg) } } -static int GattsRegisterCallback(void) -{ - g_bleGattsCallback.ServiceAddCallback = BleServiceAddCallback; - g_bleGattsCallback.CharacteristicAddCallback = BleCharacteristicAddCallback; - g_bleGattsCallback.DescriptorAddCallback = BleDescriptorAddCallback; - g_bleGattsCallback.ServiceStartCallback = BleServiceStartCallback; - g_bleGattsCallback.ServiceStopCallback = BleServiceStopCallback; - g_bleGattsCallback.ServiceDeleteCallback = BleServiceDeleteCallback; - g_bleGattsCallback.ConnectServerCallback = BleConnectServerCallback; - g_bleGattsCallback.DisconnectServerCallback = BleDisconnectServerCallback; - g_bleGattsCallback.RequestReadCallback = BleRequestReadCallback; - g_bleGattsCallback.RequestWriteCallback = BleRequestWriteCallback; - g_bleGattsCallback.ResponseConfirmationCallback = BleResponseConfirmationCallback; - g_bleGattsCallback.NotifySentCallback = BleNotifySentCallback; - g_bleGattsCallback.MtuChangeCallback = BleMtuChangeCallback; - return SoftBusRegisterGattsCallbacks(&g_bleGattsCallback); -} - static void InitBleInterface(void) { g_bleInterface.ConnectDevice = BleConnectDevice; @@ -1300,101 +1053,15 @@ static void InitBleInterface(void) g_bleInterface.StopLocalListening = BleStopLocalListening; } -static void BleConnAddSerMsgHandler(const SoftBusMessage *msg) -{ - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "call GattsRegisterCallback"); - int32_t ret = GattsRegisterCallback(); - if (ret != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "GattsRegisterCallbacks failed: %d", ret); - return; - } - if (SoftBusThreadMutexLock(&g_connectionLock) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); - return; - } - g_gattService.state = BLE_GATT_SERVICE_ADDING; - (void)SoftBusThreadMutexUnlock(&g_connectionLock); - SoftBusBtUuid uuid; - uuid.uuid = (char *)msg->obj; - uuid.uuidLen = BT_UUID_LEN; - ret = SoftBusGattsAddService(uuid, true, MAX_SERVICE_CHAR_NUM); - if (ret != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleGattsAddService failed:%d", ret); - return; - } -} -static void BleConnMsgHandler(SoftBusMessage *msg) -{ - SoftBusBtUuid uuid; - int properties, permissions; - if (msg == NULL) { - return; - } - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ble conn loop process msg type %d", msg->what); - switch (msg->what) { - case ADD_SERVICE_MSG: - BleConnAddSerMsgHandler(msg); - break; - case ADD_CHARA_MSG: - uuid.uuid = (char *)msg->obj; - uuid.uuidLen = BT_UUID_LEN; - properties = (int32_t)msg->arg1; - permissions = (int32_t)msg->arg2; - int32_t ret = SoftBusGattsAddCharacteristic(g_gattService.svcId, uuid, properties, permissions); - if (ret != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleGattsAddCharacteristic failed:%d", ret); - return; - } - break; - case ADD_DESCRIPTOR_MSG: - uuid.uuid = (char *)msg->obj; - uuid.uuidLen = BT_UUID_LEN; - permissions = (int32_t)msg->arg2; - ret = SoftBusGattsAddDescriptor(g_gattService.svcId, uuid, permissions); - if (ret != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleGattsAddDescriptor failed:%d", ret); - return; - } - break; - default: - break; - } -} - -static int BleConnLooperInit(void) -{ - g_bleAsyncHandler.looper = CreateNewLooper("ble_looper"); - if (g_bleAsyncHandler.looper == NULL) { - return SOFTBUS_ERR; - } - g_bleAsyncHandler.HandleMessage = BleConnMsgHandler; - return SOFTBUS_OK; -} - static int BleQueueInit(void) { - uint32_t sendQueueSize; - int ret = QueueSizeCalc(SEND_QUEUE_UNIT_NUM, &sendQueueSize); - if (ret != SOFTBUS_OK) { + if (BleInnerQueueInit() != SOFTBUS_OK) { return SOFTBUS_ERR; } - g_sendQueue.queue = (LockFreeQueue *)SoftBusCalloc(sendQueueSize); - if (g_sendQueue.queue == NULL) { - return SOFTBUS_ERR; - } - ret = QueueInit(g_sendQueue.queue, SEND_QUEUE_UNIT_NUM); - if (ret != SOFTBUS_OK) { - SoftBusFree(g_sendQueue.queue); - g_sendQueue.queue = NULL; - return SOFTBUS_ERR; - } - SoftBusMutexInit(&g_sendQueue.lock, NULL); - SoftBusCondInit(&g_sendQueue.cond); - SoftBusThread tid; - if (SoftBusThreadCreate(&tid, NULL, BleSendTask, NULL) != 0) { + pthread_t tid; + if (pthread_create(&tid, NULL, BleSendTask, NULL) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "create BleSendTask failed"); - SoftBusFree(g_sendQueue.queue); - g_sendQueue.queue = NULL; + BleInnerQueueDeinit(); return SOFTBUS_ERR; } return SOFTBUS_OK; @@ -1403,44 +1070,62 @@ static int BleQueueInit(void) void BleConnOnBtStateChanged(int listenerId, int state) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[BleOnBtStateChanged] id:%d, state:%d", listenerId, state); - if (state == SOFTBUS_BT_STATE_TURN_ON) { - SoftBusMessage *msg = BleConnCreateLoopMsg(ADD_SERVICE_MSG, 0, 0, SOFTBUS_SERVICE_UUID); - if (msg == NULL) { - return; - } - g_bleAsyncHandler.looper->PostMessage(g_bleAsyncHandler.looper, msg); - } + SoftBusGattServerOnBtStateChanged(state); } static SoftBusBtStateListener g_bleConnStateListener = { .OnBtStateChanged = BleConnOnBtStateChanged }; +static SoftBusBleConnCalback g_bleClientConnCalback = { + .BleOnDataReceived = BleOnDataReceived, + .BleDisconnectCallback = BleDisconnectCallback, + .BleConnectCallback = BleClientConnectCallback, + .GetBleConnInfoByHalConnId = GetBleConnInfoByHalConnId, +}; + +static SoftBusBleConnCalback g_bleServerConnCalback = { + .BleOnDataReceived = BleOnDataReceived, + .BleDisconnectCallback = BleDisconnectCallback, + .BleConnectCallback = BleServerConnectCallback, + .GetBleConnInfoByHalConnId = GetBleConnInfoByHalConnId, +}; + +static SoftBusBleTransCalback g_bleTransCallback = { + .GetBleConnInfoByHalConnId = GetBleConnInfoByHalConnId, +}; + ConnectFuncInterface *ConnInitBle(const ConnectCallback *callback) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[InitBle]"); int32_t ret; - ret = BleConnLooperInit(); + ret = SoftBusGattServerInit(&g_bleServerConnCalback); if (ret != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleConnLoopInit failed: %d", ret); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusGattServerInit failed:%d", ret); return NULL; } - SoftBusMutexAttr mutexAttr; - mutexAttr.type = SOFTBUS_MUTEX_RECURSIVE; - SoftBusMutexInit(&g_connectionLock, &mutexAttr); + ret = SoftBusGattClientInit(&g_bleClientConnCalback); + if (ret != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusGattClientInit failed:%d", ret); + return NULL; + } + ret = BleTransInit(&g_bleTransCallback); + if (ret != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleTransInit failed:%d", ret); + return NULL; + } + pthread_mutexattr_t attr; + pthread_mutexattr_init(&attr); + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); + pthread_mutex_init(&g_connectionLock, &attr); ret = BleQueueInit(); if (ret != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleQueueInit failed: %d", ret); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleQueueInit failed:%d", ret); return NULL; } ret = SoftBusAddBtStateListener(&g_bleConnStateListener); if (ret < 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusAddBtStateListener failed: %d", ret); - return NULL; - } - ret = SoftBusEnableBt(); - if (ret != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusAddBtStateListener failed: %d", ret); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusAddBtStateListener failed:%d", ret); return NULL; } g_connectCallback = (ConnectCallback*)callback; diff --git a/core/connection/ble/src/softbus_ble_gatt_client.c b/core/connection/ble/src/softbus_ble_gatt_client.c new file mode 100644 index 000000000..81ffa25b7 --- /dev/null +++ b/core/connection/ble/src/softbus_ble_gatt_client.c @@ -0,0 +1,669 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "cJSON.h" +#include "common_list.h" +#include "message_handler.h" +#include "securec.h" +#include "softbus_adapter_ble_gatt_client.h" +#include "softbus_adapter_mem.h" +#include "softbus_ble_connection_inner.h" +#include "softbus_ble_queue.h" +#include "softbus_ble_trans_manager.h" +#include "softbus_conn_manager.h" +#include "softbus_def.h" +#include "softbus_errcode.h" +#include "softbus_log.h" +#include "softbus_queue.h" +#include "softbus_type_def.h" +#include "softbus_utils.h" + +#define INVALID_GATTC_ID (-1) +#define DEFAULT_MTU_SIZE 512 +typedef enum { + BLE_GATT_CLIENT_INITIAL = 0, + BLE_GATT_CLIENT_STARTING, + BLE_GATT_CLIENT_STARTED, + BLE_GATT_CLIENT_SERVICE_SEARCHING, + BLE_GATT_CLIENT_SERVICE_SEARCHED, + BLE_GATT_CLIENT_NOTIFICATING_ONCE, + BLE_GATT_CLIENT_NOTIFICATED_ONCE, + BLE_GATT_CLIENT_NOTIFICATING_TWICE, + BLE_GATT_CLIENT_NOTIFICATED_TWICE, + BLE_GATT_CLIENT_MTU_SETTING, + BLE_GATT_CLIENT_MTU_SETTED, + BLE_GATT_CLIENT_CONNECTED, + BLE_GATT_CLIENT_STOPPING, + BLE_GATT_CLIENT_STOPPED, + BLE_GATT_CLIENT_INVALID +} GattClientState; + +typedef enum { + CLIENT_CONNECTED, + CLIENT_SERVICE_SEARCHED, + CLIENT_NOTIFICATED, + CLIENT_DISCONNECTED, + CLIENT_MTU_SETTED, +} BleClientConnLoopMsg; + +static SoftBusHandler g_bleClientAsyncHandler = { + .name ="g_bleClientAsyncHandler" +}; + +typedef struct { + ListNode node; + int32_t clientId; + int32_t state; + SoftBusBtAddr peerAddr; +} BleGattcInfo; + +static SoftBusGattcCallback g_softbusGattcCb = { 0 }; +static SoftBusBleConnCalback *g_softBusBleConnCb = NULL; +static SoftBusList *g_gattcInfoList = NULL; +static bool g_gattcIsInited = false; +static bool UpdateBleGattcInfoStateInner(BleGattcInfo *infoNode, int32_t newState); + +static BleGattcInfo *CreateNewBleGattcInfo(SoftBusBtAddr *bleAddr) +{ + BleGattcInfo *infoNode = (BleGattcInfo *)SoftBusCalloc(sizeof(BleGattcInfo)); + if (infoNode == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "calloc infoNode failed"); + return NULL; + } + ListInit(&(infoNode->node)); + infoNode->clientId = INVALID_GATTC_ID; + infoNode->state = BLE_GATT_CLIENT_INITIAL; + if (memcpy_s(infoNode->peerAddr.addr, BT_ADDR_LEN, bleAddr->addr, BT_ADDR_LEN) != EOK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "memcpy_s fail"); + SoftBusFree(infoNode); + return NULL; + } + return infoNode; +} + +static BleGattcInfo *GetBleGattcInfoByClientIdInner(int32_t clientId) +{ + BleGattcInfo *infoNode = NULL; + LIST_FOR_EACH_ENTRY(infoNode, &(g_gattcInfoList->list), BleGattcInfo, node) { + if (clientId == infoNode->clientId) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "GetBleGattcInfoByClientId exsist"); + return infoNode; + } + } + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "GetBleGattcInfoByClientId not exsist"); + return NULL; +} + +static int32_t AddGattcInfoToList(BleGattcInfo *info) +{ + BleGattcInfo *infoNode = NULL; + if (pthread_mutex_lock(&g_gattcInfoList->lock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock failed"); + return SOFTBUS_LOCK_ERR; + } + + LIST_FOR_EACH_ENTRY(infoNode, &(g_gattcInfoList->list), BleGattcInfo, node) { + if (memcmp(infoNode->peerAddr.addr, info->peerAddr.addr, BT_ADDR_LEN) != 0) { + continue; + } + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "peer bleaddr already exsisted"); + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + return SOFTBUS_GATTC_DUPLICATE_PARAM; + } + ListTailInsert(&(g_gattcInfoList->list), &(info->node)); + g_gattcInfoList->cnt++; + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + return SOFTBUS_OK; +} + +static char *GetBleAttrUuid(int32_t module) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "GetBleAttrUuid %d", module); + if (module == MODULE_BLE_NET) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "GetBleAttrUuid1"); + return SOFTBUS_CHARA_BLENET_UUID; + } else if (module == MODULE_BLE_CONN) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "GetBleAttrUuid2"); + return SOFTBUS_CHARA_BLECONN_UUID; + } else { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "GetBleAttrUuid3"); + return SOFTBUS_CHARA_BLECONN_UUID; + } +} + +int32_t SoftBusGattClientSend(const int32_t clientId, const char *data, int32_t len, int32_t module) +{ + if (g_gattcIsInited != true) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "gattc not init"); + return SOFTBUS_BLEGATTC_NONT_INIT; + } + if (clientId < 0 || data == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "invalid param"); + return SOFTBUS_ERR; + } + + SoftBusGattcData clientData; + clientData.serviceUuid.uuid = SOFTBUS_SERVICE_UUID; + clientData.serviceUuid.uuidLen = strlen(SOFTBUS_SERVICE_UUID); + clientData.characterUuid.uuid = GetBleAttrUuid(module); + clientData.characterUuid.uuidLen = strlen(SOFTBUS_SERVICE_UUID); + clientData.valueLen = len; + clientData.value = (char *)data; + BleGattcInfo *infoNode = NULL; + if (pthread_mutex_lock(&g_gattcInfoList->lock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock failed"); + return SOFTBUS_BLECONNECTION_MUTEX_LOCK_ERROR; + } + infoNode = GetBleGattcInfoByClientIdInner(clientId); + if (infoNode == NULL) { + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "GetBleGattcInfoByClientIdInner not exsist"); + return SOFTBUS_ERR; + } + if (infoNode->state != BLE_GATT_CLIENT_CONNECTED) { + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "ble connect not ready, current state=%d", infoNode->state); + return SOFTBUS_BLEGATTC_NOT_READY; + } + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + return SoftbusGattcWriteCharacteristic(clientId, &clientData); +} + +int32_t SoftBusGattClientConnect(SoftBusBtAddr *bleAddr) +{ + if (g_gattcIsInited != true) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "gattc not init"); + return SOFTBUS_BLEGATTC_NONT_INIT; + } + if (bleAddr == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "invalid param"); + return SOFTBUS_ERR; + } + BleGattcInfo *infoNode = CreateNewBleGattcInfo(bleAddr); + if (infoNode == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "gattc create infoNode failed"); + return SOFTBUS_ERR; + } + infoNode->clientId = SoftbusGattcRegister(); + if (infoNode->clientId == INVALID_GATTC_ID) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "gattc rigister failed"); + SoftBusFree(infoNode); + return SOFTBUS_ERR; + } + if (SoftbusGattcConnect(infoNode->clientId, bleAddr) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftbusGattcConnect failed"); + SoftBusFree(infoNode); + return SOFTBUS_ERR; + } + if (AddGattcInfoToList(infoNode) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "AddGattcInfoToList failed"); + SoftBusFree(infoNode); + return SOFTBUS_ERR; + } + if (UpdateBleGattcInfoStateInner(infoNode, BLE_GATT_CLIENT_STARTING) != true) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "UpdateBleGattcInfoStateInner failed"); + SoftBusFree(infoNode); + return SOFTBUS_ERR; + } + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "aaa SoftBusGattClientConnect addr=%s", bleAddr->addr); + return infoNode->clientId; +} + +int32_t SoftBusGattClientDisconnect(int32_t clientId) +{ + if (g_gattcIsInited != true) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "gattc not init"); + return SOFTBUS_BLEGATTC_NONT_INIT; + } + + if (clientId < 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "invalid param"); + return SOFTBUS_ERR; + } + BleGattcInfo *infoNode = NULL; + if (pthread_mutex_lock(&g_gattcInfoList->lock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock failed"); + return SOFTBUS_LOCK_ERR; + } + infoNode = GetBleGattcInfoByClientIdInner(clientId); + if (infoNode == NULL) { + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "GetBleGattcInfoByClientId not exsist"); + return SOFTBUS_BLEGATTC_NODE_NOT_EXIST; + } + infoNode->state = BLE_GATT_CLIENT_STOPPING; + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "SoftBusGattClientDisconnect"); + return SoftbusBleGattcDisconnect(clientId); +} + +static bool UpdateBleGattcInfoStateInner(BleGattcInfo *infoNode, int32_t newState) +{ + if (newState == (infoNode->state + 1)) { + infoNode->state = infoNode->state + 1; + return true; + } + infoNode->state = BLE_GATT_CLIENT_INVALID; + return false; +} + +static SoftBusMessage *BleClientConnCreateLoopMsg(int32_t what, uint64_t arg1, uint64_t arg2, const char *data) +{ + SoftBusMessage *msg = NULL; + msg = SoftBusCalloc(sizeof(SoftBusMessage)); + if (msg == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleClientConnCreateLoopMsg SoftBusCalloc failed"); + return NULL; + } + msg->what = what; + msg->arg1 = arg1; + msg->arg2 = arg2; + msg->handler = &g_bleClientAsyncHandler; + msg->FreeMessage = NULL; + msg->obj = (void *)data; + return msg; +} + +static void ConnectedMsgHandler(int32_t clientId, int status) +{ + BleGattcInfo *infoNode = NULL; + if (pthread_mutex_lock(&g_gattcInfoList->lock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock failed"); + } + infoNode = GetBleGattcInfoByClientIdInner(clientId); + if (infoNode == NULL) { + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "GetBleGattcInfoByClientId not exsist"); + return; + } + + if ((status != SOFTBUS_GATT_SUCCESS) || + (UpdateBleGattcInfoStateInner(infoNode, BLE_GATT_CLIENT_STARTED) != true)) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "ConnectedMsgHandler error"); + goto EXIT; + } + if (SoftbusGattcSearchServices(clientId) != SOFTBUS_OK) { + goto EXIT; + } + if (UpdateBleGattcInfoStateInner(infoNode, BLE_GATT_CLIENT_SERVICE_SEARCHING) != true) { + goto EXIT; + } + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + return; +EXIT: + g_gattcInfoList->cnt--; + ListDelete(&(infoNode->node)); + SoftBusFree(infoNode); + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + (void)SoftbusGattcUnRegister(clientId); + (void)g_softBusBleConnCb->BleDisconnectCallback(clientId, 0); // 0 == client +} + +static void SearchedMsgHandler(int32_t clientId, int status) +{ + BleGattcInfo *infoNode = NULL; + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "%d %d", clientId, status); + if (pthread_mutex_lock(&g_gattcInfoList->lock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock failed"); + } + infoNode = GetBleGattcInfoByClientIdInner(clientId); + if (infoNode == NULL) { + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "GetBleGattcInfoByClientId not exsist"); + return; + } + if (infoNode->state != BLE_GATT_CLIENT_SERVICE_SEARCHING) { + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "invalid process for client:%d", clientId); + return; + } + if (UpdateBleGattcInfoStateInner(infoNode, BLE_GATT_CLIENT_SERVICE_SEARCHED) != true) { + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "UpdateBleGattcInfoStateInner failed"); + return; + } + SoftBusBtUuid serverUuid; + SoftBusBtUuid connUuid; + serverUuid.uuid = SOFTBUS_SERVICE_UUID; + serverUuid.uuidLen = strlen(SOFTBUS_SERVICE_UUID); + connUuid.uuid = SOFTBUS_CHARA_BLECONN_UUID; + connUuid.uuidLen = strlen(SOFTBUS_SERVICE_UUID); + if (status != SOFTBUS_GATT_SUCCESS) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "invalid status:%d", status); + goto EXIT; + } + if (SoftbusGattcGetService(clientId, &serverUuid) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftbusGattcGetService failed"); + goto EXIT; + } + if (SoftbusGattcRegisterNotification(clientId, &serverUuid, &connUuid) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "bleGattcRegisterNotification connUuid error"); + goto EXIT; + } + + (void)UpdateBleGattcInfoStateInner(infoNode, BLE_GATT_CLIENT_NOTIFICATING_ONCE); + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + return; +EXIT: + infoNode->state = BLE_GATT_CLIENT_STOPPING; + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + (void)SoftbusBleGattcDisconnect(clientId); +} + +static int32_t NotificatedOnceHandler(BleGattcInfo *infoNode) +{ + SoftBusBtUuid serverUuid; + SoftBusBtUuid netUuid; + serverUuid.uuid = SOFTBUS_SERVICE_UUID; + serverUuid.uuidLen = strlen(SOFTBUS_SERVICE_UUID); + netUuid.uuid = SOFTBUS_CHARA_BLENET_UUID; + netUuid.uuidLen = strlen(SOFTBUS_SERVICE_UUID); + if (SoftbusGattcRegisterNotification(infoNode->clientId, &serverUuid, &netUuid) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftbusGattcRegisterNotification failed"); + return SOFTBUS_ERR; + } + if (UpdateBleGattcInfoStateInner(infoNode, BLE_GATT_CLIENT_NOTIFICATING_TWICE) != true) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "UpdateBleGattcInfoStateInner failed"); + return SOFTBUS_ERR; + } + return SOFTBUS_OK; +} + +static int32_t NotificatedTwiceHandler(BleGattcInfo *infoNode) +{ + if (UpdateBleGattcInfoStateInner(infoNode, BLE_GATT_CLIENT_MTU_SETTING) != true) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "UpdateBleGattcInfoStateInner failed"); + return SOFTBUS_ERR; + } + if (SoftbusGattcConfigureMtuSize(infoNode->clientId, DEFAULT_MTU_SIZE) != SOFTBUS_OK) { + return SOFTBUS_ERR; + } + return SOFTBUS_OK; +} + + +static void NotificatedMsgHandler(int32_t clientId, int status) +{ + BleGattcInfo *infoNode = NULL; + if (pthread_mutex_lock(&g_gattcInfoList->lock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock failed"); + } + infoNode = GetBleGattcInfoByClientIdInner(clientId); + if (infoNode == NULL) { + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "GetBleGattcInfoByClientId not exsist"); + return; + } + + if (infoNode->state != BLE_GATT_CLIENT_NOTIFICATING_ONCE && + infoNode->state != BLE_GATT_CLIENT_NOTIFICATING_TWICE) { + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "invalid process for client:%d", clientId); + return; + } + (void)UpdateBleGattcInfoStateInner(infoNode, infoNode->state + 1); + if (status != SOFTBUS_GATT_SUCCESS) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "NotificatedMsgHandler error"); + goto EXIT; + } + if ((infoNode->state == BLE_GATT_CLIENT_NOTIFICATED_ONCE) && + (NotificatedOnceHandler(infoNode) != SOFTBUS_OK)) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "NotificatedOnceHandler error"); + goto EXIT; + } + if ((infoNode->state == BLE_GATT_CLIENT_NOTIFICATED_TWICE) && + (NotificatedTwiceHandler(infoNode) != SOFTBUS_OK)) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "NotificatedTwiceHandler error"); + goto EXIT; + } + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + return; +EXIT: + infoNode->state = BLE_GATT_CLIENT_STOPPING; + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + (void)SoftbusBleGattcDisconnect(clientId); +} + +static void DisconnectedMsgHandler(int32_t clientId, int status) +{ + BleGattcInfo *infoNode = NULL; + if (pthread_mutex_lock(&g_gattcInfoList->lock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock failed"); + } + infoNode = GetBleGattcInfoByClientIdInner(clientId); + if (infoNode == NULL) { + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "GetBleGattcInfoByClientId not exsist"); + return; + } + if ((status != SOFTBUS_GATT_SUCCESS) || + (UpdateBleGattcInfoStateInner(infoNode, BLE_GATT_CLIENT_STOPPING) != true)) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Passavie disconnect!clientId=%d", clientId); + } + g_gattcInfoList->cnt--; + ListDelete(&(infoNode->node)); + SoftBusFree(infoNode); + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + (void)SoftbusGattcUnRegister(clientId); + (void)g_softBusBleConnCb->BleDisconnectCallback(clientId, 0); // 0 == client +} + +static void MtuSettedMsgHandler(int32_t clientId, int32_t mtuSize) +{ + BleGattcInfo *infoNode = NULL; + char bleStrMac[BT_MAC_LEN]; + if (pthread_mutex_lock(&g_gattcInfoList->lock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock failed"); + } + infoNode = GetBleGattcInfoByClientIdInner(clientId); + if (infoNode == NULL) { + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "GetBleGattcInfoByClientId not exsist"); + return; + } + if (UpdateBleGattcInfoStateInner(infoNode, BLE_GATT_CLIENT_MTU_SETTED) != true) { + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "invalid process for client:%d", clientId); + return; + } + (void)UpdateBleGattcInfoStateInner(infoNode, BLE_GATT_CLIENT_CONNECTED); + if (ConvertBtMacToStr(bleStrMac, BT_MAC_LEN, infoNode->peerAddr.addr, BT_ADDR_LEN) != SOFTBUS_OK) { + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Convert ble addr failed"); + return; + } + g_softBusBleConnCb->BleConnectCallback(clientId, bleStrMac, &(infoNode->peerAddr)); + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); +} + +static void BleGattcMsgHandler(SoftBusMessage *msg) +{ + if (msg == NULL) { + return; + } + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, " 11ble gattc conn loop process msg type %d", msg->what); + switch (msg->what) { + case CLIENT_CONNECTED: + ConnectedMsgHandler((int32_t)msg->arg1, (int32_t)msg->arg2); + break; + case CLIENT_SERVICE_SEARCHED: + SearchedMsgHandler((int32_t)msg->arg1, (int32_t)msg->arg2); + break; + case CLIENT_NOTIFICATED: + NotificatedMsgHandler((int32_t)msg->arg1, (int32_t)msg->arg2); + break; + case CLIENT_DISCONNECTED: + DisconnectedMsgHandler((int32_t)msg->arg1, (int32_t)msg->arg2); + break; + case CLIENT_MTU_SETTED: + MtuSettedMsgHandler((int32_t)msg->arg1, (int32_t)msg->arg2); + break; + default: + break; + } +} + +static void BleGattcConnStateCallback(int32_t clientId, int32_t state, int32_t status) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ConnStateCallback ble gattc id=%d,state=%d\n", + clientId, status); + if (state == SOFTBUS_BT_CONNECT) { + SoftBusMessage *msg = BleClientConnCreateLoopMsg(CLIENT_CONNECTED, clientId, status, NULL); + if (msg == NULL) { + return; + } + g_bleClientAsyncHandler.looper->PostMessage(g_bleClientAsyncHandler.looper, msg); + } + if (state == SOFTBUS_BT_DISCONNECT) { + SoftBusMessage *msg = BleClientConnCreateLoopMsg(CLIENT_DISCONNECTED, clientId, status, NULL); + if (msg == NULL) { + return; + } + g_bleClientAsyncHandler.looper->PostMessage(g_bleClientAsyncHandler.looper, msg); + } +} + +static void BleGattcSearchServiceCallback(int32_t clientId, int status) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "BleGattcSearchServiceCallback id=%d,state=%d\n", + clientId, status); + SoftBusMessage *msg = BleClientConnCreateLoopMsg(CLIENT_SERVICE_SEARCHED, clientId, status, NULL); + if (msg == NULL) { + return; + } + g_bleClientAsyncHandler.looper->PostMessage(g_bleClientAsyncHandler.looper, msg); +} + +static void BleGattcRegisterNotificationCallback(int32_t clientId, int status) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "BleGattcRegisterNotificationCallback id=%d,state=%d\n", + clientId, status); + SoftBusMessage *msg = BleClientConnCreateLoopMsg(CLIENT_NOTIFICATED, clientId, status, NULL); + if (msg == NULL) { + return; + } + g_bleClientAsyncHandler.looper->PostMessage(g_bleClientAsyncHandler.looper, msg); +} + +static void BleGattcConfigureMtuSizeCallback(int32_t clientId, int32_t mtuSize, int32_t status) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "BleGattcConfigureMtuSizeCallback id=%d,state=%d\n", + clientId, status); + if (status != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "BleGattcConfigureMtuSizeCallback status error:%d", status); + return; + } + SoftBusMessage *msg = BleClientConnCreateLoopMsg(CLIENT_MTU_SETTED, clientId, mtuSize, NULL); + if (msg == NULL) { + return; + } + g_bleClientAsyncHandler.looper->PostMessage(g_bleClientAsyncHandler.looper, msg); +} + +static int32_t GetMouduleFlags(SoftBusBtUuid *charaUuid, bool *flag) +{ + if (memcmp(charaUuid->uuid, SOFTBUS_CHARA_BLECONN_UUID, charaUuid->uuidLen) == 0) { + *flag = true; + return SOFTBUS_OK; + } + if (memcmp(charaUuid->uuid, SOFTBUS_CHARA_BLENET_UUID, charaUuid->uuidLen) == 0) { + *flag = false; + return SOFTBUS_OK; + } + return SOFTBUS_ERR; +} + +static void BleGattcNotificationReceiveCallback(int32_t clientId, SoftBusGattcNotify *param, int32_t status) +{ + BleGattcInfo *infoNode = NULL; + if (pthread_mutex_lock(&g_gattcInfoList->lock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock failed"); + return; + } + infoNode = GetBleGattcInfoByClientIdInner(clientId); + if (infoNode == NULL) { + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "GetBleGattcInfoByClientId not exsist"); + return; + } + if ((status != SOFTBUS_GATT_SUCCESS) || infoNode->state != BLE_GATT_CLIENT_CONNECTED) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "111BleGattcNotificationReceiveCallback error"); + return; + } + bool isBleConn; + if (GetMouduleFlags(&(param->charaUuid), &isBleConn) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleGattcNotificationReceiveCallback uuid error"); + return; + } + uint32_t len; + int32_t index = -1; + char *value = BleTransRecv(clientId, (char *)param->data, + (uint32_t)param->dataLen, &len, &index); + if (value == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "data not enough"); + return; + } + (void)g_softBusBleConnCb->BleOnDataReceived(isBleConn, clientId, (uint32_t)len, (char *)value); + if (index != -1) { + BleTransCacheFree(clientId, index); + } + (void)pthread_mutex_unlock(&g_gattcInfoList->lock); +} + +static int BleConnClientLooperInit(void) +{ + g_bleClientAsyncHandler.looper = CreateNewLooper("ble_gattc_looper"); + if (g_bleClientAsyncHandler.looper == NULL) { + return SOFTBUS_ERR; + } + g_bleClientAsyncHandler.HandleMessage = BleGattcMsgHandler; + return SOFTBUS_OK; +} + +static void RegistGattcCallback(SoftBusBleConnCalback *cb) +{ + g_softbusGattcCb.ConnectionStateCallback = BleGattcConnStateCallback; + g_softbusGattcCb.ServiceCompleteCallback = BleGattcSearchServiceCallback; + g_softbusGattcCb.RegistNotificationCallback = BleGattcRegisterNotificationCallback; + g_softbusGattcCb.NotificationReceiveCallback = BleGattcNotificationReceiveCallback; + g_softbusGattcCb.ConfigureMtuSizeCallback = BleGattcConfigureMtuSizeCallback; + SoftbusGattcRegisterCallback(&g_softbusGattcCb); + g_softBusBleConnCb = cb; +} + +int32_t SoftBusGattClientInit(SoftBusBleConnCalback *cb) +{ + if (g_gattcIsInited == true) { + return SOFTBUS_OK; + } + + if (cb == NULL) { + return SOFTBUS_ERR; + } + + int ret = BleConnClientLooperInit(); + if (ret != SOFTBUS_OK) { + return ret; + } + g_gattcInfoList = CreateSoftBusList(); + if (g_gattcInfoList == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "init ble gattc info list fail"); + return SOFTBUS_ERR; + } + RegistGattcCallback(cb); + g_gattcIsInited = true; + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "init gattc success!"); + return SOFTBUS_OK; +} diff --git a/core/connection/ble/src/softbus_ble_gatt_server.c b/core/connection/ble/src/softbus_ble_gatt_server.c new file mode 100644 index 000000000..1ae7ea18e --- /dev/null +++ b/core/connection/ble/src/softbus_ble_gatt_server.c @@ -0,0 +1,660 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include + +#include "cJSON.h" +#include "message_handler.h" +#include "securec.h" +#include "softbus_adapter_ble_gatt_server.h" +#include "softbus_adapter_mem.h" +#include "softbus_ble_connection_inner.h" +#include "softbus_ble_gatt_server.h" +#include "softbus_ble_queue.h" +#include "softbus_ble_trans_manager.h" +#include "softbus_conn_manager.h" +#include "softbus_def.h" +#include "softbus_errcode.h" +#include "softbus_log.h" +#include "softbus_queue.h" +#include "softbus_type_def.h" +#include "softbus_utils.h" + +typedef enum { + BLE_GATT_SERVICE_INITIAL = 0, + BLE_GATT_SERVICE_ADDING, + BLE_GATT_SERVICE_ADDED, + BLE_GATT_SERVICE_STARTING, + BLE_GATT_SERVICE_STARTED, + BLE_GATT_SERVICE_STOPPING, + BLE_GATT_SERVICE_DELETING, + BLE_GATT_SERVICE_INVALID +} GattServiceState; + +typedef struct { + GattServiceState state; + int32_t svcId; + int32_t bleConnCharaId; + int32_t bleConnDesId; + int32_t bleNetCharaId; + int32_t bleNetDesId; +} SoftBusGattService; + +typedef enum { + ADD_SERVICE_MSG, + ADD_CHARA_MSG, + ADD_DESCRIPTOR_MSG, +} BleConnLoopMsg; + +static const int MAX_SERVICE_CHAR_NUM = 8; + +static SoftBusHandler g_bleAsyncHandler = { + .name ="g_bleAsyncHandler" +}; +static SoftBusGattsCallback g_bleGattsCallback = { 0 }; +static SoftBusBleConnCalback *g_softBusBleConnCb = NULL; +static pthread_mutex_t g_serviceStateLock; +static SoftBusGattService g_gattService = { + .state = BLE_GATT_SERVICE_INITIAL, + .svcId = -1, + .bleConnCharaId = -1, + .bleConnDesId = -1, + .bleNetCharaId = -1, + .bleNetDesId = -1 +}; + +static SoftBusMessage *BleConnCreateLoopMsg(int32_t what, uint64_t arg1, uint64_t arg2, const char *data) +{ + SoftBusMessage *msg = NULL; + msg = SoftBusCalloc(sizeof(SoftBusMessage)); + if (msg == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleConnCreateLoopMsg SoftBusCalloc failed"); + return NULL; + } + msg->what = what; + msg->arg1 = arg1; + msg->arg2 = arg2; + msg->handler = &g_bleAsyncHandler; + msg->FreeMessage = NULL; + msg->obj = (void *)data; + return msg; +} + +int32_t GetBleAttrHandle(int32_t module) +{ + return (module == MODULE_BLE_NET) ? g_gattService.bleNetCharaId : g_gattService.bleConnCharaId; +} + +int32_t SoftBusGattServerSend(int32_t halConnId, const char *data, int32_t len, int32_t module) +{ + SoftBusGattsNotify notify = { + .connectId = halConnId, + .attrHandle = GetBleAttrHandle(module), + .confirm = 0, + .valueLen = len, + .value = (char *)data + }; + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "SoftBusGattServerSend halconnId:%d attrHandle:%d confirm:%d", + notify.connectId, notify.attrHandle, notify.confirm); + return SoftBusGattsSendNotify(¬ify); +} + +int32_t SoftBusGattServerStartService(void) +{ + if (pthread_mutex_lock(&g_serviceStateLock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusGattServerStartService lock mutex failed"); + return SOFTBUS_BLECONNECTION_MUTEX_LOCK_ERROR; + } + if ((g_gattService.state == BLE_GATT_SERVICE_STARTED) || + (g_gattService.state == BLE_GATT_SERVICE_STARTING)) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "Ble service already started or is starting"); + (void)pthread_mutex_unlock(&g_serviceStateLock); + return SOFTBUS_OK; + } + if (g_gattService.state == BLE_GATT_SERVICE_ADDED) { + g_gattService.state = BLE_GATT_SERVICE_STARTING; + int ret = SoftBusGattsStartService(g_gattService.svcId); + if (ret != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusGattsStartService failed"); + g_gattService.state = BLE_GATT_SERVICE_ADDED; + } + (void)pthread_mutex_unlock(&g_serviceStateLock); + return (ret == SOFTBUS_OK) ? ret : SOFTBUS_ERR; + } + (void)pthread_mutex_unlock(&g_serviceStateLock); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "start gatt service wrong state:%d", g_gattService.state); + return SOFTBUS_ERR; +} + +int32_t SoftBusGattServerStopService(void) +{ + if (pthread_mutex_lock(&g_serviceStateLock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SoftBusGattServerStopService lock mutex failed"); + return SOFTBUS_BLECONNECTION_MUTEX_LOCK_ERROR; + } + if ((g_gattService.state == BLE_GATT_SERVICE_ADDED) || + (g_gattService.state == BLE_GATT_SERVICE_STOPPING)) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "Ble service already stopped or is stopping"); + (void)pthread_mutex_unlock(&g_serviceStateLock); + return SOFTBUS_OK; + } + if (g_gattService.state == BLE_GATT_SERVICE_STARTED) { + g_gattService.state = BLE_GATT_SERVICE_STOPPING; + int ret = SoftBusGattsStopService(g_gattService.svcId); + if (ret != SOFTBUS_OK) { + g_gattService.state = BLE_GATT_SERVICE_STARTED; + } + (void)pthread_mutex_unlock(&g_serviceStateLock); + return (ret == SOFTBUS_OK) ? ret : SOFTBUS_ERR; + } + (void)pthread_mutex_unlock(&g_serviceStateLock); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "stop gatt service wrong state:%d", g_gattService.state); + return SOFTBUS_ERR; +} + +static void UpdateGattService(SoftBusGattService *service, int status) +{ + if (service == NULL) { + return; + } + if (pthread_mutex_lock(&g_serviceStateLock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); + return; + } + switch (service->state) { + case BLE_GATT_SERVICE_ADDING: + if ((service->svcId != -1) && + (service->bleConnCharaId != -1) && + (service->bleNetCharaId != -1) && + (service->bleConnDesId != -1) && + (service->bleNetDesId != -1)) { + service->state = BLE_GATT_SERVICE_ADDED; + if (SoftBusGattServerStartService() != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleStartLocalListening failed"); + } + break; + } + if (service->svcId != -1) { + service->state = BLE_GATT_SERVICE_DELETING; + int ret = SoftBusGattsDeleteService(service->svcId); + if (ret != SOFTBUS_OK) { + service->state = BLE_GATT_SERVICE_INVALID; + } + } else { + service->state = BLE_GATT_SERVICE_INITIAL; + } + break; + case BLE_GATT_SERVICE_STARTING: + service->state = (status == SOFTBUS_OK) ? BLE_GATT_SERVICE_STARTED : + BLE_GATT_SERVICE_ADDED; + break; + case BLE_GATT_SERVICE_STOPPING: + service->state = (status == SOFTBUS_OK) ? BLE_GATT_SERVICE_ADDED : + BLE_GATT_SERVICE_STARTED; + break; + case BLE_GATT_SERVICE_DELETING: + service->state = (status == SOFTBUS_OK) ? BLE_GATT_SERVICE_INITIAL : + BLE_GATT_SERVICE_INVALID; + break; + default: + break; + } + (void)pthread_mutex_unlock(&g_serviceStateLock); +} + +static void ResetGattService(SoftBusGattService *service) +{ + if (service == NULL) { + return; + } + if (pthread_mutex_lock(&g_serviceStateLock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); + return; + } + if (service->svcId != -1) { + service->state = BLE_GATT_SERVICE_DELETING; + int ret = SoftBusGattsDeleteService(service->svcId); + if (ret != SOFTBUS_OK) { + service->state = BLE_GATT_SERVICE_INVALID; + } + } else { + service->state = BLE_GATT_SERVICE_INITIAL; + } + service->svcId = -1; + service->bleConnCharaId = -1; + service->bleConnDesId = -1; + service->bleNetCharaId = -1; + service->bleNetDesId = -1; + (void)pthread_mutex_unlock(&g_serviceStateLock); +} + +static void BleServiceAddCallback(int status, SoftBusBtUuid *uuid, int srvcHandle) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ServiceAddCallback srvcHandle=%d\n", srvcHandle); + if ((uuid == NULL) || (uuid->uuid == NULL)) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleServiceAddCallback appUuid is null"); + return; + } + + if (memcmp(uuid->uuid, SOFTBUS_SERVICE_UUID, uuid->uuidLen) == 0) { + if (status != SOFTBUS_OK) { + ResetGattService(&g_gattService); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleRegisterServerCallback failed, status=%d", status); + return; + } + if (pthread_mutex_lock(&g_serviceStateLock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); + return; + } + if (g_gattService.state != BLE_GATT_SERVICE_ADDING) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, + "g_gattService wrong state, should be BLE_GATT_SERVICE_ADDING"); + (void)pthread_mutex_unlock(&g_serviceStateLock); + return; + } + g_gattService.svcId = srvcHandle; + (void)pthread_mutex_unlock(&g_serviceStateLock); + SoftBusMessage *msg = BleConnCreateLoopMsg(ADD_CHARA_MSG, + SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_READ | SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_WRITE_NO_RSP | + SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_WRITE | SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_NOTIFY | + SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_INDICATE, SOFTBUS_GATT_PERMISSION_READ | + SOFTBUS_GATT_PERMISSION_WRITE, SOFTBUS_CHARA_BLENET_UUID); + if (msg == NULL) { + return; + } + g_bleAsyncHandler.looper->PostMessage(g_bleAsyncHandler.looper, msg); + + msg = BleConnCreateLoopMsg(ADD_DESCRIPTOR_MSG, 0, + SOFTBUS_GATT_PERMISSION_READ | SOFTBUS_GATT_PERMISSION_WRITE, SOFTBUS_DESCRIPTOR_CONFIGURE_UUID); + if (msg == NULL) { + return; + } + g_bleAsyncHandler.looper->PostMessage(g_bleAsyncHandler.looper, msg); + + msg = BleConnCreateLoopMsg(ADD_CHARA_MSG, + SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_READ | SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_WRITE_NO_RSP | + SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_WRITE | SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_NOTIFY | + SOFTBUS_GATT_CHARACTER_PROPERTY_BIT_INDICATE, SOFTBUS_GATT_PERMISSION_READ | + SOFTBUS_GATT_PERMISSION_WRITE, SOFTBUS_CHARA_BLECONN_UUID); + if (msg == NULL) { + return; + } + g_bleAsyncHandler.looper->PostMessage(g_bleAsyncHandler.looper, msg); + } else { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleServiceAddCallback unknown uuid"); + } +} + +static void BleCharacteristicAddCallback(int status, SoftBusBtUuid *uuid, int srvcHandle, + int characteristicHandle) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, + "CharacteristicAddCallback srvcHandle=%d,charHandle=%d\n", srvcHandle, characteristicHandle); + if ((uuid == NULL) || (uuid->uuid == NULL)) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleServiceAddCallback appUuid is null"); + return; + } + if ((srvcHandle == g_gattService.svcId) && (memcmp(uuid->uuid, SOFTBUS_CHARA_BLENET_UUID, uuid->uuidLen) == 0)) { + if (status != SOFTBUS_OK) { + ResetGattService(&g_gattService); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleRegisterServerCallback failed, status=%d", status); + return; + } + if (pthread_mutex_lock(&g_serviceStateLock) != 0) { + return; + } + if (g_gattService.state != BLE_GATT_SERVICE_ADDING) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "g_gattService state not equal BLE_GATT_SERVICE_ADDING"); + (void)pthread_mutex_unlock(&g_serviceStateLock); + return; + } + g_gattService.bleNetCharaId = characteristicHandle; + (void)pthread_mutex_unlock(&g_serviceStateLock); + return; + } + if ((srvcHandle == g_gattService.svcId) && (memcmp(uuid->uuid, SOFTBUS_CHARA_BLECONN_UUID, uuid->uuidLen) == 0)) { + if (status != SOFTBUS_OK) { + ResetGattService(&g_gattService); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleRegisterServerCallback failed, status=%d", status); + return; + } + if (pthread_mutex_lock(&g_serviceStateLock) != 0) { + return; + } + if (g_gattService.state != BLE_GATT_SERVICE_ADDING) { + (void)pthread_mutex_unlock(&g_serviceStateLock); + return; + } + g_gattService.bleConnCharaId = characteristicHandle; + (void)pthread_mutex_unlock(&g_serviceStateLock); + SoftBusMessage *msg = BleConnCreateLoopMsg(ADD_DESCRIPTOR_MSG, 0, + SOFTBUS_GATT_PERMISSION_READ | SOFTBUS_GATT_PERMISSION_WRITE, SOFTBUS_DESCRIPTOR_CONFIGURE_UUID); + if (msg == NULL) { + return; + } + g_bleAsyncHandler.looper->PostMessage(g_bleAsyncHandler.looper, msg); + } +} + +static void BleDescriptorAddCallback(int status, SoftBusBtUuid *uuid, + int srvcHandle, int descriptorHandle) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "DescriptorAddCallback srvcHandle=%d,descriptorHandle=%d\n", + srvcHandle, descriptorHandle); + if ((uuid == NULL) || (uuid->uuid == NULL)) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleServiceAddCallback appUuid is null"); + return; + } + + if ((srvcHandle == g_gattService.svcId) && + (memcmp(uuid->uuid, SOFTBUS_DESCRIPTOR_CONFIGURE_UUID, uuid->uuidLen) == 0)) { + if (status != SOFTBUS_OK) { + ResetGattService(&g_gattService); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleRegisterServerCallback failed, status=%d", status); + return; + } + if (pthread_mutex_lock(&g_serviceStateLock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); + return; + } + if (g_gattService.state != BLE_GATT_SERVICE_ADDING) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, + "g_gattService wrong state, should be BLE_GATT_SERVICE_ADDING"); + (void)pthread_mutex_unlock(&g_serviceStateLock); + return; + } + if (g_gattService.bleNetDesId == -1) { + g_gattService.bleNetDesId = descriptorHandle; + } else { + g_gattService.bleConnDesId = descriptorHandle; + UpdateGattService(&g_gattService, 0); + } + (void)pthread_mutex_unlock(&g_serviceStateLock); + } else { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleDescriptorAddCallback unknown srvcHandle or uuid"); + } +} + +static void BleServiceStartCallback(int status, int srvcHandle) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "ServiceStartCallback srvcHandle=%d\n", srvcHandle); + if (srvcHandle != g_gattService.svcId) { + return; + } + if (status != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleServiceStartCallback start failed"); + } + UpdateGattService(&g_gattService, status); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleServiceStartCallback start success"); +} + +static void BleServiceStopCallback(int status, int srvcHandle) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ServiceStopCallback srvcHandle=%d\n", srvcHandle); + if (srvcHandle != g_gattService.svcId) { + return; + } + if (status != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleServiceStopCallback stop failed"); + } + UpdateGattService(&g_gattService, status); +} + +static void BleServiceDeleteCallback(int status, int srvcHandle) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ServiceDeleteCallback srvcHandle=%d\n", srvcHandle); + if (srvcHandle != g_gattService.svcId) { + return; + } + if (status != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleServiceStopCallback stop failed"); + } + UpdateGattService(&g_gattService, status); +} + +static void BleConnectServerCallback(int halConnId, const SoftBusBtAddr *btAddr) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ConnectServerCallback is coming, halConnId=%d\n", halConnId); + if (btAddr == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "btAddr is null"); + return; + } + char bleStrMac[BT_MAC_LEN]; + int ret = ConvertBtMacToStr(bleStrMac, BT_MAC_LEN, btAddr->addr, BT_ADDR_LEN); + if (ret != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Convert ble addr failed:%d", ret); + return; + } + g_softBusBleConnCb->BleConnectCallback(halConnId, bleStrMac, btAddr); +} + +static void BleDisconnectServerCallback(int halConnId, const SoftBusBtAddr *btAddr) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "DisconnectServerCallback is coming, halconnId=%d", halConnId); + if (btAddr == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "btAddr is null"); + return; + } + char bleStrMac[BT_MAC_LEN]; + int ret = ConvertBtMacToStr(bleStrMac, BT_MAC_LEN, btAddr->addr, BT_ADDR_LEN); + if (ret != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Convert ble addr failed:%d", ret); + return; + } + g_softBusBleConnCb->BleDisconnectCallback(halConnId, 1); +} + +static void SoftBusGattServerOnDataRecieved(int32_t handle, int32_t halConnId, uint32_t len, const char *value) +{ + if (value == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "GattServerOnDataRecieved invalid data"); + return; + } + bool isBleConn = handle == g_gattService.bleConnCharaId; + g_softBusBleConnCb->BleOnDataReceived(isBleConn, halConnId, len, value); +} + +static void BleRequestReadCallback(SoftBusGattReadRequest readCbPara) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "RequestReadCallback transId=%d, attrHandle=%d\n", + readCbPara.transId, readCbPara.attrHandle); + SoftBusGattsResponse response = { + .connectId = readCbPara.connId, + .status = SOFTBUS_BT_STATUS_SUCCESS, + .attrHandle = readCbPara.transId, + .valueLen = strlen("not support!") + 1, + .value = "not support!" + }; + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleRequestReadCallback sendresponse"); + SoftBusGattsSendResponse(&response); +} + +static void BleRequestWriteCallback(SoftBusGattWriteRequest writeCbPara) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "RequestWriteCallback halconnId=%d, transId=%d, attrHandle=%d\n", + writeCbPara.connId, writeCbPara.transId, writeCbPara.attrHandle); + if (writeCbPara.attrHandle != g_gattService.bleConnCharaId && + writeCbPara.attrHandle != g_gattService.bleNetCharaId) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleOnDataReceived not support handle :%d expect:%d", + writeCbPara.attrHandle, g_gattService.bleConnCharaId); + return; + } + if (writeCbPara.needRsp) { + SoftBusGattsResponse response = { + .connectId = writeCbPara.connId, + .status = SOFTBUS_BT_STATUS_SUCCESS, + .attrHandle = writeCbPara.transId, + .valueLen = writeCbPara.length, + .value = (char *)writeCbPara.value + }; + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleRequestWriteCallback sendresponse"); + SoftBusGattsSendResponse(&response); + } + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, + "BLEINFOPRTINT:BleRequestWriteCallback valuelen:%d", writeCbPara.length); + uint32_t len; + int32_t index = -1; + char *value = BleTransRecv(writeCbPara.connId, (char *)writeCbPara.value, + (uint32_t)writeCbPara.length, &len, &index); + if (value == NULL) { + return; + } + SoftBusGattServerOnDataRecieved(writeCbPara.attrHandle, writeCbPara.connId, len, (const char *)value); + if (index != -1) { + BleTransCacheFree(writeCbPara.connId, index); + } +} + +static void BleResponseConfirmationCallback(int status, int handle) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, + "ResponseConfirmationCallback status=%d, handle=%d\n", status, handle); +} + +static void BleNotifySentCallback(int connId, int status) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "IndicationSentCallback status=%d, connId=%d\n", status, connId); +} + +static void BleMtuChangeCallback(int connId, int mtu) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "MtuChangeCallback connId=%d, mtu=%d\n", connId, mtu); + BleConnectionInfo *connInfo = g_softBusBleConnCb->GetBleConnInfoByHalConnId(connId); + if (connInfo == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleMtuChangeCallback GetBleConnInfo failed"); + return; + } + connInfo->mtu = mtu; +} + +static int GattsRegisterCallback(void) +{ + g_bleGattsCallback.ServiceAddCallback = BleServiceAddCallback; + g_bleGattsCallback.CharacteristicAddCallback = BleCharacteristicAddCallback; + g_bleGattsCallback.DescriptorAddCallback = BleDescriptorAddCallback; + g_bleGattsCallback.ServiceStartCallback = BleServiceStartCallback; + g_bleGattsCallback.ServiceStopCallback = BleServiceStopCallback; + g_bleGattsCallback.ServiceDeleteCallback = BleServiceDeleteCallback; + g_bleGattsCallback.ConnectServerCallback = BleConnectServerCallback; + g_bleGattsCallback.DisconnectServerCallback = BleDisconnectServerCallback; + g_bleGattsCallback.RequestReadCallback = BleRequestReadCallback; + g_bleGattsCallback.RequestWriteCallback = BleRequestWriteCallback; + g_bleGattsCallback.ResponseConfirmationCallback = BleResponseConfirmationCallback; + g_bleGattsCallback.NotifySentCallback = BleNotifySentCallback; + g_bleGattsCallback.MtuChangeCallback = BleMtuChangeCallback; + return SoftBusRegisterGattsCallbacks(&g_bleGattsCallback); +} + +static void BleConnAddSerMsgHandler(const SoftBusMessage *msg) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "call GattsRegisterCallback"); + int32_t ret = GattsRegisterCallback(); + if (ret != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "GattsRegisterCallbacks failed:%d", ret); + return; + } + if (pthread_mutex_lock(&g_serviceStateLock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); + return; + } + g_gattService.state = BLE_GATT_SERVICE_ADDING; + (void)pthread_mutex_unlock(&g_serviceStateLock); + SoftBusBtUuid uuid; + uuid.uuid = (char *)msg->obj; + uuid.uuidLen = strlen(uuid.uuid); + ret = SoftBusGattsAddService(uuid, true, MAX_SERVICE_CHAR_NUM); + if (ret != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleGattsAddService failed:%d", ret); + return; + } +} + +static void BleConnMsgHandler(SoftBusMessage *msg) +{ + SoftBusBtUuid uuid; + int properties, permissions; + if (msg == NULL) { + return; + } + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ble conn loop process msg type %d", msg->what); + switch (msg->what) { + case ADD_SERVICE_MSG: + BleConnAddSerMsgHandler(msg); + break; + case ADD_CHARA_MSG: + uuid.uuid = (char *)msg->obj; + uuid.uuidLen = strlen(uuid.uuid); + properties = (int32_t)msg->arg1; + permissions = (int32_t)msg->arg2; + int32_t ret = SoftBusGattsAddCharacteristic(g_gattService.svcId, uuid, properties, permissions); + if (ret != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleGattsAddCharacteristic failed:%d", ret); + return; + } + break; + case ADD_DESCRIPTOR_MSG: + uuid.uuid = (char *)msg->obj; + uuid.uuidLen = strlen(uuid.uuid); + permissions = (int32_t)msg->arg2; + ret = SoftBusGattsAddDescriptor(g_gattService.svcId, uuid, permissions); + if (ret != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleGattsAddDescriptor failed:%d", ret); + return; + } + break; + default: + break; + } +} + +static int BleConnLooperInit(void) +{ + g_bleAsyncHandler.looper = CreateNewLooper("ble_looper"); + if (g_bleAsyncHandler.looper == NULL) { + return SOFTBUS_ERR; + } + g_bleAsyncHandler.HandleMessage = BleConnMsgHandler; + return SOFTBUS_OK; +} + +void SoftBusGattServerOnBtStateChanged(int state) +{ + if (state == SOFTBUS_BT_STATE_TURN_ON) { + SoftBusMessage *msg = BleConnCreateLoopMsg(ADD_SERVICE_MSG, 0, 0, SOFTBUS_SERVICE_UUID); + if (msg == NULL) { + return; + } + g_bleAsyncHandler.looper->PostMessage(g_bleAsyncHandler.looper, msg); + } +} + +int32_t SoftBusGattServerInit(SoftBusBleConnCalback *cb) +{ + int ret = BleConnLooperInit(); + if (ret != SOFTBUS_OK) { + return ret; + } + g_softBusBleConnCb = cb; + pthread_mutexattr_t attr; + pthread_mutexattr_init(&attr); + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); + pthread_mutex_init(&g_serviceStateLock, &attr); + return ret; +} diff --git a/core/connection/ble/src/softbus_ble_queue.c b/core/connection/ble/src/softbus_ble_queue.c new file mode 100644 index 000000000..bfcc695c4 --- /dev/null +++ b/core/connection/ble/src/softbus_ble_queue.c @@ -0,0 +1,196 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "common_list.h" +#include "securec.h" +#include "softbus_adapter_mem.h" +#include "softbus_ble_queue.h" +#include "softbus_conn_manager.h" +#include "softbus_def.h" +#include "softbus_errcode.h" +#include "softbus_log.h" +#include "softbus_queue.h" +#include "softbus_type_def.h" + +#define QUEUE_NUM_PER_PID 3 +#define HIGH_PRIORITY_DEFAULT_LIMIT 32 +#define MIDDLE_PRIORITY_DEFAULT_LIMIT 32 +#define LOW_PRIORITY_DEFAULT_LIMIT 16 + +typedef struct { + ListNode node; + int32_t pid; + LockFreeQueue *queue[QUEUE_NUM_PER_PID]; +} BleQueue; + +typedef enum { + HIGH_PRIORITY = 0, + MIDDLE_PRIORITY, + LOW_PRIORITY, + PRIORITY_BOUNDARY +} QueuePriority; + +static const int32_t QUEUE_LIMIT[QUEUE_NUM_PER_PID] = { + HIGH_PRIORITY_DEFAULT_LIMIT, + MIDDLE_PRIORITY_DEFAULT_LIMIT, + LOW_PRIORITY_DEFAULT_LIMIT +}; +static LIST_HEAD(g_bleQueueList); +static pthread_mutex_t g_bleQueueLock; +static BleQueue *g_innerQueue = NULL; + +static BleQueue *CreateBleQueue(int32_t pid) +{ + BleQueue *queue = (BleQueue *)SoftBusCalloc(sizeof(BleQueue)); + if (queue == NULL) { + return NULL; + } + queue->pid = pid; + int i; + for (i = 0; i < QUEUE_NUM_PER_PID; i++) { + queue->queue[i] = CreateQueue(QUEUE_LIMIT[i]); + if (queue->queue[i] == NULL) { + goto ERR_RETURN; + } + } + return queue; +ERR_RETURN: + for (i--; i >= 0; i--) { + SoftBusFree(queue->queue[i]); + } + SoftBusFree(queue); + return NULL; +} + +static void DestroyBleQueue(BleQueue *queue) +{ + if (queue == NULL) { + return; + } + for (int i = 0; i < QUEUE_NUM_PER_PID; i++) { + SoftBusFree(queue->queue[i]); + } + SoftBusFree(queue); +} + +static int GetPriority(int32_t flag) +{ + switch (flag) { + case CONN_HIGH: + return HIGH_PRIORITY; + case CONN_MIDDLE: + return MIDDLE_PRIORITY; + default: + return LOW_PRIORITY; + } +} + +int BleEnqueueNonBlock(const void *msg) +{ + if (msg == NULL) { + return SOFTBUS_ERR; + } + SendQueueNode *queueNode = (SendQueueNode *)msg; + if (queueNode->pid == 0) { + return QueueMultiProducerEnqueue(g_innerQueue->queue[GetPriority(queueNode->flag)], msg); + } + LockFreeQueue *lockFreeQueue = NULL; + BleQueue *item = NULL; + if (pthread_mutex_lock(&g_bleQueueLock) != EOK) { + return SOFTBUS_ERR; + } + LIST_FOR_EACH_ENTRY(item, &g_bleQueueList, BleQueue, node) { + if (item->pid == queueNode->pid) { + lockFreeQueue = item->queue[GetPriority(queueNode->flag)]; + break; + } + } + if (lockFreeQueue == NULL) { + BleQueue *newQueue = CreateBleQueue(queueNode->pid); + if (newQueue == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleEnqueueNonBlock CreateBleQueue failed"); + (void)pthread_mutex_unlock(&g_bleQueueLock); + return SOFTBUS_ERR; + } + ListTailInsert(&g_bleQueueList, &(newQueue->node)); + lockFreeQueue = newQueue->queue[GetPriority(queueNode->flag)]; + } + (void)pthread_mutex_unlock(&g_bleQueueLock); + return QueueMultiProducerEnqueue(lockFreeQueue, msg); +} + +static int GetMsg(BleQueue *queue, void **msg) +{ + for (int i = 0; i < QUEUE_NUM_PER_PID; i++) { + if (QueueSingleConsumerDequeue(queue->queue[i], msg) == 0) { + return SOFTBUS_OK; + } + } + return SOFTBUS_ERR; +} + +int BleDequeueNonBlock(void **msg) +{ + if (msg == NULL) { + return SOFTBUS_ERR; + } + if (GetMsg(g_innerQueue, msg) == SOFTBUS_OK) { + return SOFTBUS_OK; + } + + if (pthread_mutex_lock(&g_bleQueueLock) != EOK) { + return SOFTBUS_ERR; + } + if (IsListEmpty(&g_bleQueueList)) { + (void)pthread_mutex_unlock(&g_bleQueueLock); + return SOFTBUS_ERR; + } + BleQueue *item = LIST_ENTRY(g_bleQueueList.next, BleQueue, node); + ListDelete(&(item->node)); + if (GetMsg(item, msg) == SOFTBUS_OK) { + ListTailInsert(&g_bleQueueList, &(item->node)); + (void)pthread_mutex_unlock(&g_bleQueueLock); + return SOFTBUS_OK; + } + DestroyBleQueue(item); + (void)pthread_mutex_unlock(&g_bleQueueLock); + return SOFTBUS_ERR; +} + +int BleInnerQueueInit(void) +{ + if (pthread_mutex_init(&g_bleQueueLock, NULL) != 0) { + return SOFTBUS_ERR; + } + g_innerQueue = CreateBleQueue(0); + if (g_innerQueue == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleQueueInit CreateBleQueue(0) failed"); + (void)pthread_mutex_destroy(&g_bleQueueLock); + return SOFTBUS_ERR; + } + return SOFTBUS_OK; +} + +void BleInnerQueueDeinit(void) +{ + pthread_mutex_destroy(&g_bleQueueLock); + DestroyBleQueue(g_innerQueue); + g_innerQueue = NULL; +} \ No newline at end of file diff --git a/core/connection/ble/src/softbus_ble_trans_manager.c b/core/connection/ble/src/softbus_ble_trans_manager.c index e469d9034..85d0ab359 100644 --- a/core/connection/ble/src/softbus_ble_trans_manager.c +++ b/core/connection/ble/src/softbus_ble_trans_manager.c @@ -14,9 +14,13 @@ */ #include "softbus_ble_trans_manager.h" + #include + #include "securec.h" #include "softbus_adapter_mem.h" +#include "softbus_ble_gatt_client.h" +#include "softbus_ble_gatt_server.h" #include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_log.h" @@ -29,6 +33,7 @@ typedef struct { } BleTransHeader; static const int MTU_HEADER_SIZE = 3; +static SoftBusBleTransCalback *g_softBusBleTransCb = NULL; static int32_t GetTransHeader(char *value, int32_t len, BleTransHeader *header) { @@ -85,7 +90,7 @@ char *BleTransRecv(int32_t halConnId, char *value, uint32_t len, uint32_t *outLe SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleTransRecv invalid data"); return NULL; } - BleConnectionInfo *targetNode = GetBleConnInfoByHalConnId(halConnId); + BleConnectionInfo *targetNode = g_softBusBleTransCb->GetBleConnInfoByHalConnId(halConnId); if (targetNode == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleTransRecv unknown device"); return NULL; @@ -108,7 +113,7 @@ char *BleTransRecv(int32_t halConnId, char *value, uint32_t len, uint32_t *outLe } if (memcpy_s(targetNode->recvCache[canIndex].cache + header.offset, MAX_DATA_LEN - header.offset, - value + sizeof(BleTransHeader), header.size) != 0) { + value + sizeof(BleTransHeader), header.size) != EOK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleTransRecv memcpy_s failed"); targetNode->recvCache[canIndex].isUsed = 0; return NULL; @@ -127,7 +132,7 @@ char *BleTransRecv(int32_t halConnId, char *value, uint32_t len, uint32_t *outLe void BleTransCacheFree(int32_t halConnId, int32_t index) { - BleConnectionInfo *targetNode = GetBleConnInfoByHalConnId(halConnId); + BleConnectionInfo *targetNode = g_softBusBleTransCb->GetBleConnInfoByHalConnId(halConnId); if (targetNode == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BleTransCacheFree unknown device"); return; @@ -142,53 +147,59 @@ void BleTransCacheFree(int32_t halConnId, int32_t index) static int32_t BleHalSend(const BleConnectionInfo *connInfo, const char *data, int32_t len, int32_t module) { if (connInfo->info.isServer == 1) { - SoftBusGattsNotify notify = { - .connectId = connInfo->halConnId, - .attrHandle = GetBleAttrHandle(module), - .confirm = 0, - .valueLen = len, - .value = (char *)data - }; - return SoftBusGattsSendNotify(¬ify); + return SoftBusGattServerSend(connInfo->halConnId, data, len, module); } else { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SendBleData ble gatt client not support"); - return SOFTBUS_ERR; + return SoftBusGattClientSend(connInfo->halConnId, data, len, module); } } int32_t BleTransSend(BleConnectionInfo *connInfo, const char *data, int32_t len, int32_t seq, int32_t module) { - int32_t templen = len; + int32_t tempLen = len; char *sendData = (char *)data; int32_t dataLenMax = connInfo->mtu - MTU_HEADER_SIZE - sizeof(BleTransHeader); int32_t offset = 0; - while (templen > 0) { - int32_t sendlenth = templen; - if (sendlenth > dataLenMax) { - sendlenth = dataLenMax; + while (tempLen > 0) { + int32_t sendLenth = tempLen; + if (sendLenth > dataLenMax) { + sendLenth = dataLenMax; } - char *buff = (char *)SoftBusCalloc(sendlenth + sizeof(BleTransHeader)); - int ret = memcpy_s(buff + sizeof(BleTransHeader), sendlenth, sendData, sendlenth); - if (ret != SOFTBUS_OK) { - LOG_INFO("BleTransSend big msg, len:%{public}d\n", templen); + char *buff = (char *)SoftBusCalloc(sendLenth + sizeof(BleTransHeader)); + if (buff == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "malloc failed"); + return SOFTBUS_MALLOC_ERR; + } + int ret = memcpy_s(buff + sizeof(BleTransHeader), sendLenth, sendData, sendLenth); + if (ret != EOK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "BleTransSend big msg, len:%d\n", tempLen); SoftBusFree(buff); return ret; } BleTransHeader *transHeader = (BleTransHeader *)buff; transHeader->total = htonl(len); - transHeader->size = htonl(sendlenth); + transHeader->size = htonl(sendLenth); transHeader->offset = htonl(offset); transHeader->seq = htonl(seq); - ret = BleHalSend((const BleConnectionInfo *)connInfo, buff, sendlenth + sizeof(BleTransHeader), module); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "BleTransSend module:%d", module); + ret = BleHalSend((const BleConnectionInfo *)connInfo, buff, sendLenth + sizeof(BleTransHeader), module); if (ret != SOFTBUS_OK) { - LOG_INFO("BleTransSend BleHalSend failed"); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "BleTransSend BleHalSend failed"); SoftBusFree(buff); return ret; } SoftBusFree(buff); - sendData += sendlenth; - templen -= sendlenth; - offset += sendlenth; + sendData += sendLenth; + tempLen -= sendLenth; + offset += sendLenth; } return SOFTBUS_OK; +} + +int32_t BleTransInit(SoftBusBleTransCalback *cb) +{ + if (cb == NULL) { + return SOFTBUS_ERR; + } + g_softBusBleTransCb = cb; + return SOFTBUS_OK; } \ No newline at end of file diff --git a/core/connection/br/conn_br.gni b/core/connection/br/conn_br.gni index ed44dc6f4..91c8c5b32 100644 --- a/core/connection/br/conn_br.gni +++ b/core/connection/br/conn_br.gni @@ -25,8 +25,11 @@ if (enable_connection_br == false) { } else { br_connection_src = br_adapter_src br_connection_inc = br_adapter_inc - br_connection_src += - [ "$dsoftbus_root_path/core/connection/br/src/br_connection.c" ] + br_connection_src += [ + "$dsoftbus_root_path/core/connection/br/src/br_connection.c", + "$dsoftbus_root_path/core/connection/br/src/br_trans_manager.c", + "$dsoftbus_root_path/core/connection/br/src/br_connection_manager.c", + ] br_connection_inc += [ "$dsoftbus_root_path/core/connection/br/include", "//third_party/cJSON", diff --git a/core/connection/br/include/br_connection_manager.h b/core/connection/br/include/br_connection_manager.h new file mode 100644 index 000000000..c233a45a8 --- /dev/null +++ b/core/connection/br/include/br_connection_manager.h @@ -0,0 +1,119 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. + * Description: br connection management module. + * 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 BR_CONNECTION_MANAGER_H +#define BR_CONNECTION_MANAGER_H + +#include "common_list.h" +#include "softbus_conn_interface.h" + +typedef struct { + ListNode node; + int32_t requestId; + ConnectResult callback; +} RequestInfo; + +#define BT_RFCOM_CONGEST_ON 0 +#define BT_RFCOM_CONGEST_OFF 1 +#define BR_CLIENT_TYPE 0 +#define BR_SERVICE_TYPE 1 + +#define METHOD_NOTIFY_REQUEST 1 +#define METHOD_NOTIFY_RESPONSE 2 + +#define MAGIC_NUMBER 0xBABEFACE + +typedef enum { + ADD_CONN_BR_INVALID, + ADD_CONN_BR_CLIENT_CONNECTED_MSG, + ADD_CONN_BR_CLIENT_DISCONNECTED_MSG, + ADD_CONN_BR_SERVICE_CONNECTED_MSG, + ADD_CONN_BR_SERVICE_DISCONNECTED_MSG, + ADD_CONN_BR_CONGEST_MSG, + ADD_CONN_BR_RECV_MSG, + ADD_CONN_BR_MAX +} BrConnLoopMsgType; + +enum BRConnectionState { + BR_CONNECTION_STATE_CONNECTING = 0, + BR_CONNECTION_STATE_CONNECTED, + BR_CONNECTION_STATE_CLOSING, + BR_CONNECTION_STATE_CLOSED +}; + +typedef struct BrConnectionInfo { + ListNode node; + uint32_t connectionId; + int32_t socketFd; + int32_t sideType; + char mac[BT_MAC_LEN]; + int32_t connectQueueState; + int32_t state; + int32_t refCount; + int32_t refCountRemote; + int32_t infoObjRefCount; + char *recvBuf; + int32_t recvSize; + int32_t recvPos; + int32_t conGestState; + ListNode requestList; + pthread_mutex_t lock; + pthread_cond_t congestCond; +} BrConnectionInfo; + +void InitBrConnectionManager(int32_t brBuffSize); + +bool IsExitConnectionById(uint32_t connId); + +bool IsExitBrConnectByFd(int32_t socketFd); + +BrConnectionInfo *GetConnectionRef(uint32_t connId); + +void ReleaseBrconnectionNode(BrConnectionInfo *conn); + +void ReleaseConnectionRef(BrConnectionInfo *connInfo); + +void ReleaseConnectionRefByConnId(uint32_t connId); + +BrConnectionInfo* CreateBrconnectionNode(bool clientFlag); + +int32_t GetConnectionInfo(uint32_t connectionId, ConnectionInfo *info); + +int32_t SetRefCountByConnId(int32_t delta, int32_t *refCount, uint32_t connectionId); + +void SetBrConnStateByConnId(uint32_t connId, int32_t state); + +uint32_t SetBrConnStateBySocket(int32_t socket, int32_t state, int32_t *perState); + +int32_t AddRequestByConnId(uint32_t connId, RequestInfo *requestInfo); + +int32_t AddConnectionList(BrConnectionInfo *newConnInfo); + +void RfcomCongestEvent(int32_t socketFd, int32_t value); + +int32_t GetBrRequestListByConnId(uint32_t connId, ListNode *notifyList, + ConnectionInfo *connectionInfo, int32_t *sideType); + +bool HasDiffMacDeviceExit(const ConnectOption *option); + +int32_t GetBrConnStateByConnOption(const ConnectOption *option, int32_t *outCountId); + +bool IsBrDeviceReady(uint32_t connId); + +int32_t BrClosingByConnOption(const ConnectOption *option, int32_t *socketFd, int32_t *sideType); + +#endif + diff --git a/core/connection/br/include/br_trans_manager.h b/core/connection/br/include/br_trans_manager.h new file mode 100644 index 000000000..5aafa2111 --- /dev/null +++ b/core/connection/br/include/br_trans_manager.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. + * Description: br transmission management module. + * 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 BR_TRANS_MANAGER_H +#define BR_TRANS_MANAGER_H +#include "br_connection_manager.h" +#include "cJSON.h" +#include "wrapper_br_interface.h" + +#define KEY_METHOD "KEY_METHOD" +#define KEY_DELTA "KEY_DELTA" +#define KEY_REFERENCE_NUM "KEY_REFERENCE_NUM" + +int32_t BrTransReadOneFrame(uint32_t connectionId, const SppSocketDriver *sppDriver, int32_t clientId, char **outBuf); +int32_t BrTransSend(int32_t connId, const SppSocketDriver *sppDriver, + int32_t brSendPeerLen, const char *data, uint32_t len); + +char *BrPackRequestOrResponse(int32_t requestOrResponse, int32_t delta, int32_t count, int32_t *outLen); + +#endif diff --git a/core/connection/br/src/br_connection.c b/core/connection/br/src/br_connection.c index 96d1c883b..3147893ac 100644 --- a/core/connection/br/src/br_connection.c +++ b/core/connection/br/src/br_connection.c @@ -1,5 +1,6 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. + * Description: br connection module. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -15,17 +16,18 @@ #include -#include "cJSON.h" -#include "cmsis_os2.h" +#include "br_connection_manager.h" +#include "br_trans_manager.h" #include "common_list.h" #include "message_handler.h" -#include "ohos_types.h" #include "securec.h" #include "softbus_adapter_mem.h" +#include "softbus_adapter_timer.h" #include "softbus_conn_manager.h" #include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_feature_config.h" +#include "softbus_json_utils.h" #include "softbus_log.h" #include "softbus_type_def.h" #include "softbus_utils.h" @@ -35,63 +37,28 @@ #include "unistd.h" #include "wrapper_br_interface.h" -#define KEY_METHOD "KEY_METHOD" -#define KEY_DELTA "KEY_DELTA" -#define KEY_REFERENCE_NUM "KEY_REFERENCE_NUM" -#define METHOD_NOTIFY_REQUEST 1 -#define METHOD_NOTIFY_RESPONSE 2 -#define METHOD_SHUT_DOWN 3 #define DISCONN_DELAY_TIME 200 -#define MAGIC_NUMBER 0xBABEFACE -#define TIMEOUT_DISCONNECT 1000 #define CONNECT_REF_INCRESE 1 #define CONNECT_REF_DECRESE (-1) -#define BR_CONNECT_TEST 1588 -#define BR_CLIENT_TYPE 0 -#define BR_MAC_PRINT 17 -#define BR_SERVICE_TYPE 1 -#define BT_RFCOM_CONGEST_ON 0 -#define BT_RFCOM_CONGEST_OFF 1 -#define BR_NOTIFY_REQUESTID 1 -#define BR_NOTIFY_REQUESTID_DISCONNECT 2 -#define BR_STATE_RECAVER 5 -#define BR_CONNECT_TASK 10 -#define BR_SEND_THREAD_STACK 3072 +#define BR_SEND_THREAD_STACK 5120 +#define BR_ACCECT_THREAD_STACK 4096 #define BR_RECE_THREAD_STACK 4096 -#define MAX_BR_SIZE (32*1024) +#define MAX_BR_SIZE (40 * 1000) #define MAX_BR_PEER_SIZE (3*1024) #define INVALID_LENGTH (-1) #define PRIORITY_HIGH 64 #define PRIORITY_MID 8 #define PRIORITY_LOW 1 #define PRIORITY_DAF 1 -#define INVALID_VALUE (-1) -#define MAX_BR_SENDQUEQUE_SIZE (10*10) -#define BT_ADDR_LEN_RFCOM 6 -typedef struct { - ListNode node; - int32_t requestId; - ConnectResult callback; -} RequestInfo; +#define BR_SERVER_NAME_LEN 24 +#define UUID "8ce255c0-200a-11e0-ac64-0800200c9a66" -typedef struct { - ListNode node; - uint32_t connectionId; - int32_t socketFd; - int32_t sideType; - char mac[BT_MAC_LEN]; - int32_t connectQueueState; - int32_t state; - int32_t refCount; - int32_t refCountRemote; - char *recvBuf; - int32_t recvPos; - int32_t conGestState; - ListNode requestList; - pthread_mutex_t lock; - pthread_cond_t congestCond; -} BrConnectionInfo; +static pthread_mutex_t g_brConnLock; + +static SoftBusHandler g_brAsyncHandler = { + .name = "g_brAsyncHandler" +}; typedef struct { ListNode node; @@ -117,72 +84,17 @@ typedef struct { SoftBusHandler *handler; } DataQueueStruct; -typedef struct { - ListNode node; - uint32_t connectionId; - int32_t module; - long seqNum; - int32_t flag; - uint32_t dataLen; - uint8_t *data; -} ReceiveItemStruct; - -typedef struct { - ListNode recvList; - pthread_mutex_t lock; - pthread_cond_t cond; - SoftBusHandler *handler; -} RecvQueueStruct; - -enum BRConnectionState { - BR_CONNECTION_STATE_CONNECTING = 0, - BR_CONNECTION_STATE_CONNECTED, - BR_CONNECTION_STATE_CLOSING, - BR_CONNECTION_STATE_CLOSED -}; - -static void ClientOnEvent(int32_t type, int32_t socketFd, int32_t value); - -static void ClientOnDataReceived(int32_t socketFd, const char *buf, int32_t len); - -static void ServerOnEvent(int32_t type, int32_t socketFd, int32_t value); - -static void ServerOnDataReceived(int32_t socketFd, const char *buf, int32_t len); - -static bool GetJsonObjectNumberItem(const cJSON *json, const char * const string, int *target); - -static bool AddNumberToJsonObject(cJSON *obj, const char * const string, int32_t num); - static int32_t ConnectDevice(const ConnectOption *option, uint32_t requestId, const ConnectResult *result); -static int32_t PostBytes(uint32_t connectionId, const char *data, int32_t len, int32_t pid, int32_t flag); - static int32_t DisconnectDevice(uint32_t connectionId); static int32_t DisconnectDeviceNow(const ConnectOption *option); -static int32_t GetConnectionInfo(uint32_t connectionId, ConnectionInfo *info); - static int32_t StartLocalListening(const LocalListenerInfo *info); static int32_t StopLocalListening(const LocalListenerInfo *info); -static void ClientOnBrDisconnect(int32_t socketFd, int32_t value); - -static void ClearSendItemByConnId(uint32_t connectionId); - -static void ClearReceiveQueueByConnId(uint32_t connectionId); - -static SppSocketEventCallback g_sppSocketClientCallback = { - .OnEvent = ClientOnEvent, - .OnDataReceived = ClientOnDataReceived -}; - - -static SppSocketEventCallback g_sppSocketServiceCallback = { - .OnEvent = ServerOnEvent, - .OnDataReceived = ServerOnDataReceived -}; +static int32_t PostBytes(uint32_t connectionId, const char *data, int32_t len, int32_t pid, int32_t flag); static ConnectFuncInterface g_brInterface = { .ConnectDevice = ConnectDevice, @@ -194,512 +106,129 @@ static ConnectFuncInterface g_brInterface = { .StopLocalListening = StopLocalListening }; -static pthread_mutex_t g_connectionLock; -static const uint8_t UUID[BT_UUID_LEN] = { - 0x8c, 0xe2, 0x55, 0xc0, 0x20, 0x0a, 0x11, 0xe0, - 0xac, 0x64, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66 -}; - -static LIST_HEAD(g_conection_list); static DataQueueStruct g_dataQueue; -static RecvQueueStruct g_recvQueue; static SppSocketDriver *g_sppDriver = NULL; static ConnectCallback *g_connectCallback = NULL; -static int16_t g_nextConnectionId = 0; static int32_t g_brBuffSize; static int32_t g_brSendPeerLen; static int32_t g_brSendQueueMaxLen; -static int32_t AllocNewConnectionIdLocked() + +static SoftBusBtStateListener g_sppBrCallback; +static bool g_startListenFlag = false; +static int32_t g_brEnable = SOFTBUS_BT_STATE_TURN_OFF; + +static SoftBusMessage *BrConnCreateLoopMsg(BrConnLoopMsgType what, uint64_t arg1, uint64_t arg2, const char *data) { - g_nextConnectionId++; - int32_t tempId; - while (1) { - tempId = (CONNECT_BR << CONNECT_TYPE_SHIFT) + g_nextConnectionId; - ListNode *item = NULL; - LIST_FOR_EACH(item, &g_conection_list) { - BrConnectionInfo *itemNode = LIST_ENTRY(item, BrConnectionInfo, node); - if (itemNode->connectionId == tempId) { - g_nextConnectionId++; - continue; - } - } - break; - } - return tempId; -} - -static int32_t GetConnectionInfo(uint32_t connectionId, ConnectionInfo *info) -{ - int32_t result = SOFTBUS_ERR; - if (pthread_mutex_lock(&g_connectionLock) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); - return SOFTBUS_ERR; - } - ListNode *item = NULL; - LIST_FOR_EACH(item, &g_conection_list) { - BrConnectionInfo *itemNode = LIST_ENTRY(item, BrConnectionInfo, node); - if (itemNode->connectionId == connectionId) { - info->isAvailable = 1; - info->isServer = itemNode->sideType; - info->type = CONNECT_BR; - if (strncpy_s(info->info.brInfo.brMac, BT_MAC_LEN, - itemNode->mac, sizeof(itemNode->mac)) != EOK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "GetConnInfo scpy error"); - (void)pthread_mutex_unlock(&g_connectionLock); - return SOFTBUS_BRCONNECTION_GETCONNINFO_ERROR; - } - result = SOFTBUS_OK; - break; - } - } - (void)pthread_mutex_unlock(&g_connectionLock); - return result; -} - -static BrConnectionInfo *GetConnectionRef(uint32_t connID) -{ - BrConnectionInfo *result = NULL; - ListNode *item = NULL; - LIST_FOR_EACH(item, &g_conection_list) { - BrConnectionInfo *itemNode = LIST_ENTRY(item, BrConnectionInfo, node); - if (itemNode->connectionId == connID) { - result = itemNode; - break; - } - } - return result; -} - -static void ReleaseConnection(BrConnectionInfo *conn) -{ - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ReleaseConnection node + %u", conn->connectionId); - ListNode *item = NULL; - ListNode *nextItem = NULL; - LIST_FOR_EACH_SAFE(item, nextItem, &conn->requestList) { - RequestInfo *requestInfo = LIST_ENTRY(item, RequestInfo, node); - ListDelete(&(requestInfo->node)); - SoftBusFree(requestInfo); - } - pthread_cond_destroy(&conn->congestCond); - pthread_mutex_destroy(&conn->lock); - SoftBusFree(conn->recvBuf); - SoftBusFree(conn); -} - -static void ReleaseConnectionRef(BrConnectionInfo *conn) -{ - if (pthread_mutex_lock(&g_connectionLock) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); - return; - } - ListDelete(&conn->node); - ReleaseConnection(conn); - (void)pthread_mutex_unlock(&g_connectionLock); -} - -static int AddNumToJson(cJSON *json, int32_t requestOrResponse, int32_t delta, int32_t count) -{ - if (requestOrResponse == METHOD_NOTIFY_REQUEST) { - if (!AddNumberToJsonObject(json, KEY_METHOD, METHOD_NOTIFY_REQUEST) || - !AddNumberToJsonObject(json, KEY_DELTA, delta) || - !AddNumberToJsonObject(json, KEY_REFERENCE_NUM, count)) { - return SOFTBUS_BRCONNECTION_PACKJSON_ERROR; - } - } else { - if (!AddNumberToJsonObject(json, KEY_METHOD, METHOD_NOTIFY_RESPONSE) || - !AddNumberToJsonObject(json, KEY_REFERENCE_NUM, count)) { - return SOFTBUS_BRCONNECTION_PACKJSON_ERROR; - } - } - return SOFTBUS_OK; -} - -static void SendRefMessage(int32_t delta, int32_t connectionId, int32_t count, int32_t requestOrResponse) -{ - cJSON *json = cJSON_CreateObject(); - if (json == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Cannot create cJSON object"); - return; - } - if (AddNumToJson(json, requestOrResponse, delta, count) != SOFTBUS_OK) { - cJSON_Delete(json); - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Cannot AddNumToJson"); - return; - } - - char *data = cJSON_PrintUnformatted(json); - cJSON_Delete(json); - if (data == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "cJSON_PrintUnformatted failed"); - return; - } - - int32_t headSize = sizeof(ConnPktHead); - int32_t dataLen = strlen(data) + 1 + headSize; - char *buf = (char *)SoftBusCalloc(dataLen); - if (buf == NULL) { - cJSON_free(data); - return; - } - ConnPktHead head; - head.magic = MAGIC_NUMBER; - head.module = MODULE_CONNECTION; - head.seq = 1; - head.flag = 0; - head.len = strlen(data) + 1; - - if (memcpy_s(buf, dataLen, (void *)&head, headSize)) { - cJSON_free(data); - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "memcpy_s head error"); - cJSON_free(data); - SoftBusFree(buf); - return; - } - if (memcpy_s(buf + headSize, dataLen - headSize, data, strlen(data) + 1)) { - cJSON_free(data); - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "memcpy_s data error"); - cJSON_free(data); - SoftBusFree(buf); - return; - } - (void)PostBytes(connectionId, buf, dataLen, 0, 0); - cJSON_free(data); - return; -} - -static void PackRequest(int32_t delta, int32_t connectionId) -{ - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[onNotifyRequest: delta=%d, connectionIds=%u", delta, connectionId); - ListNode *item = NULL; - BrConnectionInfo *targetNode = NULL; - int refCount; - if (pthread_mutex_lock(&g_connectionLock) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); - return; - } - LIST_FOR_EACH(item, &g_conection_list) { - BrConnectionInfo *itemNode = LIST_ENTRY(item, BrConnectionInfo, node); - if (itemNode->connectionId == connectionId) { - itemNode->refCount += delta; - refCount = itemNode->refCount; - targetNode = itemNode; - break; - } - } - if (targetNode == NULL) { - (void)pthread_mutex_unlock(&g_connectionLock); - return; - } - (void)pthread_mutex_unlock(&g_connectionLock); - - SendRefMessage(delta, connectionId, refCount, METHOD_NOTIFY_REQUEST); -} - -static void OnPackResponse(int32_t delta, int32_t peerRef, int32_t connectionId) -{ - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, - "[onNotifyRequest: delta=%d, RemoteRef=%d, connectionIds=%u", delta, peerRef, connectionId); - ListNode *item = NULL; - BrConnectionInfo *targetNode = NULL; - int myRefCount; - int mySocketFd; - if (pthread_mutex_lock(&g_connectionLock) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); - return; - } - LIST_FOR_EACH(item, &g_conection_list) { - BrConnectionInfo *itemNode = LIST_ENTRY(item, BrConnectionInfo, node); - if (itemNode->connectionId == connectionId) { - targetNode = itemNode; - targetNode->refCount += delta; - myRefCount = targetNode->refCount; - mySocketFd = targetNode->socketFd; - break; - } - } - if (targetNode == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "Not find OnPackResponse device"); - (void)pthread_mutex_unlock(&g_connectionLock); - return; - } - (void)pthread_mutex_unlock(&g_connectionLock); - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[onPackRequest: myRefCount=%d]", myRefCount); - if (peerRef > 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[remote device Ref is > 0, do not reply]"); - return; - } - if (myRefCount <= 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[local device Ref <= 0, close connection now]"); - g_sppDriver->CloseClient(mySocketFd); - return; - } - SendRefMessage(delta, connectionId, myRefCount, METHOD_NOTIFY_RESPONSE); -} - -static int32_t HasDiffMacDeviceExit(const ConnectOption *option) -{ - if (IsListEmpty(&g_conection_list)) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[g_conection_list is empty, allow to connect device.]"); - return 0; - } - ListNode *item = NULL; - int32_t res; - LIST_FOR_EACH(item, &g_conection_list) { - BrConnectionInfo *itemNode = LIST_ENTRY(item, BrConnectionInfo, node); - if (memcmp(itemNode->mac, option->info.brOption.brMac, sizeof(itemNode->mac)) == 0 && - itemNode->sideType == BR_CLIENT_TYPE) { - res = SOFTBUS_OK; - } else { - res = SOFTBUS_ERR; - break; - } - } - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[check HasDiffMacDeviceExit, return value is %d", res); - return res; -} - -static void ReleaseBrconnectionNode(BrConnectionInfo *newConnectionInfo) -{ - if (newConnectionInfo == NULL) { - return; - } - - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[ReleaseBrconnectionNode"); - pthread_cond_destroy(&newConnectionInfo->congestCond); - pthread_mutex_destroy(&newConnectionInfo->lock); - if (newConnectionInfo->recvBuf != NULL) { - SoftBusFree(newConnectionInfo->recvBuf); - } - RequestInfo *requestInfo = NULL; - ListNode *item = NULL; - ListNode *itemNext = NULL; - if (IsListEmpty(&newConnectionInfo->requestList) != true) { - LIST_FOR_EACH_SAFE(item, itemNext, &newConnectionInfo->requestList) { - requestInfo = LIST_ENTRY(item, RequestInfo, node); - ListDelete(&requestInfo->node); - SoftBusFree(requestInfo); - } - } - SoftBusFree(newConnectionInfo); - return; -} - -static BrConnectionInfo* CreateBrconnectionNode(int clientFlag) -{ - BrConnectionInfo *newConnectionInfo = SoftBusCalloc(sizeof(BrConnectionInfo)); - if (newConnectionInfo == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[ConnectDeviceFristTime malloc fail.]"); + SoftBusMessage *msg = NULL; + msg = (SoftBusMessage *)SoftBusCalloc(sizeof(SoftBusMessage)); + if (msg == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BrConnCreateLoopMsg SoftBusCalloc failed"); return NULL; } - newConnectionInfo->recvBuf = SoftBusCalloc(g_brBuffSize); - if (newConnectionInfo->recvBuf == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[SoftBusMalloc recvBuf fail]"); - SoftBusFree(newConnectionInfo); - return NULL; - } - ListInit(&newConnectionInfo->node); - ListInit(&newConnectionInfo->requestList); - pthread_mutex_init(&newConnectionInfo->lock, NULL); - newConnectionInfo->connectionId = AllocNewConnectionIdLocked(); - newConnectionInfo->recvPos = 0; - newConnectionInfo->conGestState = BT_RFCOM_CONGEST_OFF; - pthread_cond_init(&newConnectionInfo->congestCond, NULL); - newConnectionInfo->refCount = 1; - return newConnectionInfo; + msg->what = what; + msg->arg1 = arg1; + msg->arg2 = arg2; + msg->handler = &g_brAsyncHandler; + msg->FreeMessage = NULL; + msg->obj = (void *)data; + return msg; } -static int32_t ConnectDeviceFristTime(const ConnectOption *option, uint32_t requestId, const ConnectResult *result) +static void PackRequest(int32_t delta, uint32_t connectionId) { - BrConnectionInfo *newConnectionInfo = CreateBrconnectionNode(true); - if (newConnectionInfo == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[client node create fail]"); - return SOFTBUS_ERR; + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[PackRequest: delta=%d, connectionId=%u]", delta, connectionId); + int32_t refCount = -1; + int32_t state = SetRefCountByConnId(delta, &refCount, connectionId); + if (state != BR_CONNECTION_STATE_CONNECTED) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "Br Not Connected!"); + return; } - RequestInfo *requestInfo = SoftBusCalloc(sizeof(RequestInfo)); - if (requestInfo == NULL) { - ReleaseBrconnectionNode(newConnectionInfo); - return NULL; + int32_t dataLen = 0; + char *buf = BrPackRequestOrResponse(METHOD_NOTIFY_REQUEST, delta, refCount, &dataLen); + if (buf != NULL) { + (void)PostBytes(connectionId, buf, dataLen, 0, 0); } - ListInit(&requestInfo->node); - ListAdd(&newConnectionInfo->requestList, &requestInfo->node); - strncpy_s(newConnectionInfo->mac, sizeof(newConnectionInfo->mac), - option->info.brOption.brMac, BT_MAC_LEN); - // init lock - - requestInfo->requestId = requestId; - (void)memcpy_s(&requestInfo->callback, sizeof(requestInfo->callback), result, sizeof(*result)); - newConnectionInfo->state = BR_CONNECTION_STATE_CONNECTING; - newConnectionInfo->sideType = BR_CLIENT_TYPE; - int32_t socketFd = SOFTBUS_ERR; - uint8_t btAddr[BT_ADDR_LEN]; - - if (ConvertBtMacToBinary(newConnectionInfo->mac, BT_MAC_LEN, btAddr, BT_ADDR_LEN) != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "convert bt mac to binary fail.]"); - ReleaseBrconnectionNode(newConnectionInfo); - return SOFTBUS_ERR; - } - if (g_sppDriver != NULL) { - socketFd = g_sppDriver->OpenSppClient(btAddr, UUID, 0); - } - if (socketFd == SOFTBUS_ERR) { - ReleaseBrconnectionNode(newConnectionInfo); - return SOFTBUS_BRCONNECTION_CONNECTDEVICE_GETSOCKETIDFAIL; - } - newConnectionInfo->socketFd = socketFd; - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, - "[new connection %d,socket=%d", newConnectionInfo->connectionId, socketFd); - ListAdd(&g_conection_list, &newConnectionInfo->node); - int32_t ret = g_sppDriver->Connect(socketFd, &g_sppSocketClientCallback); - return ret; } -static void ConnectDeviceExit(const BrConnectionInfo *itemNode, uint32_t requestId, const ConnectResult *result) -{ - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[already find mac in g_conection_list]"); - ConnectionInfo connectionInfo; - connectionInfo.isAvailable = 1; - connectionInfo.isServer = itemNode->sideType; - connectionInfo.type = CONNECT_BR; - strncpy_s(connectionInfo.info.brInfo.brMac, BT_MAC_LEN, - itemNode->mac, sizeof(itemNode->mac)); - int connectionId = itemNode->connectionId; - - (void)pthread_mutex_unlock(&g_connectionLock); - if (result->OnConnectSuccessed != NULL) { - result->OnConnectSuccessed( - requestId, connectionId, &connectionInfo); - } - - (void)PackRequest(CONNECT_REF_INCRESE, connectionId); -} - -int32_t ConnectDevice(const ConnectOption *option, uint32_t requestId, const ConnectResult *result) -{ - int32_t ret = SOFTBUS_OK; - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[ConnectDevice]"); - if (HasDiffMacDeviceExit(option) != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, - "[g_conection_list has diff mac device, mini system not support.]"); - return SOFTBUS_ERR; - } - if (pthread_mutex_lock(&g_connectionLock) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); - return SOFTBUS_ERR; - } - ListNode *item = NULL; - BrConnectionInfo *targetConnectionInfo = NULL; - LIST_FOR_EACH(item, &g_conection_list) { - BrConnectionInfo *itemNode = LIST_ENTRY(item, BrConnectionInfo, node); - if (strncmp(itemNode->mac, option->info.brOption.brMac, BT_MAC_LEN) == 0) { - targetConnectionInfo = itemNode; - if (itemNode->state == BR_CONNECTION_STATE_CONNECTED) { - ConnectDeviceExit(itemNode, requestId, result); - return SOFTBUS_OK; - } else if (itemNode->state == BR_CONNECTION_STATE_CONNECTING) { - RequestInfo *requestInfo = SoftBusMalloc(sizeof(RequestInfo)); - if (requestInfo == NULL) { - (void)pthread_mutex_unlock(&g_connectionLock); - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, - "[ConnectDevice fail and state is BR_CONNECTION_STATE_CONNECTING.]"); - return SOFTBUS_ERR; - } - (void)memset_s(requestInfo, sizeof(RequestInfo), 0, sizeof(RequestInfo)); - ListInit(&requestInfo->node); - requestInfo->requestId = requestId; - (void)memcpy_s(&requestInfo->callback, sizeof(requestInfo->callback), result, sizeof(*result)); - ListAdd(&itemNode->requestList, &requestInfo->node); - ret = SOFTBUS_OK; - } else if (itemNode->state == BR_CONNECTION_STATE_CLOSING) { - result->OnConnectFailed(requestId, 0); - ret = SOFTBUS_OK; - } - } - } - if (targetConnectionInfo == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[targetConnectionInfo == NULL]"); - ret = ConnectDeviceFristTime(option, requestId, result); - } - (void)pthread_mutex_unlock(&g_connectionLock); - return ret; -} - -static void DeviceConnectPackRequest(int32_t value, int32_t connectionId) +static void DeviceConnectPackRequest(int32_t value, uint32_t connectionId) { while (--value > 0) { (void)PackRequest(CONNECT_REF_INCRESE, connectionId); } } -void RfcomCongestEvent(int32_t socketFd, int32_t value) +static int32_t ClientOnBrConnectDevice(int32_t connId, int32_t *outSocketFd) { - ListNode *item = NULL; - BrConnectionInfo *itemNode = NULL; - - if (pthread_mutex_lock(&g_connectionLock) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); - return; + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "sppDriver connect start."); + BrConnectionInfo *brConn = GetConnectionRef(connId); + if (brConn == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "BrClient not find connInfo."); + return SOFTBUS_BRCONNECTION_GETCONNINFO_ERROR; } - LIST_FOR_EACH(item, &g_conection_list) { - itemNode = LIST_ENTRY(item, BrConnectionInfo, node); - if (itemNode->socketFd == socketFd) { - itemNode->conGestState = value; - if (value == BT_RFCOM_CONGEST_OFF) { - if (pthread_mutex_lock(&itemNode->lock) != 0) { - (void)pthread_mutex_unlock(&g_connectionLock); - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock itemNode failed"); - return; - } - pthread_cond_broadcast(&itemNode->congestCond); - (void)pthread_mutex_unlock(&itemNode->lock); - } - break; - } + if (brConn->sideType != BR_CLIENT_TYPE) { + ReleaseConnectionRef(brConn); + return SOFTBUS_INVALID_PARAM; } - (void)pthread_mutex_unlock(&g_connectionLock); + uint8_t btAddr[BT_ADDR_LEN]; + if (ConvertBtMacToBinary(brConn->mac, BT_MAC_LEN, btAddr, BT_ADDR_LEN) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "convert bt mac to binary fail."); + ReleaseConnectionRef(brConn); + return SOFTBUS_ERR; + } + int32_t socketFd = SOFTBUS_ERR; + if (g_sppDriver != NULL) { + socketFd = g_sppDriver->Connect(UUID, btAddr); + } + if (socketFd == SOFTBUS_ERR) { + ReleaseConnectionRef(brConn); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "sppDriver connect failed"); + return SOFTBUS_BRCONNECTION_CONNECTDEVICE_GETSOCKETIDFAIL; + } + brConn->socketFd = socketFd; + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "br connection ok, Id=%d, socket=%d", connId, socketFd); + if (g_sppDriver->IsConnected(socketFd)) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "sppDriver IsConnected true."); + } + if (brConn->state == BR_CONNECTION_STATE_CLOSED || brConn->state == BR_CONNECTION_STATE_CLOSING) { + g_sppDriver->DisConnect(socketFd); + ReleaseConnectionRef(brConn); + return SOFTBUS_ERR; + } + brConn->state = BR_CONNECTION_STATE_CONNECTED; + *outSocketFd = socketFd; + ReleaseConnectionRef(brConn); + return SOFTBUS_OK; } -static void ClientOnBrConnect(int32_t socketFd) +static void ClientNoticeResultBrConnect(uint32_t connId, bool result, int32_t value) { ListNode notifyList; ListInit(¬ifyList); - ListNode *britem = NULL; ListNode *item = NULL; ListNode *itemNext = NULL; RequestInfo *requestInfo = NULL; ConnectionInfo connectionInfo; - (void)pthread_mutex_lock(&g_connectionLock); - int32_t connectionId = 0; - int32_t packRequestFlag = 0; - LIST_FOR_EACH(britem, &g_conection_list) { - BrConnectionInfo *itemNode = LIST_ENTRY(britem, BrConnectionInfo, node); - if (itemNode->socketFd == socketFd) { - connectionInfo.isAvailable = 1; - connectionInfo.isServer = itemNode->sideType; - connectionInfo.type = CONNECT_BR; - strncpy_s(connectionInfo.info.brInfo.brMac, BT_MAC_LEN, - itemNode->mac, sizeof(itemNode->mac)); - connectionId = itemNode->connectionId; - itemNode->state = BR_CONNECTION_STATE_CONNECTED; - LIST_FOR_EACH_SAFE(item, itemNext, &itemNode->requestList) { - requestInfo = LIST_ENTRY(item, RequestInfo, node); - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[ClientOnEvent] requestId=%d, connectionId=%u", - requestInfo->requestId, itemNode->connectionId); - ListDelete(&requestInfo->node); - ListAdd(¬ifyList, &requestInfo->node); - packRequestFlag++; - } - break; - } + if (!result) { + SetBrConnStateByConnId(connId, BR_CONNECTION_STATE_CLOSING); } - (void)pthread_mutex_unlock(&g_connectionLock); - if (connectionId != 0) { - DeviceConnectPackRequest(packRequestFlag, connectionId); + int32_t sideType = BR_CLIENT_TYPE; + int32_t packRequestFlag = GetBrRequestListByConnId(connId, ¬ifyList, &connectionInfo, &sideType); + if (packRequestFlag != 0) { + if (result) { + connectionInfo.isAvailable = 1; + DeviceConnectPackRequest(packRequestFlag, connId); + } LIST_FOR_EACH_SAFE(item, itemNext, ¬ifyList) { requestInfo = LIST_ENTRY(item, RequestInfo, node); - if (requestInfo->callback.OnConnectSuccessed != NULL) { - requestInfo->callback.OnConnectSuccessed( - requestInfo->requestId, connectionId, &connectionInfo); + if (result) { + if (requestInfo->callback.OnConnectSuccessed != NULL) { + requestInfo->callback.OnConnectSuccessed(requestInfo->requestId, connId, &connectionInfo); + } + } else { + if (requestInfo->callback.OnConnectFailed != NULL) { + requestInfo->callback.OnConnectFailed(requestInfo->requestId, value); + } } ListDelete(&requestInfo->node); SoftBusFree(requestInfo); @@ -707,44 +236,22 @@ static void ClientOnBrConnect(int32_t socketFd) } } -static void ClientOnEvent(int32_t type, int32_t socketFd, int32_t value) +static int32_t ClientOnBrConnect(int32_t connId) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[ClientOnEvent] type=%d, socketFd=%d", type, socketFd); - if (type == SPP_EVENT_TYPE_CONNECTED) { - ClientOnBrConnect(socketFd); - } else if (type == SPP_EVENT_TYPE_DISCONNECTED) { - ClientOnBrDisconnect(socketFd, value); - } else if (type == SPP_EVENT_TYPE_CONGEST) { - RfcomCongestEvent(socketFd, value); + int32_t socketFd = -1; + bool isSuccess = true; + if (ClientOnBrConnectDevice(connId, &socketFd) != SOFTBUS_OK) { + isSuccess = false; } -} - -static int32_t InitConnectionInfo(ConnectionInfo *connectionInfo, const BrConnectionInfo *itemNode) -{ - (*connectionInfo).isAvailable = 0; - (*connectionInfo).isServer = itemNode->sideType; - (*connectionInfo).type = CONNECT_BR; - if (strncpy_s((*connectionInfo).info.brInfo.brMac, BT_MAC_LEN, - itemNode->mac, sizeof(itemNode->mac)) != EOK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "InitConnInfo scpy error"); - return SOFTBUS_BRCONNECTION_STRNCPY_ERROR; + ClientNoticeResultBrConnect(connId, isSuccess, socketFd); + if (!isSuccess) { + ReleaseConnectionRefByConnId(connId); } - return SOFTBUS_OK; -} - -static void FreeCongestEvent(BrConnectionInfo *itemNode) -{ - itemNode->conGestState = BT_RFCOM_CONGEST_OFF; - if (pthread_mutex_lock(&itemNode->lock) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "FreeCongestEvent mutex failed"); - return; - } - pthread_cond_broadcast(&itemNode->congestCond); - (void)pthread_mutex_unlock(&itemNode->lock); + return socketFd; } static void NotifyDisconnect(const ListNode *notifyList, int32_t connectionId, - ConnectionInfo connectionInfo, int32_t value) + ConnectionInfo connectionInfo, int32_t value, int32_t sideType) { ListNode *item = NULL; ListNode *itemNext = NULL; @@ -752,7 +259,7 @@ static void NotifyDisconnect(const ListNode *notifyList, int32_t connectionId, LIST_FOR_EACH_SAFE(item, itemNext, notifyList) { RequestInfo *requestInfo = LIST_ENTRY(item, RequestInfo, node); if (requestInfo->callback.OnConnectFailed != NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[ClientOnEvent] disconn connectionId=%d", connectionId); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "notify disconn connectionId=%d", connectionId); requestInfo->callback.OnConnectFailed(requestInfo->requestId, value); } ListDelete(&requestInfo->node); @@ -760,309 +267,271 @@ static void NotifyDisconnect(const ListNode *notifyList, int32_t connectionId, } } - if (g_connectCallback != NULL) { + if (sideType == BR_SERVICE_TYPE && g_connectCallback != NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[ClientOnEvent] disconn connectionId=%d", connectionId); g_connectCallback->OnDisconnected(connectionId, &connectionInfo); } } -static void ClientOnBrDisconnect(int32_t socketFd, int32_t value) +static int32_t NotifyServerConn(int connectionId, const char *mac, int32_t sideType) { - ListNode *britem = NULL; - ListNode *item = NULL; - ListNode *itemNext = NULL; - int32_t connectionId = -1; - ListNode notifyList; - ListInit(¬ifyList); - ConnectionInfo connectionInfo; - BrConnectionInfo *brNode = NULL; - if (pthread_mutex_lock(&g_connectionLock) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "ClientOnBrDisconnect mutex failed"); - return; - } - LIST_FOR_EACH(britem, &g_conection_list) { - BrConnectionInfo *itemNode = LIST_ENTRY(britem, BrConnectionInfo, node); - if (itemNode->socketFd == socketFd) { - brNode = itemNode; - itemNode->state = BR_CONNECTION_STATE_CLOSED; - FreeCongestEvent(itemNode); - if (InitConnectionInfo(&connectionInfo, itemNode) != SOFTBUS_OK) { - (void)pthread_mutex_unlock(&g_connectionLock); - return; - } - connectionId = itemNode->connectionId; - LIST_FOR_EACH_SAFE(item, itemNext, &itemNode->requestList) { - RequestInfo *requestInfo = LIST_ENTRY(item, RequestInfo, node); - ListDelete(&requestInfo->node); - ListAdd(¬ifyList, &requestInfo->node); - } - break; - } - } - ClearSendItemByConnId(connectionId); - ClearReceiveQueueByConnId(connectionId); - ReleaseConnectionRef(brNode); - (void)pthread_mutex_unlock(&g_connectionLock); - if (connectionId != -1) { - NotifyDisconnect(¬ifyList, connectionId, connectionInfo, value); - } -} - -static int32_t ReceivedHeadCheck(const ConnPktHead *head, BrConnectionInfo *conn) -{ - if (head->magic != 0xBABEFACE) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[ClientOnDataReceived] magic error 0x%x", head->magic); - conn->recvPos = 0; - return SOFTBUS_ERR; - } - - if (head->len > (g_brBuffSize - sizeof(ConnPktHead))) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, - "[ClientOnDataReceived]data too large . module=%d,seq=%lld, datalen=%d", - head->module, head->seq, head->len); - conn->recvPos = 0; - return SOFTBUS_ERR; - } - return SOFTBUS_OK; -} - -static int32_t ReceivedError(ReceiveItemStruct *recvItem, char *dataCopy, - const char *bufHead, const ConnPktHead *head, int32_t sendToManagerLen) -{ - if (recvItem == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "malloc recvItem fail"); - if (dataCopy != NULL) { - SoftBusFree(dataCopy); - } - return SOFTBUS_ERR; - } - if (dataCopy == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "malloc dataCopy fail"); - SoftBusFree(recvItem); - return SOFTBUS_ERR; - } - if (memcpy_s(dataCopy, sendToManagerLen, - bufHead, head->len + sizeof(ConnPktHead)) != EOK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "ReceivedError memcpy_s failed"); - SoftBusFree(dataCopy); - SoftBusFree(recvItem); - return SOFTBUS_ERR; - } - return SOFTBUS_OK; -} - - -static void InitRecvItemAndInsert(ReceiveItemStruct *recvItem, int32_t connectionId, - const ConnPktHead *head, int32_t sendToManagerLen, const char *dataCopy) -{ - recvItem->connectionId = connectionId; - recvItem->module = head->module; - recvItem->seqNum = head->seq; - recvItem->flag = head->flag; - recvItem->dataLen = sendToManagerLen; - recvItem->data = (uint8_t*)dataCopy; - if (pthread_mutex_lock(&g_recvQueue.lock) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "InitRecvItemAndInsert mutex failed"); - return; - } - if (recvItem->module == MODULE_DEVICE_AUTH) { - ListAdd(&g_recvQueue.recvList, &recvItem->node); - } else { - ListTailInsert(&g_recvQueue.recvList, &recvItem->node); - } - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[ClientOnDataReceived] connectionId=%d", connectionId); - pthread_cond_signal(&g_recvQueue.cond); - (void)pthread_mutex_unlock(&g_recvQueue.lock); -} - -static void ClientOnDataReceived(int32_t socketFd, const char *buf, int32_t len) -{ - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[ClientOnDataReceived] socketFd=%d,len=%d", socketFd, len); - BrConnectionInfo *conn = NULL; - (void)pthread_mutex_lock(&g_connectionLock); - ListNode *item = NULL; - LIST_FOR_EACH(item, &g_conection_list) { - BrConnectionInfo *itemNode = LIST_ENTRY(item, BrConnectionInfo, node); - if (itemNode->socketFd == socketFd) { - conn = itemNode; - break; - } - } - - if (conn == NULL) { - (void)pthread_mutex_unlock(&g_connectionLock); - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[ClientOnDataReceived] not found socket=%d", socketFd); - return; - } - - char *bufHead = (char*)buf; - int32_t bufLen = len; - bool isCopy = false; - if (conn->recvPos != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_DBG, "[ClientOnDataReceived] recvPos=%d", conn->recvPos); - (void)memcpy_s(conn->recvBuf + conn->recvPos, g_brBuffSize - conn->recvPos, buf, len); - conn->recvPos += len; - isCopy = true; - bufHead = conn->recvBuf; - bufLen = conn->recvPos; - } - // recv head - if (bufLen < sizeof(ConnPktHead)) { - if (!isCopy) { - (void)memcpy_s(conn->recvBuf + conn->recvPos, g_brBuffSize - conn->recvPos, buf, len); - conn->recvPos += len; - isCopy = true; - } - (void)pthread_mutex_unlock(&g_connectionLock); - return; - } - - ConnPktHead *head = (ConnPktHead *)bufHead; - if (ReceivedHeadCheck(head, conn) != SOFTBUS_OK) { - (void)pthread_mutex_unlock(&g_connectionLock); - return; - } - - if (head->len > (bufLen - sizeof(ConnPktHead))) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, - "[ClientOnDataReceived] socket=%d , continue to recv", socketFd); - if (!isCopy) { - (void)memcpy_s(conn->recvBuf + conn->recvPos, g_brBuffSize - conn->recvPos, buf, len); - conn->recvPos += len; - isCopy = true; - } - (void)pthread_mutex_unlock(&g_connectionLock); - return; - } - bool headtogether = false; - int32_t sendToManagerLen = bufLen; - if (head->len < (bufLen - sizeof(ConnPktHead))) { - headtogether = true; - sendToManagerLen = head->len + sizeof(ConnPktHead); - } - if (g_connectCallback != NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[ClientOnDataReceived] socket=%d , ready to insert", socketFd); - ReceiveItemStruct *recvItem = SoftBusMalloc(sizeof(ReceiveItemStruct)); - if (recvItem == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "malloc failed"); - (void)pthread_mutex_unlock(&g_connectionLock); - return; - } - char *dataCopy = SoftBusMalloc(sendToManagerLen); - if (dataCopy == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "malloc failed"); - SoftBusFree(recvItem); - (void)pthread_mutex_unlock(&g_connectionLock); - return; - } - if (ReceivedError(recvItem, dataCopy, bufHead, head, sendToManagerLen) != SOFTBUS_OK) { - conn->recvPos = 0; - (void)pthread_mutex_unlock(&g_connectionLock); - return; - } - InitRecvItemAndInsert(recvItem, conn->connectionId, head, sendToManagerLen, dataCopy); - } - if (headtogether == false) { - conn->recvPos = 0; - } else { - if (memmove_s(conn->recvBuf, g_brBuffSize, - conn->recvBuf + sendToManagerLen, bufLen - sendToManagerLen) != EOK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "memmove_s failed"); - (void)pthread_mutex_unlock(&g_connectionLock); - return; - } - conn->recvPos = bufLen - sendToManagerLen; - } - (void)pthread_mutex_unlock(&g_connectionLock); -} - -static int32_t NotifyServerConn(int connectionId, const BrConnectionInfo *conn) -{ - if (pthread_mutex_lock(&g_connectionLock) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); - return SOFTBUS_ERR; - } ConnectionInfo connectionInfo; connectionInfo.isAvailable = 1; - connectionInfo.isServer = conn->sideType; + connectionInfo.isServer = sideType; connectionInfo.type = CONNECT_BR; - if (strncpy_s(connectionInfo.info.brInfo.brMac, - BT_MAC_LEN, conn->mac, sizeof(conn->mac)) != EOK) { + if (strcpy_s(connectionInfo.info.brInfo.brMac, BT_MAC_LEN, mac) != EOK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "NotifyServerConn scpy error"); - (void)pthread_mutex_unlock(&g_connectionLock); return SOFTBUS_ERR; } - (void)pthread_mutex_unlock(&g_connectionLock); g_connectCallback->OnConnected(connectionId, &connectionInfo); return SOFTBUS_OK; } -static void ServerOnBrConnect(int32_t type, int32_t socketFd, int32_t value) +static void ClearDataPidByPid(int32_t pid) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[new connection, socket = %d", value); - (void)pthread_mutex_lock(&g_connectionLock); ListNode *item = NULL; - LIST_FOR_EACH(item, &g_conection_list) { - BrConnectionInfo *itemNode = LIST_ENTRY(item, BrConnectionInfo, node); - if (value == itemNode->socketFd) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "Serviceconnection exit, socketFd=%d", socketFd); - (void)pthread_mutex_unlock(&g_connectionLock); - return; + ListNode *nextItem = NULL; + LIST_FOR_EACH_SAFE(item, nextItem, &g_dataQueue.pidList) { + DataPidQueueStruct *itemNode = LIST_ENTRY(item, DataPidQueueStruct, node); + if (itemNode->pid == pid) { + ListDelete(item); + SoftBusFree(itemNode); } } - (void)pthread_mutex_unlock(&g_connectionLock); +} + +static void FreeSendItem(SendItemStruct *sendItem) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[FreeSendItem]"); + if (sendItem == NULL) { + return; + } + if (sendItem->data != NULL) { + SoftBusFree(sendItem->data); + } + SoftBusFree(sendItem); +} + +static void ClearSendItemByConnId(uint32_t connectionId) +{ + if (pthread_mutex_lock(&g_dataQueue.lock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[ClearSendItemByConnId] mutex failed"); + return; + } + ListNode *sendItemNode = NULL; + ListNode *nextItem = NULL; + SendItemStruct *sendItem = NULL; + LIST_FOR_EACH_SAFE(sendItemNode, nextItem, &g_dataQueue.sendList) { + sendItem = LIST_ENTRY(sendItemNode, SendItemStruct, node); + if (sendItem->connectionId == connectionId) { + ClearDataPidByPid(sendItem->pid); + ListDelete(sendItemNode); + FreeSendItem(sendItem); + } + } + (void)pthread_mutex_unlock(&g_dataQueue.lock); +} + +static void BrDisconnect(int32_t socketFd, int32_t value) +{ + ListNode notifyList; + ListInit(¬ifyList); + ConnectionInfo connectionInfo; + int32_t sideType = BR_CLIENT_TYPE; + int32_t perState = BR_CONNECTION_STATE_CLOSED; + uint32_t connectionId = SetBrConnStateBySocket(socketFd, BR_CONNECTION_STATE_CLOSED, &perState); + if (connectionId != 0) { + (void)GetBrRequestListByConnId(connectionId, ¬ifyList, &connectionInfo, &sideType); + ClearSendItemByConnId(connectionId); + if (perState != BR_CONNECTION_STATE_CLOSED) { + NotifyDisconnect(¬ifyList, connectionId, connectionInfo, value, sideType); + ReleaseConnectionRefByConnId(connectionId); + } + } +} + +int32_t ConnBrOnEvent(BrConnLoopMsgType type, int32_t socketFd, int32_t value) +{ + if (type >= ADD_CONN_BR_MAX || type <= ADD_CONN_BR_INVALID) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[ConnBrOnEvent] type(%d) failed", type); + return SOFTBUS_ERR; + } + if (type == ADD_CONN_BR_CONGEST_MSG) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[ConnBrOnEvent] ADD_CONN_BR_CONGEST_MSG"); + RfcomCongestEvent(socketFd, value); + return SOFTBUS_ERR; + } + + SoftBusMessage *msg = BrConnCreateLoopMsg(type, (uint64_t)socketFd, (uint64_t)value, NULL); + if (msg == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[ConnBrOnEvent] BrConnCreateLoopMsg failed"); + return SOFTBUS_ERR; + } + g_brAsyncHandler.looper->PostMessage(g_brAsyncHandler.looper, msg); + return SOFTBUS_OK; +} + +static void ConnectDeviceExit(const uint32_t connId, uint32_t requestId, const ConnectResult *result) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[ConnectDeviceExit]"); + BrConnectionInfo *connInfo = GetConnectionRef(connId); + if (connInfo == NULL) { + return; + } + ConnectionInfo connectionInfo; + connectionInfo.isAvailable = 1; + connectionInfo.isServer = connInfo->sideType; + connectionInfo.type = CONNECT_BR; + if (strcpy_s(connectionInfo.info.brInfo.brMac, BT_MAC_LEN, connInfo->mac) != EOK) { + ReleaseConnectionRef(connInfo); + return; + } + ReleaseConnectionRef(connInfo); + + if (result->OnConnectSuccessed != NULL) { + result->OnConnectSuccessed(requestId, connId, &connectionInfo); + } + + (void)PackRequest(CONNECT_REF_INCRESE, connId); +} + +static int32_t ConnectDeviceStateConnecting(const uint32_t connId, uint32_t requestId, const ConnectResult *result) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[ConnectDeviceStateConnecting]"); + RequestInfo *requestInfo = (RequestInfo *)SoftBusMalloc(sizeof(RequestInfo)); + if (requestInfo == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "SoftBusMalloc failed"); + return SOFTBUS_ERR; + } + (void)memset_s(requestInfo, sizeof(RequestInfo), 0, sizeof(RequestInfo)); + ListInit(&requestInfo->node); + requestInfo->requestId = requestId; + (void)memcpy_s(&requestInfo->callback, sizeof(requestInfo->callback), result, sizeof(*result)); + if (AddRequestByConnId(connId, requestInfo) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "AddRequestByConnId failed"); + SoftBusFree(requestInfo); + return SOFTBUS_ERR; + } + return SOFTBUS_OK; +} + +static int32_t ConnectDeviceFristTime(const ConnectOption *option, uint32_t requestId, const ConnectResult *result) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[ConnectDeviceFristTime]"); + if (g_sppDriver == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[sppDriver null]"); + return SOFTBUS_ERR; + } + BrConnectionInfo *newConnInfo = CreateBrconnectionNode(true); + if (newConnInfo == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[client node create fail]"); + return SOFTBUS_ERR; + } + RequestInfo *requestInfo = (RequestInfo *)SoftBusCalloc(sizeof(RequestInfo)); + if (requestInfo == NULL) { + ReleaseBrconnectionNode(newConnInfo); + return SOFTBUS_ERR; + } + ListInit(&requestInfo->node); + requestInfo->requestId = requestId; + (void)memcpy_s(&requestInfo->callback, sizeof(requestInfo->callback), result, sizeof(*result)); + ListAdd(&newConnInfo->requestList, &requestInfo->node); + if (strcpy_s(newConnInfo->mac, sizeof(newConnInfo->mac), option->info.brOption.brMac) != EOK) { + ReleaseBrconnectionNode(newConnInfo); + return SOFTBUS_ERR; + } + uint32_t connId = newConnInfo->connectionId; + if (AddConnectionList(newConnInfo) != SOFTBUS_OK) { + ReleaseBrconnectionNode(newConnInfo); + return SOFTBUS_ERR; + } + + if (ConnBrOnEvent(ADD_CONN_BR_CLIENT_CONNECTED_MSG, (int32_t)connId, (int32_t)connId) != SOFTBUS_OK) { + ReleaseConnectionRef(newConnInfo); + return SOFTBUS_ERR; + } + return SOFTBUS_OK; +} + +static int32_t ConnectDevice(const ConnectOption *option, uint32_t requestId, const ConnectResult *result) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[ConnectDevice]"); + if (HasDiffMacDeviceExit(option)) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[has diff mac device]"); + } + int32_t connId = -1; + int32_t ret = SOFTBUS_OK; + if (pthread_mutex_lock(&g_brConnLock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); + return SOFTBUS_ERR; + } + int32_t connState = GetBrConnStateByConnOption(option, &connId); + if (connState == BR_CONNECTION_STATE_CONNECTED) { + ConnectDeviceExit(connId, requestId, result); + } else if (connState == BR_CONNECTION_STATE_CONNECTING) { + ret = ConnectDeviceStateConnecting((uint32_t)connId, requestId, result); + } else if (connState == BR_CONNECTION_STATE_CLOSING) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[BR_CONNECTION_STATE_CLOSING]"); + result->OnConnectFailed(requestId, 0); + ret = SOFTBUS_ERR; + } else if (connState == BR_CONNECTION_STATE_CLOSED) { + ret = ConnectDeviceFristTime(option, requestId, result); + } + (void)pthread_mutex_unlock(&g_brConnLock); + return ret; +} + +static int32_t ServerOnBrConnect(int32_t socketFd) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[new connection, socket = %d]", socketFd); + if (IsExitBrConnectByFd(socketFd)) { + return SOFTBUS_ERR; + } + int32_t connectionId = SOFTBUS_ERR; BrConnectionInfo *newConnectionInfo = CreateBrconnectionNode(false); if (newConnectionInfo == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[service node create fail]"); - g_sppDriver->CloseClient(value); - return; + g_sppDriver->DisConnect(socketFd); + return SOFTBUS_ERR; } - RequestInfo *requestInfo = SoftBusCalloc(sizeof(RequestInfo)); + RequestInfo *requestInfo = (RequestInfo *)SoftBusCalloc(sizeof(RequestInfo)); if (requestInfo == NULL) { ReleaseBrconnectionNode(newConnectionInfo); - g_sppDriver->CloseClient(value); - return; + g_sppDriver->DisConnect(socketFd); + return SOFTBUS_ERR; } ListInit(&requestInfo->node); ListAdd(&newConnectionInfo->requestList, &requestInfo->node); - BluetoothRemoteDevice* info = NULL; - g_sppDriver->GetRemoteDeviceInfo(value, info); - if (ConvertBtMacToStr(newConnectionInfo->mac, BT_MAC_LEN, (uint8_t *)info->mac, BT_ADDR_LEN_RFCOM) != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "convert bt mac to str fail"); + BluetoothRemoteDevice deviceInfo; + if (g_sppDriver->GetRemoteDeviceInfo(socketFd, &deviceInfo) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "GetRemoteDeviceInfo fail"); ReleaseBrconnectionNode(newConnectionInfo); - g_sppDriver->CloseClient(value); - return; + g_sppDriver->DisConnect(socketFd); + return SOFTBUS_ERR; } - newConnectionInfo->socketFd = value; + if (ConvertBtMacToStr(newConnectionInfo->mac, BT_MAC_LEN, (uint8_t *)deviceInfo.mac, BT_ADDR_LEN) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BrServer convert bt mac to str fail"); + ReleaseBrconnectionNode(newConnectionInfo); + g_sppDriver->DisConnect(socketFd); + return SOFTBUS_ERR; + } + newConnectionInfo->socketFd = socketFd; newConnectionInfo->state = BR_CONNECTION_STATE_CONNECTED; - newConnectionInfo->sideType = BR_SERVICE_TYPE; - int connectionId = newConnectionInfo->connectionId; - ListAdd(&g_conection_list, &newConnectionInfo->node); - if (NotifyServerConn(connectionId, newConnectionInfo) != SOFTBUS_OK) { + connectionId = newConnectionInfo->connectionId; + char mac[BT_MAC_LEN] = {0}; + (void)memcpy_s(mac, BT_MAC_LEN, newConnectionInfo->mac, BT_MAC_LEN); + if (AddConnectionList(newConnectionInfo) != SOFTBUS_OK) { + ListDelete(&newConnectionInfo->node); ReleaseBrconnectionNode(newConnectionInfo); - g_sppDriver->CloseClient(value); + g_sppDriver->DisConnect(socketFd); + return SOFTBUS_ERR; } - return; -} - -static void ServerOnBrDisconnect(int32_t socketFd, int32_t value) -{ - ClientOnBrDisconnect(socketFd, value); -} - -static void ServerOnDataReceived(int32_t socketFd, const char *buf, int32_t len) -{ - ClientOnDataReceived(socketFd, buf, len); -} - -static void ServerOnEvent(int32_t type, int32_t socketFd, int32_t value) -{ - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[ClientOnEvent] socketFd=%d", socketFd); - if (type == SPP_EVENT_TYPE_CONNECTED) { - ServerOnBrConnect(type, socketFd, value); - } else if (type == SPP_EVENT_TYPE_DISCONNECTED) { - ServerOnBrDisconnect(socketFd, value); + if (NotifyServerConn(connectionId, mac, BR_SERVICE_TYPE) != SOFTBUS_OK) { + g_sppDriver->DisConnect(socketFd); + ReleaseConnectionRefByConnId(connectionId); + connectionId = SOFTBUS_ERR; } + return connectionId; } static int32_t GetPriority(int32_t flag) @@ -1101,18 +570,28 @@ static int32_t CheckSendQueueLength(void) } (void)pthread_mutex_unlock(&g_dataQueue.lock); if (totalSendNum > g_brSendQueueMaxLen) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SOFTBUS_CONNECTION_ERR_SENDQUEUE_FULL!!!"); return SOFTBUS_CONNECTION_ERR_SENDQUEUE_FULL; } return SOFTBUS_OK; } -static DataPidQueueStruct *CreatNewPidNode(int pid) +static DataPidQueueStruct *GetPidQueue(int pid) { - DataPidQueueStruct *pidQueue = SoftBusCalloc(sizeof(DataPidQueueStruct)); + ListNode *item = NULL; + LIST_FOR_EACH(item, &g_dataQueue.pidList) { + DataPidQueueStruct *itemNode = LIST_ENTRY(item, DataPidQueueStruct, node); + if (itemNode->pid == pid) { + return itemNode; + } + } + + DataPidQueueStruct *pidQueue = (DataPidQueueStruct *)SoftBusCalloc(sizeof(DataPidQueueStruct)); if (pidQueue == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "PostBytes CreatNewPidNode fail"); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Creat New PidNode fail"); return NULL; } + ListInit(&pidQueue->node); pidQueue->pid = pid; ListTailInsert(&g_dataQueue.pidList, &pidQueue->node); @@ -1121,7 +600,7 @@ static DataPidQueueStruct *CreatNewPidNode(int pid) static int32_t CreateNewSendItem(int pid, int flag, int connectionId, int len, const char *data) { - SendItemStruct *sendItem = SoftBusCalloc(sizeof(SendItemStruct)); + SendItemStruct *sendItem = (SendItemStruct *)SoftBusCalloc(sizeof(SendItemStruct)); if (sendItem == NULL) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "PostBytes CreateNewSendItem fail"); return SOFTBUS_ERR; @@ -1158,166 +637,92 @@ static int32_t PostBytes(uint32_t connectionId, const char *data, int32_t len, i { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "PostBytes connectionId=%u,pid=%d,len=%d flag=%d", connectionId, pid, len, flag); - (void)pthread_mutex_lock(&g_connectionLock); if (CheckSendQueueLength() != SOFTBUS_OK) { SoftBusFree((void*)data); - (void)pthread_mutex_unlock(&g_connectionLock); return SOFTBUS_CONNECTION_ERR_SENDQUEUE_FULL; } - BrConnectionInfo *conn = GetConnectionRef(connectionId); - if (conn == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "PostBytes connectionId=%u not found", connectionId); + + if (!IsBrDeviceReady(connectionId)) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "connectionId(%u) device is not ready", connectionId); SoftBusFree((void*)data); - (void)pthread_mutex_unlock(&g_connectionLock); return SOFTBUS_BRCONNECTION_POSTBYTES_ERROR; } (void)pthread_mutex_lock(&g_dataQueue.lock); - DataPidQueueStruct *pidQueue = NULL; - ListNode *item = NULL; - LIST_FOR_EACH(item, &g_dataQueue.pidList) { - DataPidQueueStruct *itemNode = LIST_ENTRY(item, DataPidQueueStruct, node); - if (itemNode->pid == pid) { - pidQueue = itemNode; - break; - } - } + DataPidQueueStruct *pidQueue = GetPidQueue(pid); if (pidQueue == NULL) { - pidQueue = CreatNewPidNode(pid); - if (pidQueue == NULL) { - (void)pthread_mutex_unlock(&g_connectionLock); - SoftBusFree((void*)data); - (void)pthread_mutex_unlock(&g_dataQueue.lock); - return SOFTBUS_BRCONNECTION_POSTBYTES_ERROR; - } + SoftBusFree((void*)data); + (void)pthread_mutex_unlock(&g_dataQueue.lock); + return SOFTBUS_BRCONNECTION_POSTBYTES_ERROR; } pidQueue->itemCount++; SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "PostBytes pidQueue count=%d", pidQueue->itemCount); if (CreateNewSendItem(pid, flag, connectionId, len, data) != SOFTBUS_OK) { - (void)pthread_mutex_unlock(&g_connectionLock); SoftBusFree((void*)data); - SoftBusFree(pidQueue); + pidQueue->itemCount--; + if (pidQueue->itemCount == 0) { + ListDelete(&pidQueue->node); + SoftBusFree(pidQueue); + } (void)pthread_mutex_unlock(&g_dataQueue.lock); return SOFTBUS_BRCONNECTION_POSTBYTES_ERROR; } - (void)pthread_mutex_unlock(&g_connectionLock); pthread_cond_broadcast(&g_dataQueue.cond); (void)pthread_mutex_unlock(&g_dataQueue.lock); return SOFTBUS_OK; } - -static void FreeSendItem(SendItemStruct *sendItem) +static int32_t DisconnectDevice(uint32_t connectionId) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "FreeSendItem"); - if (sendItem == NULL) { - return; + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[DisconnectDevice]"); + if (!IsExitConnectionById(connectionId)) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[not find connectionId: %u]", connectionId); + return SOFTBUS_BRCONNECTION_DISCONNECT_NOTFIND; } - if (sendItem->data != NULL) { - SoftBusFree(sendItem->data); - } - SoftBusFree(sendItem); + (void)PackRequest(CONNECT_REF_DECRESE, connectionId); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[DisconnectDevice over]"); + return SOFTBUS_OK; } - -static void ClearDataPidByPid(int32_t pid) +static int32_t DisconnectDeviceNow(const ConnectOption *option) { - ListNode *item = NULL; - ListNode *nextItem = NULL; - LIST_FOR_EACH_SAFE(item, nextItem, &g_dataQueue.pidList) { - DataPidQueueStruct *itemNode = LIST_ENTRY(item, DataPidQueueStruct, node); - if (itemNode->pid == pid) { - ListDelete(item); - SoftBusFree(itemNode); - } - } -} - -static void ClearSendItemByConnId(uint32_t connectionId) -{ - if (pthread_mutex_lock(&g_dataQueue.lock) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "ClearSendItemByConnId mutex failed"); - return; - } - ListNode *sendItemNode = NULL; - ListNode *nextItem = NULL; - SendItemStruct *sendItem = NULL; - LIST_FOR_EACH_SAFE(sendItemNode, nextItem, &g_dataQueue.sendList) { - sendItem = LIST_ENTRY(sendItemNode, SendItemStruct, node); - if (sendItem->connectionId == connectionId) { - ClearDataPidByPid(sendItem->pid); - ListDelete(sendItemNode); - FreeSendItem(sendItem); - } - } - (void)pthread_mutex_unlock(&g_dataQueue.lock); -} - -static int32_t SendData(SendItemStruct *sendItem) -{ - BrConnectionInfo *brConnInfo = NULL; - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "SendData"); - (void)pthread_mutex_lock(&g_connectionLock); - ListNode *item = NULL; - int32_t socketFd = -1; - LIST_FOR_EACH(item, &g_conection_list) { - brConnInfo = LIST_ENTRY(item, BrConnectionInfo, node); - if (brConnInfo->connectionId == sendItem->connectionId) { - socketFd = brConnInfo->socketFd; - } - } - - if (socketFd == -1) { - (void)pthread_mutex_unlock(&g_connectionLock); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[DisconnectDeviceNow]"); + if (option == NULL || option->type != CONNECT_BR) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "option check fail"); return SOFTBUS_ERR; } - int32_t writeRet = -1; - int freeLock = false; - - int32_t templen = sendItem->dataLen; - char *sendData = sendItem->data; - while (templen > 0) { - (void)pthread_mutex_lock(&brConnInfo->lock); - while (brConnInfo->conGestState == BT_RFCOM_CONGEST_ON && - brConnInfo->state == BR_CONNECTION_STATE_CONNECTED) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "wait congest"); - (void)pthread_mutex_unlock(&g_connectionLock); - freeLock = true; - pthread_cond_wait(&brConnInfo->congestCond, &brConnInfo->lock); - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "free congest"); - break; - } - (void)pthread_mutex_unlock(&brConnInfo->lock); - - int32_t sendlenth = templen; - if (sendlenth > g_brSendPeerLen) { - sendlenth = g_brSendPeerLen; - } - writeRet = g_sppDriver->Write(socketFd, sendItem->data, sendlenth); - sendItem->data += sendlenth; - templen -= sendlenth; + int32_t socketFd = -1; + int32_t sideType = -1; + if (BrClosingByConnOption(option, &socketFd, &sideType) != SOFTBUS_OK) { + return SOFTBUS_ERR; } - sendItem->data = sendData; - if (freeLock != true) { - (void)pthread_mutex_unlock(&g_connectionLock); + if (!IsListEmpty(&g_dataQueue.sendList)) { + SoftBusSleepMs(DISCONN_DELAY_TIME); } - return writeRet; + if (sideType == BR_SERVICE_TYPE) { + return ConnBrOnEvent(ADD_CONN_BR_SERVICE_DISCONNECTED_MSG, socketFd, socketFd); + } else { + return ConnBrOnEvent(ADD_CONN_BR_CLIENT_DISCONNECTED_MSG, socketFd, socketFd); + } + return SOFTBUS_ERR; } void *SendHandlerLoop(void *arg) { while (1) { - (void)pthread_mutex_lock(&g_dataQueue.lock); + if (pthread_mutex_lock(&g_dataQueue.lock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[SendHandlerLoop] mutex failed"); + break; + } if (IsListEmpty(&g_dataQueue.sendList)) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "SendHandlerLoop empty"); pthread_cond_wait(&g_dataQueue.cond, &g_dataQueue.lock); - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "start SendHandlerLoop"); (void)pthread_mutex_unlock(&g_dataQueue.lock); continue; } ListNode *item = NULL; + int32_t sendPid = -1; LIST_FOR_EACH(item, &g_dataQueue.pidList) { DataPidQueueStruct *itemNode = LIST_ENTRY(item, DataPidQueueStruct, node); ListDelete(item); @@ -1330,193 +735,35 @@ void *SendHandlerLoop(void *arg) } break; } - ListNode *sendItemNode = NULL; SendItemStruct *sendItem = NULL; LIST_FOR_EACH(sendItemNode, &g_dataQueue.sendList) { - sendItem = LIST_ENTRY(sendItemNode, SendItemStruct, node); - if (sendItem->pid == sendPid) { + SendItemStruct *tmpSendItem = LIST_ENTRY(sendItemNode, SendItemStruct, node); + if (tmpSendItem->pid == sendPid) { ListDelete(sendItemNode); + sendItem = tmpSendItem; break; } } + (void)pthread_mutex_unlock(&g_dataQueue.lock); if (sendItem == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SendItem fail"); continue; } - (void)pthread_mutex_unlock(&g_dataQueue.lock); - if (SendData(sendItem) != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "SendItem fail"); + if (BrTransSend(sendItem->connectionId, g_sppDriver, g_brSendPeerLen, sendItem->data, sendItem->dataLen) + != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BrTransSend fail"); } FreeSendItem(sendItem); } + return NULL; } -static void RecvConnectedComd(uint32_t connectionId, const cJSON *data) +static int32_t InitDataQueue(void) { - int32_t keyMethod = 0; - int32_t keyDelta = 0; - int32_t keyRefernceNum = 0; - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "RecvConnectedComd ID=%u", connectionId); - - if (!GetJsonObjectNumberItem(data, KEY_METHOD, &keyMethod)) { - return; - } - if (keyMethod == METHOD_NOTIFY_REQUEST) { - if (!GetJsonObjectNumberItem(data, KEY_METHOD, &keyMethod) || - !GetJsonObjectNumberItem(data, KEY_DELTA, &keyDelta) || - !GetJsonObjectNumberItem(data, KEY_REFERENCE_NUM, &keyRefernceNum)) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "REQUEST fail"); - return; - } - OnPackResponse(keyDelta, keyRefernceNum, connectionId); - } - if (keyMethod == METHOD_NOTIFY_RESPONSE) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "NOTIFY_RESPONSE"); - if (!GetJsonObjectNumberItem(data, KEY_METHOD, &keyMethod) || - !GetJsonObjectNumberItem(data, KEY_REFERENCE_NUM, &keyRefernceNum)) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "RESPONSE fail"); - return; - } - (void)pthread_mutex_lock(&g_connectionLock); - ListNode *item = NULL; - LIST_FOR_EACH(item, &g_conection_list) { - BrConnectionInfo *itemNode = LIST_ENTRY(item, BrConnectionInfo, node); - if (itemNode->connectionId == connectionId) { - if (itemNode->state == BR_CONNECTION_STATE_CLOSING) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "NOTIFY_CHANGE"); - itemNode->state = BR_CONNECTION_STATE_CONNECTED; - } - break; - } - } - (void)pthread_mutex_unlock(&g_connectionLock); - } -} - -void *RecvHandlerLoop(void *arg) -{ - while (1) { - (void)pthread_mutex_lock(&g_recvQueue.lock); - if (IsListEmpty(&g_recvQueue.recvList)) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "RecvHandlerLoop empty"); - pthread_cond_wait(&g_recvQueue.cond, &g_recvQueue.lock); - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "Recv recvQueueCond"); - (void)pthread_mutex_unlock(&g_recvQueue.lock); - continue; - } - - ListNode *recvItemNode = NULL; - ReceiveItemStruct *recvItem = NULL; - LIST_FOR_EACH(recvItemNode, &g_recvQueue.recvList) { - recvItem = LIST_ENTRY(recvItemNode, ReceiveItemStruct, node); - ListDelete(recvItemNode); - break; - } - (void)pthread_mutex_unlock(&g_recvQueue.lock); - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "RecvHandlerLoop OnDataReceived"); - if (recvItem->module == MODULE_CONNECTION) { - cJSON *data = NULL; - data = cJSON_Parse((char *)(recvItem->data + sizeof(ConnPktHead))); - if (data == NULL) { - SoftBusFree(recvItem->data); - SoftBusFree(recvItem); - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[receive data invalid]"); - continue; - } - RecvConnectedComd(recvItem->connectionId, (const cJSON*)data); - cJSON_Delete(data); - } else { - if (g_connectCallback != NULL) { - g_connectCallback->OnDataReceived(recvItem->connectionId, (ConnModule)recvItem->module, recvItem->seqNum, - (char*)recvItem->data, recvItem->dataLen); - } - } - SoftBusFree(recvItem->data); - SoftBusFree(recvItem); - } -} - -static void ClearReceiveQueueByConnId(uint32_t connectionId) -{ - if (pthread_mutex_lock(&g_recvQueue.lock) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "ClearReceiveQueueByConnId mutex failed"); - return; - } - ListNode *recvItemNode = NULL; - ListNode *nextItem = NULL; - ReceiveItemStruct *recvItem = NULL; - LIST_FOR_EACH_SAFE(recvItemNode, nextItem, &g_recvQueue.recvList) { - recvItem = LIST_ENTRY(recvItemNode, ReceiveItemStruct, node); - if (recvItem->connectionId == connectionId) { - ListDelete(recvItemNode); - SoftBusFree(recvItem->data); - SoftBusFree(recvItem); - } - } - (void)pthread_mutex_unlock(&g_recvQueue.lock); -} - -static int32_t DisconnectDevice(uint32_t connectionId) -{ - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[DisconnectDevice]"); - if (pthread_mutex_lock(&g_connectionLock) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "DisconnectDevice mutex failed"); - return SOFTBUS_ERR; - } - ListNode *item = NULL; - ListNode *nextItem = NULL; - int getConnectionId = -1; - LIST_FOR_EACH_SAFE(item, nextItem, &g_conection_list) { - BrConnectionInfo *itemNode = LIST_ENTRY(item, BrConnectionInfo, node); - if (itemNode->connectionId == connectionId) { - getConnectionId = itemNode->connectionId; - break; - } - } - (void)pthread_mutex_unlock(&g_connectionLock); - if (getConnectionId == -1) { - return SOFTBUS_BRCONNECTION_DISCONNECT_NOTFIND; - } - (void)PackRequest(CONNECT_REF_DECRESE, getConnectionId); - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[DisconnectDevice over]"); - return SOFTBUS_OK; -} - -static int32_t DisconnectDeviceNow(const ConnectOption *option) -{ - int32_t ret = (int32_t)SOFTBUS_ERR; - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[DisconnectDeviceByOption]"); - if (option == NULL || option->type != CONNECT_BR) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "option check fail"); - return ret; - } - if (pthread_mutex_lock(&g_connectionLock) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "DisconnectDevice mutex failed"); - return ret; - } - ListNode *item = NULL; - ListNode *nextItem = NULL; - ConnectionInfo connectionInfo; - LIST_FOR_EACH_SAFE(item, nextItem, &g_conection_list) { - BrConnectionInfo *itemNode = LIST_ENTRY(item, BrConnectionInfo, node); - if (memcmp(itemNode->mac, option->info.brOption.brMac, sizeof(itemNode->mac)) == 0) { - if (!IsListEmpty(&g_dataQueue.sendList)) { - osDelay(DISCONN_DELAY_TIME); - } - ret = g_sppDriver->CloseClient(itemNode->socketFd); - } - } - (void)pthread_mutex_unlock(&g_connectionLock); - return ret; -} - -static void InitDataQueue(DataQueueStruct *dataQueue) -{ - ListInit(&dataQueue->sendList); - ListInit(&dataQueue->pidList); - pthread_mutex_init(&dataQueue->lock, NULL); - pthread_cond_init(&dataQueue->cond, NULL); + ListInit(&g_dataQueue.sendList); + ListInit(&g_dataQueue.pidList); + pthread_mutex_init(&g_dataQueue.lock, NULL); + pthread_cond_init(&g_dataQueue.cond, NULL); pthread_t tid; pthread_attr_t threadAttr; @@ -1524,40 +771,90 @@ static void InitDataQueue(DataQueueStruct *dataQueue) pthread_attr_setstacksize(&threadAttr, BR_SEND_THREAD_STACK); if (pthread_create(&tid, &threadAttr, SendHandlerLoop, NULL) != 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "create DeathProcTask failed"); + pthread_attr_destroy(&threadAttr); + return SOFTBUS_ERR; } + + pthread_attr_destroy(&threadAttr); + return SOFTBUS_OK; } -static void InitRecvQueue(RecvQueueStruct *recvQueue) +void *ConnBrAccept(void *arg) { - ListInit(&recvQueue->recvList); - pthread_mutex_init(&recvQueue->lock, NULL); - pthread_cond_init(&recvQueue->cond, NULL); - - pthread_t tid; - pthread_attr_t threadAttr; - pthread_attr_init(&threadAttr); - pthread_attr_setstacksize(&threadAttr, BR_RECE_THREAD_STACK); - if (pthread_create(&tid, &threadAttr, RecvHandlerLoop, NULL) != 0) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "create DeathProcTask failed"); +#define TRY_OPEN_SERVER_COUNT 5 + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ConnBrAccept start\n"); + int32_t serverId; + int32_t clientId; + char name[BR_SERVER_NAME_LEN] = {0}; + int32_t ret; + int32_t num = 0; + int32_t tryCount = 0; + while (tryCount < TRY_OPEN_SERVER_COUNT) { + if (g_sppDriver == NULL || !g_startListenFlag || g_brEnable != SOFTBUS_BT_STATE_TURN_ON) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "g_sppDriver failed EXIT!"); + break; + } + ret = sprintf_s(name, BR_SERVER_NAME_LEN, "SOFTBUS_BR_%d", num); + if (ret <= 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "ConnBrAccept sprintf_s failed %d", num); + sleep(1); + tryCount++; + continue; + } + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "OpenSppServer %s start", name); + serverId = g_sppDriver->OpenSppServer(name, strlen(name), UUID, 0); + if (serverId == SOFTBUS_ERR) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "OpenSppServer name %s failed", name); + sleep(1); + tryCount++; + continue; + } + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "OpenSppServer ok"); + clientId = g_sppDriver->Accept(serverId); + if (clientId != SOFTBUS_ERR && g_brEnable == SOFTBUS_BT_STATE_TURN_ON) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "Accept ok clientId: %d", clientId); + ConnBrOnEvent(ADD_CONN_BR_SERVICE_CONNECTED_MSG, clientId, clientId); + } else { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "spp Accept %s failed, clientId: %d", name, clientId); + } + g_sppDriver->CloseSppServer(serverId); + num++; + tryCount = 0; } + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "OpenSppServer failed EXIT!"); + return NULL; } static int32_t StartLocalListening(const LocalListenerInfo *info) { - if (g_sppDriver == NULL) { + if (g_sppDriver == NULL || info->type != CONNECT_BR) { return SOFTBUS_ERR; } - int32_t socketId = g_sppDriver->OpenSppServer(NULL, UUID, 0); - g_sppDriver->Accept(socketId, (const SppSocketEventCallback*)&g_sppSocketServiceCallback); + + if (g_startListenFlag) { + return SOFTBUS_OK; + } + + pthread_t tid; + pthread_attr_t threadAttr; + pthread_attr_init(&threadAttr); + pthread_attr_setstacksize(&threadAttr, BR_ACCECT_THREAD_STACK); + if (pthread_create(&tid, &threadAttr, ConnBrAccept, NULL) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "create ConnBrAccept failed"); + pthread_attr_destroy(&threadAttr); + return SOFTBUS_ERR; + } + g_startListenFlag = true; + pthread_attr_destroy(&threadAttr); return SOFTBUS_OK; } static int32_t StopLocalListening(const LocalListenerInfo *info) { - if (g_sppDriver == NULL) { + if (g_sppDriver == NULL || info->type != CONNECT_BR) { return SOFTBUS_ERR; } - g_sppDriver->CloseServer(0); + g_startListenFlag = false; return SOFTBUS_OK; } @@ -1567,19 +864,19 @@ static int32_t InitProperty() g_brSendPeerLen = INVALID_LENGTH; if (SoftbusGetConfig(SOFTBUS_INT_CONN_BR_MAX_DATA_LENGTH, (unsigned char*)&g_brBuffSize, sizeof(g_brBuffSize)) != SOFTBUS_OK) { - LOG_ERR("get br BuffSize fail"); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "get br BuffSize fail"); } - LOG_INFO("br BuffSize is %u", g_brBuffSize); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "br BuffSize is %u", g_brBuffSize); if (SoftbusGetConfig(SOFTBUS_INT_CONN_RFCOM_SEND_MAX_LEN, (unsigned char*)&g_brSendPeerLen, sizeof(g_brSendPeerLen)) != SOFTBUS_OK) { - LOG_ERR("get br SendPeerLen fail"); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "get br SendPeerLen fail"); } - LOG_INFO("br SendPeerLen is %u", g_brSendPeerLen); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "br SendPeerLen is %u", g_brSendPeerLen); if (SoftbusGetConfig(SOFTBUS_INT_CONN_BR_RECEIVE_MAX_LEN, (unsigned char*)&g_brSendQueueMaxLen, sizeof(g_brSendQueueMaxLen)) != SOFTBUS_OK) { - LOG_ERR("get br SendQueueMaxLen fail"); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "get br SendQueueMaxLen fail"); } - LOG_INFO("br SendQueueMaxLen is %u", g_brSendQueueMaxLen); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "br SendQueueMaxLen is %u", g_brSendQueueMaxLen); if (g_brBuffSize == INVALID_LENGTH || g_brBuffSize > MAX_BR_SIZE) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Cannot get brBuffSize"); return SOFTBUS_ERR; @@ -1595,48 +892,262 @@ static int32_t InitProperty() return SOFTBUS_OK; } +typedef struct BrReadThreadParams { + uint32_t connInfoId; + int32_t socketFd; +} BrReadThreadParams; + +void *ConnBrRead(void *arg) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "ConnBrRead start"); + if (arg == NULL) { + return NULL; + } + BrReadThreadParams *values = (BrReadThreadParams *)arg; + uint32_t connId = values->connInfoId; + int32_t socketFd = values->socketFd; + SoftBusFree(arg); + + if (socketFd == -1) { + socketFd = ClientOnBrConnect(connId); + if (socketFd == -1) { + return NULL; + } + } + while (1) { + char *outBuf = NULL; + int32_t packLen = BrTransReadOneFrame(connId, g_sppDriver, socketFd, &outBuf); + if (packLen == BR_READ_SOCKET_CLOSED) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[ConnBrRead] failed socket close"); + g_sppDriver->DisConnect(socketFd); + BrDisconnect(socketFd, socketFd); + return NULL; + } + if (packLen == BR_READ_FAILED) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[ConnBrRead] failed"); + continue; + } + if (outBuf == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[ConnBrRead] outBuf null"); + continue; + } + SoftBusMessage *msg = BrConnCreateLoopMsg(ADD_CONN_BR_RECV_MSG, (uint64_t)connId, (uint64_t)packLen, outBuf); + if (msg == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[ConnBrRead] BrConnCreateLoopMsg failed"); + SoftBusFree(outBuf); + continue; + } + g_brAsyncHandler.looper->PostMessage(g_brAsyncHandler.looper, msg); + } + return NULL; +} + +int32_t BrConnectedEventHandle(bool isClient, int32_t value) +{ + int32_t connInfoId; + int32_t socketFd = -1; + if (isClient) { + connInfoId = value; + } else { + socketFd = value; + connInfoId = ServerOnBrConnect(socketFd); + } + if (connInfoId == -1) { + return SOFTBUS_ERR; + } + pthread_t tid; + BrReadThreadParams *args = (BrReadThreadParams *)SoftBusCalloc(sizeof(BrReadThreadParams)); + if (args == NULL) { + goto EXIT; + } + args->connInfoId = connInfoId; + args->socketFd = socketFd; + if (pthread_create(&tid, NULL, ConnBrRead, (void *)args) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "create ConnBrRead failed"); + goto EXIT; + } + return SOFTBUS_OK; +EXIT: + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BrConnectedEventHandle EXIT"); + if (!isClient) { + ConnBrOnEvent(ADD_CONN_BR_SERVICE_DISCONNECTED_MSG, socketFd, socketFd); + } else { + ClientNoticeResultBrConnect(connInfoId, false, socketFd); + ReleaseConnectionRefByConnId(connInfoId); + } + return SOFTBUS_ERR; +} + +static void OnPackResponse(int32_t delta, int32_t peerRef, int32_t connectionId) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, + "[OnPackResponse: delta=%d, RemoteRef=%d, connectionIds=%u", delta, peerRef, connectionId); + BrConnectionInfo *connInfo = GetConnectionRef(connectionId); + if (connInfo == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[OnPackResponse] not find device"); + return; + } + connInfo->refCount += delta; + int32_t myRefCount = connInfo->refCount; + int32_t mySocketFd = connInfo->socketFd; + int32_t sideType = connInfo->sideType; + ReleaseConnectionRef(connInfo); + + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[onPackRequest: myRefCount=%d]", myRefCount); + if (peerRef > 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[remote device Ref is > 0, do not reply]"); + return; + } + if (myRefCount <= 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[local device Ref <= 0, close connection now]"); + SetBrConnStateByConnId(connectionId, BR_CONNECTION_STATE_CLOSING); + if (sideType == BR_SERVICE_TYPE) { + ConnBrOnEvent(ADD_CONN_BR_SERVICE_DISCONNECTED_MSG, mySocketFd, mySocketFd); + } else { + ConnBrOnEvent(ADD_CONN_BR_CLIENT_DISCONNECTED_MSG, mySocketFd, mySocketFd); + } + return; + } + int32_t outLen = -1; + char *buf = BrPackRequestOrResponse(METHOD_NOTIFY_RESPONSE, delta, myRefCount, &outLen); + if (buf == NULL) { + return; + } + (void)PostBytes(connectionId, buf, outLen, 0, 0); +} + +static void BrConnectedComdHandl(uint32_t connectionId, const cJSON *data) +{ + int32_t keyMethod = 0; + int32_t keyDelta = 0; + int32_t keyRefernceNum = 0; + + if (!GetJsonObjectNumberItem(data, KEY_METHOD, &keyMethod)) { + return; + } + if (keyMethod == METHOD_NOTIFY_REQUEST) { + if (!GetJsonObjectNumberItem(data, KEY_METHOD, &keyMethod) || + !GetJsonObjectSignedNumberItem(data, KEY_DELTA, &keyDelta) || + !GetJsonObjectSignedNumberItem(data, KEY_REFERENCE_NUM, &keyRefernceNum)) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "REQUEST fail"); + return; + } + OnPackResponse(keyDelta, keyRefernceNum, connectionId); + } + if (keyMethod == METHOD_NOTIFY_RESPONSE) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "NOTIFY_RESPONSE"); + if (!GetJsonObjectNumberItem(data, KEY_METHOD, &keyMethod) || + !GetJsonObjectSignedNumberItem(data, KEY_REFERENCE_NUM, &keyRefernceNum)) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "RESPONSE fail"); + return; + } + + SetBrConnStateByConnId(connectionId, BR_CONNECTION_STATE_CONNECTED); + } +} + +static void BrRecvDataHandle(uint32_t connectionId, const char *buf, int32_t len) +{ + ConnPktHead *head = (ConnPktHead *)buf; + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "BrRecvDataHandle module: %d", head->module); + if (head->module == MODULE_CONNECTION) { + cJSON *data = NULL; + data = cJSON_Parse((char *)(buf + sizeof(ConnPktHead))); + if (data == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "br recv data invalid"); + return; + } + BrConnectedComdHandl(connectionId, (const cJSON *)data); + cJSON_Delete(data); + } else { + if (g_connectCallback != NULL) { + g_connectCallback->OnDataReceived(connectionId, (ConnModule)head->module, head->seq, (char *)buf, len); + } + } +} + +static void BrConnMsgHandler(SoftBusMessage *msg) +{ + if (msg == NULL) { + return; + } + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "br conn loop process msg type %d", msg->what); + switch (msg->what) { + case ADD_CONN_BR_CLIENT_CONNECTED_MSG: + BrConnectedEventHandle(true, msg->arg1); + break; + case ADD_CONN_BR_SERVICE_CONNECTED_MSG: + BrConnectedEventHandle(false, msg->arg1); + break; + case ADD_CONN_BR_CLIENT_DISCONNECTED_MSG: + case ADD_CONN_BR_SERVICE_DISCONNECTED_MSG: + g_sppDriver->DisConnect(msg->arg1); + BrDisconnect(msg->arg1, msg->arg2); + break; + case ADD_CONN_BR_RECV_MSG: { + uint32_t connId = (uint32_t)msg->arg1; + int32_t len = (int32_t)msg->arg2; + BrRecvDataHandle(connId, (const char *)msg->obj, len); + SoftBusFree((void *)msg->obj); + break; + } + default: + break; + } +} + +static int32_t BrConnLooperInit(void) +{ + g_brAsyncHandler.looper = CreateNewLooper("brRecv_looper"); + if (g_brAsyncHandler.looper == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BrConnLooperInit failed"); + return SOFTBUS_ERR; + } + g_brAsyncHandler.HandleMessage = BrConnMsgHandler; + return SOFTBUS_OK; +} + +static void StateChangedCallback(int32_t listenerId, int32_t status) +{ + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "StateChanged id: %d, status: %d", listenerId, status); + g_brEnable = status; + LocalListenerInfo info; + info.type = CONNECT_BR; + if (status == SOFTBUS_BT_STATE_TURN_ON) { + (void)StartLocalListening(&info); + } else if (status == SOFTBUS_BT_STATE_TURN_OFF) { + (void)StopLocalListening(&info); + } +} + +static int32_t SppRegisterConnCallback(void) +{ + (void)memset_s(&g_sppBrCallback, sizeof(g_sppBrCallback), 0, sizeof(g_sppBrCallback)); + g_sppBrCallback.OnBtStateChanged = StateChangedCallback; + return SppGattsRegisterHalCallback(&g_sppBrCallback); +} + ConnectFuncInterface *ConnInitBr(const ConnectCallback *callback) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[InitBR]"); if (InitProperty() != SOFTBUS_OK) { return NULL; } - pthread_mutex_init(&g_connectionLock, NULL); - InitDataQueue(&g_dataQueue); - InitRecvQueue(&g_recvQueue); - g_connectCallback = (ConnectCallback*)callback; g_sppDriver = InitSppSocketDriver(); - if (g_sppDriver != NULL) { - g_sppDriver->Init(g_sppDriver); + if (g_sppDriver == NULL) { + return NULL; } + InitBrConnectionManager(g_brBuffSize); + if (InitDataQueue() != SOFTBUS_OK) { + return NULL; + } + if (BrConnLooperInit() != SOFTBUS_OK) { + return NULL; + } + if (SppRegisterConnCallback() != SOFTBUS_OK) { + return NULL; + } + pthread_mutex_init(&g_brConnLock, NULL); + g_connectCallback = (ConnectCallback*)callback; return &g_brInterface; } - -static bool GetJsonObjectNumberItem(const cJSON *json, const char * const string, int *target) -{ - cJSON *item = cJSON_GetObjectItemCaseSensitive(json, string); - if (item == NULL || !cJSON_IsNumber(item) || (item->valuedouble < 0)) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Cannot find or invalid [%s]", string); - return false; - } - *target = (int)item->valuedouble; - return true; -} - -static bool AddNumberToJsonObject(cJSON *obj, const char * const string, int32_t num) -{ - if (obj == NULL || string == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "AddNumberToJsonObject fail"); - return false; - } - cJSON *item = cJSON_CreateNumber(num); - if (item == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Cannot create cJSON number object [%s]", string); - return false; - } - if (!cJSON_AddItemToObject(obj, string, item)) { - cJSON_Delete(item); - return false; - } - return true; -} diff --git a/core/connection/br/src/br_connection_manager.c b/core/connection/br/src/br_connection_manager.c new file mode 100644 index 000000000..20c026a71 --- /dev/null +++ b/core/connection/br/src/br_connection_manager.c @@ -0,0 +1,502 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. + * Description: br connection mannager module. + * 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 "br_connection_manager.h" + +#include "common_list.h" +#include "message_handler.h" + +#ifdef __LITEOS_M__ +#include "ohos_types.h" +#endif + +#include "securec.h" +#include "softbus_adapter_mem.h" +#include "softbus_conn_manager.h" +#include "softbus_def.h" +#include "softbus_errcode.h" +#include "softbus_log.h" +#include "softbus_type_def.h" +#include "softbus_utils.h" +#include "stdbool.h" +#include "string.h" +#include "time.h" +#include "unistd.h" +#include "wrapper_br_interface.h" + +static pthread_mutex_t g_connectionLock; +static LIST_HEAD(g_conection_list); +static int32_t g_brBuffSize; +static int16_t g_nextConnectionId = 0; + +void InitBrConnectionManager(int32_t brBuffSize) +{ + g_brBuffSize = brBuffSize + sizeof(ConnPktHead); + pthread_mutex_init(&g_connectionLock, NULL); +} + +bool IsExitConnectionById(uint32_t connId) +{ + (void)pthread_mutex_lock(&g_connectionLock); + ListNode *item = NULL; + BrConnectionInfo *itemNode = NULL; + LIST_FOR_EACH(item, &g_conection_list) { + itemNode = LIST_ENTRY(item, BrConnectionInfo, node); + if (itemNode->connectionId != connId) { + continue; + } + (void)pthread_mutex_unlock(&g_connectionLock); + return true; + } + (void)pthread_mutex_unlock(&g_connectionLock); + return false; +} + +bool IsExitBrConnectByFd(int32_t socketFd) +{ + (void)pthread_mutex_lock(&g_connectionLock); + ListNode *item = NULL; + BrConnectionInfo *itemNode = NULL; + LIST_FOR_EACH(item, &g_conection_list) { + itemNode = LIST_ENTRY(item, BrConnectionInfo, node); + if (socketFd == itemNode->socketFd) { + (void)pthread_mutex_unlock(&g_connectionLock); + return true; + } + } + (void)pthread_mutex_unlock(&g_connectionLock); + return false; +} + +BrConnectionInfo *GetConnectionRef(uint32_t connId) +{ + if (pthread_mutex_lock(&g_connectionLock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[GetConnectionRef] mutex failed"); + return NULL; + } + ListNode *item = NULL; + BrConnectionInfo *itemNode = NULL; + LIST_FOR_EACH(item, &g_conection_list) { + itemNode = LIST_ENTRY(item, BrConnectionInfo, node); + if (itemNode->connectionId == connId) { + itemNode->infoObjRefCount++; + (void)pthread_mutex_unlock(&g_connectionLock); + return itemNode; + } + } + (void)pthread_mutex_unlock(&g_connectionLock); + return NULL; +} + +void ReleaseBrconnectionNode(BrConnectionInfo *conn) +{ + if (conn == NULL) { + return; + } + ListNode *item = NULL; + ListNode *nextItem = NULL; + RequestInfo *requestInfo = NULL; + LIST_FOR_EACH_SAFE(item, nextItem, &conn->requestList) { + requestInfo = LIST_ENTRY(item, RequestInfo, node); + ListDelete(&requestInfo->node); + SoftBusFree(requestInfo); + } + pthread_cond_destroy(&conn->congestCond); + pthread_mutex_destroy(&conn->lock); + SoftBusFree(conn->recvBuf); + SoftBusFree(conn); +} + +void ReleaseConnectionRef(BrConnectionInfo *connInfo) +{ + if (connInfo == NULL) { + return; + } + if (pthread_mutex_lock(&g_connectionLock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[ReleaseConnectionRef] lock mutex failed"); + return; + } + connInfo->infoObjRefCount--; + if (connInfo->infoObjRefCount <= 0) { + ListDelete(&connInfo->node); + ReleaseBrconnectionNode(connInfo); + } + (void)pthread_mutex_unlock(&g_connectionLock); +} + +void ReleaseConnectionRefByConnId(uint32_t connId) +{ + if (pthread_mutex_lock(&g_connectionLock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[ReleaseConnectionRef] lock mutex failed"); + return; + } + ListNode *item = NULL; + BrConnectionInfo *connInfo = NULL; + LIST_FOR_EACH(item, &g_conection_list) { + BrConnectionInfo *itemNode = LIST_ENTRY(item, BrConnectionInfo, node); + if (itemNode->connectionId == connId) { + connInfo = itemNode; + break; + } + } + if (connInfo != NULL) { + connInfo->infoObjRefCount--; + if (connInfo->infoObjRefCount <= 0) { + ListDelete(&connInfo->node); + ReleaseBrconnectionNode(connInfo); + } + } + (void)pthread_mutex_unlock(&g_connectionLock); +} + +static uint32_t AllocNewConnectionIdLocked(void) +{ + uint32_t tempId; + while (1) { + g_nextConnectionId++; + tempId = (CONNECT_BR << CONNECT_TYPE_SHIFT) + g_nextConnectionId; + if (!IsExitConnectionById(tempId)) { + break; + } + } + return tempId; +} + +BrConnectionInfo* CreateBrconnectionNode(bool clientFlag) +{ + BrConnectionInfo *newConnInfo = (BrConnectionInfo *)SoftBusCalloc(sizeof(BrConnectionInfo)); + if (newConnInfo == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[Create BrConnInfo malloc fail.]"); + return NULL; + } + newConnInfo->recvBuf = (char *)SoftBusCalloc(g_brBuffSize); + newConnInfo->recvSize = g_brBuffSize; + if (newConnInfo->recvBuf == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[Create BrConnInfo malloc recvBuf fail]"); + SoftBusFree(newConnInfo); + return NULL; + } + ListInit(&newConnInfo->node); + ListInit(&newConnInfo->requestList); + pthread_mutex_init(&newConnInfo->lock, NULL); + newConnInfo->connectionId = AllocNewConnectionIdLocked(); + newConnInfo->recvPos = 0; + newConnInfo->conGestState = BT_RFCOM_CONGEST_OFF; + pthread_cond_init(&newConnInfo->congestCond, NULL); + newConnInfo->refCount = 1; + newConnInfo->infoObjRefCount = 1; + newConnInfo->state = BR_CONNECTION_STATE_CONNECTING; + newConnInfo->sideType = clientFlag ? BR_CLIENT_TYPE : BR_SERVICE_TYPE; + return newConnInfo; +} + +int32_t GetConnectionInfo(uint32_t connectionId, ConnectionInfo *info) +{ + int32_t result = SOFTBUS_ERR; + if (pthread_mutex_lock(&g_connectionLock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); + return SOFTBUS_ERR; + } + ListNode *item = NULL; + LIST_FOR_EACH(item, &g_conection_list) { + BrConnectionInfo *itemNode = LIST_ENTRY(item, BrConnectionInfo, node); + if (itemNode->connectionId == connectionId) { + info->isAvailable = 1; + info->isServer = itemNode->sideType; + info->type = CONNECT_BR; + if (strcpy_s(info->info.brInfo.brMac, BT_MAC_LEN, itemNode->mac) != EOK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "GetConnInfo scpy error"); + (void)pthread_mutex_unlock(&g_connectionLock); + return SOFTBUS_BRCONNECTION_GETCONNINFO_ERROR; + } + result = SOFTBUS_OK; + break; + } + } + (void)pthread_mutex_unlock(&g_connectionLock); + return result; +} + +int32_t SetRefCountByConnId(int32_t delta, int32_t *refCount, uint32_t connectionId) +{ + int32_t state = BR_CONNECTION_STATE_CLOSED; + if (pthread_mutex_lock(&g_connectionLock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); + return state; + } + ListNode *item = NULL; + LIST_FOR_EACH(item, &g_conection_list) { + BrConnectionInfo *itemNode = LIST_ENTRY(item, BrConnectionInfo, node); + if (itemNode->connectionId == connectionId) { + itemNode->refCount += delta; + (*refCount) = itemNode->refCount; + state = itemNode->state; + break; + } + } + (void)pthread_mutex_unlock(&g_connectionLock); + return state; +} + +static void FreeCongestEvent(BrConnectionInfo *itemNode) +{ + itemNode->conGestState = BT_RFCOM_CONGEST_OFF; + if (pthread_mutex_lock(&itemNode->lock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[FreeCongestEvent] mutex failed"); + return; + } + pthread_cond_broadcast(&itemNode->congestCond); + (void)pthread_mutex_unlock(&itemNode->lock); +} + +void SetBrConnStateByConnId(uint32_t connId, int32_t state) +{ + if (pthread_mutex_lock(&g_connectionLock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SetBrConnStateByConnId lock mutex failed"); + return; + } + ListNode *britem = NULL; + BrConnectionInfo *itemNode = NULL; + LIST_FOR_EACH(britem, &g_conection_list) { + itemNode = LIST_ENTRY(britem, BrConnectionInfo, node); + if (itemNode->connectionId == connId) { + itemNode->state = state; + if (state == BR_CONNECTION_STATE_CLOSED) { + FreeCongestEvent(itemNode); + } + break; + } + } + (void)pthread_mutex_unlock(&g_connectionLock); +} + +uint32_t SetBrConnStateBySocket(int32_t socket, int32_t state, int32_t *perState) +{ + uint32_t connId = 0; + if (pthread_mutex_lock(&g_connectionLock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "SetBrConnStateByConnId lock mutex failed"); + return connId; + } + ListNode *britem = NULL; + BrConnectionInfo *itemNode = NULL; + LIST_FOR_EACH(britem, &g_conection_list) { + itemNode = LIST_ENTRY(britem, BrConnectionInfo, node); + if (itemNode->socketFd == socket) { + if (perState != NULL) { + (*perState) = itemNode->state; + } + itemNode->state = state; + if (state == BR_CONNECTION_STATE_CLOSED) { + FreeCongestEvent(itemNode); + } + connId = itemNode->connectionId; + break; + } + } + (void)pthread_mutex_unlock(&g_connectionLock); + return connId; +} + +int32_t AddRequestByConnId(uint32_t connId, RequestInfo *requestInfo) +{ + if (pthread_mutex_lock(&g_connectionLock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); + return SOFTBUS_ERR; + } + ListNode *item = NULL; + LIST_FOR_EACH(item, &g_conection_list) { + BrConnectionInfo *itemNode = LIST_ENTRY(item, BrConnectionInfo, node); + if (itemNode->connectionId == connId) { + ListAdd(&itemNode->requestList, &requestInfo->node); + break; + } + } + (void)pthread_mutex_unlock(&g_connectionLock); + return SOFTBUS_OK; +} + +int32_t AddConnectionList(BrConnectionInfo *newConnInfo) +{ + if (pthread_mutex_lock(&g_connectionLock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); + return SOFTBUS_ERR; + } + ListAdd(&g_conection_list, &newConnInfo->node); + (void)pthread_mutex_unlock(&g_connectionLock); + return SOFTBUS_OK; +} + +void RfcomCongestEvent(int32_t socketFd, int32_t value) +{ + if (pthread_mutex_lock(&g_connectionLock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[RfcomCongestEvent] lock mutex failed"); + return; + } + ListNode *item = NULL; + BrConnectionInfo *itemNode = NULL; + LIST_FOR_EACH(item, &g_conection_list) { + itemNode = LIST_ENTRY(item, BrConnectionInfo, node); + if (itemNode->socketFd == socketFd) { + itemNode->conGestState = value; + if (value == BT_RFCOM_CONGEST_OFF) { + if (pthread_mutex_lock(&itemNode->lock) != 0) { + (void)pthread_mutex_unlock(&g_connectionLock); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "CongestEvent lock itemNode failed"); + return; + } + pthread_cond_broadcast(&itemNode->congestCond); + (void)pthread_mutex_unlock(&itemNode->lock); + } + break; + } + } + (void)pthread_mutex_unlock(&g_connectionLock); +} + +static int32_t InitConnectionInfo(ConnectionInfo *connectionInfo, const BrConnectionInfo *itemNode) +{ + (*connectionInfo).isAvailable = 0; + (*connectionInfo).isServer = itemNode->sideType; + (*connectionInfo).type = CONNECT_BR; + if (strcpy_s((*connectionInfo).info.brInfo.brMac, BT_MAC_LEN, itemNode->mac) != EOK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "InitConnInfo scpy error"); + return SOFTBUS_BRCONNECTION_STRNCPY_ERROR; + } + return SOFTBUS_OK; +} + +int32_t GetBrRequestListByConnId(uint32_t connId, ListNode *notifyList, + ConnectionInfo *connectionInfo, int32_t *sideType) +{ + int32_t packRequestFlag = 0; + if (pthread_mutex_lock(&g_connectionLock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BrClient lock mutex failed"); + return packRequestFlag; + } + ListNode *britem = NULL; + ListNode *item = NULL; + ListNode *itemNext = NULL; + RequestInfo *requestInfo = NULL; + LIST_FOR_EACH(britem, &g_conection_list) { + BrConnectionInfo *itemNode = LIST_ENTRY(britem, BrConnectionInfo, node); + if (itemNode->connectionId == connId) { + (void)InitConnectionInfo(connectionInfo, itemNode); + (*sideType) = itemNode->sideType; + LIST_FOR_EACH_SAFE(item, itemNext, &itemNode->requestList) { + requestInfo = LIST_ENTRY(item, RequestInfo, node); + ListDelete(&requestInfo->node); + ListAdd(notifyList, &requestInfo->node); + packRequestFlag++; + } + break; + } + } + (void)pthread_mutex_unlock(&g_connectionLock); + return packRequestFlag; +} + +bool HasDiffMacDeviceExit(const ConnectOption *option) +{ + if (pthread_mutex_lock(&g_connectionLock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); + return true; + } + if (IsListEmpty(&g_conection_list)) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[g_conection_list is empty, allow to connect device.]"); + (void)pthread_mutex_unlock(&g_connectionLock); + return false; + } + ListNode *item = NULL; + bool res = false; + LIST_FOR_EACH(item, &g_conection_list) { + BrConnectionInfo *itemNode = LIST_ENTRY(item, BrConnectionInfo, node); + if (itemNode->sideType == BR_CLIENT_TYPE) { + if (memcmp(itemNode->mac, option->info.brOption.brMac, sizeof(itemNode->mac)) != 0) { + res = true; + break; + } + } + } + (void)pthread_mutex_unlock(&g_connectionLock); + return res; +} + +int32_t GetBrConnStateByConnOption(const ConnectOption *option, int32_t *outCountId) +{ + if (pthread_mutex_lock(&g_connectionLock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "lock mutex failed"); + return BR_CONNECTION_STATE_CLOSED; + } + ListNode *item = NULL; + LIST_FOR_EACH(item, &g_conection_list) { + BrConnectionInfo *itemNode = LIST_ENTRY(item, BrConnectionInfo, node); + if (strncmp(itemNode->mac, option->info.brOption.brMac, BT_MAC_LEN) == 0) { + if (outCountId != NULL) { + *outCountId = itemNode->connectionId; + } + (void)pthread_mutex_unlock(&g_connectionLock); + return itemNode->state; + } + } + (void)pthread_mutex_unlock(&g_connectionLock); + return BR_CONNECTION_STATE_CLOSED; +} + +bool IsBrDeviceReady(uint32_t connId) +{ + (void)pthread_mutex_lock(&g_connectionLock); + ListNode *item = NULL; + BrConnectionInfo *itemNode = NULL; + LIST_FOR_EACH(item, &g_conection_list) { + itemNode = LIST_ENTRY(item, BrConnectionInfo, node); + if (itemNode->connectionId != connId) { + continue; + } + if (itemNode->state != BR_CONNECTION_STATE_CONNECTED) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "br state not connected, state: %d", itemNode->state); + (void)pthread_mutex_unlock(&g_connectionLock); + return false; + } + (void)pthread_mutex_unlock(&g_connectionLock); + return true; + } + (void)pthread_mutex_unlock(&g_connectionLock); + return false; +} + +int32_t BrClosingByConnOption(const ConnectOption *option, int32_t *socketFd, int32_t *sideType) +{ + if (pthread_mutex_lock(&g_connectionLock) != 0) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "mutex failed"); + return SOFTBUS_ERR; + } + + ListNode *item = NULL; + BrConnectionInfo *itemNode = NULL; + LIST_FOR_EACH(item, &g_conection_list) { + itemNode = LIST_ENTRY(item, BrConnectionInfo, node); + if (memcmp(itemNode->mac, option->info.brOption.brMac, sizeof(itemNode->mac)) == 0) { + *socketFd = itemNode->socketFd; + *sideType = itemNode->sideType; + itemNode->state = BR_CONNECTION_STATE_CLOSING; + break; + } + } + (void)pthread_mutex_unlock(&g_connectionLock); + return SOFTBUS_OK; +} diff --git a/core/connection/br/src/br_trans_manager.c b/core/connection/br/src/br_trans_manager.c new file mode 100644 index 000000000..b7560f663 --- /dev/null +++ b/core/connection/br/src/br_trans_manager.c @@ -0,0 +1,212 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. + * Description: br transmission management module. + * 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 "br_trans_manager.h" + +#include + +#include "securec.h" +#include "softbus_adapter_mem.h" +#include "softbus_conn_interface.h" +#include "softbus_conn_manager.h" +#include "softbus_def.h" +#include "softbus_errcode.h" +#include "softbus_json_utils.h" +#include "softbus_log.h" + +static int32_t ReceivedHeadCheck(BrConnectionInfo *conn) +{ + int32_t pktHeadLen = sizeof(ConnPktHead); + if (conn->recvPos < pktHeadLen) { + return SOFTBUS_ERR; + } + ConnPktHead *head = (ConnPktHead *)(conn->recvBuf); + if ((uint32_t)(head->magic) != MAGIC_NUMBER) { + conn->recvPos = 0; + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[ReceivedHeadCheck] magic error 0x%x", head->magic); + return SOFTBUS_ERR; + } + + if (head->len + pktHeadLen > conn->recvSize) { + conn->recvPos = 0; + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, + "[ReceivedHeadCheck]data too large. module=%d, seq=%lld, datalen=%d", head->module, head->seq, head->len); + return SOFTBUS_ERR; + } + return SOFTBUS_OK; +} + +int32_t BrTransReadOneFrame(uint32_t connectionId, const SppSocketDriver *sppDriver, int32_t clientId, char **outBuf) +{ + BrConnectionInfo *conn = GetConnectionRef(connectionId); + if (conn == NULL) { + return BR_READ_FAILED; + } + int32_t recvLen; + int32_t bufLen; + while (1) { + if (conn->recvSize - conn->recvPos > 0) { + recvLen = sppDriver->Read(clientId, conn->recvBuf + conn->recvPos, conn->recvSize - conn->recvPos); + if (recvLen == BR_READ_SOCKET_CLOSED) { + ReleaseConnectionRef(conn); + return BR_READ_SOCKET_CLOSED; + } + if (recvLen == BR_READ_FAILED) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "sppDriver Read BR_READ_FAILED"); + continue; + } + conn->recvPos += recvLen; + } + if (ReceivedHeadCheck(conn) != SOFTBUS_OK) { + continue; + } + bufLen = conn->recvPos; + ConnPktHead *head = (ConnPktHead *)(conn->recvBuf); + int32_t packLen = head->len + sizeof(ConnPktHead); + if (bufLen < packLen) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "not a complete package, continue"); + continue; + } + + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "[BrTransRead] a complete package packLen: %d", packLen); + char *dataCopy = SoftBusMalloc(packLen); + if (dataCopy == NULL || memcpy_s(dataCopy, packLen, conn->recvBuf, packLen) != EOK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[BrTransRead] memcpy_s failed"); + SoftBusFree(dataCopy); + continue; + } + + if (bufLen > packLen && + memmove_s(conn->recvBuf, conn->recvSize, conn->recvBuf + packLen, bufLen - packLen) != EOK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[BrTransRead] memmove_s failed"); + SoftBusFree(dataCopy); + continue; + } + conn->recvPos = bufLen - packLen; + *outBuf = dataCopy; + ReleaseConnectionRef(conn); + return packLen; + } +} + +int32_t BrTransSend(int32_t connId, const SppSocketDriver *sppDriver, + int32_t brSendPeerLen, const char *data, uint32_t len) +{ + BrConnectionInfo *brConnInfo = GetConnectionRef(connId); + if (brConnInfo == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "[BrTransSend] connId: %d, not fount failed", connId); + return SOFTBUS_ERR; + } + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "BrTransSend"); + int32_t socketFd = brConnInfo->socketFd; + if (socketFd == -1) { + ReleaseConnectionRef(brConnInfo); + return SOFTBUS_ERR; + } + int32_t ret = SOFTBUS_OK; + int32_t writeRet; + int32_t tempLen = len; + while (tempLen > 0) { + (void)pthread_mutex_lock(&brConnInfo->lock); + while (brConnInfo->conGestState == BT_RFCOM_CONGEST_ON && + brConnInfo->state == BR_CONNECTION_STATE_CONNECTED) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "wait congest"); + pthread_cond_wait(&brConnInfo->congestCond, &brConnInfo->lock); + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "free congest"); + break; + } + (void)pthread_mutex_unlock(&brConnInfo->lock); + + int32_t sendLenth = tempLen; + if (sendLenth > brSendPeerLen) { + sendLenth = brSendPeerLen; + } + writeRet = sppDriver->Write(socketFd, data, sendLenth); + if (writeRet == -1) { + ret = SOFTBUS_ERR; + break; + } + data += sendLenth; + tempLen -= sendLenth; + } + ReleaseConnectionRef(brConnInfo); + return ret; +} + +static char *BrAddNumToJson(int32_t requestOrResponse, int32_t delta, int32_t count) +{ + cJSON *json = cJSON_CreateObject(); + if (json == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Cannot create cJSON object"); + return NULL; + } + if (requestOrResponse == METHOD_NOTIFY_REQUEST) { + if (!AddNumberToJsonObject(json, KEY_METHOD, METHOD_NOTIFY_REQUEST) || + !AddNumberToJsonObject(json, KEY_DELTA, delta) || + !AddNumberToJsonObject(json, KEY_REFERENCE_NUM, count)) { + cJSON_Delete(json); + return NULL; + } + } else { + if (!AddNumberToJsonObject(json, KEY_METHOD, METHOD_NOTIFY_RESPONSE) || + !AddNumberToJsonObject(json, KEY_REFERENCE_NUM, count)) { + cJSON_Delete(json); + return NULL; + } + } + char *data = cJSON_PrintUnformatted(json); + cJSON_Delete(json); + return data; +} + +char *BrPackRequestOrResponse(int32_t requestOrResponse, int32_t delta, int32_t count, int32_t *outLen) +{ + char *data = BrAddNumToJson(requestOrResponse, delta, count); + if (data == NULL) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "BrAddNumToJson failed"); + return NULL; + } + + int32_t headSize = sizeof(ConnPktHead); + int32_t dataLen = strlen(data) + 1 + headSize; + char *buf = (char *)SoftBusCalloc(dataLen); + if (buf == NULL) { + cJSON_free(data); + return NULL; + } + ConnPktHead head; + head.magic = MAGIC_NUMBER; + head.module = MODULE_CONNECTION; + head.seq = 1; + head.flag = 0; + head.len = strlen(data) + 1; + + if (memcpy_s(buf, dataLen, (void *)&head, headSize)) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "memcpy_s head error"); + cJSON_free(data); + SoftBusFree(buf); + return NULL; + } + if (memcpy_s(buf + headSize, dataLen - headSize, data, strlen(data) + 1)) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "memcpy_s data error"); + cJSON_free(data); + SoftBusFree(buf); + return NULL; + } + *outLen = dataLen; + cJSON_free(data); + return buf; +} diff --git a/core/connection/interface/softbus_base_listener.h b/core/connection/interface/softbus_base_listener.h index e1cf7b866..3dcf4d0b9 100644 --- a/core/connection/interface/softbus_base_listener.h +++ b/core/connection/interface/softbus_base_listener.h @@ -45,6 +45,7 @@ typedef enum { typedef enum { PROXY = 0, AUTH, + AUTH_P2P, DIRECT_CHANNEL_CLIENT, DIRECT_CHANNEL_SERVER, UNUSE_BUTT, diff --git a/core/connection/interface/softbus_conn_interface.h b/core/connection/interface/softbus_conn_interface.h index 629785eae..b90e713e1 100644 --- a/core/connection/interface/softbus_conn_interface.h +++ b/core/connection/interface/softbus_conn_interface.h @@ -40,6 +40,7 @@ typedef enum { MODULE_PROXY_CHANNEL = 13, MODULE_DEVICE_AUTH = 14, MODULE_P2P_LINK = 15, + MODULE_P2P_LISTEN = 16, MODULE_UDP_INFO = 17, MODULE_TIME_SYNC = 18, MODULE_PKG_VERIFY = 20, @@ -70,6 +71,7 @@ typedef struct { char ip[IP_LEN]; int32_t port; int32_t fd; + int32_t moduleId; /* For details, see {@link ListenerModule}. */ } ipInfo; } info; } ConnectionInfo; @@ -124,6 +126,7 @@ typedef struct { struct IpListenerInfo { char ip[IP_LEN]; int32_t port; + int32_t moduleId; /* For details, see {@link ListenerModule}. */ } ipListenerInfo; } info; } LocalListenerInfo; diff --git a/core/connection/tcp/src/softbus_tcp_connect_manager.c b/core/connection/tcp/src/softbus_tcp_connect_manager.c index fac6d25e8..f2d608e6b 100644 --- a/core/connection/tcp/src/softbus_tcp_connect_manager.c +++ b/core/connection/tcp/src/softbus_tcp_connect_manager.c @@ -33,13 +33,16 @@ #include "softbus_type_def.h" #include "softbus_utils.h" - #define INVALID_DATA (-1) static int32_t g_tcpMaxConnNum; static int32_t g_tcpTimeOut; static int32_t g_tcpMaxLen; -static char g_localIp[IP_LEN]; + +typedef struct { + ListenerModule moduleId; + SoftbusBaseListener listener; +} TcpListenerItem; typedef struct TcpConnInfoNode { ListNode node; @@ -48,13 +51,12 @@ typedef struct TcpConnInfoNode { } TcpConnInfoNode; static SoftBusList *g_tcpConnInfoList = NULL; -static SoftbusBaseListener *g_tcpListener = NULL; static const ConnectCallback *g_tcpConnCallback; static int32_t AddTcpConnInfo(TcpConnInfoNode *item); -static int32_t DelTcpConnInfo(uint32_t connectionId, ConnectionInfo *info); -static void DelAllConnInfo(void); -static int32_t TcpOnConnectEvent(int32_t events, int32_t cfd, const char *ip); +static int32_t DelTcpConnInfo(uint32_t connectionId); +static void DelAllConnInfo(ListenerModule moduleId); +static int32_t TcpOnConnectEvent(ListenerModule module, int32_t events, int32_t cfd, const char *ip); static int32_t TcpOnDataEvent(int32_t events, int32_t fd); int32_t TcpGetConnNum(void) @@ -95,7 +97,7 @@ int32_t AddTcpConnInfo(TcpConnInfoNode *item) return SOFTBUS_OK; } -int32_t DelTcpConnInfo(uint32_t connectionId, ConnectionInfo *info) +static int32_t DelTcpConnInfo(uint32_t connectionId) { if (g_tcpConnInfoList == NULL) { return SOFTBUS_ERR; @@ -107,19 +109,13 @@ int32_t DelTcpConnInfo(uint32_t connectionId, ConnectionInfo *info) } LIST_FOR_EACH_ENTRY(item, &g_tcpConnInfoList->list, TcpConnInfoNode, node) { if (item->connectionId == connectionId) { - if (info != NULL) { - if (memcpy_s((void *)info, sizeof(ConnectionInfo), (void *)&item->info, - sizeof(ConnectionInfo)) != EOK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "memcpy_s failed."); - (void)SoftBusMutexUnlock(&g_tcpConnInfoList->lock); - return SOFTBUS_MEM_ERR; - } - } + (void)DelTrigger(item->info.info.ipInfo.moduleId, item->info.info.ipInfo.fd, RW_TRIGGER); TcpShutDown(item->info.info.ipInfo.fd); ListDelete(&item->node); - SoftBusFree(item); g_tcpConnInfoList->cnt--; (void)SoftBusMutexUnlock(&g_tcpConnInfoList->lock); + g_tcpConnCallback->OnDisconnected(connectionId, &item->info); + SoftBusFree(item); return SOFTBUS_OK; } } @@ -129,13 +125,13 @@ int32_t DelTcpConnInfo(uint32_t connectionId, ConnectionInfo *info) return SOFTBUS_OK; } -int32_t TcpOnConnectEvent(int32_t events, int32_t cfd, const char *ip) +static int32_t TcpOnConnectEvent(ListenerModule module, int32_t events, int32_t cfd, const char *ip) { if (events == SOFTBUS_SOCKET_EXCEPTION) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Exception occurred"); return SOFTBUS_ERR; } - if (cfd < 0 || ip == NULL || g_tcpListener == NULL) { + if (cfd < 0 || ip == NULL) { return SOFTBUS_INVALID_PARAM; } TcpConnInfoNode *tcpConnInfoNode = (TcpConnInfoNode *)SoftBusCalloc(sizeof(TcpConnInfoNode)); @@ -153,7 +149,8 @@ int32_t TcpOnConnectEvent(int32_t events, int32_t cfd, const char *ip) } tcpConnInfoNode->info.info.ipInfo.port = GetTcpSockPort(cfd); tcpConnInfoNode->info.info.ipInfo.fd = cfd; - if (AddTrigger(PROXY, cfd, READ_TRIGGER) != SOFTBUS_OK) { + tcpConnInfoNode->info.info.ipInfo.moduleId = module; + if (AddTrigger(module, cfd, READ_TRIGGER) != SOFTBUS_OK) { goto EXIT; } if (AddTcpConnInfo(tcpConnInfoNode) != SOFTBUS_OK) { @@ -164,7 +161,7 @@ int32_t TcpOnConnectEvent(int32_t events, int32_t cfd, const char *ip) EXIT: SoftBusFree(tcpConnInfoNode); - (void)DelTrigger(PROXY, cfd, READ_TRIGGER); + (void)DelTrigger(module, cfd, READ_TRIGGER); TcpShutDown(cfd); return SOFTBUS_ERR; } @@ -203,7 +200,7 @@ EXIT: int32_t TcpOnDataEvent(int32_t events, int32_t fd) { - if (g_tcpListener == NULL || events != SOFTBUS_SOCKET_IN) { + if (events != SOFTBUS_SOCKET_IN) { return SOFTBUS_ERR; } uint32_t connectionId = CalTcpConnectionId(fd); @@ -212,12 +209,7 @@ int32_t TcpOnDataEvent(int32_t events, int32_t fd) ssize_t bytes = RecvTcpData(fd, (char *)&head, headSize, g_tcpTimeOut); if (bytes <= 0) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "TcpOnDataEvent Disconnect fd:%d", fd); - (void)DelTrigger(PROXY, fd, RW_TRIGGER); - ConnectionInfo *info = SoftBusCalloc(sizeof(ConnectionInfo)); - if (DelTcpConnInfo(connectionId, info) == SOFTBUS_OK) { - g_tcpConnCallback->OnDisconnected(connectionId, info); - } - SoftBusFree(info); + (void)DelTcpConnInfo(connectionId); return SOFTBUS_OK; } else if (bytes != (ssize_t)headSize) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Recv Head failed."); @@ -225,8 +217,7 @@ int32_t TcpOnDataEvent(int32_t events, int32_t fd) } char *data = RecvData(&head, fd, head.len); if (data == NULL) { - (void)DelTrigger(PROXY, fd, RW_TRIGGER); - DelTcpConnInfo(connectionId, NULL); + (void)DelTcpConnInfo(connectionId); return SOFTBUS_ERR; } g_tcpConnCallback->OnDataReceived(connectionId, head.module, head.seq, data, headSize + head.len); @@ -234,7 +225,7 @@ int32_t TcpOnDataEvent(int32_t events, int32_t fd) return SOFTBUS_OK; } -static void DelAllConnInfo(void) +static void DelAllConnInfo(ListenerModule moduleId) { if (g_tcpConnInfoList == NULL) { return; @@ -244,20 +235,21 @@ static void DelAllConnInfo(void) return; } TcpConnInfoNode *item = NULL; - LIST_FOR_EACH_ENTRY(item, &g_tcpConnInfoList->list, TcpConnInfoNode, node) { - (void)DelTrigger(PROXY, item->info.info.ipInfo.fd, RW_TRIGGER); - } - while (1) { - if (IsListEmpty(&g_tcpConnInfoList->list)) { - break; + TcpConnInfoNode *next = NULL; + LIST_FOR_EACH_ENTRY_SAFE(item, next, &g_tcpConnInfoList->list, TcpConnInfoNode, node) { + if (item->info.info.ipInfo.moduleId == (int32_t)moduleId) { + (void)DelTrigger(moduleId, item->info.info.ipInfo.fd, RW_TRIGGER); + ListDelete(&item->node); + TcpShutDown(item->info.info.ipInfo.fd); + g_tcpConnCallback->OnDisconnected(item->connectionId, &item->info); + SoftBusFree(item); + g_tcpConnInfoList->cnt--; } - item = LIST_ENTRY((&g_tcpConnInfoList->list)->next, TcpConnInfoNode, node); - ListDelete(&item->node); - TcpShutDown(item->info.info.ipInfo.fd); - SoftBusFree(item); - g_tcpConnInfoList->cnt--; } - ListInit(&g_tcpConnInfoList->list); + if (g_tcpConnInfoList->cnt == 0) { + ListInit(&g_tcpConnInfoList->list); + } + SoftBusMutexUnlock(&g_tcpConnInfoList->lock); } @@ -268,6 +260,7 @@ uint32_t CalTcpConnectionId(int32_t fd) return connectionId; } +/* Note: all tcp clients use PROXY as default listener. */ int32_t TcpConnectDevice(const ConnectOption *option, uint32_t requestId, const ConnectResult *result) { if (result == NULL || @@ -307,6 +300,7 @@ int32_t TcpConnectDevice(const ConnectOption *option, uint32_t requestId, const tcpConnInfoNode->info.type = CONNECT_TCP; tcpConnInfoNode->info.info.ipInfo.port = option->info.ipOption.port; tcpConnInfoNode->info.info.ipInfo.fd = fd; + tcpConnInfoNode->info.info.ipInfo.moduleId = PROXY; if (strcpy_s(tcpConnInfoNode->info.info.ipInfo.ip, IP_LEN, option->info.ipOption.ip) != EOK || AddTcpConnInfo(tcpConnInfoNode) != SOFTBUS_OK) { (void)DelTrigger(PROXY, fd, READ_TRIGGER); @@ -325,8 +319,7 @@ int32_t TcpDisconnectDevice(uint32_t connectionId) if (TcpGetConnectionInfo(connectionId, &info) != SOFTBUS_OK || !info.isAvailable) { return SOFTBUS_ERR; } - (void)DelTrigger(PROXY, info.info.ipInfo.fd, RW_TRIGGER); - return DelTcpConnInfo(connectionId, NULL); + return DelTcpConnInfo(connectionId); } int32_t TcpDisconnectDeviceNow(const ConnectOption *option) @@ -339,20 +332,15 @@ int32_t TcpDisconnectDeviceNow(const ConnectOption *option) return SOFTBUS_LOCK_ERR; } TcpConnInfoNode *item = NULL; - TcpConnInfoNode *itemPrev = NULL; - LIST_FOR_EACH_ENTRY(item, &g_tcpConnInfoList->list, TcpConnInfoNode, node) { - if (strcmp(option->info.ipOption.ip, item->info.info.ipInfo.ip) == 0) { - (void)DelTrigger(PROXY, item->info.info.ipInfo.fd, RW_TRIGGER); - } - } - LIST_FOR_EACH_ENTRY(item, &g_tcpConnInfoList->list, TcpConnInfoNode, node) { - itemPrev = (TcpConnInfoNode *)LIST_ENTRY(item, TcpConnInfoNode, node)->node.prev; + TcpConnInfoNode *next = NULL; + LIST_FOR_EACH_ENTRY_SAFE(item, next, &g_tcpConnInfoList->list, TcpConnInfoNode, node) { if (strcmp(option->info.ipOption.ip, item->info.info.ipInfo.ip) == 0) { + (void)DelTrigger(item->info.info.ipInfo.moduleId, item->info.info.ipInfo.fd, RW_TRIGGER); TcpShutDown(item->info.info.ipInfo.fd); ListDelete(&item->node); - SoftBusFree(item); g_tcpConnInfoList->cnt--; - item = itemPrev; + g_tcpConnCallback->OnDisconnected(item->connectionId, &item->info); + SoftBusFree(item); } } if (g_tcpConnInfoList->cnt == 0) { @@ -430,46 +418,80 @@ int32_t TcpGetConnectionInfo(uint32_t connectionId, ConnectionInfo *info) return SOFTBUS_ERR; } +static int32_t OnProxyServerConnectEvent(int32_t events, int32_t cfd, const char *ip) +{ + return TcpOnConnectEvent(PROXY, events, cfd, ip); +} + +static int32_t OnAuthP2pServerConnectEvent(int32_t events, int32_t cfd, const char *ip) +{ + return TcpOnConnectEvent(AUTH_P2P, events, cfd, ip); +} + +static TcpListenerItem g_tcpListenerItems[] = { + { + .moduleId = PROXY, + .listener = { + .onConnectEvent = OnProxyServerConnectEvent, + .onDataEvent = TcpOnDataEvent + } + }, + { + .moduleId = AUTH_P2P, + .listener = { + .onConnectEvent = OnAuthP2pServerConnectEvent, + .onDataEvent = TcpOnDataEvent + } + }, + /* Note: if add new tcp server, expend it here according to the above codes. */ +}; + +static SoftbusBaseListener *GetTcpListener(ListenerModule moduleId) +{ + for (uint32_t i = 0; i < sizeof(g_tcpListenerItems) / sizeof(TcpListenerItem); i++) { + if (g_tcpListenerItems[i].moduleId == moduleId) { + return &(g_tcpListenerItems[i].listener); + } + } + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "unsupport ListenerModule, id = %d.", moduleId); + return NULL; +} + int32_t TcpStartListening(const LocalListenerInfo *info) { if (info == NULL || info->type != CONNECT_TCP) { return SOFTBUS_INVALID_PARAM; } - if (g_tcpListener == NULL) { - g_tcpListener = (SoftbusBaseListener *)SoftBusCalloc(sizeof(SoftbusBaseListener)); - if (g_tcpListener == NULL) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "malloc tcp listener failed"); - return SOFTBUS_MALLOC_ERR; - } - g_tcpListener->onConnectEvent = TcpOnConnectEvent; - g_tcpListener->onDataEvent = TcpOnDataEvent; + ListenerModule moduleId = info->info.ipListenerInfo.moduleId; + SoftbusBaseListener *listener = GetTcpListener(moduleId); + if (listener == NULL) { + return SOFTBUS_INVALID_PARAM; } - int32_t rc = SetSoftbusBaseListener(PROXY, g_tcpListener); + int32_t rc = SetSoftbusBaseListener(moduleId, listener); if (rc != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Set BaseListener Failed."); return rc; } - if (strcpy_s(g_localIp, IP_LEN, info->info.ipListenerInfo.ip) != EOK) { - SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "Get local ip addr failed."); - return SOFTBUS_MEM_ERR; - } - - rc = StartBaseListener(PROXY, g_localIp, info->info.ipListenerInfo.port, SERVER_MODE); - return rc; + return StartBaseListener(moduleId, info->info.ipListenerInfo.ip, info->info.ipListenerInfo.port, SERVER_MODE); } int32_t TcpStopListening(const LocalListenerInfo *info) { - if (info == NULL || g_tcpListener == NULL) { + if (info == NULL) { return SOFTBUS_INVALID_PARAM; } - int32_t ret = StopBaseListener(PROXY); + + ListenerModule moduleId = info->info.ipListenerInfo.moduleId; + if (GetTcpListener(moduleId) == NULL) { + return SOFTBUS_INVALID_PARAM; + } + + int32_t ret = StopBaseListener(moduleId); if (ret != SOFTBUS_OK) { return ret; } - DelAllConnInfo(); - DestroyBaseListener(PROXY); - g_tcpListener = NULL; + DelAllConnInfo(moduleId); + DestroyBaseListener(moduleId); return SOFTBUS_OK; } @@ -534,16 +556,5 @@ ConnectFuncInterface *ConnInitTcp(const ConnectCallback *callback) } g_tcpConnInfoList->cnt = 0; } - if (g_tcpListener == NULL) { - g_tcpListener = (SoftbusBaseListener *)SoftBusCalloc(sizeof(SoftbusBaseListener)); - if (g_tcpListener == NULL) { - SoftBusFree(interface); - DestroySoftBusList(g_tcpConnInfoList); - g_tcpConnInfoList = NULL; - return NULL; - } - } - g_tcpListener->onConnectEvent = TcpOnConnectEvent; - g_tcpListener->onDataEvent = TcpOnDataEvent; return interface; } \ No newline at end of file diff --git a/core/discovery/ble/include/disc_ble_utils.h b/core/discovery/ble/include/disc_ble_utils.h index 66f1e0566..cb5445b6a 100644 --- a/core/discovery/ble/include/disc_ble_utils.h +++ b/core/discovery/ble/include/disc_ble_utils.h @@ -48,7 +48,7 @@ bool CheckCapBitMapEqual(const uint32_t *srcBitMap, const uint32_t *dstBitMap, u void SetCapBitMapPos(uint32_t capBitMapNum, uint32_t *capBitMap, uint32_t pos); void UnsetCapBitMapPos(uint32_t capBitMapNum, uint32_t *capBitMap, uint32_t pos); -int32_t DiscBleGetDeviceUdid(char *devId); +int32_t DiscBleGetDeviceUdid(char *devId, uint32_t len); int32_t DiscBleGetDeviceName(char *deviceName); int32_t DiscBleGetHwAccount(char *hwAccount); uint8_t DiscBleGetDeviceType(void); diff --git a/core/discovery/ble/src/disc_ble.c b/core/discovery/ble/src/disc_ble.c index 990912098..f55989725 100755 --- a/core/discovery/ble/src/disc_ble.c +++ b/core/discovery/ble/src/disc_ble.c @@ -29,7 +29,7 @@ #include "softbus_adapter_ble_gatt.h" #include "softbus_adapter_bt_common.h" #include "softbus_adapter_mem.h" -#include "softbus_adapter_thread.h" +#include "softbus_bitmap.h" #include "softbus_def.h" #include "softbus_errcode.h" #include "softbus_log.h" @@ -119,7 +119,7 @@ typedef struct { uint32_t numNeedBrMac; uint32_t numNeedResp; ListNode node; - SoftBusMutex lock; + pthread_mutex_t lock; } RecvMessageInfo; typedef struct { @@ -145,7 +145,7 @@ static ScanSetting g_scanTable[FREQ_BUTT] = { static DiscInnerCallback *g_discBleInnerCb = NULL; static DiscBleInfo g_bleInfoManager[BLE_INFO_COUNT]; -static SoftBusMutex g_bleInfoLock; +static pthread_mutex_t g_bleInfoLock = PTHREAD_MUTEX_INITIALIZER; static DiscBleAdvertiser g_bleAdvertiser[NUM_ADVERTISER]; static bool g_isScanning = false; static SoftBusHandler g_discBleHandler = {0}; @@ -154,10 +154,11 @@ static DiscBleListener g_bleListener = { .stateListenerId = -1, .scanListenerId = -1 }; +static const int g_bleTransCapabilityMap[CAPABILITY_MAX_BITNUM] = {0, 3, 5, 3, 6, 5, 6, 7}; static SoftBusMessage *CreateBleHandlerMsg(int32_t what, uint64_t arg1, uint64_t arg2, void *obj); static int32_t AddRecvMessage(const char *key, const uint32_t *capBitMap, bool needBrMac); -static int32_t MatchRecvMessage(const uint32_t *publishInfoMap, uint32_t *capBitMap); +static int32_t MatchRecvMessage(const uint32_t *publishInfoMap, uint32_t *capBitMap, uint32_t len); static RecvMessage *GetRecvMessage(const char *key); static int32_t StartAdvertiser(int32_t adv); static int32_t StopAdvertiser(int32_t adv); @@ -182,6 +183,17 @@ static int ConvertCapBitMap(int oldCap) return oldCap; } +static void DeConvertBitMap(unsigned int *dstCap, unsigned int *srcCap, int nums) +{ + (void)nums; + for (int32_t i = 0; i < CAPABILITY_MAX_BITNUM; i++) { + if (SoftbusIsBitmapSet(srcCap, i)) { + SoftbusBitmapSet(dstCap, g_bleTransCapabilityMap[i]); + } + } + SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_INFO, "old= %d,new= %d", *srcCap, *dstCap); +} + static void ResetInfoUpdate(int adv) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_INFO, "ResetInfoUpdate"); @@ -245,11 +257,11 @@ static void BleAdvUpdateCallback(int advId, int status) static bool CheckScanner(void) { - (void)SoftBusMutexLock(&g_bleInfoLock); + (void)pthread_mutex_lock(&g_bleInfoLock); uint32_t scanCapBit = g_bleInfoManager[BLE_SUBSCRIBE | BLE_ACTIVE].capBitMap[0] | g_bleInfoManager[BLE_SUBSCRIBE | BLE_PASSIVE].capBitMap[0] | g_bleInfoManager[BLE_PUBLISH | BLE_PASSIVE].capBitMap[0]; - (void)SoftBusMutexUnlock(&g_bleInfoLock); + (void)pthread_mutex_unlock(&g_bleInfoLock); if (scanCapBit == 0x0) { return false; } @@ -292,15 +304,15 @@ static void ProcessDisConPacket(const unsigned char *advData, uint32_t advLen, D SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "GetDeviceInfoFromDisAdvData failed"); return; } - (void)SoftBusMutexLock(&g_bleInfoLock); + (void)pthread_mutex_lock(&g_bleInfoLock); if ((foundInfo->capabilityBitmap[0] & g_bleInfoManager[BLE_PUBLISH | BLE_PASSIVE].capBitMap[0]) == 0x0) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_INFO, "don't match passive publish capBitMap"); - (void)SoftBusMutexUnlock(&g_bleInfoLock); + (void)pthread_mutex_unlock(&g_bleInfoLock); return; } - (void)SoftBusMutexUnlock(&g_bleInfoLock); + (void)pthread_mutex_unlock(&g_bleInfoLock); char key[SHA_HASH_LEN]; - if (GenerateStrHash(advData, advLen, key) != SOFTBUS_OK) { + if (GenerateStrHash(advData, advLen, (unsigned char *)key) != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "GenerateStrHash failed"); return; } @@ -310,23 +322,52 @@ static void ProcessDisConPacket(const unsigned char *advData, uint32_t advLen, D }; } +static bool ProcessHwHashAccout(DeviceInfo *foundInfo) +{ + for (uint32_t pos = 0; pos < CAPABILITY_MAX_BITNUM; pos++) { + if (!CheckCapBitMapExist(CAPABILITY_NUM, foundInfo->capabilityBitmap, pos)) { + continue; + } + if (g_bleInfoManager[BLE_SUBSCRIBE | BLE_ACTIVE].isSameAccount[pos] == false) { + return true; + } + unsigned char hwAccountHash[MAX_ACCOUNT_HASH_LEN] = {0}; + if (DiscBleGetShortUserIdHash(hwAccountHash) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "DiscBleGetShortUserIdHash error"); + return false; + } + SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_INFO, "my account = %s", hwAccountHash); + if (strcmp((char *)hwAccountHash, foundInfo->hwAccountHash) == EOK) { + return true; + } + return false; + } + return false; +} + static void ProcessDisNonPacket(const unsigned char *advData, uint32_t advLen, DeviceInfo *foundInfo) { if (GetDeviceInfoFromDisAdvData(foundInfo, advData, advLen) != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "GetDeviceInfoFromDisAdvData failed"); return; } - (void)SoftBusMutexLock(&g_bleInfoLock); + (void)pthread_mutex_lock(&g_bleInfoLock); uint32_t subscribeCap = g_bleInfoManager[BLE_SUBSCRIBE | BLE_ACTIVE].capBitMap[0] | g_bleInfoManager[BLE_SUBSCRIBE | BLE_PASSIVE].capBitMap[0]; - if (subscribeCap & (foundInfo->capabilityBitmap[0] == 0x0)) { + if (subscribeCap & (uint32_t)(foundInfo->capabilityBitmap[0] == 0x0)) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "Capbitmap unmatch"); - (void)SoftBusMutexUnlock(&g_bleInfoLock); + (void)pthread_mutex_unlock(&g_bleInfoLock); return; } + unsigned int tempCap = 0; foundInfo->capabilityBitmap[0] = subscribeCap & foundInfo->capabilityBitmap[0]; - (void)SoftBusMutexUnlock(&g_bleInfoLock); - g_discBleInnerCb->OnDeviceFound(foundInfo); + (void)pthread_mutex_unlock(&g_bleInfoLock); + if (ProcessHwHashAccout(foundInfo)) { + SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_INFO, "same account"); + DeConvertBitMap(&tempCap, foundInfo->capabilityBitmap, foundInfo->capabilityBitmapNum); + foundInfo->capabilityBitmap[0] = tempCap; + g_discBleInnerCb->OnDeviceFound(foundInfo); + } } static void ProcessDistributePacket(const SoftBusBleScanResult *scanResultData) @@ -335,7 +376,10 @@ static void ProcessDistributePacket(const SoftBusBleScanResult *scanResultData) unsigned char *advData = scanResultData->advData; DeviceInfo foundInfo = {0}; foundInfo.addrNum = 1; - (void)memcpy_s(foundInfo.addr[0].info.ble.bleMac, BT_ADDR_LEN, scanResultData->addr.addr, BT_ADDR_LEN); + if (memcpy_s(foundInfo.addr[0].info.ble.bleMac, BT_ADDR_LEN, scanResultData->addr.addr, BT_ADDR_LEN) != EOK) { + SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "memcpy_s failed"); + return; + } if ((advData[POS_BUSSINESS_EXTENSION + ADV_HEAD_LEN] & BIT_HEART_BIT) != 0) { return; } @@ -386,7 +430,7 @@ static void BleOnScanStop(int listenerId, int status) static void BleOnStateChanged(int listenerId, int state) { (void)listenerId; - SoftBusMessage *msg; + SoftBusMessage *msg = NULL; switch (state) { case SOFTBUS_BT_STATE_TURN_ON: SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_INFO, "BleOnStateChanged to SOFTBUS_BT_STATE_TURNING_ON"); @@ -437,7 +481,7 @@ static int32_t GetMaxExchangeFreq(void) return maxFreq; } -static bool GetSameAccount(void) +bool GetSameAccount(void) { for (uint32_t index = 0; index < CAPABILITY_MAX_BITNUM; index++) { if (g_bleInfoManager[BLE_SUBSCRIBE | BLE_ACTIVE].isSameAccount[index]) { @@ -469,7 +513,7 @@ static int32_t GetConDeviceInfo(DeviceInfo *info) SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "All capbit is zero"); return SOFTBUS_ERR; } - if (DiscBleGetDeviceIdHash(info->devId) != SOFTBUS_OK) { + if (DiscBleGetDeviceIdHash((unsigned char *)info->devId) != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "Get deviceId failed"); } if (DiscBleGetDeviceName(info->devName) != SOFTBUS_OK) { @@ -484,7 +528,7 @@ static int32_t GetConDeviceInfo(DeviceInfo *info) } (void)memset_s(info->hwAccountHash, MAX_ACCOUNT_HASH_LEN, 0x0, MAX_ACCOUNT_HASH_LEN); if (isSameAccount) { - if (DiscBleGetShortUserIdHash(info->hwAccountHash) != SOFTBUS_OK) { + if (DiscBleGetShortUserIdHash((unsigned char *)info->hwAccountHash) != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "GetShortUserIdHash failed"); } } @@ -501,7 +545,7 @@ static int32_t GetNonDeviceInfo(DeviceInfo *info) return SOFTBUS_INVALID_PARAM; } (void)memset_s(info, sizeof(DeviceInfo), 0x0, sizeof(DeviceInfo)); - if (DiscBleGetDeviceIdHash(info->devId) != SOFTBUS_OK) { + if (DiscBleGetDeviceIdHash((unsigned char *)info->devId) != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "Get deviceId failed"); } if (DiscBleGetDeviceName(info->devName) != SOFTBUS_OK) { @@ -509,7 +553,8 @@ static int32_t GetNonDeviceInfo(DeviceInfo *info) } info->devType = DiscBleGetDeviceType(); uint32_t passiveCapBitMap[CAPABILITY_NUM] = {0}; - if (MatchRecvMessage(g_bleInfoManager[BLE_PUBLISH | BLE_PASSIVE].capBitMap, passiveCapBitMap) != SOFTBUS_OK) { + if (MatchRecvMessage(g_bleInfoManager[BLE_PUBLISH | BLE_PASSIVE].capBitMap, + passiveCapBitMap, CAPABILITY_NUM) != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "MatchRecvMessage failed"); return SOFTBUS_ERR; } @@ -529,12 +574,12 @@ static int32_t BuildBleConfigAdvData(SoftBusBleAdvData *advData, const Boardcast if (advData == NULL || boardcastData == NULL) { return SOFTBUS_INVALID_PARAM; } - advData->advData = (unsigned char *)SoftBusCalloc(ADV_DATA_MAX_LEN + ADV_HEAD_LEN); + advData->advData = (char *)SoftBusCalloc(ADV_DATA_MAX_LEN + ADV_HEAD_LEN); if (advData->advData == NULL) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "malloc failed"); return SOFTBUS_MALLOC_ERR; } - advData->scanRspData = (unsigned char *)SoftBusCalloc(RESP_DATA_MAX_LEN + RSP_HEAD_LEN); + advData->scanRspData = (char *)SoftBusCalloc(RESP_DATA_MAX_LEN + RSP_HEAD_LEN); if (advData->scanRspData == NULL) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "malloc failed"); SoftBusFree(advData->advData); @@ -586,7 +631,6 @@ static int32_t GetBroadcastData(DeviceInfo *info, int32_t advId, BoardcastData * SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "GetBroadcastData input param invalid"); return SOFTBUS_INVALID_PARAM; } - bool isSameAccount = GetSameAccount(); bool isWakeRemote = GetWakeRemote(); if (memset_s(boardcastData->data.data, BOARDCAST_MAX_LEN, 0x0, BOARDCAST_MAX_LEN) != EOK) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "memset failed"); @@ -600,8 +644,11 @@ static int32_t GetBroadcastData(DeviceInfo *info, int32_t advId, BoardcastData * if (isWakeRemote) { boardcastData->data.data[POS_BUSSINESS_EXTENSION] |= BIT_WAKE_UP; } - (void)memcpy_s(&boardcastData->data.data[POS_USER_ID_HASH], SHORT_USER_ID_HASH_LEN, - info->hwAccountHash, SHORT_USER_ID_HASH_LEN); + if (memcpy_s(&boardcastData->data.data[POS_USER_ID_HASH], SHORT_USER_ID_HASH_LEN, + info->hwAccountHash, SHORT_USER_ID_HASH_LEN) != EOK) { + SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "memcpy_s failed"); + return SOFTBUS_ERR; + } } else { if (DiscBleGetShortUserIdHash(&boardcastData->data.data[POS_USER_ID_HASH]) != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "GetShortUserIdHash failed"); @@ -611,16 +658,17 @@ static int32_t GetBroadcastData(DeviceInfo *info, int32_t advId, BoardcastData * boardcastData->data.data[POS_CAPABLITY_EXTENSION] = 0x0; boardcastData->dataLen = POS_TLV; char deviceIdHash[SHORT_DEVICE_ID_HASH_LENGTH + 1] = {0}; - if (DiscBleGetDeviceIdHash(deviceIdHash) != SOFTBUS_OK) { + if (DiscBleGetDeviceIdHash((unsigned char *)deviceIdHash) != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "Get deviceId Hash failed"); } uint8_t devType = info->devType; - (void)AssembleTLV(boardcastData, TLV_TYPE_DEVICE_ID_HASH, deviceIdHash, SHORT_DEVICE_ID_HASH_LENGTH); + (void)AssembleTLV(boardcastData, TLV_TYPE_DEVICE_ID_HASH, (const unsigned char *)deviceIdHash, + SHORT_DEVICE_ID_HASH_LENGTH); (void)AssembleTLV(boardcastData, TLV_TYPE_DEVICE_TYPE, &devType, DEVICE_TYPE_LEN); if (advId == NON_ADV_ID && g_recvMessageInfo.numNeedBrMac > 0) { SoftBusBtAddr addr; if (SoftBusGetBtMacAddr(&addr) == SOFTBUS_OK) { - (void)AssembleTLV(boardcastData, TLV_TYPE_BR_MAC, &addr.addr, BT_ADDR_LEN); + (void)AssembleTLV(boardcastData, TLV_TYPE_BR_MAC, (const unsigned char *)&addr.addr, BT_ADDR_LEN); } } SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_INFO, "boardcastData->dataLen:%d", boardcastData->dataLen); @@ -702,9 +750,9 @@ static int32_t StopAdvertiser(int32_t adv) SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "stop advertiser advId:%d failed.", adv); } if (adv == NON_ADV_ID) { - (void)SoftBusMutexLock(&g_recvMessageInfo.lock); + (void)pthread_mutex_lock(&g_recvMessageInfo.lock); ClearRecvMessage(); - (void)SoftBusMutexUnlock(&g_recvMessageInfo.lock); + (void)pthread_mutex_unlock(&g_recvMessageInfo.lock); } return SOFTBUS_OK; } @@ -875,7 +923,7 @@ static int32_t UnregisterCapability(DiscBleInfo *info, DiscBleOption *option) (option->publishOption != NULL && option->subscribeOption != NULL)) { return SOFTBUS_INVALID_PARAM; } - uint32_t *optionCapBitMap; + uint32_t *optionCapBitMap = NULL; bool isSameAccount = false; bool isWakeRemote = false; if (option->publishOption != NULL) { @@ -922,24 +970,24 @@ static int32_t ProcessBleInfoManager(bool isStart, uint8_t publishFlags, uint8_t regOption.subscribeOption = (SubscribeOption *)option; } unsigned char index = publishFlags | activeFlags; - if (SoftBusMutexLock(&g_bleInfoLock) != 0) { + if (pthread_mutex_lock(&g_bleInfoLock) != 0) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "lock failed."); return SOFTBUS_LOCK_ERR; } if (isStart) { if (RegisterCapability(&g_bleInfoManager[index], ®Option) != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "RegisterCapability failed."); - SoftBusMutexUnlock(&g_bleInfoLock); + pthread_mutex_unlock(&g_bleInfoLock); return SOFTBUS_ERR; } } else { if (UnregisterCapability(&g_bleInfoManager[index], ®Option) != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "UnregisterCapability failed."); - SoftBusMutexUnlock(&g_bleInfoLock); + pthread_mutex_unlock(&g_bleInfoLock); return SOFTBUS_ERR; } } - SoftBusMutexUnlock(&g_bleInfoLock); + pthread_mutex_unlock(&g_bleInfoLock); return SOFTBUS_OK; } @@ -960,7 +1008,7 @@ static SoftBusMessage *CreateBleHandlerMsg(int32_t what, uint64_t arg1, uint64_t } static int32_t ProcessBleDiscFunc(bool isStart, uint8_t publishFlags, - uint8_t activeFlags, int32_t funcCode, void *option) + uint8_t activeFlags, int32_t funcCode, const void *option) { if (option == NULL) { return SOFTBUS_INVALID_PARAM; @@ -968,7 +1016,7 @@ static int32_t ProcessBleDiscFunc(bool isStart, uint8_t publishFlags, if (SoftBusGetBtState() != BLE_ENABLE) { return SOFTBUS_ERR; } - int32_t ret = ProcessBleInfoManager(isStart, publishFlags, activeFlags, (void *)option); + int32_t ret = ProcessBleInfoManager(isStart, publishFlags, activeFlags, option); if (ret != SOFTBUS_OK) { return ret; } @@ -1179,7 +1227,7 @@ static int32_t ReplyPassiveNonBroadcast(void) static int32_t RemoveRecvMsgFunc(const SoftBusMessage *msg, void *args) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_INFO, "RemoveRecvMsgFunc"); - int64_t key = (int64_t)args; + uintptr_t key = (uintptr_t)args; if (msg->what == PROCESS_TIME_OUT && msg->arg1 == key) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_INFO, "find key"); return 0; @@ -1193,7 +1241,7 @@ static RecvMessage *GetRecvMessage(const char *key) if (key == NULL) { return NULL; } - RecvMessage *msg; + RecvMessage *msg = NULL; LIST_FOR_EACH_ENTRY(msg, &g_recvMessageInfo.node, RecvMessage, node) { if (memcmp((void *)key, (void *)msg->key, SHA_HASH_LEN) == 0) { return msg; @@ -1202,20 +1250,20 @@ static RecvMessage *GetRecvMessage(const char *key) return NULL; } -static int32_t MatchRecvMessage(const uint32_t *publishInfoMap, uint32_t *capBitMap) +static int32_t MatchRecvMessage(const uint32_t *publishInfoMap, uint32_t *capBitMap, uint32_t len) { if (capBitMap == NULL || publishInfoMap == NULL) { return SOFTBUS_INVALID_PARAM; } - (void)SoftBusMutexLock(&g_recvMessageInfo.lock); - RecvMessage *msg; + (void)pthread_mutex_lock(&g_recvMessageInfo.lock); + RecvMessage *msg = NULL; SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_INFO, "recv message cnt: %d", g_recvMessageInfo.numNeedResp); LIST_FOR_EACH_ENTRY(msg, &g_recvMessageInfo.node, RecvMessage, node) { - for (uint32_t index = 0; index < CAPABILITY_NUM; index++) { + for (uint32_t index = 0; index < len; index++) { capBitMap[index] = msg->capBitMap[index] & publishInfoMap[index]; } } - (void)SoftBusMutexUnlock(&g_recvMessageInfo.lock); + (void)pthread_mutex_unlock(&g_recvMessageInfo.lock); return SOFTBUS_OK; } @@ -1226,17 +1274,17 @@ static void StartTimeout(const char *key) SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "key is null"); return; } - if (SoftBusMutexLock(&g_recvMessageInfo.lock) != 0) { + if (pthread_mutex_lock(&g_recvMessageInfo.lock) != 0) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "lock failed"); return; } if (GetRecvMessage(key) == NULL) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "key is not exists"); - SoftBusMutexUnlock(&g_recvMessageInfo.lock); + pthread_mutex_unlock(&g_recvMessageInfo.lock); return; } - SoftBusMutexUnlock(&g_recvMessageInfo.lock); - SoftBusMessage *msg = CreateBleHandlerMsg(PROCESS_TIME_OUT, (uint64_t)key, 0, NULL); + pthread_mutex_unlock(&g_recvMessageInfo.lock); + SoftBusMessage *msg = CreateBleHandlerMsg(PROCESS_TIME_OUT, (uintptr_t)key, 0, NULL); if (msg == NULL) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "malloc msg failed"); return; @@ -1251,16 +1299,16 @@ static void RemoveTimeout(const char *key) SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "key is null"); return; } - if (SoftBusMutexLock(&g_recvMessageInfo.lock) != 0) { + if (pthread_mutex_lock(&g_recvMessageInfo.lock) != 0) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "lock failed"); return; } if (GetRecvMessage(key) == NULL) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_INFO, "key is not in recv message"); - SoftBusMutexUnlock(&g_recvMessageInfo.lock); + pthread_mutex_unlock(&g_recvMessageInfo.lock); return; } - SoftBusMutexUnlock(&g_recvMessageInfo.lock); + pthread_mutex_unlock(&g_recvMessageInfo.lock); g_discBleHandler.looper->RemoveMessageCustom(g_discBleHandler.looper, &g_discBleHandler, RemoveRecvMsgFunc, (void *)key); } @@ -1272,7 +1320,7 @@ static int32_t AddRecvMessage(const char *key, const uint32_t *capBitMap, bool n SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "AddRecvMessage input param invalid"); return SOFTBUS_INVALID_PARAM; } - if (SoftBusMutexLock(&g_recvMessageInfo.lock) != 0) { + if (pthread_mutex_lock(&g_recvMessageInfo.lock) != 0) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "lock failed"); return SOFTBUS_LOCK_ERR; } @@ -1282,13 +1330,13 @@ static int32_t AddRecvMessage(const char *key, const uint32_t *capBitMap, bool n recvMsg = SoftBusCalloc(sizeof(RecvMessage)); if (recvMsg == NULL) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "malloc recv msg failed"); - SoftBusMutexUnlock(&g_recvMessageInfo.lock); + pthread_mutex_unlock(&g_recvMessageInfo.lock); return SOFTBUS_MALLOC_ERR; } if (memcpy_s(&recvMsg->key, SHA_HASH_LEN, key, SHA_HASH_LEN) != EOK) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "Copy key to create recv msg failed"); SoftBusFree(recvMsg); - SoftBusMutexUnlock(&g_recvMessageInfo.lock); + pthread_mutex_unlock(&g_recvMessageInfo.lock); return SOFTBUS_MEM_ERR; } for (uint32_t index = 0; index < CAPABILITY_NUM; index++) { @@ -1298,9 +1346,9 @@ static int32_t AddRecvMessage(const char *key, const uint32_t *capBitMap, bool n g_recvMessageInfo.numNeedBrMac++; g_recvMessageInfo.numNeedResp++; ListTailInsert(&g_recvMessageInfo.node, &recvMsg->node); - SoftBusMutexUnlock(&g_recvMessageInfo.lock); + pthread_mutex_unlock(&g_recvMessageInfo.lock); } else { - SoftBusMutexUnlock(&g_recvMessageInfo.lock); + pthread_mutex_unlock(&g_recvMessageInfo.lock); RemoveTimeout(recvMsg->key); } StartTimeout(recvMsg->key); @@ -1310,15 +1358,15 @@ static int32_t AddRecvMessage(const char *key, const uint32_t *capBitMap, bool n static void RemoveRecvMessage(uint64_t key) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_INFO, "RemoveRecvMessage"); - if (SoftBusMutexLock(&g_recvMessageInfo.lock) != 0) { + if (pthread_mutex_lock(&g_recvMessageInfo.lock) != 0) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "lock failed"); return; } - RecvMessage *recvMsg = GetRecvMessage((char *)key); + RecvMessage *recvMsg = GetRecvMessage((char *)(uintptr_t)key); if (recvMsg != NULL) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_INFO, "recvMsg founded"); g_discBleHandler.looper->RemoveMessageCustom(g_discBleHandler.looper, &g_discBleHandler, - RemoveRecvMsgFunc, key); + RemoveRecvMsgFunc, (void *)(uintptr_t)key); if (recvMsg->needBrMac) { g_recvMessageInfo.numNeedBrMac--; } @@ -1328,7 +1376,7 @@ static void RemoveRecvMessage(uint64_t key) } else { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "recvMsg is not find."); } - SoftBusMutexUnlock(&g_recvMessageInfo.lock); + pthread_mutex_unlock(&g_recvMessageInfo.lock); } static void ClearRecvMessage(void) @@ -1426,24 +1474,16 @@ static int32_t InitBleListener(void) DiscoveryFuncInterface *DiscBleInit(DiscInnerCallback *discInnerCb) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_INFO, "DiscBleInit"); - ListInit(&g_recvMessageInfo.node); if (discInnerCb == NULL || discInnerCb->OnDeviceFound == NULL) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "discInnerCb invalid."); goto EXIT; } g_discBleInnerCb = discInnerCb; - - if (SoftBusMutexInit(&g_recvMessageInfo.lock, NULL) != SOFTBUS_OK) { + if (pthread_mutex_init(&g_recvMessageInfo.lock, NULL) != 0) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "Init ble recvMsg lock failed"); goto EXIT; } - - if (SoftBusMutexInit(&g_bleInfoLock, NULL) != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "Init ble Info lock failed"); - return SOFTBUS_ERR; - } - if (DiscBleLooperInit() != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "disc ble Init looper falied"); goto EXIT; @@ -1476,12 +1516,12 @@ EXIT: return NULL; } -static bool CheckLockInit(SoftBusMutex *lock) +static bool CheckLockInit(pthread_mutex_t *lock) { - if (SoftBusMutexLock(lock) != 0) { + if (pthread_mutex_lock(lock) != 0) { return false; } - SoftBusMutexUnlock(lock); + pthread_mutex_unlock(lock); return true; } @@ -1489,7 +1529,7 @@ static void RecvMessageDeinit(void) { ClearRecvMessage(); if (CheckLockInit(&g_recvMessageInfo.lock)) { - (void)SoftBusMutexDestroy(&g_recvMessageInfo.lock); + (void)pthread_mutex_destroy(&g_recvMessageInfo.lock); } g_recvMessageInfo.numNeedBrMac = 0; g_recvMessageInfo.numNeedResp = 0; diff --git a/core/discovery/ble/src/disc_ble_utils.c b/core/discovery/ble/src/disc_ble_utils.c index e0dad9470..fbb3d0a11 100755 --- a/core/discovery/ble/src/disc_ble_utils.c +++ b/core/discovery/ble/src/disc_ble_utils.c @@ -59,7 +59,7 @@ int32_t GenerateStrHash(const unsigned char *str, uint32_t len, unsigned char *h return SOFTBUS_INVALID_PARAM; } mbedtls_md_context_t ctx; - const mbedtls_md_info_t *info; + const mbedtls_md_info_t *info = NULL; mbedtls_md_init(&ctx); info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256); if (mbedtls_md_setup(&ctx, info, 0) != 0) { @@ -149,19 +149,19 @@ int32_t DiscBleGetHwAccount(char *hwAccount) if (hwAccount == NULL) { return SOFTBUS_INVALID_PARAM; } - const char *account = ""; + const char *account = "1234567890"; if (memcpy_s(hwAccount, strlen(account) + 1, account, strlen(account) + 1) != EOK) { return SOFTBUS_MEM_ERR; } return SOFTBUS_OK; } -int32_t DiscBleGetDeviceUdid(char *devId) +int32_t DiscBleGetDeviceUdid(char *devId, uint32_t len) { if (devId == NULL) { return SOFTBUS_INVALID_PARAM; } - if (LnnGetLocalStrInfo(STRING_KEY_DEV_UDID, devId, UDID_BUF_LEN) != SOFTBUS_OK) { + if (LnnGetLocalStrInfo(STRING_KEY_DEV_UDID, devId, len) != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "Get local dev Id failed."); return SOFTBUS_ERR; } @@ -182,13 +182,13 @@ int32_t DiscBleGetDeviceName(char *deviceName) uint8_t DiscBleGetDeviceType(void) { - char type[DEVICE_TYPE_BUF_LEN]; + char type[DEVICE_TYPE_BUF_LEN] = {0}; uint8_t typeId; if (LnnGetLocalStrInfo(STRING_KEY_DEV_TYPE, type, DEVICE_TYPE_BUF_LEN) != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "Get local device type failed."); return TYPE_UNKNOW_ID; } - if (LnnConvertDeviceTypeToId(type, &typeId) != SOFTBUS_OK) { + if (LnnConvertDeviceTypeToId(type, (uint16_t *)&typeId) != SOFTBUS_OK) { return TYPE_UNKNOW_ID; } return typeId; @@ -202,17 +202,17 @@ int32_t DiscBleGetDeviceIdHash(unsigned char *hashStr) } char devId[DISC_MAX_DEVICE_ID_LEN] = {0}; char hashResult[SHA_HASH_LEN] = {0}; - int32_t ret = DiscBleGetDeviceUdid(devId); + int32_t ret = DiscBleGetDeviceUdid(devId, sizeof(devId)); if (ret != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "GetDeviceId failed"); return ret; } - ret = GenerateStrHash(devId, strlen(devId), hashResult); + ret = GenerateStrHash((const unsigned char *)devId, strlen(devId) + 1, (unsigned char *)hashResult); if (ret != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "GenerateStrHash failed"); return ret; } - ret = ConvertBytesToHexString(hashStr, SHORT_DEVICE_ID_HASH_LENGTH + 1, hashResult, + ret = ConvertBytesToHexString((char *)hashStr, SHORT_DEVICE_ID_HASH_LENGTH + 1, (const unsigned char *)hashResult, SHORT_DEVICE_ID_HASH_LENGTH / HEXIFY_UNIT_LEN); if (ret != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "ConvertBytesToHexString failed"); @@ -229,17 +229,17 @@ int32_t DiscBleGetShortUserIdHash(unsigned char *hashStr) } unsigned char account[MAX_ACCOUNT_HASH_LEN] = {0}; unsigned char hashResult[SHA_HASH_LEN] = {0}; - int32_t ret = DiscBleGetHwAccount(account); + int32_t ret = DiscBleGetHwAccount((char *)account); if (ret != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "DiscBleGetHwAccount failed"); return ret; } - ret = GenerateStrHash(account, strlen(account) + 1, hashResult); + ret = GenerateStrHash(account, strlen((const char *)account) + 1, hashResult); if (ret != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "GenerateStrHash failed"); return ret; } - ret = ConvertBytesToHexString(hashStr, SHORT_USER_ID_HASH_LEN + 1, hashResult, + ret = ConvertBytesToHexString((char *)hashStr, SHORT_USER_ID_HASH_LEN + 1, hashResult, SHORT_USER_ID_HASH_LEN / HEXIFY_UNIT_LEN); if (ret != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "ConvertBytesToHexString failed"); @@ -259,6 +259,10 @@ int32_t AssembleTLV(BoardcastData *boardcastData, unsigned char dataType, const boardcastData->data.data[boardcastData->dataLen] |= dataLen & DATA_LENGTH_MASK; boardcastData->dataLen += 1; uint32_t remainLen = BOARDCAST_MAX_LEN - boardcastData->dataLen; + if (remainLen == 0) { + SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "tlv remainLen is 0."); + return SOFTBUS_ERR; + } uint32_t validLen = (len > remainLen) ? remainLen : len; if (memcpy_s(&(boardcastData->data.data[boardcastData->dataLen]), validLen, value, validLen) != EOK) { SoftBusLog(SOFTBUS_LOG_DISC, SOFTBUS_LOG_ERROR, "assemble tlv memcpy failed"); @@ -312,7 +316,7 @@ int32_t GetDeviceInfoFromDisAdvData(DeviceInfo *info, const unsigned char *data, info->capabilityBitmap[0] = data[POS_CAPABLITY + ADV_HEAD_LEN]; int32_t curLen = POS_TLV + ADV_HEAD_LEN; unsigned char devType; - int32_t len = ParseRecvAdvData(data, dataLen, TLV_TYPE_DEVICE_ID_HASH, curLen, info->devId); + int32_t len = ParseRecvAdvData(data, dataLen, TLV_TYPE_DEVICE_ID_HASH, curLen, (unsigned char *)info->devId); PACKET_CHECK_LENGTH(len); len = ParseRecvAdvData(data, dataLen, TLV_TYPE_DEVICE_TYPE, curLen, &devType); PACKET_CHECK_LENGTH(len); @@ -320,7 +324,7 @@ int32_t GetDeviceInfoFromDisAdvData(DeviceInfo *info, const unsigned char *data, len = ParseRecvAdvData(data, dataLen, TLV_TYPE_BR_MAC, curLen, (unsigned char *)info->addr[0].info.ble.bleMac); len = ParseRecvAdvData(data, dataLen, TLV_TYPE_CUST, curLen, (unsigned char *)info->custData); PACKET_CHECK_LENGTH(len); - len = ParseRecvAdvData(data, dataLen, TLV_TYPE_DEVICE_NAME, curLen, info->devName); + len = ParseRecvAdvData(data, dataLen, TLV_TYPE_DEVICE_NAME, curLen, (unsigned char *)info->devName); PACKET_CHECK_LENGTH(len); return SOFTBUS_OK; } \ No newline at end of file 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 da4eb2d8e..d65550419 100644 --- a/core/transmission/trans_channel/manager/src/trans_channel_manager.c +++ b/core/transmission/trans_channel/manager/src/trans_channel_manager.c @@ -284,17 +284,69 @@ EXIT_ERR: return INVALID_CHANNEL_ID; } +static AppInfo *GetAuthAppInfo(const char *mySessionName) +{ + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, "GetAuthAppInfo"); + AppInfo *appInfo = (AppInfo *)SoftBusCalloc(sizeof(AppInfo)); + if (appInfo == NULL) { + return NULL; + } + appInfo->appType = APP_TYPE_AUTH; + appInfo->myData.apiVersion = API_V2; + if (TransGetUidAndPid(mySessionName, &appInfo->myData.uid, &appInfo->myData.pid) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "GetAuthAppInfo GetUidAndPid failed"); + goto EXIT_ERR; + } + if (LnnGetLocalStrInfo(STRING_KEY_DEV_UDID, appInfo->myData.deviceId, + sizeof(appInfo->myData.deviceId)) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "GetAuthAppInfo get deviceId failed"); + goto EXIT_ERR; + } + if (strcpy_s(appInfo->myData.sessionName, sizeof(appInfo->myData.sessionName), mySessionName) != EOK) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "GetAuthAppInfo strcpy_s mySessionName failed"); + goto EXIT_ERR; + } + if (strcpy_s(appInfo->peerData.sessionName, sizeof(appInfo->peerData.sessionName), mySessionName) != EOK) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "GetAuthAppInfo strcpy_s peerSessionName failed"); + goto EXIT_ERR; + } + if (TransGetPkgNameBySessionName(mySessionName, appInfo->myData.pkgName, PKG_NAME_SIZE_MAX) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "GetAuthAppInfo get PkgName failed"); + goto EXIT_ERR; + } + + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, "GetAuthAppInfo ok"); + return appInfo; +EXIT_ERR: + if (appInfo != NULL) { + SoftBusFree(appInfo); + } + return NULL; +} + int32_t TransOpenAuthChannel(const char *sessionName, const ConnectOption *connOpt) { int32_t channelId = INVALID_CHANNEL_ID; if (!IsValidString(sessionName, SESSION_NAME_SIZE_MAX) || connOpt == NULL) { return channelId; } - if (connOpt->type != CONNECT_TCP) { - return channelId; - } - if (TransOpenAuthMsgChannel(sessionName, connOpt, &channelId) != SOFTBUS_OK) { - return INVALID_CHANNEL_ID; + + if (connOpt->type == CONNECT_TCP) { + if (TransOpenAuthMsgChannel(sessionName, connOpt, &channelId) != SOFTBUS_OK) { + return INVALID_CHANNEL_ID; + } + } else if (connOpt->type == CONNECT_BR || connOpt->type == CONNECT_BLE) { + AppInfo *appInfo = GetAuthAppInfo(sessionName); + if (appInfo == NULL) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "GetAuthAppInfo failed"); + return INVALID_CHANNEL_ID; + } + if (TransProxyOpenProxyChannel(appInfo, connOpt, &channelId) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "TransOpenAuthChannel proxy channel err"); + SoftBusFree(appInfo); + return INVALID_CHANNEL_ID; + } + SoftBusFree(appInfo); } return channelId; } diff --git a/core/transmission/trans_channel/proxy/include/softbus_proxychannel_manager.h b/core/transmission/trans_channel/proxy/include/softbus_proxychannel_manager.h index c31ceebb4..6cb8f4c3e 100644 --- a/core/transmission/trans_channel/proxy/include/softbus_proxychannel_manager.h +++ b/core/transmission/trans_channel/proxy/include/softbus_proxychannel_manager.h @@ -25,6 +25,8 @@ int32_t TransProxyManagerInit(const IServerChannelCallBack *cb); void TransProxyManagerDeinit(void); +int32_t TransProxyAuthSessionDataLenCheck(uint32_t dataLen, int32_t type); + int32_t TransProxyGetNewChanSeq(int32_t channelId); int32_t TransProxyOpenProxyChannel(const AppInfo *appInfo, const ConnectOption *connInfo, int32_t *channelId); int32_t TransProxyCloseProxyChannel(int32_t channelId); diff --git a/core/transmission/trans_channel/proxy/include/softbus_proxychannel_session.h b/core/transmission/trans_channel/proxy/include/softbus_proxychannel_session.h index 1cb2bf9f0..3470ba7ff 100644 --- a/core/transmission/trans_channel/proxy/include/softbus_proxychannel_session.h +++ b/core/transmission/trans_channel/proxy/include/softbus_proxychannel_session.h @@ -40,6 +40,7 @@ typedef enum { int32_t TransProxyPostSessionData(int32_t channelId, const uint8_t *data, uint32_t len, SessionPktType flags); int32_t TransOnNormalMsgReceived(const char *pkgName, int32_t channelId, const char *data, uint32_t len); +int32_t TransOnAuthMsgReceived(const char *pkgName, int32_t channelId, const char *data, uint32_t len); int32_t TransProxyDelSliceProcessorByChannelId(int32_t channelId); int32_t TransProxyTransNetWorkMsg(ProxyMessageHead *msghead, const ProxyChannelInfo *info, const char *payLoad, int payLoadLen, int priority); diff --git a/core/transmission/trans_channel/proxy/src/softbus_proxychannel_control.c b/core/transmission/trans_channel/proxy/src/softbus_proxychannel_control.c index a92ed43f6..71094f78a 100644 --- a/core/transmission/trans_channel/proxy/src/softbus_proxychannel_control.c +++ b/core/transmission/trans_channel/proxy/src/softbus_proxychannel_control.c @@ -33,7 +33,7 @@ int32_t TransProxySendMessage(ProxyChannelInfo *info, const char *payLoad, int32 ProxyMessageHead msgHead = {0}; msgHead.type = (PROXYCHANNEL_MSG_TYPE_NORMAL & FOUR_BIT_MASK) | (VERSION << VERSION_SHIFT); - if (info->appInfo.appType != APP_TYPE_NORMAL) { + if (info->appInfo.appType != APP_TYPE_AUTH) { msgHead.chiper = (msgHead.chiper | ENCRYPTED); } msgHead.myId = info->myId; @@ -55,7 +55,9 @@ int32_t TransProxyHandshake(ProxyChannelInfo *info) ProxyMessageHead msgHead = {0}; msgHead.type = (PROXYCHANNEL_MSG_TYPE_HANDSHAKE & FOUR_BIT_MASK) | (VERSION << VERSION_SHIFT); - msgHead.chiper = (msgHead.chiper | ENCRYPTED); + if (info->appInfo.appType != APP_TYPE_AUTH) { + msgHead.chiper = (msgHead.chiper | ENCRYPTED); + } msgHead.myId = info->myId; msgHead.peerId = INVALID_CHANNEL_ID; SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, "handshake myId %d", msgHead.myId); @@ -96,7 +98,9 @@ int32_t TransProxyAckHandshake(uint32_t connId, ProxyChannelInfo *chan) SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, "send handshake ack msg myid %d peerid %d", chan->myId, chan->peerId); msgHead.type = (PROXYCHANNEL_MSG_TYPE_HANDSHAKE_ACK & FOUR_BIT_MASK) | (VERSION << VERSION_SHIFT); - msgHead.chiper = (msgHead.chiper | ENCRYPTED); + if (chan->appInfo.appType != APP_TYPE_AUTH) { + msgHead.chiper = (msgHead.chiper | ENCRYPTED); + } payLoad = TransProxyPackHandshakeAckMsg(chan); if (payLoad == NULL) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "pack handshake ack fail"); @@ -137,7 +141,9 @@ void TransProxyKeepalive(uint32_t connId, const ProxyChannelInfo *info) payLoadLen = strlen(payLoad) + 1; msgHead.myId = info->myId; msgHead.peerId = info->peerId; - msgHead.chiper = (msgHead.chiper | ENCRYPTED); + if (info->appInfo.appType != APP_TYPE_AUTH) { + msgHead.chiper = (msgHead.chiper | ENCRYPTED); + } if (TransProxyPackMessage(&msgHead, connId, payLoad, payLoadLen, &buf, &bufLen) != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "pack keepalive head fail"); @@ -169,7 +175,9 @@ int32_t TransProxyAckKeepalive(ProxyChannelInfo *info) payLoadLen = strlen(payLoad) + 1; msgHead.myId = info->myId; msgHead.peerId = info->peerId; - msgHead.chiper = (msgHead.chiper | ENCRYPTED); + if (info->appInfo.appType != APP_TYPE_AUTH) { + msgHead.chiper = (msgHead.chiper | ENCRYPTED); + } if (TransProxyPackMessage(&msgHead, info->connId, payLoad, payLoadLen, &buf, &bufLen) != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "pack keepalive ack head fail"); @@ -203,7 +211,9 @@ int32_t TransProxyResetPeer(ProxyChannelInfo *info) payLoadLen = strlen(payLoad) + 1; msgHead.myId = info->myId; msgHead.peerId = info->peerId; - msgHead.chiper = (msgHead.chiper | ENCRYPTED); + if (info->appInfo.appType != APP_TYPE_AUTH) { + msgHead.chiper = (msgHead.chiper | ENCRYPTED); + } if (TransProxyPackMessage(&msgHead, info->connId, payLoad, payLoadLen, &buf, &bufLen) != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "pack reset head fail"); diff --git a/core/transmission/trans_channel/proxy/src/softbus_proxychannel_listener.c b/core/transmission/trans_channel/proxy/src/softbus_proxychannel_listener.c index 677f19b00..af3888312 100644 --- a/core/transmission/trans_channel/proxy/src/softbus_proxychannel_listener.c +++ b/core/transmission/trans_channel/proxy/src/softbus_proxychannel_listener.c @@ -56,12 +56,17 @@ static int32_t NotifyNormalChannelOpened(int32_t channelId, const AppInfo *appIn info.sessionKey = (char*)appInfo->sessionKey; info.keyLen = SESSION_KEY_LENGTH; - int32_t ret = LnnGetNetworkIdByUuid(appInfo->peerData.deviceId, buf, NETWORK_ID_BUF_LEN); - if (ret != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "get info networkId fail."); - return SOFTBUS_ERR; + int32_t ret; + if (appInfo->appType != APP_TYPE_AUTH) { + ret = LnnGetNetworkIdByUuid(appInfo->peerData.deviceId, buf, NETWORK_ID_BUF_LEN); + if (ret != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "get info networkId fail."); + return SOFTBUS_ERR; + } + info.peerDeviceId = buf; + } else { + info.peerDeviceId = (char *)appInfo->peerData.deviceId; } - info.peerDeviceId = buf; ret = TransProxyOnChannelOpened(appInfo->myData.pkgName, appInfo->myData.sessionName, &info); SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, "proxy channel open, channelId = %d, ret = %d", channelId, ret); @@ -81,10 +86,8 @@ int32_t OnProxyChannelOpened(int32_t channelId, const AppInfo *appInfo, unsigned switch (appInfo->appType) { case APP_TYPE_NORMAL: - ret = NotifyNormalChannelOpened(channelId, appInfo, isServer); - break; case APP_TYPE_AUTH: - ret = SOFTBUS_ERR; + ret = NotifyNormalChannelOpened(channelId, appInfo, isServer); break; case APP_TYPE_INNER: ret = NotifyNetworkingChannelOpened(channelId, appInfo, isServer); @@ -109,10 +112,8 @@ int32_t OnProxyChannelOpenFailed(int32_t channelId, const AppInfo *appInfo) switch (appInfo->appType) { case APP_TYPE_NORMAL: - ret = NotifyNormalChannelOpenFailed(appInfo->myData.pkgName, channelId); - break; case APP_TYPE_AUTH: - ret = SOFTBUS_ERR; + ret = NotifyNormalChannelOpenFailed(appInfo->myData.pkgName, channelId); break; case APP_TYPE_INNER: NotifyNetworkingChannelOpenFailed(channelId, appInfo->peerData.deviceId); @@ -134,10 +135,8 @@ int32_t OnProxyChannelClosed(int32_t channelId, const AppInfo *appInfo) int32_t ret = SOFTBUS_OK; switch (appInfo->appType) { case APP_TYPE_NORMAL: - ret = NotifyNormalChannelClosed(appInfo->myData.pkgName, channelId); - break; case APP_TYPE_AUTH: - ret = SOFTBUS_ERR; + ret = NotifyNormalChannelClosed(appInfo->myData.pkgName, channelId); break; case APP_TYPE_INNER: NotifyNetworkingChannelClosed(channelId); @@ -163,7 +162,7 @@ int32_t OnProxyChannelMsgReceived(int32_t channelId, const AppInfo *appInfo, TransOnNormalMsgReceived(appInfo->myData.pkgName, channelId, data, len); break; case APP_TYPE_AUTH: - ret = SOFTBUS_ERR; + TransOnAuthMsgReceived(appInfo->myData.pkgName, channelId, data, len); break; case APP_TYPE_INNER: NotifyNetworkingMsgReceived(channelId, data, len); 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 324f0f44b..8c6ed68bf 100644 --- a/core/transmission/trans_channel/proxy/src/softbus_proxychannel_manager.c +++ b/core/transmission/trans_channel/proxy/src/softbus_proxychannel_manager.c @@ -25,6 +25,7 @@ #include "softbus_adapter_thread.h" #include "softbus_conn_interface.h" #include "softbus_errcode.h" +#include "softbus_feature_config.h" #include "softbus_log.h" #include "softbus_proxychannel_callback.h" #include "softbus_proxychannel_control.h" @@ -42,6 +43,8 @@ static SoftBusList *g_proxyChannelList = NULL; static SoftBusMutex g_myIdLock; +static int32_t g_authMaxByteBufSize; +static int32_t g_authMaxMessageBufSize; static int32_t MyIdIsValid(int16_t myId) { @@ -816,10 +819,13 @@ int32_t TransProxyCreateChanInfo(ProxyChannelInfo *chan, int32_t channelId, cons SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "GenerateRandomStr err"); return SOFTBUS_ERR; } - - if (SoftBusGenerateRandomArray((unsigned char *)appInfo->sessionKey, sizeof(appInfo->sessionKey)) != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "GenerateRandomArray err"); - return SOFTBUS_ERR; + + if (appInfo->appType != APP_TYPE_AUTH) { + if (SoftBusGenerateRandomArray((unsigned char *)appInfo->sessionKey, sizeof(appInfo->sessionKey)) + != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "GenerateRandomArray err"); + return SOFTBUS_ERR; + } } (void)memcpy_s(&(chan->appInfo), sizeof(chan->appInfo), appInfo, sizeof(AppInfo)); @@ -1007,6 +1013,29 @@ void TransProxyTimerProc(void) TransProxyTimerItemProc(&proxyProcList); } +int32_t TransProxyAuthSessionDataLenCheck(uint32_t dataLen, int32_t type) +{ + switch (type) { + case PROXY_FLAG_MESSAGE: + case PROXY_FLAG_ASYNC_MESSAGE: { + if (dataLen > g_authMaxMessageBufSize) { + return SOFTBUS_ERR; + } + break; + } + case PROXY_FLAG_BYTES: { + if (dataLen > g_authMaxByteBufSize) { + return SOFTBUS_ERR; + } + break; + } + default: { + return SOFTBUS_OK; + } + } + return SOFTBUS_OK; +} + int32_t TransProxyManagerInit(const IServerChannelCallBack *cb) { if (SoftBusMutexInit(&g_myIdLock, NULL) != SOFTBUS_OK) { @@ -1038,6 +1067,18 @@ int32_t TransProxyManagerInit(const IServerChannelCallBack *cb) return SOFTBUS_ERR; } + if (SoftbusGetConfig(SOFTBUS_INT_AUTH_MAX_BYTES_LENGTH, + (unsigned char*)&g_authMaxByteBufSize, sizeof(g_authMaxByteBufSize)) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "get auth proxy channel max bytes length fail"); + } + + if (SoftbusGetConfig(SOFTBUS_INT_AUTH_MAX_MESSAGE_LENGTH, + (unsigned char*)&g_authMaxMessageBufSize, sizeof(g_authMaxMessageBufSize)) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "get auth proxy channel max message length fail"); + } + + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "proxy auth byteSize[%u], messageSize[%u]", + g_authMaxByteBufSize, g_authMaxMessageBufSize); SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, "proxy channel init ok"); return SOFTBUS_OK; } 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 7036be1d9..05a740455 100644 --- a/core/transmission/trans_channel/proxy/src/softbus_proxychannel_message.c +++ b/core/transmission/trans_channel/proxy/src/softbus_proxychannel_message.c @@ -198,9 +198,9 @@ static int32_t PackHandshakeMsgForNormal(SessionKeyBase64 *sessionBase64, AppInf char *TransProxyPackHandshakeMsg(ProxyChannelInfo *info) { - cJSON *root = 0; + cJSON *root = NULL; SessionKeyBase64 sessionBase64; - char *buf = 0; + char *buf = NULL; AppInfo *appInfo = &(info->appInfo); int32_t ret; @@ -214,38 +214,39 @@ char *TransProxyPackHandshakeMsg(ProxyChannelInfo *info) !AddStringToJsonObject(root, JSON_KEY_DEVICE_ID, appInfo->myData.deviceId) || !AddStringToJsonObject(root, JSON_KEY_SRC_BUS_NAME, appInfo->myData.sessionName) || !AddStringToJsonObject(root, JSON_KEY_DST_BUS_NAME, appInfo->peerData.sessionName)) { - cJSON_Delete(root); - return NULL; + goto EXIT; } (void)cJSON_AddTrueToObject(root, JSON_KEY_HAS_PRIORITY); if (appInfo->appType == APP_TYPE_NORMAL) { ret = PackHandshakeMsgForNormal(&sessionBase64, appInfo, root); if (ret != SOFTBUS_OK) { - cJSON_Delete(root); - return NULL; + goto EXIT; } } else if (appInfo->appType == APP_TYPE_AUTH) { + if (strlen(appInfo->reqId) == 0 && GenerateRandomStr(appInfo->reqId, REQ_ID_SIZE_MAX) != SOFTBUS_OK) { + goto EXIT; + } + if (!AddStringToJsonObject(root, JSON_KEY_REQUEST_ID, appInfo->reqId)) { + goto EXIT; + } if (!AddStringToJsonObject(root, JSON_KEY_PKG_NAME, appInfo->myData.pkgName)) { - cJSON_Delete(root); - return NULL; + goto EXIT; } } else { - ret = SoftBusBase64Encode((uint8_t *)sessionBase64.sessionKeyBase64, - sizeof(sessionBase64.sessionKeyBase64), &(sessionBase64.len), - (uint8_t *)appInfo->sessionKey, sizeof(appInfo->sessionKey)); + ret = SoftBusBase64Encode((uint8_t *)sessionBase64.sessionKeyBase64, sizeof(sessionBase64.sessionKeyBase64), + &(sessionBase64.len), (uint8_t *)appInfo->sessionKey, sizeof(appInfo->sessionKey)); if (ret != 0) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "mbedtls_base64_encode FAIL %d", ret); - cJSON_Delete(root); - return NULL; + goto EXIT; } if (!AddStringToJsonObject(root, JSON_KEY_SESSION_KEY, sessionBase64.sessionKeyBase64)) { - cJSON_Delete(root); - return NULL; + goto EXIT; } } buf = cJSON_PrintUnformatted(root); +EXIT: cJSON_Delete(root); return buf; } @@ -336,6 +337,20 @@ static int32_t UnpackHandshakeMsgForNormal(cJSON *root, AppInfo *appInfo, char * return SOFTBUS_OK; } +static int32_t TransProxyUnpackAuthHandshakeMsg(cJSON *root, AppInfo *appInfo) +{ + if (!GetJsonObjectStringItem(root, JSON_KEY_REQUEST_ID, appInfo->reqId, REQ_ID_SIZE_MAX)) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "Failed to get handshake msg REQUEST_ID"); + return SOFTBUS_ERR; + } + if (!GetJsonObjectStringItem(root, JSON_KEY_PKG_NAME, + appInfo->peerData.pkgName, sizeof(appInfo->peerData.pkgName))) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "Failed to get handshake msg pkgName"); + return SOFTBUS_ERR; + } + return SOFTBUS_OK; +} + int32_t TransProxyUnpackHandshakeMsg(const char *msg, ProxyChannelInfo *chan) { cJSON *root = cJSON_Parse(msg); @@ -367,9 +382,7 @@ int32_t TransProxyUnpackHandshakeMsg(const char *msg, ProxyChannelInfo *chan) return ret; } } else if (appInfo->appType == APP_TYPE_AUTH) { - if (!GetJsonObjectStringItem(root, JSON_KEY_PKG_NAME, - appInfo->peerData.pkgName, sizeof(appInfo->peerData.pkgName))) { - SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "Failed to get handshake msg"); + if (TransProxyUnpackAuthHandshakeMsg(root, appInfo) != SOFTBUS_OK) { cJSON_Delete(root); return SOFTBUS_ERR; } diff --git a/core/transmission/trans_channel/proxy/src/softbus_proxychannel_session.c b/core/transmission/trans_channel/proxy/src/softbus_proxychannel_session.c index df62c2798..ee7845cd4 100644 --- a/core/transmission/trans_channel/proxy/src/softbus_proxychannel_session.c +++ b/core/transmission/trans_channel/proxy/src/softbus_proxychannel_session.c @@ -250,7 +250,7 @@ int32_t TransProxyPostPacketData(int32_t channelId, const unsigned char *data, u { ProxyDataInfo packDataInfo = {0}; int32_t ret; - int32_t seq; + int32_t seq = 0; if (data == NULL) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "invalid para"); @@ -259,10 +259,29 @@ int32_t TransProxyPostPacketData(int32_t channelId, const unsigned char *data, u packDataInfo.inData = (unsigned char *)data; packDataInfo.inLen = len; - ret = TransProxyPackBytes(channelId, &packDataInfo, flags, &seq); - if (ret != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "PackBytes err"); - return ret; + ProxyChannelInfo *chanInfo = (ProxyChannelInfo *)SoftBusCalloc(sizeof(ProxyChannelInfo)); + if (chanInfo == NULL) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "malloc in TransProxyPostPacketData.id[%d]", channelId); + return SOFTBUS_MALLOC_ERR; + } + if (TransProxyGetSendMsgChanInfo(channelId, chanInfo) != SOFTBUS_OK) { + SoftBusFree(chanInfo); + return SOFTBUS_ERR; + } + AppType appType = chanInfo->appInfo.appType; + SoftBusFree(chanInfo); + if (appType != APP_TYPE_AUTH) { + ret = TransProxyPackBytes(channelId, &packDataInfo, flags, &seq); + if (ret != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "PackBytes err"); + return ret; + } + } else { + packDataInfo.outData = (uint8_t *)data; + packDataInfo.outLen = len; + if (flags == PROXY_FLAG_MESSAGE) { + flags = PROXY_FLAG_BYTES; + } } SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, "InLen[%d] seq[%d] outLen[%d] flags[%d]", len, seq, packDataInfo.outLen, flags); @@ -271,8 +290,9 @@ int32_t TransProxyPostPacketData(int32_t channelId, const unsigned char *data, u } else { ret = TransProxyTransDataSendMsg(channelId, (char *)packDataInfo.outData, packDataInfo.outLen, flags); } - - SoftBusFree(packDataInfo.outData); + if (appType != APP_TYPE_AUTH) { + SoftBusFree(packDataInfo.outData); + } return ret; } @@ -296,7 +316,10 @@ static char *TransProxyPackAppNormalMsg(const ProxyMessageHead *msg, const Slice int dstLen; connHeadLen = ConnGetHeadSize(); - bufLen = PROXY_CHANNEL_HEAD_LEN + connHeadLen + sizeof(SliceHead) + datalen; + bufLen = PROXY_CHANNEL_HEAD_LEN + connHeadLen + datalen; + if (sliceHead != NULL) { + bufLen += sizeof(SliceHead); + } buf = (char*)SoftBusCalloc(bufLen); if (buf == NULL) { return NULL; @@ -306,21 +329,55 @@ static char *TransProxyPackAppNormalMsg(const ProxyMessageHead *msg, const Slice SoftBusFree(buf); return NULL; } - dstLen = bufLen - connHeadLen - sizeof(ProxyMessageHead); - if (memcpy_s(buf + connHeadLen + sizeof(ProxyMessageHead), dstLen, sliceHead, sizeof(SliceHead)) != EOK) { - SoftBusFree(buf); - return NULL; - } - dstLen = bufLen - connHeadLen - MSG_SLICE_HEAD_LEN; - if (memcpy_s(buf + connHeadLen + MSG_SLICE_HEAD_LEN, dstLen, payLoad, datalen) != EOK) { - SoftBusFree(buf); - return NULL; + if (sliceHead != NULL) { + dstLen = bufLen - connHeadLen - sizeof(ProxyMessageHead); + if (memcpy_s(buf + connHeadLen + sizeof(ProxyMessageHead), dstLen, sliceHead, sizeof(SliceHead)) != EOK) { + SoftBusFree(buf); + return NULL; + } + dstLen = bufLen - connHeadLen - MSG_SLICE_HEAD_LEN; + if (memcpy_s(buf + connHeadLen + MSG_SLICE_HEAD_LEN, dstLen, payLoad, datalen) != EOK) { + SoftBusFree(buf); + return NULL; + } + } else { + dstLen = bufLen - connHeadLen - sizeof(ProxyMessageHead); + if (memcpy_s(buf + connHeadLen + sizeof(ProxyMessageHead), dstLen, payLoad, datalen) != EOK) { + SoftBusFree(buf); + return NULL; + } } *outlen = bufLen; return buf; } +static int32_t TransProxyTransAuthMsg(const ProxyChannelInfo *info, const char *payLoad, int payLoadLen, + ProxyPacketType flag) +{ + ProxyMessageHead msgHead = {0}; + msgHead.type = (PROXYCHANNEL_MSG_TYPE_NORMAL & FOUR_BIT_MASK) | (VERSION << VERSION_SHIFT); + msgHead.myId = info->myId; + msgHead.peerId = info->peerId; + char *buf = NULL; + int bufLen = 0; + buf = TransProxyPackAppNormalMsg(&msgHead, NULL, payLoad, payLoadLen, &bufLen); + if (buf == NULL) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "proxy pack msg error"); + return SOFTBUS_TRANS_PROXY_PACKMSG_ERR; + } + int32_t ret = TransProxyTransSendMsg(info->connId, buf, bufLen, ProxyTypeToConnPri(flag)); + if (ret == SOFTBUS_CONNECTION_ERR_SENDQUEUE_FULL) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "proxy send queue full!!"); + return SOFTBUS_CONNECTION_ERR_SENDQUEUE_FULL; + } + if (ret != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "proxy send msg error"); + return SOFTBUS_TRANS_PROXY_SENDMSG_ERR; + } + return SOFTBUS_OK; +} + static int32_t TransProxyTransAppNormalMsg(const ProxyChannelInfo *info, const char *payLoad, int payLoadLen, ProxyPacketType flag) { @@ -401,7 +458,11 @@ int32_t TransProxyTransDataSendMsg(int32_t channelId, const char *payLoad, int p ret = SOFTBUS_TRANS_PROXY_CHANNLE_STATUS_INVALID; goto EXIT; } - ret = TransProxyTransAppNormalMsg(info, payLoad, payLoadLen, flag); + if (info->appInfo.appType == APP_TYPE_AUTH) { + ret = TransProxyTransAuthMsg(info, payLoad, payLoadLen, flag); + } else { + ret = TransProxyTransAppNormalMsg(info, payLoad, payLoadLen, flag); + } if (ret != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "pack msg error"); goto EXIT; @@ -745,6 +806,28 @@ int32_t TransOnNormalMsgReceived(const char *pkgName, int32_t channelId, const c } } +int32_t TransOnAuthMsgReceived(const char *pkgName, int32_t channelId, const char *data, uint32_t len) +{ + if (data == NULL) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "data null."); + return SOFTBUS_ERR; + } + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, "AuthReceived inputLen[%d]", len); + + ProxyPacketType type = PROXY_FLAG_BYTES; + if (TransProxyAuthSessionDataLenCheck(len, type) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "data len is too large %d type %d", len, type); + return SOFTBUS_ERR; + } + + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, "Auth ProcessData debug: len %d \n", len); + if (TransProxyNotifySession(pkgName, channelId, type, 0, (const char *)data, len) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "Auth process data err"); + return SOFTBUS_ERR; + } + return SOFTBUS_OK; +} + int32_t TransProxyDelSliceProcessorByChannelId(int32_t channelId) { ChannelSliceProcessor *node = NULL; diff --git a/core/transmission/trans_channel/proxy/src/softbus_proxychannel_transceiver.c b/core/transmission/trans_channel/proxy/src/softbus_proxychannel_transceiver.c index a10065c80..11fad2694 100644 --- a/core/transmission/trans_channel/proxy/src/softbus_proxychannel_transceiver.c +++ b/core/transmission/trans_channel/proxy/src/softbus_proxychannel_transceiver.c @@ -502,6 +502,11 @@ static int32_t TransGetConn(const ConnectOption *connInfo, ProxyConnInfo *proxyC break; } case CONNECT_BLE: + if (strcmp(connInfo->info.bleOption.bleMac, item->connInfo.info.bleOption.bleMac) == 0) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "strcpy error"); + find = true; + } + break; default: break; } diff --git a/interfaces/kits/common/softbus_common.h b/interfaces/kits/common/softbus_common.h index 11958e44e..113ed8635 100644 --- a/interfaces/kits/common/softbus_common.h +++ b/interfaces/kits/common/softbus_common.h @@ -45,6 +45,7 @@ #ifndef SOFTBUS_CLIENT_COMMON_H #define SOFTBUS_CLIENT_COMMON_H +#include #include #ifdef __cplusplus @@ -99,6 +100,36 @@ extern "C" { */ #define MAX_ACCOUNT_HASH_LEN 96 +/** + * @brief Indicates the maximum length of the capability data in PublishInfo and SubscribeInfo. + * + */ +#define MAX_CAPABILITYDATA_LEN 513 + +/** + * @brief Indicates the maximum length of the custom data in IDiscoveryCallback. + * + */ +#define DISC_MAX_CUST_DATA_LEN 219 + +/** + * @brief Indicates the maximum number of capabilities contained in the bitmap in IDiscoveryCallback. + * + */ +#define DISC_MAX_CAPABILITY_NUM 2 + +/** + * @brief Indicates the maximum length of the device name in IDiscoveryCallback. + * + */ +#define DISC_MAX_DEVICE_NAME_LEN 65 + +/** + * @brief Indicates the maximum length of the device ID in IDiscoveryCallback. + * + */ +#define DISC_MAX_DEVICE_ID_LEN 96 + /** * @brief Enumerates {@link ConnectionAddr} types of a device that is added to a LNN. * @@ -144,6 +175,201 @@ typedef struct { } info; char peerUid[MAX_ACCOUNT_HASH_LEN]; } ConnectionAddr; + +/** + * @brief Enumerates the modes in which services are published. + * + */ +typedef enum { + /* Passive */ + DISCOVER_MODE_PASSIVE = 0x55, + /* Proactive */ + DISCOVER_MODE_ACTIVE = 0xAA +} DiscoverMode; + +/** + * @brief Enumerates media, such as Bluetooth, Wi-Fi, and USB, used for publishing services. + * + * Currently, only COAP is supported. + * When AUTO is selected, all the supported media will be called automatically. + */ +typedef enum { + /** Automatic medium selection */ + AUTO = 0, + /** Bluetooth */ + BLE = 1, + /** Wi-Fi */ + COAP = 2, + /** USB */ + USB = 3, + /** HiLink */ + COAP1 = 4, + MEDIUM_BUTT +} ExchanageMedium; + +/** + * @brief Enumerates frequencies for publishing services. + * + * This enumeration applies only to Bluetooth and is not supported currently. + */ +typedef enum { + /** Low */ + LOW = 0, + /** Medium */ + MID = 1, + /** High */ + HIGH = 2, + /** Super-high */ + SUPER_HIGH = 3, + FREQ_BUTT +} ExchangeFreq; + +/** + * @brief Enumerates supported capabilities published by a device. + * + */ +typedef enum { + /** MeeTime */ + HICALL_CAPABILITY_BITMAP = 0, + /** Video reverse connection in the smart domain */ + PROFILE_CAPABILITY_BITMAP = 1, + /** Gallery in Vision */ + HOMEVISIONPIC_CAPABILITY_BITMAP = 2, + /** cast+ */ + CASTPLUS_CAPABILITY_BITMAP, + /** Input method in Vision */ + AA_CAPABILITY_BITMAP, + /** Device virtualization tool package */ + DVKIT_CAPABILITY_BITMAP, + /** Distributed middleware */ + DDMP_CAPABILITY_BITMAP, + /** Osd capability */ + OSD_CAPABILITY_BITMAP +} DataBitMap; + +/** + * @brief Defines the mapping between supported capabilities and bitmaps. + * + */ +typedef struct { + /** Bitmaps. For details, see {@link DataBitMap}. */ + DataBitMap bitmap; + /** Capability. For details, see {@link g_capabilityMap}. */ + char *capability; +} CapabilityMap; + +/** + * @brief Defines the mapping between supported capabilities and bitmaps. + * + */ +static const CapabilityMap g_capabilityMap[] = { + {HICALL_CAPABILITY_BITMAP, (char *)"hicall"}, + {PROFILE_CAPABILITY_BITMAP, (char *)"profile"}, + {HOMEVISIONPIC_CAPABILITY_BITMAP, (char *)"homevisionPic"}, + {CASTPLUS_CAPABILITY_BITMAP, (char *)"castPlus"}, + {AA_CAPABILITY_BITMAP, (char *)"aaCapability"}, + {DVKIT_CAPABILITY_BITMAP, (char *)"dvKit"}, + {DDMP_CAPABILITY_BITMAP, (char *)"ddmpCapability"}, + {OSD_CAPABILITY_BITMAP, (char *)"osdCapability"}, +}; + +/** + * @brief Defines service publishing information. + * + */ +typedef struct { + /** Service ID */ + int publishId; + /** Discovery mode for service publishing. For details, see {@link Discovermode}. */ + DiscoverMode mode; + /** Service publishing medium. For details, see {@link ExchanageMedium}. */ + ExchanageMedium medium; + /** Service publishing frequency. For details, see {@link ExchangeFre}. */ + ExchangeFreq freq; + /** Service publishing capabilities. For details, see {@link g_capabilityMap}. */ + const char *capability; + /** Capability data for service publishing */ + unsigned char *capabilityData; + /** Maximum length of the capability data for service publishing (512 bytes) */ + unsigned int dataLen; +} PublishInfo; + +/** + * @brief Defines service subscription information. + * + */ +typedef struct { + /** Service ID */ + int subscribeId; + /** Discovery mode for service subscription. For details, see {@link Discovermode}. */ + DiscoverMode mode; + /** Service subscription medium. For details, see {@link ExchanageMedium}. */ + ExchanageMedium medium; + /** Service subscription frequency. For details, see {@link ExchangeFre}. */ + ExchangeFreq freq; + /** only find the device with the same account */ + bool isSameAccount; + /** find the sleeping devices */ + bool isWakeRemote; + /** Service subscription capability. For details, see {@link g_capabilityMap}. */ + const char *capability; + /** Capability data for service subscription */ + unsigned char *capabilityData; + /** Maximum length of the capability data for service subscription (512 bytes) */ + unsigned int dataLen; +} SubscribeInfo; + +/** + * @brief Enumerates device types. + * + */ +typedef enum { + /* Smart speaker */ + SMART_SPEAKER = 0x00, + /* PC */ + DESKTOP_PC, + /* Laptop */ + LAPTOP, + /* Mobile phone */ + SMART_PHONE, + /* Tablet */ + SMART_PAD, + /* Smart watch */ + SMART_WATCH, + /* Smart car */ + SMART_CAR, + /* Kids' watch */ + CHILDREN_WATCH, + /* Smart TV */ + SMART_TV, +} DeviceType; + +/** + * @brief Defines the device information returned by IDiscoveryCallback. + * + */ +typedef struct { + /** Device ID. Its maximum length is specified by {@link DISC_MAX_DEVICE_ID_LEN}. */ + char devId[DISC_MAX_DEVICE_ID_LEN]; + /** Account hash code. Its maximum length is specified by {@link MAX_ACCOUNT_HASH_LEN}. */ + char hwAccountHash[MAX_ACCOUNT_HASH_LEN]; + /** Device type. For details, see {@link DeviceType}. */ + DeviceType devType; + /** Device name. Its maximum length is specified by {@link DISC_MAX_DEVICE_NAME_LEN}. */ + char devName[DISC_MAX_DEVICE_NAME_LEN]; + /** Number of available connections */ + unsigned int addrNum; + /** Connection information. For details, see {@link ConnectAddr}. */ + ConnectionAddr addr[CONNECTION_ADDR_MAX]; + /** Number of capabilities */ + unsigned int capabilityBitmapNum; + /** Device capability bitmap. + * The maximum number of capabilities in the bitmap is specified by {@link DISC_MAX_CAPABILITY_NUM}. + */ + unsigned int capabilityBitmap[DISC_MAX_CAPABILITY_NUM]; + /** Custom data. Its length is specified by {@link DISC_MAX_CUST_DATA_LEN}. */ + char custData[DISC_MAX_CUST_DATA_LEN]; +} DeviceInfo; #ifdef __cplusplus } #endif diff --git a/interfaces/kits/discovery/discovery_service.h b/interfaces/kits/discovery/discovery_service.h index 6f99233e9..6df0583f8 100644 --- a/interfaces/kits/discovery/discovery_service.h +++ b/interfaces/kits/discovery/discovery_service.h @@ -16,8 +16,6 @@ #ifndef DISCOVERY_SERVICE_H #define DISCOVERY_SERVICE_H -#include - #include "softbus_common.h" #ifdef __cplusplus @@ -26,109 +24,12 @@ extern "C" { #endif #endif -/** - * @brief Indicates the maximum length of the capability data in PublishInfo and SubscribeInfo. - * - */ -#define MAX_CAPABILITYDATA_LEN 513 - -/** - * @brief Indicates the maximum length of the device ID in IDiscoveryCallback. - * - */ -#define DISC_MAX_DEVICE_ID_LEN 96 - -/** - * @brief Indicates the maximum length of the device name in IDiscoveryCallback. - * - */ -#define DISC_MAX_DEVICE_NAME_LEN 65 - -/** - * @brief Indicates the maximum length of the custom data in IDiscoveryCallback. - * - */ -#define DISC_MAX_CUST_DATA_LEN 219 - -/** - * @brief Indicates the maximum number of capabilities contained in the bitmap in IDiscoveryCallback. - * - */ -#define DISC_MAX_CAPABILITY_NUM 2 - /** * @brief Indicates the maximum length of the device address in IDiscoveryCallback. * */ #define CONNECT_ADDR_LEN 46 -/** - * @brief Enumerates the modes in which services are published. - * - */ -typedef enum { - /* Passive */ - DISCOVER_MODE_PASSIVE = 0x55, - /* Proactive */ - DISCOVER_MODE_ACTIVE = 0xAA -} DiscoverMode; - -/** - * @brief Enumerates media, such as Bluetooth, Wi-Fi, and USB, used for publishing services. - * - * Currently, only COAP is supported. - * When AUTO is selected, all the supported media will be called automatically. - */ -typedef enum { - /** Automatic medium selection */ - AUTO = 0, - /** Bluetooth */ - BLE = 1, - /** Wi-Fi */ - COAP = 2, - /** USB */ - USB = 3, - MEDIUM_BUTT -} ExchanageMedium; - -/** - * @brief Enumerates frequencies for publishing services. - * - * This enumeration applies only to Bluetooth and is not supported currently. - */ -typedef enum { - /** Low */ - LOW = 0, - /** Medium */ - MID = 1, - /** High */ - HIGH = 2, - /** Super-high */ - SUPER_HIGH = 3, - FREQ_BUTT -} ExchangeFreq; - -/** - * @brief Defines service publishing information. - * - */ -typedef struct { - /** Service ID */ - int publishId; - /** Discovery mode for service publishing. For details, see {@link Discovermode}. */ - DiscoverMode mode; - /** Service publishing medium. For details, see {@link ExchanageMedium}. */ - ExchanageMedium medium; - /** Service publishing frequency. For details, see {@link ExchangeFre}. */ - ExchangeFreq freq; - /** Service publishing capabilities. For details, see {@link g_capabilityMap}. */ - const char *capability; - /** Capability data for service publishing */ - unsigned char *capabilityData; - /** Maximum length of the capability data for service publishing (512 bytes) */ - unsigned int dataLen; -} PublishInfo; - /** * @brief Enumerates error codes for service publishing failures. * @@ -155,80 +56,6 @@ typedef struct { void (*OnPublishFail)(int publishId, PublishFailReason reason); } IPublishCallback; -/** - * @brief Enumerates supported capabilities published by a device. - * - */ -typedef enum { - /** MeeTime */ - HICALL_CAPABILITY_BITMAP = 0, - /** Video reverse connection in the smart domain */ - PROFILE_CAPABILITY_BITMAP = 1, - /** Gallery in Vision */ - HOMEVISIONPIC_CAPABILITY_BITMAP = 2, - /** cast+ */ - CASTPLUS_CAPABILITY_BITMAP, - /** Input method in Vision */ - AA_CAPABILITY_BITMAP, - /** Device virtualization tool package */ - DVKIT_CAPABILITY_BITMAP, - /** Distributed middleware */ - DDMP_CAPABILITY_BITMAP, - /** Osd capability */ - OSD_CAPABILITY_BITMAP -} DataBitMap; - -/** - * @brief Defines the mapping between supported capabilities and bitmaps. - * - */ -typedef struct { - /** Bitmaps. For details, see {@link DataBitMap}. */ - DataBitMap bitmap; - /** Capability. For details, see {@link g_capabilityMap}. */ - char *capability; -} CapabilityMap; - -/** - * @brief Defines the mapping between supported capabilities and bitmaps. - * - */ -static const CapabilityMap g_capabilityMap[] = { - {HICALL_CAPABILITY_BITMAP, (char *)"hicall"}, - {PROFILE_CAPABILITY_BITMAP, (char *)"profile"}, - {HOMEVISIONPIC_CAPABILITY_BITMAP, (char *)"homevisionPic"}, - {CASTPLUS_CAPABILITY_BITMAP, (char *)"castPlus"}, - {AA_CAPABILITY_BITMAP, (char *)"aaCapability"}, - {DVKIT_CAPABILITY_BITMAP, (char *)"dvKit"}, - {DDMP_CAPABILITY_BITMAP, (char *)"ddmpCapability"}, - {OSD_CAPABILITY_BITMAP, (char *)"osdCapability"}, -}; - -/** - * @brief Defines service subscription information. - * - */ -typedef struct { - /** Service ID */ - int subscribeId; - /** Discovery mode for service subscription. For details, see {@link Discovermode}. */ - DiscoverMode mode; - /** Service subscription medium. For details, see {@link ExchanageMedium}. */ - ExchanageMedium medium; - /** Service subscription frequency. For details, see {@link ExchangeFre}. */ - ExchangeFreq freq; - /** only find the device with the same account */ - bool isSameAccount; - /** find the sleeping devices */ - bool isWakeRemote; - /** Service subscription capability. For details, see {@link g_capabilityMap}. */ - const char *capability; - /** Capability data for service subscription */ - unsigned char *capabilityData; - /** Maximum length of the capability data for service subscription (512 bytes) */ - unsigned int dataLen; -} SubscribeInfo; - /** * @brief Enumerates error codes for service subscription failures. * @@ -244,33 +71,6 @@ typedef enum { DISCOVERY_FAIL_REASON_UNKNOWN = 0xFF } DiscoveryFailReason; -/** - * @brief Defines the device information returned by IDiscoveryCallback. - * - */ -typedef struct { - /** Device ID. Its maximum length is specified by {@link DISC_MAX_DEVICE_ID_LEN}. */ - char devId[DISC_MAX_DEVICE_ID_LEN]; - /** Account hash code. Its maximum length is specified by {@link MAX_ACCOUNT_HASH_LEN}. */ - char hwAccountHash[MAX_ACCOUNT_HASH_LEN]; - /** Device type. For details, see {@link DeviceType}. */ - unsigned int devType; - /** Device name. Its maximum length is specified by {@link DISC_MAX_DEVICE_NAME_LEN}. */ - char devName[DISC_MAX_DEVICE_NAME_LEN]; - /** Number of available connections */ - unsigned int addrNum; - /** Connection information. For details, see {@link ConnectAddr}. */ - ConnectionAddr addr[CONNECTION_ADDR_MAX]; - /** Number of capabilities */ - unsigned int capabilityBitmapNum; - /** Device capability bitmap. - * The maximum number of capabilities in the bitmap is specified by {@link DISC_MAX_CAPABILITY_NUM}. - */ - unsigned int capabilityBitmap[DISC_MAX_CAPABILITY_NUM]; - /** Custom data. Its length is specified by {@link DISC_MAX_CUST_DATA_LEN}. */ - char custData[DISC_MAX_CUST_DATA_LEN]; -} DeviceInfo; - /** * @brief Defines a callback for service subscription. * diff --git a/interfaces/kits/transport/session.h b/interfaces/kits/transport/session.h index 68929d2d2..438c3f229 100644 --- a/interfaces/kits/transport/session.h +++ b/interfaces/kits/transport/session.h @@ -93,7 +93,7 @@ typedef enum { /** * @brief session attribute. * - * control the attribute of session + * control the attribute of session. * * @since 1.0 * @version 1.0 @@ -144,9 +144,63 @@ typedef enum { QOS_EVENT_MAX } QosEvent; +typedef enum { + WIFI_CHANNEL_QUALITY = 1, + FRAME_REALTIME_STATUS = 2, + BANDWIDTH_ESTIMATE_VALUE = 3, + JITTER_DETECTION_VALUE = 4, + STREAM_TRAFFIC_STASTICS = 5, +} TransEnumEventType; + typedef struct { - int type; - void *value; + int32_t channel; + int32_t score; +} WifiChannelQuality; + +typedef struct { + int32_t streamId; + int32_t seqNum; + int32_t level; + int32_t transStatus; + int32_t interval; +} FrameStatus; + +typedef struct { + uint32_t trend; + uint32_t rate; /* kbps */ +} BandwidthDetection; + +typedef struct { + int32_t jitterLevel; + uint32_t bufferTime; /* ms */ +} JitterEstimation; + +typedef struct { + uint64_t statisticsGotTime; /* time point that stream traficc statistics are obtained (ms) */ + uint64_t periodRecvBits; + uint32_t pktNum; + uint32_t periodRecvPkts; + uint32_t periodRecvPktLoss; + uint32_t periodRecvRate; /* kbps */ + uint64_t periodRecvRateBps; /* bps */ + uint32_t periodRtt; /* ms */ + uint32_t periodRecvPktLossHighPrecision; /* for example when lost rate is 1.10%, then 110 will returned */ + uint32_t periodSendLostPkts; + uint32_t periodSendPkts; + uint32_t periodSendPktLossHighPrecision; /* for example when lost rate is 1.10%, then 110 will returned */ + uint64_t periodSendBits; + uint64_t periodSendRateBps; /* bps */ +} StreamStatistics; + +typedef struct { + TransEnumEventType type; + union { + WifiChannelQuality wifiChannelInfo; + FrameStatus frameStatusInfo; + BandwidthDetection bandwidthInfo; + JitterEstimation jitterInfo; + StreamStatistics appStatistics; + } info; } QosTv; /** @@ -213,6 +267,18 @@ typedef struct { void (*OnStreamReceived)(int sessionId, const StreamData *data, const StreamData *ext, const StreamFrameInfo *param); + /** + * @brief Called when QoS information is retrieved. + * + * This function is used to notify that QoS information is retrieved. + * + * @param sessionId Indicates the session ID. + * @param eventId Indicates the type of QoS information, e.g., channel quality and stream quality + * @param tvCount Indicates the number of structure returned in the fourth parameters, i.e., tvList. + * @param tvList Indicates the detailed information of data transmission. + * @since 1.0 + * @version 1.0 + */ void (*OnQosEvent)(int sessionId, int eventId, int tvCount, const QosTv *tvList); } ISessionListener; diff --git a/sdk/frame/small/src/bus_center_client_stub.c b/sdk/frame/small/src/bus_center_client_stub.c index 8adede521..8ee6fe1aa 100644 --- a/sdk/frame/small/src/bus_center_client_stub.c +++ b/sdk/frame/small/src/bus_center_client_stub.c @@ -16,7 +16,9 @@ #include "bus_center_client_stub.h" #include + #include "client_bus_center_manager.h" +#include "liteipc_adapter.h" #include "softbus_errcode.h" #include "softbus_log.h" diff --git a/sdk/frame/standard/src/softbus_server_proxy_frame.cpp b/sdk/frame/standard/src/softbus_server_proxy_frame.cpp index 744c3fea8..b2a8cd127 100644 --- a/sdk/frame/standard/src/softbus_server_proxy_frame.cpp +++ b/sdk/frame/standard/src/softbus_server_proxy_frame.cpp @@ -58,12 +58,11 @@ static int InnerRegisterService(void) SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "get client name failed"); return SOFTBUS_ERR; } - int ret = serverProxyFrame->SoftbusRegisterService(clientName, nullptr); - if (ret != SOFTBUS_OK) { - SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "ServerIpcRegisterService failed!\n"); - return ret; + while (serverProxyFrame->SoftbusRegisterService(clientName, nullptr) != SOFTBUS_OK) { + SoftBusSleepMs(WAIT_SERVER_READY_INTERVAL); + continue; } - ret = ReCreateSessionServerToServer(); + int32_t ret = ReCreateSessionServerToServer(); if (ret != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_COMM, SOFTBUS_LOG_ERROR, "ReCreateSessionServerToServer failed!\n"); return ret; diff --git a/sdk/transmission/session/include/client_trans_session_manager.h b/sdk/transmission/session/include/client_trans_session_manager.h index e143381af..f64c164a8 100644 --- a/sdk/transmission/session/include/client_trans_session_manager.h +++ b/sdk/transmission/session/include/client_trans_session_manager.h @@ -45,6 +45,7 @@ typedef struct { bool isEnable; int32_t peerUid; int32_t peerPid; + bool isEncrypt; } SessionInfo; typedef struct { @@ -90,6 +91,8 @@ int32_t ClientGetChannelBySessionId(int32_t sessionId, int32_t *channelId, int32 int32_t ClientSetChannelBySessionId(int32_t sessionId, TransInfo *transInfo); +int32_t GetEncryptByChannelId(int32_t channelId, int32_t channelType, int32_t *data); + int32_t ClientGetSessionIdByChannelId(int32_t channelId, int32_t channelType, int32_t *sessionId); int32_t ClientEnableSessionByChannelId(const ChannelInfo *channel, int32_t *sessionId); diff --git a/sdk/transmission/session/src/client_trans_session_manager.c b/sdk/transmission/session/src/client_trans_session_manager.c index 3372a53b6..1161b9589 100644 --- a/sdk/transmission/session/src/client_trans_session_manager.c +++ b/sdk/transmission/session/src/client_trans_session_manager.c @@ -297,6 +297,7 @@ static SessionInfo *CreateNewSession(const SessionParam *param) session->isServer = false; session->isEnable = false; session->info.flag = param->attr->dataType; + session->isEncrypt = true; return session; } @@ -447,6 +448,7 @@ static SessionInfo *CreateNonEncryptSessionInfo(const char *sessionName) return NULL; } session->channelType = CHANNEL_TYPE_AUTH; + session->isEncrypt = false; if (strcpy_s(session->info.peerSessionName, SESSION_NAME_SIZE_MAX, sessionName) != EOK) { SoftBusFree(session); return NULL; @@ -715,6 +717,45 @@ int32_t ClientSetChannelBySessionId(int32_t sessionId, TransInfo *transInfo) return SOFTBUS_OK; } +int32_t GetEncryptByChannelId(int32_t channelId, int32_t channelType, int32_t *data) +{ + if ((channelId < 0) || (data == NULL)) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "Invalid param"); + return SOFTBUS_INVALID_PARAM; + } + + if (g_clientSessionServerList == NULL) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "not init"); + return SOFTBUS_ERR; + } + + ClientSessionServer *serverNode = NULL; + SessionInfo *sessionNode = NULL; + + if (SoftBusMutexLock(&(g_clientSessionServerList->lock)) != 0) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "lock failed"); + return SOFTBUS_ERR; + } + + 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 && (int32_t)sessionNode->channelType == channelType) { + *data = (int32_t)sessionNode->isEncrypt; + (void)SoftBusMutexUnlock(&(g_clientSessionServerList->lock)); + return SOFTBUS_OK; + } + } + } + + (void)SoftBusMutexUnlock(&(g_clientSessionServerList->lock)); + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "not found session with channelId [%d]", channelId); + return SOFTBUS_ERR; +} + int32_t ClientGetSessionIdByChannelId(int32_t channelId, int32_t channelType, int32_t *sessionId) { if ((channelId < 0) || (sessionId == NULL)) { @@ -787,7 +828,7 @@ int32_t ClientEnableSessionByChannelId(const ChannelInfo *channel, int32_t *sess sessionNode->isServer = channel->isServer; sessionNode->isEnable = true; *sessionId = sessionNode->sessionId; - if (channel->channelType == CHANNEL_TYPE_AUTH) { + if (channel->channelType == CHANNEL_TYPE_AUTH || !sessionNode->isEncrypt) { if (memcpy_s(sessionNode->info.peerDeviceId, DEVICE_ID_SIZE_MAX, channel->peerDeviceId, DEVICE_ID_SIZE_MAX) != EOK) { (void)SoftBusMutexUnlock(&g_clientSessionServerList->lock); diff --git a/sdk/transmission/session/src/client_trans_session_service.c b/sdk/transmission/session/src/client_trans_session_service.c index 9d3d6ac53..e7ca3e3f0 100644 --- a/sdk/transmission/session/src/client_trans_session_service.c +++ b/sdk/transmission/session/src/client_trans_session_service.c @@ -316,7 +316,11 @@ int OpenAuthSession(const char *sessionName, const ConnectionAddr *addrInfo, int } transInfo.channelId = ServerIpcOpenAuthSession(sessionName, addr); - transInfo.channelType = CHANNEL_TYPE_AUTH; + if (addr->type == CONNECTION_ADDR_BR || addr->type == CONNECTION_ADDR_BLE) { + transInfo.channelType = CHANNEL_TYPE_PROXY; + } else { + transInfo.channelType = CHANNEL_TYPE_AUTH; + } ret = ClientSetChannelBySessionId(sessionId, &transInfo); if (ret != SOFTBUS_OK) { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "OpenAuthSession failed"); diff --git a/sdk/transmission/trans_channel/proxy/src/client_trans_proxy_manager.c b/sdk/transmission/trans_channel/proxy/src/client_trans_proxy_manager.c index 97a07fbe5..d6d20699b 100644 --- a/sdk/transmission/trans_channel/proxy/src/client_trans_proxy_manager.c +++ b/sdk/transmission/trans_channel/proxy/src/client_trans_proxy_manager.c @@ -14,12 +14,16 @@ */ #include "client_trans_proxy_manager.h" +#include "client_trans_session_manager.h" #include "softbus_errcode.h" +#include "softbus_feature_config.h" #include "softbus_log.h" #include "trans_server_proxy.h" static IClientSessionCallBack g_sessionCb; +static uint32_t g_authMaxByteBufSize; +static uint32_t g_authMaxMessageBufSize; int32_t ClinetTransProxyInit(const IClientSessionCallBack *cb) { @@ -28,6 +32,16 @@ int32_t ClinetTransProxyInit(const IClientSessionCallBack *cb) } g_sessionCb = *cb; + if (SoftbusGetConfig(SOFTBUS_INT_AUTH_MAX_BYTES_LENGTH, + (unsigned char*)&g_authMaxByteBufSize, sizeof(g_authMaxByteBufSize)) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "get auth proxy channel max bytes length fail"); + } + if (SoftbusGetConfig(SOFTBUS_INT_AUTH_MAX_MESSAGE_LENGTH, + (unsigned char*)&g_authMaxMessageBufSize, sizeof(g_authMaxMessageBufSize)) != SOFTBUS_OK) { + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_ERROR, "get auth proxy channel max message length fail"); + } + SoftBusLog(SOFTBUS_LOG_CONN, SOFTBUS_LOG_INFO, "proxy auth byteSize[%u], messageSize[%u]", + g_authMaxByteBufSize, g_authMaxMessageBufSize); return SOFTBUS_OK; } @@ -92,10 +106,21 @@ void ClientTransProxyCloseChannel(int32_t channelId) int32_t TransProxyChannelSendBytes(int32_t channelId, const void *data, uint32_t len) { #define PROXY_MAX_BYTES_LEN (4 * 1024) - if (len > PROXY_MAX_BYTES_LEN) { - return SOFTBUS_TRANS_INVALID_DATA_LENGTH; + int32_t encryp = 0; + int32_t ret = GetEncryptByChannelId(channelId, CHANNEL_TYPE_PROXY, &encryp); + if (ret != SOFTBUS_OK) { + return SOFTBUS_ERR; } - int ret = ServerIpcSendMessage(channelId, CHANNEL_TYPE_PROXY, data, len, TRANS_SESSION_BYTES); + if (encryp == 1) { + if (len > PROXY_MAX_BYTES_LEN) { + return SOFTBUS_TRANS_INVALID_DATA_LENGTH; + } + } else { + if (len > g_authMaxByteBufSize) { + return SOFTBUS_TRANS_INVALID_DATA_LENGTH; + } + } + ret = ServerIpcSendMessage(channelId, CHANNEL_TYPE_PROXY, data, len, TRANS_SESSION_BYTES); SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, "send bytes: channelId=%d, ret=%d", channelId, ret); return ret; } @@ -103,10 +128,21 @@ int32_t TransProxyChannelSendBytes(int32_t channelId, const void *data, uint32_t int32_t TransProxyChannelSendMessage(int32_t channelId, const void *data, uint32_t len) { #define PROXY_MAX_MESSAGE_LEN (1 * 1024) - if (len > PROXY_MAX_MESSAGE_LEN) { - return SOFTBUS_TRANS_INVALID_DATA_LENGTH; + int32_t encryp = 0; + int32_t ret = GetEncryptByChannelId(channelId, CHANNEL_TYPE_PROXY, &encryp); + if (ret != SOFTBUS_OK) { + return SOFTBUS_ERR; } - int ret = ServerIpcSendMessage(channelId, CHANNEL_TYPE_PROXY, data, len, TRANS_SESSION_MESSAGE); + if (encryp == 1) { + if (len > PROXY_MAX_MESSAGE_LEN) { + return SOFTBUS_TRANS_INVALID_DATA_LENGTH; + } + } else { + if (len > g_authMaxMessageBufSize) { + return SOFTBUS_TRANS_INVALID_DATA_LENGTH; + } + } + ret = ServerIpcSendMessage(channelId, CHANNEL_TYPE_PROXY, data, len, TRANS_SESSION_MESSAGE); SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, "send msg: channelId=%d, ret=%d", channelId, ret); return ret; } 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 63814e3e8..a927e0617 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 @@ -14,6 +14,7 @@ */ #include "client_trans_tcp_direct_message.h" + #include #include diff --git a/sdk/transmission/trans_channel/udp/common/include/client_trans_udp_manager.h b/sdk/transmission/trans_channel/udp/common/include/client_trans_udp_manager.h index 0784f05ac..3373ba1b7 100644 --- a/sdk/transmission/trans_channel/udp/common/include/client_trans_udp_manager.h +++ b/sdk/transmission/trans_channel/udp/common/include/client_trans_udp_manager.h @@ -33,6 +33,7 @@ typedef struct { void (*OnMessageReceived)(void); void (*OnUdpChannelOpened)(int32_t channelId); void (*OnUdpChannelClosed)(int32_t channelId); + void (*OnQosEvent)(int channelId, int eventId, int tvCount, const QosTv *tvList); } UdpChannelMgrCb; typedef struct { 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 269accae1..f81a382a1 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,12 +368,21 @@ static int32_t OnFileGetSessionId(int32_t channelId, int32_t *sessionId) return g_sessionCb->OnGetSessionId(channelId, CHANNEL_TYPE_UDP, sessionId); } +static void OnQosEvent(int channelId, int eventId, int tvCount, const QosTv *tvList) +{ + if ((g_sessionCb == NULL) || (g_sessionCb->OnQosEvent == NULL)) { + return; + } + g_sessionCb->OnQosEvent(channelId, CHANNEL_TYPE_UDP, eventId, tvCount, tvList); +} + static UdpChannelMgrCb g_udpChannelCb = { .OnUdpChannelOpened = OnUdpChannelOpened, .OnUdpChannelClosed = OnUdpChannelClosed, .OnFileGetSessionId = OnFileGetSessionId, .OnMessageReceived = NULL, .OnStreamReceived = OnStreamReceived, + .OnQosEvent = OnQosEvent, }; int32_t ClientTransUdpMgrInit(IClientSessionCallBack *callback) 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 96c223ca0..06bf35539 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 @@ -45,6 +45,7 @@ typedef struct { void (*OnStatusChange)(int32_t channelId, int32_t newStatus); void (*OnStreamReceived)(int32_t channelId, const StreamData *data, const StreamData *ext, const StreamFrameInfo *param); + void (*OnQosEvent)(int32_t channelId, int32_t eventId, int32_t tvCount, const QosTv *tvList); } IStreamListener; typedef struct { @@ -60,8 +61,7 @@ int32_t StartVtpStreamChannelServer(int32_t channelId, const VtpStreamOpenParam const IStreamListener *callback); int32_t StartVtpStreamChannelClient(int32_t channelId, const VtpStreamOpenParam *param, const IStreamListener *callback); -int32_t SendVtpStream(int32_t channelId, const StreamData *data, const StreamData *ext, - const StreamFrameInfo *param); +int32_t SendVtpStream(int32_t channelId, const StreamData *data, const StreamData *ext, const StreamFrameInfo *param); int32_t CloseVtpStreamChannel(int32_t channelId, const char *pkgName); #ifdef __cplusplus diff --git a/sdk/transmission/trans_channel/udp/stream/adaptor/include/stream_adaptor_listener.h b/sdk/transmission/trans_channel/udp/stream/adaptor/include/stream_adaptor_listener.h index 244ab58e0..b256016dc 100644 --- a/sdk/transmission/trans_channel/udp/stream/adaptor/include/stream_adaptor_listener.h +++ b/sdk/transmission/trans_channel/udp/stream/adaptor/include/stream_adaptor_listener.h @@ -81,6 +81,18 @@ public: } } + void OnQosEvent(int32_t eventId, int32_t tvCount, const QosTv *tvList) + { + if (adaptor_->GetListenerCallback() != nullptr && adaptor_->GetListenerCallback()->OnQosEvent != nullptr) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, "StreamAdaptorListener: OnQosEvent for channelId = %ld", + adaptor_->GetChannelId()); + adaptor_->GetListenerCallback()->OnQosEvent(adaptor_->GetChannelId(), eventId, tvCount, tvList); + } else { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, + "Get ListenerCallback by StreamAdaptor is failed, channelId = %ld", adaptor_->GetChannelId()); + } + } + private: std::shared_ptr adaptor_ = nullptr; }; 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 64b0bdc22..1b138593f 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 @@ -23,6 +23,7 @@ #include #include "i_stream.h" +#include "session.h" #include "stream_common.h" namespace Communication { @@ -35,6 +36,7 @@ public: virtual void OnStreamReceived(std::unique_ptr stream) = 0; virtual void OnStreamStatus(int status) = 0; virtual int OnStreamHdrReceived(std::unique_ptr header, int size) = 0; + virtual void OnQosEvent(int32_t eventId, int32_t tvCount, const QosTv *tvList) const = 0; }; class IStreamSocket { diff --git a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/include/i_stream.h b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/include/i_stream.h index 3bb1cc2ff..9761912df 100644 --- a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/include/i_stream.h +++ b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/include/i_stream.h @@ -49,8 +49,8 @@ public: static std::unique_ptr MakeCommonStream(StreamData &data, const StreamFrameInfo &info); static std::unique_ptr MakeSliceStream(StreamData &data, const StreamFrameInfo &info); static std::unique_ptr MakeRawStream(StreamData &data, const StreamFrameInfo &info); - static std::unique_ptr MakeRawStream(const char *buf, ssize_t bufLen, - const StreamFrameInfo &info, int scene); + static std::unique_ptr MakeRawStream(const char *buf, ssize_t bufLen, const StreamFrameInfo &info, + int scene); virtual void SetTimeStamp(uint32_t timestamp) = 0; virtual uint32_t GetTimeStamp() const = 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 fb0ea5479..60fd2c8df 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 @@ -20,6 +20,7 @@ #include "i_stream.h" #include "i_stream_msg_manager.h" +#include "session.h" #include "stream_common.h" namespace Communication { @@ -30,6 +31,7 @@ public: virtual ~IStreamManagerListener() = default; virtual void OnStreamReceived(std::unique_ptr stream) = 0; virtual void OnStreamStatus(int status) = 0; + virtual void OnQosEvent(int32_t eventId, int32_t tvCount, const QosTv *tvList) = 0; }; class IStreamManager { 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 180bebb08..1b7993f3f 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 @@ -14,12 +14,27 @@ import("//foundation/communication/dsoftbus/dsoftbus.gni") libsoftbus_stream_sdk_path = "$dsoftbus_root_path/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream" +dstream_native_source_path = rebase_path("$dsoftbus_root_path") +dstream_dep_file = "components/nstackx_enhanced/fillp/BUILD.gn" +enhanced = exec_script( + "$dsoftbus_root_path/run_shell_cmd.py", + [ "cd $dstream_native_source_path; if [ -f $dstream_dep_file ]; then echo true; else echo false; fi" ], + "value") + libsoftbus_stream_inc = [ "$libsoftbus_stream_sdk_path/include", - "$dsoftbus_root_path/components/nstackx_enhanced/fillp/include/", "//third_party/cJSON", "//third_party/openssl/include", ] + +if (enhanced) { + libsoftbus_stream_inc += + [ "$dsoftbus_root_path/components/nstackx_enhanced/fillp/include/" ] +} else { + libsoftbus_stream_inc += + [ "$dsoftbus_root_path/components/nstackx/fillp/include/" ] +} + libsoftbus_stream_src = [ "$libsoftbus_stream_sdk_path/raw_stream_data.cpp", "$libsoftbus_stream_sdk_path/stream_common_data.cpp", @@ -30,12 +45,25 @@ libsoftbus_stream_src = [ "$libsoftbus_stream_sdk_path/vtp_instance.cpp", "$libsoftbus_stream_sdk_path/vtp_stream_socket.cpp", ] + if (defined(ohos_lite)) { - libsoftbus_stream_deps = - [ "$dsoftbus_root_path/components/nstackx_enhanced/fillp:FillpSo" ] + if (enhanced) { + libsoftbus_stream_deps = + [ "$dsoftbus_root_path/components/nstackx_enhanced/fillp:FillpSo" ] + } else { + libsoftbus_stream_deps = + [ "$dsoftbus_root_path/components/nstackx/fillp:FillpSo.open" ] + } } else { - libsoftbus_stream_deps = [ - "$dsoftbus_root_path/components/nstackx_enhanced/fillp:FillpSo", - "//utils/native/base:utilsecurec_shared", - ] + if (enhanced) { + libsoftbus_stream_deps = [ + "$dsoftbus_root_path/components/nstackx_enhanced/fillp:FillpSo", + "//utils/native/base:utilsecurec_shared", + ] + } else { + libsoftbus_stream_deps = [ + "$dsoftbus_root_path/components/nstackx/fillp:FillpSo.open", + "//utils/native/base:utilsecurec_shared", + ] + } } diff --git a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_common_data.cpp b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_common_data.cpp index b570932ef..0d96b6d52 100644 --- a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_common_data.cpp +++ b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_common_data.cpp @@ -13,8 +13,8 @@ * limitations under the License. */ - #include "stream_common_data.h" + #include "common_inner.h" namespace Communication { 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 e2a415389..237bf3f48 100644 --- a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_manager.cpp +++ b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_manager.cpp @@ -15,6 +15,7 @@ #include "stream_manager.h" +#include "session.h" #include "vtp_stream_socket.h" namespace Communication { 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 c301d52ec..d3afc2c9d 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 @@ -25,6 +25,7 @@ #include "i_stream_manager.h" #include "i_stream_msg_manager.h" #include "i_stream_socket.h" +#include "session.h" #include "stream_common.h" namespace Communication { @@ -53,6 +54,11 @@ public: return 0; } + void OnQosEvent(int32_t eventId, int32_t tvCount, const QosTv *tvList) const override + { + listener_->OnQosEvent(eventId, tvCount, tvList); + } + private: std::shared_ptr listener_ = nullptr; }; @@ -63,8 +69,10 @@ public: int CreateStreamClientChannel(IpAndPort &local, IpAndPort remote, Proto protocol, int streamType, const std::string &sessionKey) override; + int CreateStreamServerChannel(IpAndPort &local, Proto protocol, int streamType, const std::string &sessionKey) override; + bool DestroyStreamDataChannel() override; bool Send(std::unique_ptr data) override; diff --git a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_packet_header.h b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_packet_header.h index fe6d80db9..f668b84e1 100644 --- a/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_packet_header.h +++ b/sdk/transmission/trans_channel/udp/stream/libsoftbus_stream/stream_packet_header.h @@ -64,7 +64,7 @@ struct CommonHeader { struct TypeLength { uint16_t type = 0; - uint16_t length = 0; + uint32_t length = 0; }; class TwoLevelsTlv { 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 f5ec88ab6..81c424be0 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 @@ -15,15 +15,18 @@ #include "vtp_stream_socket.h" +#include #include #include #include #include #include +#include #include #include "fillpinc.h" #include "raw_stream_data.h" +#include "session.h" #include "softbus_adapter_crypto.h" #include "softbus_errcode.h" #include "softbus_log.h" @@ -33,6 +36,10 @@ namespace Communication { namespace SoftBus { bool g_logOn = false; +const int FEED_BACK_PERIOD = 1; /* feedback period of fillp stream traffic statistics is 1s */ +const int MS_PER_SECOND = 1000; +const int US_PER_MS = 1000; + namespace { void PrintOptionInfo(int type, const StreamAttr &value) { @@ -57,6 +64,52 @@ void PrintOptionInfo(int type, const StreamAttr &value) } // namespace std::shared_ptr VtpStreamSocket::vtpInstance_ = VtpInstance::GetVtpInstance(); +std::map VtpStreamSocket::g_streamSocketLockMap; +std::map> VtpStreamSocket::g_streamReceiverMap; + +void VtpStreamSocket::AddStreamSocketLock(int fd, std::mutex &streamsocketlock) +{ + if (!g_streamSocketLockMap.empty() && g_streamSocketLockMap.find(fd) != g_streamSocketLockMap.end()) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "streamsocketlock for fd = %d already exists", fd); + return; + } + + g_streamSocketLockMap.emplace(std::pair(fd, streamsocketlock)); +} + +void VtpStreamSocket::AddStreamSocketListener(int fd, std::shared_ptr streamreceiver) +{ + if (!g_streamReceiverMap.empty() && g_streamReceiverMap.find(fd) != g_streamReceiverMap.end()) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "streamreceiver for fd = %d already exists", fd); + return; + } + + g_streamReceiverMap.emplace(std::pair>(fd, streamreceiver)); +} + +void VtpStreamSocket::RemoveStreamSocketLock(int fd) +{ + if (g_streamSocketLockMap.find(fd) != g_streamSocketLockMap.end()) { + g_streamSocketLockMap.erase(fd); + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "Remove streamsocketlock for fd = %d success", fd); + } else { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, + "Streamsocketlock for fd = %d not exist in the map", fd); + } + return; +} + +void VtpStreamSocket::RemoveStreamSocketListener(int fd) +{ + if (g_streamReceiverMap.find(fd) != g_streamReceiverMap.end()) { + g_streamReceiverMap.erase(fd); + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "Remove streamreceiver for fd = %d success", fd); + } else { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "Streamreceiver for fd = %d not exist in the map", fd); + } + return; +} + void VtpStreamSocket::InsertElementToFuncMap(int type, ValueType valueType, MySetFunc set, MyGetFunc get) { OptionFunc fun = { @@ -121,6 +174,113 @@ std::shared_ptr VtpStreamSocket::GetSelf() return shared_from_this(); } +/* This function is used to prompt the metrics returned by FtApiRegEventCallbackFunc() function */ +int VtpStreamSocket::FillpBwAndJitterStatistics(int fd, const FtEventCbkInfo *info) +{ +#if (defined(FILLP_SUPPORT_BW_DET) && defined(FILLP_SUPPORT_BW_DET)) + if (info->evt == FT_EVT_BW_DET || info->evt == FT_EVT_JITTER_DET) { + int32_t eventId = TRANS_STREAM_QUALITY_EVENT; + int32_t tvCount = 1; + QosTv metricList = {}; + + if (info->evt == FT_EVT_BW_DET) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, + "[Metric Return]: Fillp bandwidth information of socket(%d) is returned", fd); + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, + "[Metric Return]: Changed amount of current available bandwidth is: %d", info->info.bwInfo.bwStat); + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, + "[Metric Return]: Current bandwidth for receiving data is: %d kbps", info->info.bwInfo.rate); + metricList.type = BANDWIDTH_ESTIMATE_VALUE; + metricList.info.bandwidthInfo.trend = info->info.bwInfo.bwStat; + metricList.info.bandwidthInfo.rate = info->info.bwInfo.rate; + } + if (info->evt == FT_EVT_JITTER_DET) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, + "[Metric Return]: Fillp connection quality information of socket(%d) is returned", fd); + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, + "[Metric Return]: Predeicted network condition is: %d", info->info.jitterInfo.jitterLevel); + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, + "[Metric Return]: Current available receiving buffer is: %d ms", info->info.jitterInfo.bufferTime); + metricList.type = JITTER_DETECTION_VALUE; + metricList.info.jitterInfo.jitterLevel = info->info.jitterInfo.jitterLevel; + metricList.info.jitterInfo.bufferTime = info->info.jitterInfo.bufferTime; + } + metricList.info.wifiChannelInfo = {}; + metricList.info.frameStatusInfo = {}; + + auto itLock = g_streamSocketLockMap.find(fd); + if (itLock != g_streamSocketLockMap.end()) { + auto itListener = g_streamReceiverMap.find(fd); + if (itListener != g_streamReceiverMap.end()) { + std::thread([itListener, eventId, tvCount, metricList, &itLock]() { + std::lock_guard guard(itLock->second); + itListener->second->OnQosEvent(eventId, tvCount, &metricList); + }).detach(); + } else { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "StreamReceiver for fd = %d is empty in the map", fd); + } + } else { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "StreamSocketLock for fd = %d is empty in the map", fd); + } + } else { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, + "[Metric Return]: Fail to retrieve bandwidth and connection quality information"); + return -1; + } +#endif + return 0; +} + +void VtpStreamSocket::FillpAppStatistics() +{ + int32_t eventId = TRANS_STREAM_QUALITY_EVENT; + int32_t tvCount = 1; + QosTv metricList = {}; + FillpStatisticsPcb fillpPcbStats = {}; + struct timeval fillpStatsGetTime = {}; + + int getStatisticsRet = FtFillpStatsGet(streamFd_, &fillpPcbStats); + gettimeofday(&fillpStatsGetTime, nullptr); + if (getStatisticsRet == 0) { + metricList.type = STREAM_TRAFFIC_STASTICS; + metricList.info.appStatistics.statisticsGotTime = fillpStatsGetTime.tv_sec * MS_PER_SECOND + + fillpStatsGetTime.tv_usec / US_PER_MS; /* ms */ + metricList.info.appStatistics.periodRecvBits = fillpPcbStats.appFcStastics.periodRecvBits; + metricList.info.appStatistics.pktNum = fillpPcbStats.appFcStastics.pktNum; + metricList.info.appStatistics.periodRecvPkts = fillpPcbStats.appFcStastics.periodRecvPkts; + metricList.info.appStatistics.periodRecvPktLoss = fillpPcbStats.appFcStastics.periodRecvPktLoss; + metricList.info.appStatistics.periodRecvRate = fillpPcbStats.appFcStastics.periodRecvRate; + metricList.info.appStatistics.periodRecvRateBps = fillpPcbStats.appFcStastics.periodRecvRateBps; + metricList.info.appStatistics.periodRtt = fillpPcbStats.appFcStastics.periodRtt; + metricList.info.appStatistics.periodRecvPktLossHighPrecision = + fillpPcbStats.appFcStastics.periodRecvPktLossHighPrecision; + metricList.info.appStatistics.periodSendLostPkts = fillpPcbStats.appFcStastics.periodSendLostPkts; + metricList.info.appStatistics.periodSendPkts = fillpPcbStats.appFcStastics.periodSendPkts; + metricList.info.appStatistics.periodSendPktLossHighPrecision = + fillpPcbStats.appFcStastics.periodSendPktLossHighPrecision; + metricList.info.appStatistics.periodSendBits = fillpPcbStats.appFcStastics.periodSendBits; + metricList.info.appStatistics.periodSendRateBps = fillpPcbStats.appFcStastics.periodSendRateBps; + + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, + "Succeed to get fillp statistics information for streamfd = %d", streamFd_); + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, + "[Metric Return]: periodRtt is: %d", fillpPcbStats.appFcStastics.periodRtt); + + std::lock_guard guard(streamSocketLock_); + + if (streamReceiver_ != nullptr) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, + "[Metric Notify]: Fillp traffic statistics information of socket(%d) is notified", streamFd_); + streamReceiver_->OnQosEvent(eventId, tvCount, &metricList); + } else { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, "StreamReceiver for fd = %d is empty", streamFd_); + } + } else { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, + "Fail to get fillp statistics information for streamfd = %d, errorcode = %d", streamFd_, FtGetErrno()); + } +} + bool VtpStreamSocket::CreateClient(IpAndPort &local, int streamType, const std::string &sessionKey) { int fd = CreateAndBindSocket(local); @@ -148,8 +308,20 @@ bool VtpStreamSocket::CreateClient(IpAndPort &local, const IpAndPort &remote, in if (!CreateClient(local, streamType, sessionKey)) { return false; } + /* enable the bandwidth and CQE estimation algorithms by FtSetSockOpt() for current ftsocket */ +#ifdef FILLP_SUPPORT_BW_DET + bool isServer = false; + EnableBwEstimationAlgo(streamFd_, isServer); +#endif - return Connect(remote); + bool connectRet = Connect(remote); +#ifdef FILLP_SUPPORT_BW_DET + if (connectRet == true) { + bool isServer = false; + RegisterMetricCallback(isServer); /* register the callback function */ + } +#endif + return connectRet; } bool VtpStreamSocket::CreateServer(IpAndPort &local, int streamType, const std::string &sessionKey) @@ -190,6 +362,14 @@ bool VtpStreamSocket::CreateServer(IpAndPort &local, int streamType, const std:: self->DestroyStreamSocket(); }).detach(); + bool &isDestoryed = isDestoryed_; + std::thread([self, &isDestoryed]() { + while (isDestoryed == false) { + self->FillpAppStatistics(); + std::this_thread::sleep_for(std::chrono::seconds(FEED_BACK_PERIOD)); + } + }).detach(); + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, "CreateServer end, listenFd:%d, epollFd:%d, streamType:%d", listenFd_, epollFd_, streamType_); return true; @@ -209,6 +389,8 @@ void VtpStreamSocket::DestroyStreamSocket() } if (streamFd_ != -1) { + RemoveStreamSocketLock(streamFd_); /* remove the socket lock from the map */ + RemoveStreamSocketListener(streamFd_); /* remove the socket listener from the map */ FtClose(streamFd_); streamFd_ = -1; } @@ -271,10 +453,19 @@ bool VtpStreamSocket::Connect(const IpAndPort &remote) auto self = this->GetSelf(); std::thread([self]() { self->NotifyStreamListener(); }).detach(); + std::thread([self]() { self->DoStreamRecv(); self->DestroyStreamSocket(); }).detach(); + + bool &isDestoryed = isDestoryed_; + std::thread([self, &isDestoryed]() { + while (isDestoryed == false) { + self->FillpAppStatistics(); + std::this_thread::sleep_for(std::chrono::seconds(FEED_BACK_PERIOD)); + } + }).detach(); return true; } @@ -459,6 +650,79 @@ int VtpStreamSocket::CreateAndBindSocket(IpAndPort &local) return sockFd; } + +bool VtpStreamSocket::EnableBwEstimationAlgo(int streamFd, bool isServer) const +{ +#ifdef FILLP_SUPPORT_BW_DET + int errBwDet; + if (isServer == true) { + int32_t enableBwDet = FILLP_BW_DET_RX_ENABLE; + errBwDet = FtSetSockOpt(streamFd, IPPROTO_FILLP, FILLP_SOCK_BW_DET_ALGO, + &enableBwDet, sizeof(enableBwDet)); + } else { + int32_t enableBwDet = FILLP_BW_DET_TX_ENABLE; + errBwDet = FtSetSockOpt(streamFd, IPPROTO_FILLP, FILLP_SOCK_BW_DET_ALGO, + &enableBwDet, sizeof(enableBwDet)); + } + if (errBwDet < 0) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, + "Fail to enable bandwidth estimation algorithm for stream: %d, errorcode = %d", streamFd, FtGetErrno()); + return true; + } else { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, + "Success to enable bandwidth estimation algorithm for stream: %d", streamFd); + return false; + } +#else + return true; +#endif +} + +bool VtpStreamSocket::EnableJitterDetectionAlgo(int streamFd) const +{ +#ifdef FILLP_SUPPORT_CQE + int32_t enableCQE = FILLP_CQE_ENABLE; + auto errCQE = FtSetSockOpt(streamFd, IPPROTO_FILLP, FILLP_SOCK_CQE_ALGO, &enableCQE, sizeof(enableCQE)); + if (errCQE < 0) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, + "Fail to enable CQE algorithm for stream: %d, errorcode = %d", streamFd, FtGetErrno()); + return true; + } else { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, + "Success to enable CQE algorithm for stream: %d", streamFd); + return false; + } +#else + return true; +#endif +} + +void VtpStreamSocket::RegisterMetricCallback(bool isServer) +{ + VtpStreamSocket::AddStreamSocketLock(streamFd_, streamSocketLock_); + VtpStreamSocket::AddStreamSocketListener(streamFd_, streamReceiver_); +#if (defined(FILLP_SUPPORT_BW_DET) && defined(FILLP_SUPPORT_BW_DET)) + int regStatisticsRet = FtApiRegEventCallbackFunc(streamFd_, FillpBwAndJitterStatistics); + if (isServer == true) { + if (regStatisticsRet == 0) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, + "Success to register the stream callback function at server side with Fd = %d", streamFd_); + } else { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, + "Fail to register the stream callback function at server side with Fd = %d", streamFd_); + } + } else { + if (regStatisticsRet == 0) { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, + "Success to register the stream callback function at client side with Fd = %d", streamFd_); + } else { + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_ERROR, + "Fail to register the stream callback function at client side with Fd = %d", streamFd_); + } + } +#endif +} + bool VtpStreamSocket::Accept() { SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_DBG, "accept start"); @@ -508,6 +772,16 @@ bool VtpStreamSocket::Accept() streamReceiver_->OnStreamStatus(STREAM_CONNECTED); } + /* enable the bandwidth and CQE estimation algorithms for current ftsocket */ +#ifdef FILLP_SUPPORT_BW_DET + bool isServer = true; + EnableBwEstimationAlgo(streamFd_, isServer); + RegisterMetricCallback(isServer); /* register the callback function */ +#endif +#ifdef FILLP_SUPPORT_CQE + EnableJitterDetectionAlgo(streamFd_); +#endif + SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_INFO, "accept success!"); return true; } @@ -640,7 +914,6 @@ void VtpStreamSocket::DoStreamRecv() int extLen = 0; StreamFrameInfo info = {}; int dataLength = 0; - SoftBusLog(SOFTBUS_LOG_TRAN, SOFTBUS_LOG_DBG, "recv stream"); dataLength = VtpStreamSocket::RecvStreamLen(); if (dataLength <= 0 || dataLength > MAX_STREAM_LEN) { 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 d341892fc..b5d46bd33 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 @@ -56,7 +56,9 @@ public: bool CreateClient(IpAndPort &local, int streamType, const std::string &sessionKey) override; bool CreateClient(IpAndPort &local, const IpAndPort &remote, int streamType, const std::string &sessionKey) override; + bool CreateServer(IpAndPort &local, int streamType, const std::string &sessionKey) override; + void DestroyStreamSocket() override; bool Connect(const IpAndPort &remote) override; @@ -160,6 +162,27 @@ private: void GetCryptErrorReason(void) const; + bool EnableBwEstimationAlgo(int streamfd, bool isServer) const; + + bool EnableJitterDetectionAlgo(int streamfd) const; + + void RegisterMetricCallback(bool isServer); /* register the metric callback function */ + + static void AddStreamSocketLock(int fd, std::mutex &streamsocketlock); + + static void AddStreamSocketListener(int fd, std::shared_ptr streamreceiver); + + static void RemoveStreamSocketLock(int fd); + + static void RemoveStreamSocketListener(int fd); + + static int FillpBwAndJitterStatistics(int fd, const FtEventCbkInfo *info); + + void FillpAppStatistics(); + + static std::map g_streamSocketLockMap; + static std::map> g_streamReceiverMap; + std::map optFuncMap_ {}; static std::shared_ptr vtpInstance_; std::condition_variable configCv_; 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 433e2d816..30ae943d0 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 @@ -16,6 +16,7 @@ #include "client_trans_stream.h" #include "client_trans_udp_stream_interface.h" +#include "session.h" #include "softbus_errcode.h" #include "softbus_log.h" #include "softbus_utils.h" @@ -86,9 +87,18 @@ static void OnStreamReceived(int32_t channelId, const StreamData *data, const St g_udpChannelMgrCb->OnStreamReceived(channelId, data, ext, param); } +static void OnQosEvent(int channelId, int eventId, int tvCount, const QosTv *tvList) +{ + if ((g_udpChannelMgrCb == NULL) || (g_udpChannelMgrCb->OnQosEvent == NULL)) { + return; + } + g_udpChannelMgrCb->OnQosEvent(channelId, eventId, tvCount, tvList); +} + static IStreamListener g_streamCallcb = { .OnStatusChange = SetStreamChannelStatus, .OnStreamReceived = OnStreamReceived, + .OnQosEvent = OnQosEvent, }; int32_t TransOnstreamChannelOpened(const ChannelInfo *channel, int32_t *streamPort) diff --git a/tests/core/connection/ble/BUILD.gn b/tests/core/connection/ble/BUILD.gn new file mode 100644 index 000000000..b16a2d054 --- /dev/null +++ b/tests/core/connection/ble/BUILD.gn @@ -0,0 +1,44 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/communication/dsoftbus/dsoftbus.gni") + +module_output_path = "dsoftbus_standard/connection" + +ohos_unittest("softbus_conn_ble_test") { + module_out_path = module_output_path + include_dirs = [ + "$dsoftbus_root_path/core/common/include", + "$softbus_adapter_common/include", + "$dsoftbus_root_path/interfaces/kits/common", + "$dsoftbus_root_path/core/connection/interface", + "$dsoftbus_root_path/core/connection/manager", + "$dsoftbus_root_path/core/connection/tcp/include", + "//third_party/googletest/googletest/include", + "//third_party/googletest/googletest/src", + "//third_party/bounds_checking_function/include", + ] + + deps = [ + "$dsoftbus_root_path/core/common:softbus_utils", + "$dsoftbus_root_path/core/frame:softbus_server", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "//utils/native/base:utilsecurec_shared", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + sources = [ "connection_ble_test.cpp" ] +} diff --git a/tests/core/connection/ble/connection_ble_test.cpp b/tests/core/connection/ble/connection_ble_test.cpp new file mode 100644 index 000000000..3f68ec9d4 --- /dev/null +++ b/tests/core/connection/ble/connection_ble_test.cpp @@ -0,0 +1,203 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. + * Description: br connection test. + * 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 + +#include "common_list.h" +#include "softbus_conn_interface.h" +#include "softbus_conn_manager.h" +#include "softbus_def.h" +#include "softbus_errcode.h" +#include "softbus_feature_config.h" +#include "softbus_log.h" + +static const int CONN_HEAD_SIZE = 24; +#define TEST_BLE_MAC "11:22:33:44:55:66" + +static unsigned int g_connId = 0; +#define WAIT_CONNECTION_COUNT 8 +#define WAIT_CONNECTION_SLEEP_TIME 1 + +using namespace testing::ext; + +namespace OHOS { +void ConnectedCB(unsigned int connectionId, const ConnectionInfo *info) +{ + return; +} + +void DisConnectCB(unsigned int connectionId, const ConnectionInfo *info) +{ + return; +} + +void DataReceivedCB(unsigned int connectionId, ConnModule moduleId, int64_t seq, char *data, int len) +{ + return; +} + +void ConnectSuccessedCB(unsigned int requestId, unsigned int connectionId, const ConnectionInfo *info) +{ + return; +} + +void ConnectFailedCB(unsigned int requestId, int reason) +{ + return; +} + +class SoftbusBleConnmangerFuncTest : public testing::Test { +public: + SoftbusBleConnmangerFuncTest() + {} + ~SoftbusBleConnmangerFuncTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void SoftbusBleConnmangerFuncTest::SetUpTestCase(void) +{ + SoftbusConfigInit(); + ConnServerInit(); +} + +void SoftbusBleConnmangerFuncTest::TearDownTestCase(void) +{} + +void SoftbusBleConnmangerFuncTest::SetUp(void) +{} + +void SoftbusBleConnmangerFuncTest::TearDown(void) +{} + +/* +* @tc.name: testConnmanger001 +* @tc.desc: test ConnTypeIsSupport +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(SoftbusBleConnmangerFuncTest, testConnmanger001, TestSize.Level1) +{ + int ret; + printf("testConnmanger001\r\n"); + + ret = ConnTypeIsSupport(CONNECT_BLE); + EXPECT_EQ(SOFTBUS_OK, ret); +}; + +/* +* @tc.name: testConnmanger002 +* @tc.desc: test invalid param +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(SoftbusBleConnmangerFuncTest, testConnmanger002, TestSize.Level1) +{ + printf("test begin testConnmanger002 \r\n"); + int ret; + ret = ConnSetConnectCallback(static_cast(0), nullptr); + ASSERT_TRUE(ret != SOFTBUS_OK); + ret = ConnConnectDevice(nullptr, 0, nullptr); + ASSERT_TRUE(ret != SOFTBUS_OK); + ret = ConnPostBytes(0, nullptr); + ASSERT_TRUE(ret != SOFTBUS_OK); + ret = ConnStartLocalListening(nullptr); + ASSERT_TRUE(ret != SOFTBUS_OK); + ret = ConnStopLocalListening(nullptr); + ASSERT_TRUE(ret != SOFTBUS_OK); + EXPECT_EQ(SOFTBUS_OK, SOFTBUS_OK); +}; + +/* +* @tc.name: testConnmanger003 +* @tc.desc: test set unset callback and connect post disconnect +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(SoftbusBleConnmangerFuncTest, testConnmanger003, TestSize.Level1) +{ + int ret; + int reqId; + ConnectCallback connCb; + ConnectResult connRet; + ConnPostData data; + ConnectOption info; + const char *str = "send msg local2\r\n"; + printf("test begin testConnmanger003 \r\n"); + + connCb.OnConnected = ConnectedCB; + connCb.OnDisconnected = DisConnectCB; + connCb.OnDataReceived = DataReceivedCB; + ret = ConnSetConnectCallback(MODULE_TRUST_ENGINE, &connCb); + EXPECT_EQ(SOFTBUS_OK, ret); + info.type = CONNECT_BLE; + (void)memcpy_s(info.info.bleOption.bleMac, BT_MAC_LEN, TEST_BLE_MAC, BT_MAC_LEN); + printf("brMac: %s\n", info.info.bleOption.bleMac); + connRet.OnConnectFailed = ConnectFailedCB; + connRet.OnConnectSuccessed = ConnectSuccessedCB; + reqId = ConnGetNewRequestId(MODULE_TRUST_ENGINE); + ret = ConnConnectDevice(&info, reqId, &connRet); + EXPECT_EQ(SOFTBUS_OK, ret); + if (g_connId != 0) { + data.buf = (char *)calloc(1, CONN_HEAD_SIZE + 20); + ASSERT_TRUE(data.buf != NULL); + (void)strcpy_s(data.buf + 1, strlen(str), str); + data.len = CONN_HEAD_SIZE + 20; + data.module = MODULE_TRUST_ENGINE; + data.pid = 0; + data.flag = 1; + data.seq = 1; + ret = ConnPostBytes(g_connId, &data); + EXPECT_EQ(SOFTBUS_OK, ret); + if (data.buf != nullptr) { + free(data.buf); + } + ret = ConnDisconnectDevice(g_connId); + EXPECT_EQ(SOFTBUS_OK, ret); + } + + ConnUnSetConnectCallback(MODULE_TRUST_ENGINE); + g_connId = 0; +}; + +/* +* @tc.name: testConnmanger004 +* @tc.desc: test set unset callback and post disconnect without connect +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(SoftbusBleConnmangerFuncTest, testConnmanger004, TestSize.Level1) +{ + printf("test begin ConnManagerTest004 \r\n"); + int ret; + ConnectCallback connCb; + + connCb.OnConnected = ConnectedCB; + connCb.OnDisconnected = DisConnectCB; + connCb.OnDataReceived = DataReceivedCB; + ret = ConnSetConnectCallback(MODULE_TRUST_ENGINE, &connCb); + EXPECT_EQ(SOFTBUS_OK, ret); + ConnUnSetConnectCallback(MODULE_TRUST_ENGINE); + g_connId = 0; +}; +} diff --git a/tests/core/connection/br/BUILD.gn b/tests/core/connection/br/BUILD.gn new file mode 100644 index 000000000..dca025830 --- /dev/null +++ b/tests/core/connection/br/BUILD.gn @@ -0,0 +1,44 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/communication/dsoftbus/dsoftbus.gni") + +module_output_path = "dsoftbus_standard/connection" + +ohos_unittest("softbus_conn_br_test") { + module_out_path = module_output_path + include_dirs = [ + "$dsoftbus_root_path/core/common/include", + "$softbus_adapter_common/include", + "$dsoftbus_root_path/interfaces/kits/common", + "$dsoftbus_root_path/core/connection/interface", + "$dsoftbus_root_path/core/connection/manager", + "$dsoftbus_root_path/core/connection/tcp/include", + "//third_party/googletest/googletest/include", + "//third_party/googletest/googletest/src", + "//third_party/bounds_checking_function/include", + ] + + deps = [ + "$dsoftbus_root_path/core/common:softbus_utils", + "$dsoftbus_root_path/core/frame:softbus_server", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "//utils/native/base:utilsecurec_shared", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + sources = [ "connection_br_test.cpp" ] +} diff --git a/tests/core/connection/br/connection_br_test.cpp b/tests/core/connection/br/connection_br_test.cpp new file mode 100644 index 000000000..c22d2619c --- /dev/null +++ b/tests/core/connection/br/connection_br_test.cpp @@ -0,0 +1,262 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. + * Description: br connection test. + * 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 + +#include "common_list.h" +#include "softbus_conn_interface.h" +#include "softbus_conn_manager.h" +#include "softbus_def.h" +#include "softbus_errcode.h" +#include "softbus_feature_config.h" +#include "softbus_log.h" + +static const int CONN_HEAD_SIZE = 24; +#define TEST_BR_MAC "24:DA:33:6A:06:EC" + +static unsigned int g_connId = 0; +#define WAIT_CONNECTION_COUNT 8 +#define WAIT_CONNECTION_SLEEP_TIME 1 + +using namespace testing::ext; + +namespace OHOS { +void ConnectedCB(unsigned int connectionId, const ConnectionInfo *info) +{ + printf("recv remote ConnectedCB %u %d\r\n", connectionId, info->type); + if (info->type == CONNECT_BR) { + g_connId = connectionId; + } + return; +} + +void DisConnectCB(unsigned int connectionId, const ConnectionInfo *info) +{ + printf("DconDisConnect %u\r\n", connectionId); + return; +} + +void DataReceivedCB(unsigned int connectionId, ConnModule moduleId, int64_t seq, char *data, int len) +{ + printf("DconDataReceived moduleId %d %s %d\r\n", moduleId, data, len); + return; +} + +void ConnectSuccessedCB(unsigned int requestId, unsigned int connectionId, const ConnectionInfo *info) +{ + printf("ConnectSuccessedCB %u\r\n", connectionId); + g_connId = connectionId; + return; +} + +void ConnectFailedCB(unsigned int requestId, int reason) +{ + (void)requestId; + (void)reason; + printf("DconConnectFailed\r\n"); + return; +} + +class SoftbusBrConnmangerFuncTest : public testing::Test { +public: + SoftbusBrConnmangerFuncTest() + {} + ~SoftbusBrConnmangerFuncTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void SoftbusBrConnmangerFuncTest::SetUpTestCase(void) +{ + SoftbusConfigInit(); + ConnServerInit(); +} + +void SoftbusBrConnmangerFuncTest::TearDownTestCase(void) +{} + +void SoftbusBrConnmangerFuncTest::SetUp(void) +{} + +void SoftbusBrConnmangerFuncTest::TearDown(void) +{} + +/* +* @tc.name: testConnmanger001 +* @tc.desc: test ConnTypeIsSupport +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(SoftbusBrConnmangerFuncTest, testConnmanger001, TestSize.Level1) +{ + int ret; + printf("testConnmanger001\r\n"); + + ret = ConnTypeIsSupport(CONNECT_BR); + EXPECT_EQ(SOFTBUS_OK, ret); +}; + +/* +* @tc.name: testConnmanger002 +* @tc.desc: test invalid param +* @tc.type: FUNC +* @tc.require:AR000GIIE9 +*/ +HWTEST_F(SoftbusBrConnmangerFuncTest, testConnmanger002, TestSize.Level1) +{ + printf("test begin testConnmanger002 \r\n"); + int ret; + ret = ConnSetConnectCallback(static_cast(0), nullptr); + ASSERT_TRUE(ret != SOFTBUS_OK); + ret = ConnConnectDevice(nullptr, 0, nullptr); + ASSERT_TRUE(ret != SOFTBUS_OK); + ret = ConnPostBytes(0, nullptr); + ASSERT_TRUE(ret != SOFTBUS_OK); + ret = ConnStartLocalListening(nullptr); + ASSERT_TRUE(ret != SOFTBUS_OK); + ret = ConnStopLocalListening(nullptr); + ASSERT_TRUE(ret != SOFTBUS_OK); + EXPECT_EQ(SOFTBUS_OK, SOFTBUS_OK); +}; + +/* +* @tc.name: testConnmanger003 +* @tc.desc: test set unset callback and connect post disconnect +* @tc.type: FUNC +* @tc.require:AR000GIRGE +*/ +HWTEST_F(SoftbusBrConnmangerFuncTest, testConnmanger003, TestSize.Level1) +{ + int ret; + int reqId; + ConnectCallback connCb; + ConnectResult connRet; + ConnPostData data; + ConnectOption info; + const char *str = "send msg local2\r\n"; + printf("test begin testConnmanger003 \r\n"); + + connCb.OnConnected = ConnectedCB; + connCb.OnDisconnected = DisConnectCB; + connCb.OnDataReceived = DataReceivedCB; + ret = ConnSetConnectCallback(MODULE_TRUST_ENGINE, &connCb); + EXPECT_EQ(SOFTBUS_OK, ret); + info.type = CONNECT_BR; + (void)memcpy_s(info.info.brOption.brMac, BT_MAC_LEN, TEST_BR_MAC, BT_MAC_LEN); + printf("brMac: %s\n", info.info.brOption.brMac); + connRet.OnConnectFailed = ConnectFailedCB; + connRet.OnConnectSuccessed = ConnectSuccessedCB; + reqId = ConnGetNewRequestId(MODULE_TRUST_ENGINE); + ret = ConnConnectDevice(&info, reqId, &connRet); + EXPECT_EQ(SOFTBUS_OK, ret); + if (g_connId) { + data.buf = (char *)calloc(1, CONN_HEAD_SIZE + 20); + ASSERT_TRUE(data.buf != NULL); + (void)strcpy_s(data.buf + 1, strlen(str), str); + data.len = CONN_HEAD_SIZE + 20; + data.module = MODULE_TRUST_ENGINE; + data.pid = 0; + data.flag = 1; + data.seq = 1; + ret = ConnPostBytes(g_connId, &data); + EXPECT_EQ(SOFTBUS_OK, ret); + if (data.buf != nullptr) { + free(data.buf); + } + ret = ConnDisconnectDevice(g_connId); + EXPECT_EQ(SOFTBUS_OK, ret); + } + + ConnUnSetConnectCallback(MODULE_TRUST_ENGINE); + g_connId = 0; +}; + +/* +* @tc.name: testConnmanger004 +* @tc.desc: test set unset callback and post disconnect without connect +* @tc.type: FUNC +* @tc.require:AR000GIIE9 +*/ +HWTEST_F(SoftbusBrConnmangerFuncTest, testConnmanger004, TestSize.Level1) +{ + printf("test begin ConnManagerTest004 \r\n"); + int ret; + ConnectCallback connCb; + LocalListenerInfo info; + + connCb.OnConnected = ConnectedCB; + connCb.OnDisconnected = DisConnectCB; + connCb.OnDataReceived = DataReceivedCB; + ret = ConnSetConnectCallback(MODULE_TRUST_ENGINE, &connCb); + EXPECT_EQ(SOFTBUS_OK, ret); + info.type = CONNECT_BR; + ret = ConnStartLocalListening(&info); + EXPECT_EQ(SOFTBUS_OK, ret); + ret = ConnStopLocalListening(&info); + EXPECT_EQ(SOFTBUS_OK, ret); + ConnUnSetConnectCallback(MODULE_TRUST_ENGINE); + g_connId = 0; +}; + +/* +* @tc.name: testConnmanger005 +* @tc.desc: test set unset callback and connect post disconnect +* @tc.type: FUNC +* @tc.require:AR000GIRGE +*/ +HWTEST_F(SoftbusBrConnmangerFuncTest, testConnmanger005, TestSize.Level1) +{ + int reqId = 1; + int ret; + ConnectCallback connCb; + ConnectOption optionInfo; + ConnectionInfo info; + ConnectResult connRet; + + connCb.OnConnected = ConnectedCB; + connCb.OnDisconnected = DisConnectCB; + connCb.OnDataReceived = DataReceivedCB; + ret = ConnSetConnectCallback(MODULE_TRUST_ENGINE, &connCb); + EXPECT_EQ(SOFTBUS_OK, ret); + + optionInfo.type = CONNECT_BR; + (void)memcpy_s(optionInfo.info.brOption.brMac, BT_MAC_LEN, TEST_BR_MAC, BT_MAC_LEN); + printf("brMac: %s\n", optionInfo.info.brOption.brMac); + connRet.OnConnectFailed = ConnectFailedCB; + connRet.OnConnectSuccessed = ConnectSuccessedCB; + reqId = ConnGetNewRequestId(MODULE_TRUST_ENGINE); + ret = ConnConnectDevice(&optionInfo, reqId, &connRet); + EXPECT_EQ(SOFTBUS_OK, ret); + if (g_connId) { + ret = ConnGetConnectionInfo(g_connId, &info); + EXPECT_EQ(SOFTBUS_OK, ret); + ret = ConnDisconnectDeviceAllConn(&optionInfo); + g_connId = 0; + EXPECT_EQ(SOFTBUS_OK, ret); + printf("testConnmanger005 ConnDisconnectDevice\r\n"); + } + printf("testConnmanger005 ConnUnSetConnectCallback\r\n"); + ConnUnSetConnectCallback(MODULE_TRUST_ENGINE); + printf("testConnmanger005 ConnUnSetConnectCallback end 11\r\n"); +}; +} diff --git a/tests/sdk/discovery/account/BUILD.gn b/tests/sdk/discovery/account/BUILD.gn new file mode 100644 index 000000000..37364f53e --- /dev/null +++ b/tests/sdk/discovery/account/BUILD.gn @@ -0,0 +1,50 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/communication/dsoftbus/dsoftbus.gni") +module_output_path = "dsoftbus_standard/discovery" +ohos_unittest("disc_account_test") { + module_out_path = module_output_path + sources = [ "disc_account_test.cpp" ] + include_dirs = [ + "$dsoftbus_root_path/core/common/inner_communication", + "$dsoftbus_root_path/adapter/common/include", + "$dsoftbus_root_path/core/common/include", + "$dsoftbus_root_path/interfaces/kits/discovery", + "$dsoftbus_root_path/interfaces/kits/common", + "$dsoftbus_root_path/interfaces/inner_kits/transport", + "$dsoftbus_root_path/sdk/discovery/include", + "//utils/native/base/include", + "//third_party/bounds_checking_function/include", + "unittest/common/", + "$dsoftbus_root_path/sdk/discovery/manager/include", + ] + deps = [ + "$dsoftbus_root_path/core/common:softbus_utils", + "$dsoftbus_root_path/sdk:softbus_client", + "//third_party/bounds_checking_function:libsec_static", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "//utils/native/base:utilsecurec_shared", + ] + if (is_standard_system) { + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + } else { + external_deps = [ "hilog:libhilog" ] + } +} +group("unittest") { + testonly = true + deps = [ ":disc_account_test" ] +} diff --git a/tests/sdk/discovery/account/disc_account_test.cpp b/tests/sdk/discovery/account/disc_account_test.cpp new file mode 100644 index 000000000..7b26ae92e --- /dev/null +++ b/tests/sdk/discovery/account/disc_account_test.cpp @@ -0,0 +1,239 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include "discovery_service.h" +#include "inner_session.h" +#include "session.h" +#include "softbus_utils.h" + +using namespace testing::ext; + +namespace OHOS { +int32_t g_testWay = -1; +int32_t g_accountWay = -1; +int32_t g_publishId = 1; +int32_t g_subscribeId = 1; +enum TEST_WAY { + STARTDISCOVERY_WAY = 0, + PUBLISHSERVICE_WAY +}; + +enum ACCOUNT_MODE { + SAMEACCOUNT_TRUE = 0, + SAMEACCOUNT_FALSE +}; + +const char *g_pkgName = "com.objectstore.foundation"; +bool g_state = false; +static void Wait(void); + +ConnectionAddr g_addr; +ConnectionAddr g_addr1; + +static SubscribeInfo g_sInfo = { + .subscribeId = g_subscribeId, + .medium = BLE, + .mode = DISCOVER_MODE_ACTIVE, + .freq = MID, + .capability = "dvKit", + .capabilityData = (unsigned char *)"capdata3", + .dataLen = sizeof("capdata3"), + .isSameAccount = false, + .isWakeRemote = false +}; + +static PublishInfo g_pInfo = { + .publishId = g_publishId, + .medium = BLE, + .mode = DISCOVER_MODE_PASSIVE, + .freq = MID, + .capability = "dvKit", + .capabilityData = (unsigned char *)"capdata4", + .dataLen = sizeof("capdata4") +}; + +static void TestDeviceFound(const DeviceInfo *device) +{ + if (ConvertBtMacToStr(g_addr.info.ble.bleMac, 18, (const uint8_t *)&(device->addr[0].info.ble.bleMac[0]), 6) != 0) { + return; + } + if (strcmp(g_addr1.info.ble.bleMac, g_addr.info.ble.bleMac) != 0) { + strcpy_s(g_addr1.info.ble.bleMac, BT_MAC_LEN, g_addr.info.ble.bleMac); + printf("[client]TestDeviceFound\r\n"); + printf("addr mac = %s\r\n", g_addr1.info.ble.bleMac); + printf("account = %s\r\n", device->hwAccountHash); + g_state = true; + } +} + +static void TestDiscoverFailed(int subscribeId, DiscoveryFailReason failReason) +{ + printf("[test]TestDiscoverFailed\r\n"); +} + +static void TestDiscoverySuccess(int subscribeId) +{ + printf("[test]TestDiscoverySuccess\r\n"); +} + +static void TestPublishSuccess(int publishId) +{ + printf("[test]TestPublishSuccess\r\n"); +} + +static void TestPublishFail(int publishId, PublishFailReason reason) +{ + printf("[test]TestPublishFail\r\n"); +} + +static IDiscoveryCallback g_subscribeCb = { + .OnDeviceFound = TestDeviceFound, + .OnDiscoverFailed = TestDiscoverFailed, + .OnDiscoverySuccess = TestDiscoverySuccess +}; + +static IPublishCallback g_publishCb = { + .OnPublishSuccess = TestPublishSuccess, + .OnPublishFail = TestPublishFail +}; + +class DiscAccountTest : public testing::Test { +public: + DiscAccountTest() + {} + ~DiscAccountTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp() override + {} + void TearDown() override + {} +}; + +void DiscAccountTest::SetUpTestCase(void) +{ + printf("********Ble Test Begin*********\r\n"); + printf("* 0.discovery *\r\n"); + printf("* 1.publish *\r\n"); + printf("*******************************\r\n"); + printf("input the num:"); + if (scanf_s("%d", &g_testWay, sizeof(g_testWay)) < 0) { + printf("input error!\n"); + } + getchar(); + if (g_testWay == PUBLISHSERVICE_WAY) { + return; + } + printf("***********Account*************\r\n"); + printf("* 0.true *\r\n"); + printf("* 1.false *\r\n"); + printf("*******************************\r\n"); + printf("input the num:"); + if (scanf_s("%d", &g_accountWay, sizeof(g_accountWay)) < 0) { + printf("input error!\n"); + } + getchar(); + if (g_accountWay == SAMEACCOUNT_TRUE) { + g_sInfo.isSameAccount = true; + return; + } + g_sInfo.isSameAccount = false; +} + +void DiscAccountTest::TearDownTestCase(void) +{ + if (g_testWay == STARTDISCOVERY_WAY) { + StopDiscovery(g_pkgName, g_subscribeId); + return; + } + UnPublishService(g_pkgName, g_publishId); +} + +static void Wait(void) +{ + printf("[test]wait enter...\r\n"); +SLEEP: + sleep(1); + if (g_state == false) { + goto SLEEP; + } + printf("[test]wait end!\r\n"); + g_state = false; +} + +static int32_t TestPublishServer() +{ + printf("[test]TestPublishServer enter\r\n"); + g_pInfo.mode = DISCOVER_MODE_ACTIVE; + int32_t ret = PublishService(g_pkgName, &g_pInfo, &g_publishCb); + EXPECT_TRUE(ret == 0); + printf("[test]TestPublishServer end\r\n"); + return ret; +} + +static int32_t TestStartDiscovery() +{ + printf("[test]TestStartDiscovery enter\r\n"); + g_sInfo.mode = DISCOVER_MODE_ACTIVE; + int32_t ret = StartDiscovery(g_pkgName, &g_sInfo, &g_subscribeCb); + EXPECT_TRUE(ret == 0); + printf("[test]TestStartDiscovery end\r\n"); + return ret; +} + +/** + * @tc.name: StartDiscovery001 + * @tc.desc: Verify wrong parameter + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(DiscAccountTest, StartDiscovery001, TestSize.Level0) +{ + if (g_testWay != STARTDISCOVERY_WAY) { + printf("[test]start dsicovery test skip...\r\n"); + EXPECT_TRUE(0 == 0); + return; + } + int32_t ret = TestStartDiscovery(); + EXPECT_TRUE(ret == 0); + Wait(); +}; + + +/** + * @tc.name: PublishServiceTest001 + * @tc.desc: Verify wrong parameter + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(DiscAccountTest, PublishServiceTest001, TestSize.Level0) +{ + if (g_testWay != PUBLISHSERVICE_WAY) { + printf("[test]passive test skip...\r\n"); + EXPECT_TRUE(0 == 0); + return; + } + int32_t ret = TestPublishServer(); + EXPECT_TRUE(ret == 0); + Wait(); +}; +} \ No newline at end of file diff --git a/tests/sdk/transmission/trans_channel/auth/BUILD.gn b/tests/sdk/transmission/trans_channel/auth/BUILD.gn new file mode 100644 index 000000000..e05a33560 --- /dev/null +++ b/tests/sdk/transmission/trans_channel/auth/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/lite/config/component/lite_component.gni") +import("//foundation/communication/dsoftbus/dsoftbus.gni") + +if (defined(ohos_lite)) { + # L0 + static_library("auth_session_test") { + sources = [ "auth_session_test.c" ] + include_dirs = [ + "$dsoftbus_root_path/core/common/include", + "$dsoftbus_root_path/core/frame/common/include", + "//foundation/communication/wifi_lite/interfaces/wifiservice", + ] + deps = [ "$dsoftbus_root_path/sdk:softbus_client" ] + cflags = [ + "-Wall", + "-fPIC", + "-std=c99", + ] + ldflags = [ "-fPIC" ] + } +} else { + # L2 + ohos_executable("auth_session_test") { + install_enable = true + sources = [ "auth_session_test.c" ] + + include_dirs = [ + "$dsoftbus_root_path/core/common/include", + "$dsoftbus_root_path/interfaces/inner_kits/transport", + "$dsoftbus_root_path/core/frame/common/include", + + #"//foundation/communication/wifi_lite/interfaces/wifiservice", + ] + + deps = [ + "$dsoftbus_root_path/adapter:softbus_adapter", + "$dsoftbus_root_path/core/common:softbus_utils", + "$dsoftbus_root_path/sdk:softbus_client", + ] + + if (is_standard_system) { + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + part_name = "dsoftbus_standard" + } + subsystem_name = "communication" + } +} diff --git a/tests/sdk/transmission/trans_channel/auth/auth_session_test.c b/tests/sdk/transmission/trans_channel/auth/auth_session_test.c new file mode 100644 index 000000000..3367fd0e6 --- /dev/null +++ b/tests/sdk/transmission/trans_channel/auth/auth_session_test.c @@ -0,0 +1,304 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. + * Description: auth channel test. + * 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 "discovery_service.h" +#include "inner_session.h" +#include "session.h" +#include "softbus_adapter_mem.h" +#include "softbus_bus_center.h" +#include "softbus_common.h" +#include "softbus_errcode.h" +#include "softbus_utils.h" + +#define TICK_TIME 1 +#define CREATE_SESSION_CASE 0 +#define OPEN_SESSION_CASE 1 +#define SEND_DATA_TEST_CASE 2 +#define WAIT_OPEN_SESSION_CASE 3 + +#define TEST_CASE_NUM 10 +#define MAXT_WAIT_COUNT 6 +#define WIFI_CONFIG_INTERVAL 10 +#define TEST_COUNT_INTREVAL 5 +#define WAIT_SERVER_READY 5 +#define MAX_TEST_COUNT 8 +#define NSTACKX_MAX_IP_STRING_LEN 20 +#define DISC_TEST_PKG_NAME "com.huawei.plrdtest" +static const char *g_testModuleName = DISC_TEST_PKG_NAME; +static const char *g_testSessionName = "com.huawei.plrdtest.dsoftbus"; +static ISessionListener g_sessionlistener; +static SessionAttribute g_sessionAttr; +static bool g_successFlag = false; + +#define CONN_ADDR_INFO_COUNT 5 +static int32_t g_sessionId = -1; +ConnectionAddr g_addrInfo[CONN_ADDR_INFO_COUNT]; + +static int32_t g_connectCnt = 0; + +static int OnSessionOpened(int sessionId, int result) +{ + printf("############# session opened,sesison id[%d] result[%d]\n", sessionId, result); + if (result == SOFTBUS_OK) { + if (g_sessionId == -1 || sessionId == g_sessionId) { + if (g_sessionId == -1) { + g_connectCnt++; + g_sessionId = sessionId; + } + g_successFlag = true; + } + } + + return result; +} + +static void OnSessionClosed(int sessionId) +{ + printf("############# session closed, session id = %d\n", sessionId); + g_sessionId = -1; + g_successFlag = false; +} + +static void OnBytesReceived(int sessionId, const void *data, unsigned int len) +{ + (void)data; + if (g_sessionId == -1 || sessionId == g_sessionId) { + printf("client bytes received, data[%s], dataLen[%d]\n", data, len); + } else { + printf("server bytes received, sessionid[%d], data[%s], dataLen[%d]\n", sessionId, data, len); + } +} + +static void OnMessageReceived(int sessionId, const void *data, unsigned int len) +{ + (void)data; + if (g_sessionId == -1 || sessionId == g_sessionId) { + printf("client msg received, data[%s], dataLen[%d]\n", data, len); + } else { + printf("server msg received, sessionid[%d], data[%s], dataLen[%d]\n", sessionId, data, len); + } +} + +static void TestSessionListenerInit(void) +{ + g_sessionlistener.OnSessionOpened = OnSessionOpened; + g_sessionlistener.OnSessionClosed = OnSessionClosed; + g_sessionlistener.OnBytesReceived = OnBytesReceived; + g_sessionlistener.OnMessageReceived = OnMessageReceived; +} + +static const char *g_testData = "{\n \"data\":\"open auth session test!!!\"\n}"; + +static int32_t TestSendBytesData(const char *data, int32_t len) +{ + printf("SendBytes start\n"); + int32_t ret = SendBytes(g_sessionId, data, len); + if (ret != SOFTBUS_OK) { + printf("SendBytes failed ret[%d] len[%d]\n", ret, len); + } + printf("SendBytes end\n"); + return ret; +} + +static int32_t TestSendMessageData(const char *data, int32_t len) +{ + printf("SendMessage start\n"); + int32_t ret = SendMessage(g_sessionId, data, len); + if (ret != SOFTBUS_OK) { + printf("SendMessage failed ret[%d] len[%d]\n", ret, len); + } + printf("SendMessage end\n"); + return ret; +} + +static int32_t TestCreateSessionServer(int testWay) +{ + int32_t state = -1; + int32_t ret = CreateSessionServer(g_testModuleName, g_testSessionName, &g_sessionlistener); + printf("CreateSessionServer ret: %d \n", ret); + if (ret != SOFTBUS_SERVER_NAME_REPEATED && ret != SOFTBUS_OK) { // -986: SOFTBUS_SERVER_NAME_REPEATED + printf("CreateSessionServer ret: %d \n", ret); + } else if (testWay == 1) { + state = OPEN_SESSION_CASE; + } else if (testWay == 0) { + state = WAIT_OPEN_SESSION_CASE; + } + return state; +} + +static void TestCloseSession(void) +{ + printf("TestCloseSession exit\n"); + if (g_sessionId > 0) { + CloseSession(g_sessionId); + g_sessionId = -1; + } +} + +static int32_t TestOpenAuthSession(void) +{ + printf("OpenAuthSession start\n"); + int32_t state = -1; + g_addrInfo[0].type = CONNECTION_ADDR_BR; + printf("input macaddr: \n"); + if (scanf_s("%s", g_addrInfo[0].info.br.brMac, BT_MAC_LEN) < 0) { + printf("input error!\n"); + return OPEN_SESSION_CASE; + } + printf("brMac: %s\n", g_addrInfo[0].info.br.brMac); + g_sessionId = OpenAuthSession(g_testSessionName, &(g_addrInfo[0]), 1, NULL); + if (g_sessionId < 0) { + printf("OpenAuthSession ret[%d]", g_sessionId); + } else { + state = SEND_DATA_TEST_CASE; + } + printf("OpenAuthSession end\n"); + return state; +} + +#define SEND_DATA_SIZE_1K 1024 +#define SEND_DATA_SIZE_4K (4 * 1024) +#define SEND_DATA_SIZE_40K (40 * 1000 - 8) +#define SEND_DATA_SIZE_64K (64 * 1024) +static int32_t GetSize(char cSize) +{ + int32_t size = SEND_DATA_SIZE_64K + 1; + if (cSize == '0') { + size = SEND_DATA_SIZE_1K; + } else if (cSize == '1') { + size = SEND_DATA_SIZE_4K; + } else if (cSize == '2') { + size = SEND_DATA_SIZE_40K; + } else if (cSize == '3') { + size = SEND_DATA_SIZE_40K + 1; + } else if (cSize == '4') { + size = SEND_DATA_SIZE_64K; + } + return size; +} +static int32_t TestAuthSessionSendData(const char *testData, int32_t count, char cSize) +{ + int32_t waitCnt = 0; + while (!g_successFlag) { + printf("wait OpenAuthSession success Cnt: %d *******\n", waitCnt); + waitCnt++; + if (waitCnt > count) { + printf("wait OpenAuthSession success timeout!\n"); + return SOFTBUS_ERR; + } + sleep(TICK_TIME); + } + int32_t size = GetSize(cSize); + int32_t sendCnt = 0; + int32_t ret; + while (sendCnt < count) { + printf("******* sendCnt[%d] *******\n", sendCnt); + ret = TestSendBytesData(testData, size); + if (size <= SEND_DATA_SIZE_64K) { + if (ret != SOFTBUS_CONNECTION_ERR_SENDQUEUE_FULL && ret != SOFTBUS_OK) { + printf("******* TestSendBytesData %d failed *******\n", size); + return SOFTBUS_ERR; + } + } else { + if (ret == SOFTBUS_OK) { + printf("******* TestSendBytesData %d failed *******\n", size); + return SOFTBUS_ERR; + } + } + sleep(TICK_TIME); + ret = TestSendMessageData(testData, size); + if (size <= SEND_DATA_SIZE_4K) { + if (ret != SOFTBUS_CONNECTION_ERR_SENDQUEUE_FULL && ret != SOFTBUS_OK) { + printf("******* TestSendMessageData %d failed *******\n", size); + return SOFTBUS_ERR; + } + } else { + if (ret == SOFTBUS_OK) { + printf("******* TestSendMessageData %d failed *******\n", size); + return SOFTBUS_ERR; + } + } + sendCnt++; + } + return SOFTBUS_OK; +} + +static void DiscoveryTestEntry(int testWay, int count) +{ + TestSessionListenerInit(); + g_sessionAttr.dataType = TYPE_BYTES; + int stat = 0; + char *testData = (char *)SoftBusCalloc(SEND_DATA_SIZE_64K + 1); + if (memcpy_s(testData, SEND_DATA_SIZE_64K + 1, g_testData, strlen(g_testData)) != EOK) { + printf("memcpy_s g_testData failed!\n"); + return; + } + int ret = SOFTBUS_OK; + while (1) { + if (stat == CREATE_SESSION_CASE) { + stat = TestCreateSessionServer(testWay); + } else if (stat == OPEN_SESSION_CASE) { + stat = TestOpenAuthSession(); + } else if (stat == SEND_DATA_TEST_CASE) { + getchar(); + char cSize; + printf("data size(0:1K, 1:4K, 2:40000, 3:40001, 4:64K, 5:>64K, q:exit): \n"); + if (scanf_s("%c", &cSize, 1) < 0) { + printf("input error!\n"); + continue; + } + if (cSize == 'q') { + stat = -1; + continue; + } + ret = TestAuthSessionSendData(testData, count, cSize); + if (ret != SOFTBUS_OK) { + stat = -1; + } + } else if (stat == WAIT_OPEN_SESSION_CASE) { + if (g_connectCnt >= count) { + stat = -1; + } + } else if (stat == -1) { + TestCloseSession(); + break; + } + sleep(TICK_TIME); + } + SoftBusFree(testData); + if (ret == SOFTBUS_OK) { + printf("Test Auth Channel OK!\n"); + } else { + printf("Test Auth Channel failed!\n"); + } +} + +int main(int argc, char *argv[]) +{ +#define ARGC_NUM 2 + if (argc <= ARGC_NUM) { + printf("error argc <= 2\n"); + return -1; + } + int testWay = atoi(argv[1]); + int count = atoi(argv[ARGC_NUM]); + DiscoveryTestEntry(testWay, count); +} diff --git a/tests/sdk/transmission/trans_channel/ble/BUILD.gn b/tests/sdk/transmission/trans_channel/ble/BUILD.gn new file mode 100644 index 000000000..87ed03b64 --- /dev/null +++ b/tests/sdk/transmission/trans_channel/ble/BUILD.gn @@ -0,0 +1,20 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +group("bleAuthChannelTest") { + testonly = true + deps = [ + "board:dsoftbus_auth_ble_board", + "phone:dsoftbus_auth_ble_phone", + ] +} diff --git a/tests/sdk/transmission/trans_channel/ble/board/BUILD.gn b/tests/sdk/transmission/trans_channel/ble/board/BUILD.gn new file mode 100644 index 000000000..451388d23 --- /dev/null +++ b/tests/sdk/transmission/trans_channel/ble/board/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/communication/dsoftbus/dsoftbus.gni") +module_output_path = "dsoftbus_standard/transmission" +ohos_unittest("dsoftbus_auth_ble_board") { + module_out_path = module_output_path + sources = [ "dsoftbus_auth_ble.cpp" ] + include_dirs = [ + "$dsoftbus_root_path/core/common/inner_communication", + "$dsoftbus_root_path/adapter/common/include", + "$dsoftbus_root_path/core/common/include", + "$dsoftbus_root_path/interfaces/kits/discovery", + "$dsoftbus_root_path/interfaces/kits/common", + "$dsoftbus_root_path/interfaces/inner_kits/transport", + "$dsoftbus_root_path/sdk/discovery/include", + "//utils/native/base/include", + "//third_party/bounds_checking_function/include", + "unittest/common/", + "$dsoftbus_root_path/sdk/discovery/manager/include", + ] + deps = [ + "$dsoftbus_root_path/core/common:softbus_utils", + "$dsoftbus_root_path/sdk:softbus_client", + "//third_party/bounds_checking_function:libsec_static", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "//utils/native/base:utilsecurec_shared", + ] + if (is_standard_system) { + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + } else { + external_deps = [ "hilog:libhilog" ] + } +} diff --git a/tests/sdk/transmission/trans_channel/ble/board/dsoftbus_auth_ble.cpp b/tests/sdk/transmission/trans_channel/ble/board/dsoftbus_auth_ble.cpp new file mode 100644 index 000000000..ff826541f --- /dev/null +++ b/tests/sdk/transmission/trans_channel/ble/board/dsoftbus_auth_ble.cpp @@ -0,0 +1,362 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include "discovery_service.h" +#include "inner_session.h" +#include "session.h" +#include "softbus_utils.h" + +using namespace testing::ext; + +namespace OHOS { +int32_t g_testWay = -1; +enum TEST_WAY { + PASSIVE_OPENAUTHSESSION_WAY = 0, + ACTIVE_OPENAUTHSESSION_WAY +}; + +enum TEST_PROCESS { + TEST_INICIAL = 0, + TEST_BEGIN, + TEST_DEVICEFOUND, + TEST_SESSIONOPEN, + TEST_DATARECEIVE, + TEST_SESSIONCLOSE, +}; +const char *g_pkgName = "com.objectstore.foundation"; +const char *g_sessionName = "objectstore"; +const char *g_testData = "{\"data\":\"open auth session test!!!\"}"; +bool g_state = false; +int g_sessionId = -1; +int g_testCount = 0; +int g_testTimes = 0; +static void Wait(void); +static void Start(void); + +ConnectionAddr g_addr; +ConnectionAddr g_addr1; +class BleAuthChannelTest : public testing::Test { +public: + BleAuthChannelTest() + {} + ~BleAuthChannelTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp() override + {} + void TearDown() override + {} +}; + +void BleAuthChannelTest::SetUpTestCase(void) +{ + printf("********Ble Test Begin*********\r\n"); + printf("* 0.passive openAuthSession *\r\n"); + printf("* 1.active openAuthSession *\r\n"); + printf("********************************\r\n"); + printf("input the num:"); + if (scanf_s("%d", &g_testWay, sizeof(g_testWay)) < 0) { + printf("input error!\n"); + } + getchar(); + printf("input test times:"); + if (scanf_s("%d", &g_testTimes, sizeof(g_testTimes)) < 0) { + printf("input error!\n"); + } + getchar(); +} + +void BleAuthChannelTest::TearDownTestCase(void) +{} + +static SubscribeInfo g_sInfo = { + .subscribeId = 1, + .medium = BLE, + .mode = DISCOVER_MODE_ACTIVE, + .freq = MID, + .capability = "dvKit", + .capabilityData = (unsigned char *)"capdata3", + .dataLen = sizeof("capdata3"), + .isSameAccount = false, + .isWakeRemote = false +}; + +static PublishInfo g_pInfo = { + .publishId = 1, + .medium = BLE, + .mode = DISCOVER_MODE_PASSIVE, + .freq = MID, + .capability = "dvKit", + .capabilityData = (unsigned char *)"capdata4", + .dataLen = sizeof("capdata4") +}; + +static void TestDeviceFound(const DeviceInfo *device) +{ + if (ConvertBtMacToStr(g_addr.info.ble.bleMac, 18, (const uint8_t *)&(device->addr[0].info.ble.bleMac[0]), 6) != 0) { + return; + } + if (strcmp(g_addr1.info.ble.bleMac, g_addr.info.ble.bleMac) != 0) { + EXPECT_TRUE(g_testCount == TEST_BEGIN); + g_testCount++; + strcpy_s(g_addr1.info.ble.bleMac, BT_MAC_LEN, g_addr.info.ble.bleMac); + printf("[client]TestDeviceFound\r\n"); + printf("addr mac = %s\r\n", g_addr1.info.ble.bleMac); + printf("account = %s\r\n", device->hwAccountHash); + g_state = true; + } +} + +static void TestDiscoverFailed(int subscribeId, DiscoveryFailReason failReason) +{ + printf("[test]TestDiscoverFailed\r\n"); +} + +static void TestDiscoverySuccess(int subscribeId) +{ + printf("[test]TestDiscoverySuccess\r\n"); +} + +static void TestPublishSuccess(int publishId) +{ + printf("[test]TestPublishSuccess\r\n"); +} + +static void TestPublishFail(int publishId, PublishFailReason reason) +{ + printf("[test]TestPublishFail\r\n"); +} + +static IDiscoveryCallback g_subscribeCb = { + .OnDeviceFound = TestDeviceFound, + .OnDiscoverFailed = TestDiscoverFailed, + .OnDiscoverySuccess = TestDiscoverySuccess +}; + +static IPublishCallback g_publishCb = { + .OnPublishSuccess = TestPublishSuccess, + .OnPublishFail = TestPublishFail +}; + +static int OnSessionOpened(int sessionId, int result) +{ + printf("[test]session opened,sesison id = %d\r\n", sessionId); + EXPECT_TRUE(g_sessionId == sessionId); + EXPECT_TRUE(g_testCount == TEST_DEVICEFOUND); + g_testCount++; + Start(); + return 0; +} + +static void OnSessionClosed(int sessionId) +{ + printf("[test]session closed, session id = %d\r\n", sessionId); + EXPECT_TRUE(g_testCount == TEST_DATARECEIVE); + g_testCount++; + Start(); +} + +static void OnBytesReceived(int sessionId, const void *data, unsigned int len) +{ + printf("[test]session bytes received, session id = %d data =%s\r\n", sessionId, data); + if (g_testWay == PASSIVE_OPENAUTHSESSION_WAY) { + SendBytes(sessionId, "{\"received ok\"}", strlen("{\"received ok\"}")); + } + EXPECT_TRUE(g_testCount == TEST_SESSIONOPEN); + g_testCount++; + Start(); +} + +static void OnMessageReceived(int sessionId, const void *data, unsigned int len) +{ + printf("[test]session msg received, session id = %d data =%s\r\n", sessionId, data); +} + +static ISessionListener g_sessionlistener = { + .OnSessionOpened = OnSessionOpened, + .OnSessionClosed = OnSessionClosed, + .OnBytesReceived = OnBytesReceived, + .OnMessageReceived = OnMessageReceived, +}; + +static void Wait(void) +{ + printf("[test]wait enter...\r\n"); +SLEEP: + sleep(1); + if (g_state == false) { + goto SLEEP; + } + printf("[test]wait end!\r\n"); + g_state = false; +} + +static void Start(void) +{ + g_state = true; +} + +static int32_t TestPublishServer() +{ + printf("[test]TestPublishServer enter\r\n"); + g_pInfo.mode = DISCOVER_MODE_ACTIVE; + int32_t ret = PublishService(g_pkgName, &g_pInfo, &g_publishCb); + EXPECT_TRUE(ret == 0); + printf("[test]TestPublishServer end\r\n"); + return ret; +} + +static int32_t TestStartDiscovery() +{ + printf("[test]TestStartDiscovery enter\r\n"); + g_sInfo.mode = DISCOVER_MODE_ACTIVE; + int32_t ret = StartDiscovery(g_pkgName, &g_sInfo, &g_subscribeCb); + EXPECT_TRUE(ret == 0); + printf("[test]TestStartDiscovery end\r\n"); + return ret; +} + +static int32_t TestCreateSessionServer() +{ + printf("[test]TestCreateSessionServer enter\r\n"); + int32_t ret = CreateSessionServer(g_pkgName, g_sessionName, &g_sessionlistener); + EXPECT_TRUE(ret == 0); + printf("[test]TestCreateSessionServer end\r\n"); + return ret; +} + +static int32_t TestOpenSession() +{ + printf("[test]TestOpenSession enter\r\n"); + g_addr1.type = CONNECTION_ADDR_BLE; + int32_t ret = OpenAuthSession(g_sessionName, &g_addr1, 1, NULL); + EXPECT_TRUE(ret >= 0); + printf("[test]TestOpenSession end\r\n"); + return ret; +} + +static int32_t TestSendData(const char *data, int32_t len) +{ + printf("[test]TestSendData enter\r\n"); + int32_t ret = SendBytes(g_sessionId, data, len); + EXPECT_TRUE(ret == 0); + printf("[test]TestSendData end\r\n"); + return ret; +} + +static void TestCloseSeeesion() +{ + printf("[test]TestCloseSession enter\n"); + if (g_sessionId > 0) { + CloseSession(g_sessionId); + g_sessionId = -1; + } + printf("[test]TestCloseSession end\n"); +} + +static int32_t TestRemoveSessionServer() +{ + printf("[test]TestRemoveSessionServer enter\r\n"); + int32_t ret = RemoveSessionServer(g_pkgName, g_sessionName); + EXPECT_TRUE(ret == 0); + printf("[test]TestRemoveSessionServer end\r\n"); + return ret; +} + +/** + * @tc.name: PublishServiceTest001 + * @tc.desc: Verify wrong parameter + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(BleAuthChannelTest, ProcessActive001, TestSize.Level0) +{ + if (g_testWay != ACTIVE_OPENAUTHSESSION_WAY) { + printf("[test]active test skip...\r\n"); + EXPECT_TRUE(TEST_INICIAL == 0); + goto END; + } + int32_t ret; + g_testCount = TEST_BEGIN; + ret = TestStartDiscovery(); + EXPECT_TRUE(ret == 0); + Wait(); + ret = TestCreateSessionServer(); + EXPECT_TRUE(ret == 0); + EXPECT_TRUE(g_testCount == TEST_DEVICEFOUND); + for (int i = 0; i < g_testTimes; i++) { + g_testCount = TEST_DEVICEFOUND; + g_sessionId = TestOpenSession(); + EXPECT_TRUE(g_sessionId >= 0); + Wait(); + EXPECT_TRUE(g_testCount == TEST_SESSIONOPEN); + ret = TestSendData(g_testData, strlen(g_testData) + 1); + EXPECT_TRUE(ret == 0); + Wait(); + EXPECT_TRUE(g_testCount == TEST_DATARECEIVE); + TestCloseSeeesion(); + sleep(5); + EXPECT_TRUE(g_testCount == TEST_DATARECEIVE); + } + ret = TestRemoveSessionServer(); + EXPECT_TRUE(ret == 0); +END: + EXPECT_TRUE(TEST_INICIAL == 0); +}; + + +/** + * @tc.name: PublishServiceTest001 + * @tc.desc: Verify wrong parameter + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(BleAuthChannelTest, ProcessPassive001, TestSize.Level0) +{ + if (g_testWay != PASSIVE_OPENAUTHSESSION_WAY) { + printf("[test]passive test skip...\r\n"); + EXPECT_TRUE(TEST_INICIAL == 0); + goto END; + } + int32_t ret; + ret = TestPublishServer(); + EXPECT_TRUE(ret == 0); + ret = TestCreateSessionServer(); + EXPECT_TRUE(ret == 0); + for (int i = 0; i < g_testTimes; i++) { + g_testCount = TEST_DEVICEFOUND; + printf("[test][times:%d],Waiting for session opening...\r\n", i); + Wait(); + EXPECT_TRUE(g_testCount == TEST_SESSIONOPEN); + printf("[test][times:%d],session opened,Waiting for data receiving...\r\n", i); + Wait(); + EXPECT_TRUE(g_testCount == TEST_DATARECEIVE); + printf("[test][times:%d],data received,Waiting for session closing...\r\n", i); + Wait(); + EXPECT_TRUE(g_testCount == TEST_SESSIONCLOSE); + printf("[test][times:%d],session closed,time time over\r\n", i); + } + printf("passive test over\r\n"); +END: + EXPECT_TRUE(TEST_INICIAL == 0); +}; +} \ No newline at end of file diff --git a/tests/sdk/transmission/trans_channel/ble/phone/BUILD.gn b/tests/sdk/transmission/trans_channel/ble/phone/BUILD.gn new file mode 100644 index 000000000..d1f041b16 --- /dev/null +++ b/tests/sdk/transmission/trans_channel/ble/phone/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/communication/dsoftbus/dsoftbus.gni") +module_output_path = "dsoftbus_standard/transmission" +ohos_unittest("dsoftbus_auth_ble_phone") { + module_out_path = module_output_path + sources = [ "dsoftbus_ble_phone.cpp" ] + include_dirs = [ + "$dsoftbus_root_path/core/common/inner_communication", + "$dsoftbus_root_path/adapter/common/include", + "$dsoftbus_root_path/core/common/include", + "$dsoftbus_root_path/interfaces/kits/discovery", + "$dsoftbus_root_path/interfaces/kits/common", + "$dsoftbus_root_path/interfaces/inner_kits/transport", + "$dsoftbus_root_path/sdk/discovery/include", + "//utils/native/base/include", + "//third_party/bounds_checking_function/include", + "unittest/common/", + "$dsoftbus_root_path/sdk/discovery/manager/include", + ] + deps = [ + "$dsoftbus_root_path/core/common:softbus_utils", + "$dsoftbus_root_path/sdk:softbus_client", + "//third_party/bounds_checking_function:libsec_static", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "//utils/native/base:utilsecurec_shared", + ] + if (is_standard_system) { + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + } else { + external_deps = [ "hilog:libhilog" ] + } +} diff --git a/tests/sdk/transmission/trans_channel/ble/phone/dsoftbus_ble_phone.cpp b/tests/sdk/transmission/trans_channel/ble/phone/dsoftbus_ble_phone.cpp new file mode 100644 index 000000000..671e88c50 --- /dev/null +++ b/tests/sdk/transmission/trans_channel/ble/phone/dsoftbus_ble_phone.cpp @@ -0,0 +1,275 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include "discovery_service.h" +#include "inner_session.h" +#include "session.h" +#include "softbus_utils.h" + +using namespace testing::ext; + +namespace OHOS { + +enum TEST_PROCESS { + TEST_INICIAL = 0, + TEST_BEGIN, + TEST_DEVICEFOUND, + TEST_SESSIONOPEN, + TEST_DATARECEIVE, + TEST_SESSIONCLOSE, +}; +const char *g_pkgName = "com.plrdtest"; +const char *g_sessionName = "com.plrdtest.dsoftbus"; +const char *g_testData = "{\"data\":\"open auth session test!!!\"}"; +bool g_state = false; +int g_sessionId = -1; +int g_testCount = 0; +int g_testTimes = 0; +static void Wait(void); +static void Start(void); + +ConnectionAddr g_addr; +ConnectionAddr g_addr1; +class BleAuthChannelPhoneTest : public testing::Test { +public: + BleAuthChannelPhoneTest() + {} + ~BleAuthChannelPhoneTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp() override + {} + void TearDown() override + {} +}; + +void BleAuthChannelPhoneTest::SetUpTestCase(void) +{ + printf("input test times:"); + if (scanf_s("%d", &g_testTimes, sizeof(g_testTimes)) < 0) { + printf("input error!\n"); + } + getchar(); +} + +void BleAuthChannelPhoneTest::TearDownTestCase(void) +{} + +static SubscribeInfo g_sInfo = { + .subscribeId = 1, + .medium = BLE, + .mode = DISCOVER_MODE_ACTIVE, + .freq = MID, + .capability = "dvKit", + .capabilityData = (unsigned char *)"capdata3", + .dataLen = sizeof("capdata3"), + .isSameAccount = false, + .isWakeRemote = false +}; + +static void TestDeviceFound(const DeviceInfo *device) +{ + if (ConvertBtMacToStr(g_addr.info.ble.bleMac, 18, (const uint8_t *)&(device->addr[0].info.ble.bleMac[0]), 6) != 0) { + return; + } + if (strcmp(g_addr1.info.ble.bleMac, g_addr.info.ble.bleMac) != 0) { + EXPECT_TRUE(g_testCount == TEST_BEGIN); + g_testCount++; + strcpy_s(g_addr1.info.ble.bleMac, BT_MAC_LEN, g_addr.info.ble.bleMac); + printf("[client]TestDeviceFound\r\n"); + printf("addr mac = %s\r\n", g_addr1.info.ble.bleMac); + printf("account = %s\r\n", device->hwAccountHash); + g_state = true; + } +} + +static void TestDiscoverFailed(int subscribeId, DiscoveryFailReason failReason) +{ + printf("[test]TestDiscoverFailed\r\n"); +} + +static void TestDiscoverySuccess(int subscribeId) +{ + printf("[test]TestDiscoverySuccess\r\n"); +} + +static void TestPublishSuccess(int publishId) +{ + printf("[test]TestPublishSuccess\r\n"); +} + +static void TestPublishFail(int publishId, PublishFailReason reason) +{ + printf("[test]TestPublishFail\r\n"); +} + +static IDiscoveryCallback g_subscribeCb = { + .OnDeviceFound = TestDeviceFound, + .OnDiscoverFailed = TestDiscoverFailed, + .OnDiscoverySuccess = TestDiscoverySuccess +}; + +static IPublishCallback g_publishCb = { + .OnPublishSuccess = TestPublishSuccess, + .OnPublishFail = TestPublishFail +}; + +static int OnSessionOpened(int sessionId, int result) +{ + printf("[test]session opened,sesison id = %d\r\n", sessionId); + EXPECT_TRUE(g_sessionId == sessionId); + EXPECT_TRUE(g_testCount == TEST_DEVICEFOUND); + g_testCount++; + Start(); + return 0; +} + +static void OnSessionClosed(int sessionId) +{ + printf("[test]session closed, session id = %d\r\n", sessionId); +} + +static void OnBytesReceived(int sessionId, const void *data, unsigned int len) +{ + printf("[test]session bytes received, session id = %d data =%s\r\n", sessionId, data); +} + +static void OnMessageReceived(int sessionId, const void *data, unsigned int len) +{ + printf("[test]session msg received, session id = %d data =%s\r\n", sessionId, data); +} + +static ISessionListener g_sessionlistener = { + .OnSessionOpened = OnSessionOpened, + .OnSessionClosed = OnSessionClosed, + .OnBytesReceived = OnBytesReceived, + .OnMessageReceived = OnMessageReceived, +}; + +static void Wait(void) +{ + printf("[test]wait enter...\r\n"); +SLEEP: + sleep(1); + if (g_state == false) { + goto SLEEP; + } + printf("[test]wait end!\r\n"); + g_state = false; +} + +static void Start(void) +{ + g_state = true; +} + +static int32_t TestStartDiscovery() +{ + printf("[test]TestStartDiscovery enter\r\n"); + g_sInfo.mode = DISCOVER_MODE_ACTIVE; + int32_t ret = StartDiscovery(g_pkgName, &g_sInfo, &g_subscribeCb); + EXPECT_TRUE(ret == 0); + printf("[test]TestStartDiscovery end\r\n"); + return ret; +} + +static int32_t TestCreateSessionServer() +{ + printf("[test]TestCreateSessionServer enter\r\n"); + int32_t ret = CreateSessionServer(g_pkgName, g_sessionName, &g_sessionlistener); + EXPECT_TRUE(ret == 0); + printf("[test]TestCreateSessionServer end\r\n"); + return ret; +} + +static int32_t TestOpenSession() +{ + printf("[test]TestOpenSession enter\r\n"); + g_addr1.type = CONNECTION_ADDR_BLE; + int32_t ret = OpenAuthSession(g_sessionName, &g_addr1, 1, NULL); + EXPECT_TRUE(ret >= 0); + printf("[test]TestOpenSession end\r\n"); + return ret; +} + +static int32_t TestSendData(const char *data, int32_t len) +{ + printf("[test]TestSendData enter\r\n"); + int32_t ret = SendBytes(g_sessionId, data, len); + EXPECT_TRUE(ret == 0); + printf("[test]TestSendData end\r\n"); + return ret; +} + +static void TestCloseSeeesion() +{ + printf("[test]TestCloseSession enter\n"); + if (g_sessionId > 0) { + CloseSession(g_sessionId); + g_sessionId = -1; + } + printf("[test]TestCloseSession end\n"); +} + +static int32_t TestRemoveSessionServer() +{ + printf("[test]TestRemoveSessionServer enter\r\n"); + int32_t ret = RemoveSessionServer(g_pkgName, g_sessionName); + EXPECT_TRUE(ret == 0); + printf("[test]TestRemoveSessionServer end\r\n"); + return ret; +} + +/** + * @tc.name: PublishServiceTest001 + * @tc.desc: Verify wrong parameter + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(BleAuthChannelPhoneTest, ProcessPhoneActive001, TestSize.Level0) +{ + int32_t ret; + g_testCount = TEST_BEGIN; + ret = TestStartDiscovery(); + EXPECT_TRUE(ret == 0); + Wait(); + ret = TestCreateSessionServer(); + EXPECT_TRUE(ret == 0); + EXPECT_TRUE(g_testCount == TEST_DEVICEFOUND); + for (int i = 0; i < g_testTimes; i++) { + g_testCount = TEST_DEVICEFOUND; + g_sessionId = TestOpenSession(); + EXPECT_TRUE(g_sessionId >= 0); + Wait(); + EXPECT_TRUE(g_testCount == TEST_SESSIONOPEN); + ret = TestSendData(g_testData, strlen(g_testData) + 1); + EXPECT_TRUE(ret == 0); + sleep(3); + TestCloseSeeesion(); + sleep(5); + } + ret = TestRemoveSessionServer(); + EXPECT_TRUE(ret == 0); +END: + EXPECT_TRUE(TEST_INICIAL == 0); +}; +} \ No newline at end of file diff --git a/tests/sdk/transmission/trans_channel/br/BUILD.gn b/tests/sdk/transmission/trans_channel/br/BUILD.gn new file mode 100644 index 000000000..b05dd5c06 --- /dev/null +++ b/tests/sdk/transmission/trans_channel/br/BUILD.gn @@ -0,0 +1,43 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/communication/dsoftbus/dsoftbus.gni") + +module_output_path = "dsoftbus_standard/connection" + +ohos_unittest("auth_session_gtest") { + module_out_path = module_output_path + include_dirs = [ + "$dsoftbus_root_path/core/common/include", + "$softbus_adapter_common/include", + "$dsoftbus_root_path/interfaces/kits/common", + "$dsoftbus_root_path/interfaces/inner_kits/transport", + "//third_party/googletest/googletest/include", + "//third_party/googletest/googletest/src", + "//third_party/bounds_checking_function/include", + ] + + deps = [ + "$dsoftbus_root_path/adapter:softbus_adapter", + "$dsoftbus_root_path/core/common:softbus_utils", + "$dsoftbus_root_path/sdk:softbus_client", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "//utils/native/base:utilsecurec_shared", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + sources = [ "auth_session_gtest.cpp" ] +} diff --git a/tests/sdk/transmission/trans_channel/br/auth_session_gtest.cpp b/tests/sdk/transmission/trans_channel/br/auth_session_gtest.cpp new file mode 100644 index 000000000..bfb3d2c3f --- /dev/null +++ b/tests/sdk/transmission/trans_channel/br/auth_session_gtest.cpp @@ -0,0 +1,409 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved. + * Description: br connection test. + * 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 +#include + +#include "common_list.h" +#include "inner_session.h" +#include "session.h" +#include "softbus_adapter_mem.h" +#include "softbus_adapter_timer.h" +#include "softbus_bus_center.h" +#include "softbus_common.h" +#include "softbus_def.h" +#include "softbus_errcode.h" +#include "softbus_feature_config.h" +#include "softbus_log.h" +#include "softbus_utils.h" + +using namespace testing::ext; + +namespace OHOS { +enum TEST_WAY { + PASSIVE_OPENAUTHSESSION_WAY = 0, + ACTIVE_OPENAUTHSESSION_WAY +}; + +const int CONN_SINGLE_WAIT_TIMEOUT = 5; +const int CONN_SLEEP_TIME = 1; +const int CLOSE_DELAY_TIME = 500; + +const int SEND_DATA_SIZE_1K = 1024; +const int SEND_DATA_SIZE_4K = 4 * 1024; +const int SEND_DATA_SIZE_40K = 40 * 1000 - 8; + +const int CONN_ADDR_INFO_COUNT = 5; +ConnectionAddr g_addrInfo[CONN_ADDR_INFO_COUNT]; + +ISessionListener g_sessionlistener; +int32_t g_openCount = 0; +const char *g_testModuleName = "com.huawei.plrdtest"; +const char *g_testSessionName = "com.huawei.plrdtest.dsoftbus"; +const char *g_testData = "{\"data\":\"open auth session test!!!\"}"; + +int32_t g_sessionId = -1; +int32_t g_sessionIdTwo = -1; +bool g_successFlag = false; +int32_t g_testWay = -1; + +int32_t TestSendBytesData(int32_t sessionId, const char *data) +{ + int32_t ret = SendBytes(sessionId, data, SEND_DATA_SIZE_1K); + if (ret != SOFTBUS_OK) { + printf("SendBytes 1K err.\n"); + return SOFTBUS_ERR; + } + ret = SendBytes(sessionId, data, SEND_DATA_SIZE_4K); + if (ret != SOFTBUS_OK) { + printf("SendBytes 4K err.\n"); + return SOFTBUS_ERR; + } + ret = SendBytes(sessionId, data, SEND_DATA_SIZE_40K); + if (ret != SOFTBUS_OK) { + printf("SendBytes 40000 err.\n"); + return SOFTBUS_ERR; + } + ret = SendBytes(sessionId, data, SEND_DATA_SIZE_40K + 1); + if (ret == SOFTBUS_OK) { + printf("SendBytes 40001 err.\n"); + return SOFTBUS_ERR; + } + return SOFTBUS_OK; +} + +int32_t TestSendMessageData(int32_t sessionId, const char *data) +{ + int32_t ret = SendMessage(sessionId, data, SEND_DATA_SIZE_1K); + if (ret != SOFTBUS_OK) { + printf("SendMessage 1K err.\n"); + return SOFTBUS_ERR; + } + ret = SendMessage(sessionId, data, SEND_DATA_SIZE_4K); + if (ret != SOFTBUS_OK) { + printf("SendMessage 4K err.\n"); + return SOFTBUS_ERR; + } + ret = SendMessage(sessionId, data, SEND_DATA_SIZE_4K + 1); + if (ret == SOFTBUS_OK) { + printf("SendMessage 4K + 1 err.\n"); + return SOFTBUS_ERR; + } + return SOFTBUS_OK; +} + +int32_t TestSendData(int32_t sessionId, const char *data, int32_t len) +{ + int32_t ret; + if (len <= SEND_DATA_SIZE_40K) { + ret = SendBytes(sessionId, data, len); + if (ret != SOFTBUS_OK) { + return ret; + } + } else { + ret = TestSendBytesData(sessionId, data); + if (ret != SOFTBUS_OK) { + return ret; + } + ret = TestSendMessageData(sessionId, data); + if (ret != SOFTBUS_OK) { + return ret; + } + } + return SOFTBUS_OK; +} + +int OnSessionOpened(int sessionId, int result) +{ + printf("############# session opened,sesison id[%d] result[%d]\n", sessionId, result); + if (result == SOFTBUS_OK) { + if (g_sessionId == -1) { + g_sessionId = sessionId; + } + g_successFlag = true; + g_openCount++; + } + return result; +} + +void OnSessionClosed(int sessionId) +{ + printf("############# session closed, session id = %d\n", sessionId); + g_sessionId = -1; + g_successFlag = false; +} + +void OnBytesReceived(int sessionId, const void *data, unsigned int len) +{ + if (g_testWay == PASSIVE_OPENAUTHSESSION_WAY) { + SendBytes(sessionId, "{\"received ok\"}", strlen("{\"received ok\"}")); + } + printf("bytes received, sessionid[%d], data[%s], dataLen[%d]\n", sessionId, data, len); +} + +void OnMessageReceived(int sessionId, const void *data, unsigned int len) +{ + printf("msg received, sessionid[%d], data[%s], dataLen[%d]\n", sessionId, data, len); +} + +void TestSessionListenerInit(void) +{ + g_sessionlistener.OnSessionOpened = OnSessionOpened; + g_sessionlistener.OnSessionClosed = OnSessionClosed; + g_sessionlistener.OnBytesReceived = OnBytesReceived; + g_sessionlistener.OnMessageReceived = OnMessageReceived; +} + +int32_t TestCreateSessionServer(void) +{ + int32_t ret = CreateSessionServer(g_testModuleName, g_testSessionName, &g_sessionlistener); + if (ret != SOFTBUS_SERVER_NAME_REPEATED && ret != SOFTBUS_OK) { // -986: SOFTBUS_SERVER_NAME_REPEATED + printf("CreateSessionServer ret: %d \n", ret); + return SOFTBUS_ERR; + } + printf("CreateSessionServer ret: %d \n", ret); + return SOFTBUS_OK; +} + +int32_t TestOpenAuthSession(const ConnectionAddr *addrInfo, bool two) +{ + g_sessionId = OpenAuthSession(g_testSessionName, addrInfo, 1, NULL); + if (g_sessionId < 0) { + printf("OpenAuthSession ret[%d]", g_sessionId); + return SOFTBUS_ERR; + } + if (two) { + g_sessionIdTwo = OpenAuthSession(g_testSessionName, addrInfo, 1, NULL); + if (g_sessionIdTwo < 0) { + printf("OpenAuthSession ret[%d]", g_sessionIdTwo); + return SOFTBUS_ERR; + } + } + int32_t timeout = 0; + while (!g_successFlag) { + timeout++; + if (timeout > CONN_SINGLE_WAIT_TIMEOUT) { + printf("wait [%ds] timeout!!\n", CONN_SINGLE_WAIT_TIMEOUT); + return SOFTBUS_ERR; + } + sleep(CONN_SLEEP_TIME); + } + return SOFTBUS_OK; +} + +void TestCloseSession(void) +{ + printf("TestCloseSession exit\n"); + if (g_sessionId > 0) { + CloseSession(g_sessionId); + g_sessionId = -1; + g_successFlag = false; + } +} + +void TestCloseSessionTwo(void) +{ + printf("TestCloseSessionTwo exit\n"); + if (g_sessionIdTwo > 0) { + CloseSession(g_sessionIdTwo); + g_sessionIdTwo = -1; + } +} + +class SoftbusOpenAuthTest : public testing::Test { +public: + SoftbusOpenAuthTest() + {} + ~SoftbusOpenAuthTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + int32_t TestWaitOpenSession(int32_t count); +}; + +void SoftbusOpenAuthTest::SetUpTestCase(void) +{ + SoftbusConfigInit(); + TestSessionListenerInit(); + printf("********Disc Test Begin*********\r\n"); + printf("* 0.passive openAuthSession *\r\n"); + printf("* 1.active openAuthSession *\r\n"); + printf("********************************\r\n"); + printf("input the num:"); + if (scanf_s("%d", &g_testWay, sizeof(g_testWay)) < 0) { + printf("input error!\n"); + } + getchar(); +} + +void SoftbusOpenAuthTest::TearDownTestCase(void) +{} + +void SoftbusOpenAuthTest::SetUp(void) +{} + +void SoftbusOpenAuthTest::TearDown(void) +{ + TestCloseSession(); +} + +int32_t SoftbusOpenAuthTest::TestWaitOpenSession(int32_t count) +{ + int32_t timeout = count * CONN_SINGLE_WAIT_TIMEOUT; + while (g_openCount < count) { + --timeout; + if (!timeout) { + printf("wait [%d] timeout!!\n", count); + break; + } + sleep(CONN_SLEEP_TIME); + } + return (g_openCount < count) ? SOFTBUS_ERR : SOFTBUS_OK; +} + +/* +* @tc.name: testPassiveOpenAuthSession001 +* @tc.desc: test passive open auth session +* @tc.type: FUNC +* @tc.require:AR000GIRGG +*/ +HWTEST_F(SoftbusOpenAuthTest, testPassiveOpenAuthSession001, TestSize.Level1) +{ + if (g_testWay != PASSIVE_OPENAUTHSESSION_WAY) { + printf("skip testPassiveOpenAuthSession001 test."); + EXPECT_EQ(SOFTBUS_OK, SOFTBUS_OK); + return; + } + printf("test begin testPassiveOpenAuthSession001 \r\n"); + int32_t ret = TestCreateSessionServer(); + EXPECT_EQ(SOFTBUS_OK, ret); + int32_t count = 10; + printf("input the test count: \n"); + if (scanf_s("%d", &count, sizeof(count)) < 0) { + printf("input error!\n"); + EXPECT_EQ(SOFTBUS_OK, SOFTBUS_ERR); + return; + } + getchar(); + ret = TestWaitOpenSession(count); + EXPECT_EQ(SOFTBUS_OK, ret); + sleep(CONN_SLEEP_TIME); + sleep(CONN_SLEEP_TIME); + TestCloseSession(); +}; + +/* +* @tc.name: testActiveOpenAuthSession001 +* @tc.desc: test active open auth session +* @tc.type: FUNC +* @tc.require:AR000GIRGG +*/ +HWTEST_F(SoftbusOpenAuthTest, testActiveOpenAuthSession001, TestSize.Level1) +{ + if (g_testWay != ACTIVE_OPENAUTHSESSION_WAY) { + printf("skip testActiveOpenAuthSession001 test."); + EXPECT_EQ(SOFTBUS_OK, SOFTBUS_OK); + return; + } + printf("test begin testActiveOpenAuthSession001 \r\n"); + int32_t ret = TestCreateSessionServer(); + EXPECT_EQ(SOFTBUS_OK, ret); + g_addrInfo[0].type = CONNECTION_ADDR_BR; + printf("input macaddr: \n"); + if (scanf_s("%s", g_addrInfo[0].info.br.brMac, BT_MAC_LEN) < 0) { + printf("input error!\n"); + EXPECT_EQ(SOFTBUS_OK, SOFTBUS_ERR); + return; + } + printf("brMac: %s\n", g_addrInfo[0].info.br.brMac); + getchar(); + int32_t count = 10; + printf("input the test count: \n"); + if (scanf_s("%d", &count, sizeof(count)) < 0) { + printf("input error!\n"); + EXPECT_EQ(SOFTBUS_OK, SOFTBUS_ERR); + return; + } + char *testData = (char *)SoftBusCalloc(SEND_DATA_SIZE_40K + 1); + if (testData == nullptr) { + printf("SoftBusCalloc error!\n"); + EXPECT_EQ(SOFTBUS_OK, SOFTBUS_ERR); + return; + } + if (memcpy_s(testData, SEND_DATA_SIZE_40K + 1, g_testData, strlen(g_testData)) != EOK) { + printf("memcpy_s g_testData failed!\n"); + SoftBusFree(testData); + return; + } + for (int32_t i = 0; i < count; i++) { + ret = TestOpenAuthSession(&(g_addrInfo[0]), false); + EXPECT_EQ(SOFTBUS_OK, ret); + ret = TestSendData(g_sessionId, testData, SEND_DATA_SIZE_40K + 1); + EXPECT_EQ(SOFTBUS_OK, ret); + sleep(CONN_SLEEP_TIME); + TestCloseSession(); + SoftBusSleepMs(CLOSE_DELAY_TIME); + } + SoftBusFree(testData); + EXPECT_EQ(SOFTBUS_OK, SOFTBUS_OK); +}; + +/* +* @tc.name: testActiveOpenAuthSession002 +* @tc.desc: test active open 2 auth session +* @tc.type: FUNC +* @tc.require:AR000GIRGG +*/ +HWTEST_F(SoftbusOpenAuthTest, testActiveOpenAuthSession002, TestSize.Level1) +{ + if (g_testWay != ACTIVE_OPENAUTHSESSION_WAY) { + printf("skip testActiveOpenAuthSession002 test."); + EXPECT_EQ(SOFTBUS_OK, SOFTBUS_OK); + return; + } + printf("test begin testActiveOpenAuthSession002 \r\n"); + int32_t ret = TestCreateSessionServer(); + EXPECT_EQ(SOFTBUS_OK, ret); + char *testData = (char *)SoftBusCalloc(SEND_DATA_SIZE_1K); + if (testData == nullptr) { + printf("SoftBusCalloc error!\n"); + EXPECT_EQ(SOFTBUS_OK, SOFTBUS_ERR); + return; + } + if (memcpy_s(testData, SEND_DATA_SIZE_1K, g_testData, strlen(g_testData)) != EOK) { + printf("memcpy_s g_testData failed!\n"); + SoftBusFree(testData); + return; + } + ret = TestOpenAuthSession(&(g_addrInfo[0]), true); + EXPECT_EQ(SOFTBUS_OK, ret); + ret = TestSendData(g_sessionId, testData, SEND_DATA_SIZE_1K); + ret = TestSendData(g_sessionIdTwo, testData, SEND_DATA_SIZE_1K); + EXPECT_EQ(SOFTBUS_OK, ret); + sleep(CONN_SLEEP_TIME); + TestCloseSession(); + TestCloseSessionTwo(); + SoftBusSleepMs(CLOSE_DELAY_TIME); + SoftBusFree(testData); + EXPECT_EQ(SOFTBUS_OK, SOFTBUS_OK); +}; +} \ No newline at end of file diff --git a/tests/sdk/transmission/trans_channel/qos/BUILD.gn b/tests/sdk/transmission/trans_channel/qos/BUILD.gn new file mode 100644 index 000000000..6fc048dec --- /dev/null +++ b/tests/sdk/transmission/trans_channel/qos/BUILD.gn @@ -0,0 +1,101 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/communication/dsoftbus/dsoftbus.gni") + +module_output_path = "dsoftbus_standard/transmission" + +ohos_unittest("TransQosTest") { + module_out_path = module_output_path + sources = [ "trans_qos_test.cpp" ] + + include_dirs = [ + "$dsoftbus_root_path/core/common/include", + "$dsoftbus_root_path/interfaces/kits/transport", + "$dsoftbus_root_path/interfaces/kits/common", + "//utils/native/base/include", + ] + + deps = [ + "$dsoftbus_root_path/sdk:softbus_client", + "//third_party/bounds_checking_function:libsec_static", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + if (is_standard_system) { + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + } else { + external_deps = [ "hilog:libhilog" ] + } +} + +ohos_unittest("TransQosStatClientTest") { + module_out_path = module_output_path + sources = [ "trans_qos_stat_client_test.cpp" ] + + include_dirs = [ + "$dsoftbus_root_path/core/common/include", + "$dsoftbus_root_path/interfaces/kits/transport", + "$dsoftbus_root_path/interfaces/kits/common", + "//utils/native/base/include", + ] + + deps = [ + "$dsoftbus_root_path/sdk:softbus_client", + "//third_party/bounds_checking_function:libsec_static", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + if (is_standard_system) { + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + } else { + external_deps = [ "hilog:libhilog" ] + } +} + +ohos_unittest("TransQosStatServerTest") { + module_out_path = module_output_path + sources = [ "trans_qos_stat_server_test.cpp" ] + + include_dirs = [ + "$dsoftbus_root_path/core/common/include", + "$dsoftbus_root_path/interfaces/kits/transport", + "$dsoftbus_root_path/interfaces/kits/common", + "//utils/native/base/include", + ] + + deps = [ + "$dsoftbus_root_path/sdk:softbus_client", + "//third_party/bounds_checking_function:libsec_static", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + if (is_standard_system) { + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + } else { + external_deps = [ "hilog:libhilog" ] + } +} + +group("unittest") { + testonly = true + deps = [ + ":TransQosStatClientTest", + ":TransQosStatServerTest", + ":TransQosTest", + ] +} diff --git a/tests/sdk/transmission/trans_channel/qos/trans_qos_stat_client_test.cpp b/tests/sdk/transmission/trans_channel/qos/trans_qos_stat_client_test.cpp new file mode 100644 index 000000000..6cf5b511f --- /dev/null +++ b/tests/sdk/transmission/trans_channel/qos/trans_qos_stat_client_test.cpp @@ -0,0 +1,429 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include "securec.h" +#include "session.h" +#include "softbus_bus_center.h" +#include "softbus_errcode.h" + +using namespace testing::ext; +namespace OHOS { +const std::string UDP_TEST_PKG_NAME = "com.huawei.plrdtest.dsoftbus.client"; +const std::string UDP_TEST_SESSION_NAME = "com.huawei.plrdtest.dsoftbus.JtSendRawStream_0"; +const int32_t PERIOD_MS = 1000; +std::map g_qosEventCount; +std::map g_timeDiff; +std::map g_lastTimeStamp; +std::map> g_speedStat; + +class TransQosStatClientTest : public testing::Test { +public: + TransQosStatClientTest() + {} + ~TransQosStatClientTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp() override + { + g_timeDiff.clear(); + g_speedStat.clear(); + g_lastTimeStamp.clear(); + g_qosEventCount.clear(); + } + void TearDown() override + { + g_timeDiff.clear(); + g_speedStat.clear(); + g_lastTimeStamp.clear(); + g_qosEventCount.clear(); + } +}; + +void TransQosStatClientTest::SetUpTestCase(void) +{ + g_timeDiff.clear(); + g_speedStat.clear(); + g_lastTimeStamp.clear(); + g_qosEventCount.clear(); +} + +void TransQosStatClientTest::TearDownTestCase(void) +{ + g_timeDiff.clear(); + g_speedStat.clear(); + g_lastTimeStamp.clear(); + g_qosEventCount.clear(); +} + +static int OnSessionOpend(int sessionId, int result) +{ + printf("on session opened[sessionId = %d, result = %d]\n", sessionId, result); + g_qosEventCount[sessionId] = 0; + g_timeDiff[sessionId] = 0; + g_speedStat[sessionId] = std::vector(); + return 0; +} + +static void OnSessionClosed(int sessionId) +{ + printf("on session closed[sessionId = %d]\n", sessionId); +} + +static void OnStreamReceived(int sessionId, const StreamData *data, const StreamData *ext, const StreamFrameInfo *param) +{} + +static void OnBytesReceived(int sessionId, const void *data, unsigned int dataLen) +{} + +static void OnMessageReceived(int sessionId, const void *data, unsigned int dataLen) +{} + +static void OnQosEvent(int sessionId, int eventId, int tvCount, const QosTv *tvList) +{ + if (eventId == TRANS_STREAM_QUALITY_EVENT && tvCount == 1 && tvList[0].type == STREAM_TRAFFIC_STASTICS) { + if (g_qosEventCount.find(sessionId) != g_qosEventCount.end()) { + g_qosEventCount[sessionId]++; + } + if (g_timeDiff.find(sessionId) == g_timeDiff.end()) { + g_timeDiff[sessionId] = 0; + } + if (g_speedStat.find(sessionId) != g_speedStat.end()) { + g_speedStat[sessionId].push_back(tvList[0].info.appStatistics.periodSendBits); + } else { + g_speedStat[sessionId] = std::vector(); + } + if (g_lastTimeStamp.find(sessionId) != g_lastTimeStamp.end()) { + g_timeDiff[sessionId] += + tvList[0].info.appStatistics.statisticsGotTime - g_lastTimeStamp[sessionId] - PERIOD_MS; + } + g_lastTimeStamp[sessionId] = tvList[0].info.appStatistics.statisticsGotTime; + } +} + +static uint64_t CalSendBits(const std::vector &rateList) +{ + uint64_t sum = 0; + if (rateList.size() > 0) { + return rateList[rateList.size() - 1]; + } + return 0; +} + +static ISessionListener g_hasQosCb = { + .OnSessionOpened = OnSessionOpend, + .OnSessionClosed = OnSessionClosed, + .OnStreamReceived = OnStreamReceived, + .OnBytesReceived = OnBytesReceived, + .OnMessageReceived = OnMessageReceived, + .OnQosEvent = OnQosEvent, +}; + +static ISessionListener g_noQosCb = { + .OnSessionOpened = OnSessionOpend, + .OnSessionClosed = OnSessionClosed, + .OnStreamReceived = OnStreamReceived, + .OnBytesReceived = OnBytesReceived, + .OnMessageReceived = OnMessageReceived, + .OnQosEvent = NULL, +}; + +/** + * @tc.name: TransQosStatClientTest001 + * @tc.desc: null sessionListener + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(TransQosStatClientTest, QosStatClientTest001, TestSize.Level0) +{ + int32_t ret = CreateSessionServer(UDP_TEST_PKG_NAME.c_str(), UDP_TEST_SESSION_NAME.c_str(), NULL); + EXPECT_NE(ret, SOFTBUS_OK); +} + +/** + * @tc.name: TransQosStatClientTest002 + * @tc.desc: sessionListener without onQosEvent + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(TransQosStatClientTest, QosStatClientTest002, TestSize.Level0) +{ + int32_t sendTimes = 10; + int32_t ret = CreateSessionServer(UDP_TEST_PKG_NAME.c_str(), UDP_TEST_SESSION_NAME.c_str(), &g_noQosCb); + EXPECT_EQ(ret, SOFTBUS_OK); + NodeBasicInfo *info; + int32_t infoNum; + ret = GetAllNodeDeviceInfo(UDP_TEST_PKG_NAME.c_str(), &info, &infoNum); + EXPECT_EQ(ret, SOFTBUS_OK); + SessionAttribute attr = {0}; + attr.dataType = TYPE_STREAM; + attr.attr.streamAttr.streamType = RAW_STREAM; + int32_t sessionId = OpenSession(UDP_TEST_SESSION_NAME.c_str(), UDP_TEST_SESSION_NAME.c_str(), + info[0].networkId, "0", &attr); + EXPECT_NE(-1, sessionId); + sleep(2); + + char sendStringData[100000]; + memset_s(sendStringData, sizeof(sendStringData), 97, sizeof(sendStringData)); + StreamData d1 = { + sendStringData, + 100000, + }; + StreamData d2 = { + "maogeniubi", + 10, + }; + StreamFrameInfo tmpf = {}; + for (int32_t times = 0; times < sendTimes; times++) { + ret = SendStream(sessionId, &d1, &d2, &tmpf); + EXPECT_EQ(ret, SOFTBUS_OK); + sleep(1); + } + EXPECT_EQ(g_qosEventCount[sessionId], 0); + CloseSession(sessionId); + sleep(1); + ret = RemoveSessionServer(UDP_TEST_PKG_NAME.c_str(), UDP_TEST_SESSION_NAME.c_str()); + EXPECT_EQ(ret, SOFTBUS_OK); +} + +/** + * @tc.name: TransQosStatClientTest003 + * @tc.desc: sessionListener with onQosEvent + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(TransQosStatClientTest, QosStatClientTest003, TestSize.Level0) +{ + int32_t sendTimes = 10; + int32_t ret = CreateSessionServer(UDP_TEST_PKG_NAME.c_str(), UDP_TEST_SESSION_NAME.c_str(), &g_hasQosCb); + EXPECT_EQ(ret, SOFTBUS_OK); + NodeBasicInfo *info; + int32_t infoNum; + ret = GetAllNodeDeviceInfo(UDP_TEST_PKG_NAME.c_str(), &info, &infoNum); + EXPECT_EQ(ret, SOFTBUS_OK); + SessionAttribute attr = {0}; + attr.dataType = TYPE_STREAM; + attr.attr.streamAttr.streamType = RAW_STREAM; + int32_t sessionId = OpenSession(UDP_TEST_SESSION_NAME.c_str(), UDP_TEST_SESSION_NAME.c_str(), + info[0].networkId, "0", &attr); + EXPECT_NE(-1, sessionId); + sleep(2); + + char sendStringData[100000]; + memset_s(sendStringData, sizeof(sendStringData), 97, sizeof(sendStringData)); + StreamData d1 = { + sendStringData, + 100000, + }; + StreamData d2 = { + "maogeniubi", + 10, + }; + StreamFrameInfo tmpf = {}; + for (int32_t times = 0; times < sendTimes; times++) { + ret = SendStream(sessionId, &d1, &d2, &tmpf); + EXPECT_EQ(ret, SOFTBUS_OK); + sleep(1); + } + EXPECT_GT(g_qosEventCount[sessionId], 0); + CloseSession(sessionId); + sleep(1); + EXPECT_LE(g_timeDiff[sessionId], 100); + ret = RemoveSessionServer(UDP_TEST_PKG_NAME.c_str(), UDP_TEST_SESSION_NAME.c_str()); + EXPECT_EQ(ret, SOFTBUS_OK); +} + +/** + * @tc.name: TransQosStatClientTest004 + * @tc.desc: sessionListener with onQosEvent multichannel + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(TransQosStatClientTest, QosStatClientTest004, TestSize.Level0) +{ + int32_t sendTimes = 10; + int32_t numChannels = 5; + int32_t ret = CreateSessionServer(UDP_TEST_PKG_NAME.c_str(), UDP_TEST_SESSION_NAME.c_str(), &g_hasQosCb); + EXPECT_EQ(ret, SOFTBUS_OK); + NodeBasicInfo *info; + int32_t infoNum; + ret = GetAllNodeDeviceInfo(UDP_TEST_PKG_NAME.c_str(), &info, &infoNum); + EXPECT_EQ(ret, SOFTBUS_OK); + SessionAttribute attr = {0}; + attr.dataType = TYPE_STREAM; + attr.attr.streamAttr.streamType = RAW_STREAM; + for (int32_t index = 0; index < numChannels; index++) { + std::string groupId = std::to_string(index); + int32_t sessionId = OpenSession(UDP_TEST_SESSION_NAME.c_str(), UDP_TEST_SESSION_NAME.c_str(), + info[0].networkId, groupId.c_str(), &attr); + EXPECT_NE(-1, sessionId); + } + sleep(2); + char sendStringData[100000]; + memset_s(sendStringData, sizeof(sendStringData), 97, sizeof(sendStringData)); + StreamData d1 = { + sendStringData, + 100000, + }; + StreamData d2 = { + "maogeniubi", + 10, + }; + StreamFrameInfo tmpf = {}; + std::map::iterator iter; + for (int32_t times = 0; times < sendTimes; times++) { + iter = g_qosEventCount.begin(); + while (iter != g_qosEventCount.end()) { + ret = SendStream(iter->first, &d1, &d2, &tmpf); + EXPECT_EQ(ret, SOFTBUS_OK); + iter++; + } + sleep(1); + } + iter = g_qosEventCount.begin(); + while (iter != g_qosEventCount.end()) { + EXPECT_GT(iter->second, 0); + CloseSession(iter->second); + iter++; + } + sleep(1); + ret = RemoveSessionServer(UDP_TEST_PKG_NAME.c_str(), UDP_TEST_SESSION_NAME.c_str()); + EXPECT_EQ(ret, SOFTBUS_OK); +} + +/** + * @tc.name: TransQosStatClientTest005 + * @tc.desc: sessionListener with onQosEvent speedUp + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(TransQosStatClientTest, QosStatClientTest005, TestSize.Level0) +{ + int32_t sendTimes = 10; + uint64_t bigSpeed = 0; + uint64_t smallSpeed = 0; + int32_t ret = CreateSessionServer(UDP_TEST_PKG_NAME.c_str(), UDP_TEST_SESSION_NAME.c_str(), &g_hasQosCb); + EXPECT_EQ(ret, SOFTBUS_OK); + NodeBasicInfo *info; + int32_t infoNum; + ret = GetAllNodeDeviceInfo(UDP_TEST_PKG_NAME.c_str(), &info, &infoNum); + EXPECT_EQ(ret, SOFTBUS_OK); + SessionAttribute attr = {0}; + attr.dataType = TYPE_STREAM; + attr.attr.streamAttr.streamType = RAW_STREAM; + int32_t sessionId = OpenSession(UDP_TEST_SESSION_NAME.c_str(), UDP_TEST_SESSION_NAME.c_str(), + info[0].networkId, "0", &attr); + EXPECT_NE(-1, sessionId); + sleep(2); + + // big speed + char sendStringData[100000]; + memset_s(sendStringData, sizeof(sendStringData), 97, sizeof(sendStringData)); + StreamData d1 = { + sendStringData, + 100000, + }; + StreamData d2 = { + "maogeniubi", + 10, + }; + StreamFrameInfo tmpf = {}; + for (int32_t times = 0; times < sendTimes; times++) { + ret = SendStream(sessionId, &d1, &d2, &tmpf); + EXPECT_EQ(ret, SOFTBUS_OK); + sleep(1); + } + bigSpeed = CalSendBits(g_speedStat[sessionId]); + g_speedStat[sessionId].clear(); + + // small speed + d1.bufLen = 1000; + for (int32_t times = 0; times < sendTimes; times++) { + ret = SendStream(sessionId, &d1, &d2, &tmpf); + EXPECT_EQ(ret, SOFTBUS_OK); + sleep(1); + } + smallSpeed = CalSendBits(g_speedStat[sessionId]) - bigSpeed; + EXPECT_LE(smallSpeed, bigSpeed); + CloseSession(sessionId); + sleep(1); + ret = RemoveSessionServer(UDP_TEST_PKG_NAME.c_str(), UDP_TEST_SESSION_NAME.c_str()); + EXPECT_EQ(ret, SOFTBUS_OK); +} + +/** + * @tc.name: TransQosStatClientTest006 + * @tc.desc: sessionListener with onQosEvent speedDown + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(TransQosStatClientTest, QosStatClientTest006, TestSize.Level0) +{ + int32_t sendTimes = 10; + uint64_t bigSpeed = 0; + uint64_t smallSpeed = 0; + int32_t ret = CreateSessionServer(UDP_TEST_PKG_NAME.c_str(), UDP_TEST_SESSION_NAME.c_str(), &g_hasQosCb); + EXPECT_EQ(ret, SOFTBUS_OK); + NodeBasicInfo *info; + int32_t infoNum; + ret = GetAllNodeDeviceInfo(UDP_TEST_PKG_NAME.c_str(), &info, &infoNum); + EXPECT_EQ(ret, SOFTBUS_OK); + SessionAttribute attr = {0}; + attr.dataType = TYPE_STREAM; + attr.attr.streamAttr.streamType = RAW_STREAM; + int32_t sessionId = OpenSession(UDP_TEST_SESSION_NAME.c_str(), UDP_TEST_SESSION_NAME.c_str(), + info[0].networkId, "0", &attr); + EXPECT_NE(-1, sessionId); + sleep(2); + + // small speed + char sendStringData[100000]; + memset_s(sendStringData, sizeof(sendStringData), 97, sizeof(sendStringData)); + StreamData d1 = { + sendStringData, + 100000, + }; + StreamData d2 = { + "maogeniubi", + 10, + }; + StreamFrameInfo tmpf = {}; + for (int32_t times = 0; times < sendTimes; times++) { + ret = SendStream(sessionId, &d1, &d2, &tmpf); + EXPECT_EQ(ret, SOFTBUS_OK); + sleep(1); + } + bigSpeed = CalSendBits(g_speedStat[sessionId]); + g_speedStat[sessionId].clear(); + + // small speed + d1.bufLen = 1000; + for (int32_t times = 0; times < sendTimes; times++) { + ret = SendStream(sessionId, &d1, &d2, &tmpf); + EXPECT_EQ(ret, SOFTBUS_OK); + sleep(1); + } + smallSpeed = CalSendBits(g_speedStat[sessionId]) - bigSpeed; + EXPECT_LE(smallSpeed, bigSpeed); + CloseSession(sessionId); + sleep(1); + ret = RemoveSessionServer(UDP_TEST_PKG_NAME.c_str(), UDP_TEST_SESSION_NAME.c_str()); + EXPECT_EQ(ret, SOFTBUS_OK); +} +} \ No newline at end of file diff --git a/tests/sdk/transmission/trans_channel/qos/trans_qos_stat_server_test.cpp b/tests/sdk/transmission/trans_channel/qos/trans_qos_stat_server_test.cpp new file mode 100644 index 000000000..8cfbec48e --- /dev/null +++ b/tests/sdk/transmission/trans_channel/qos/trans_qos_stat_server_test.cpp @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include "session.h" +#include "softbus_errcode.h" + +using namespace testing::ext; +namespace OHOS { +const std::string UDP_TEST_PKG_NAME = "com.huawei.plrdtest.dsoftbus.server"; +const std::string UDP_TEST_SESSION_NAME = "com.huawei.plrdtest.dsoftbus.JtSendRawStream_0"; +int32_t g_testWay = 0; +class TransQosStatServerTest : public testing::Test { +public: + TransQosStatServerTest() + {} + ~TransQosStatServerTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp() override + {} + void TearDown() override + {} +}; + +void TransQosStatServerTest::SetUpTestCase(void) +{ + printf("********Qos Test Begin*********\r\n"); + printf("* 0.with onQosEvent *\r\n"); + printf("* 1.without onQosEvent *\r\n"); + printf("********************************\r\n"); + printf("input the num:"); + std::cin >> g_testWay; +} + +void TransQosStatServerTest::TearDownTestCase(void) +{} + +static int OnSessionOpend(int sessionId, int result) +{ + printf("on session opened[sessionId = %d, result = %d]\n", sessionId, result); + return 0; +} + +static void OnSessionClosed(int sessionId) +{ + printf("on session closed[sessionId = %d]\n", sessionId); +} + +static void OnStreamReceived(int sessionId, const StreamData *data, const StreamData *ext, const StreamFrameInfo *param) +{} + +static void OnBytesReceived(int sessionId, const void *data, unsigned int dataLen) +{} + +static void OnMessageReceived(int sessionId, const void *data, unsigned int dataLen) +{} + +static void OnQosEvent(int sessionId, int eventId, int tvCount, const QosTv *tvList) +{ + printf("on QoS metric retrieved [sessionId = %d] [eventId=%d]!!!!!!\n", sessionId, eventId); + printf("pktNum:%u\n", tvList->info.appStatistics.pktNum); + printf("periodRecvPkts:%u\n", tvList->info.appStatistics.periodRecvPkts); + printf("periodRecvPktLoss:%u\n", tvList->info.appStatistics.periodRecvPktLoss); + printf("periodRecvRate:%u\n", tvList->info.appStatistics.periodRecvRate); + printf("periodRecvRateBps:%llu\n", tvList->info.appStatistics.periodRecvRateBps); + printf("periodRtt:%u\n", tvList->info.appStatistics.periodRtt); + printf("periodRecvPktLossHighPrecision:%u\n", tvList->info.appStatistics.periodRecvPktLossHighPrecision); + printf("periodSendLostPkts:%u\n", tvList->info.appStatistics.periodSendLostPkts); + printf("periodSendPkts:%u\n", tvList->info.appStatistics.periodSendPkts); + printf("periodSendPktLossHighPrecision:%u\n", tvList->info.appStatistics.periodSendPktLossHighPrecision); + printf("periodSendBits:%llu\n", tvList->info.appStatistics.periodSendBits); + printf("periodSendRateBps:%llu\n", tvList->info.appStatistics.periodSendRateBps); +} + +static ISessionListener g_hasQosCb = { + .OnSessionOpened = OnSessionOpend, + .OnSessionClosed = OnSessionClosed, + .OnStreamReceived = OnStreamReceived, + .OnBytesReceived = OnBytesReceived, + .OnMessageReceived = OnMessageReceived, + .OnQosEvent = OnQosEvent, +}; + +static ISessionListener g_noQosCb = { + .OnSessionOpened = OnSessionOpend, + .OnSessionClosed = OnSessionClosed, + .OnStreamReceived = OnStreamReceived, + .OnBytesReceived = OnBytesReceived, + .OnMessageReceived = OnMessageReceived, + .OnQosEvent = NULL, +}; + +/** + * @tc.name: TransQosStatServerTest001 + * @tc.desc: receive with onQosEvent + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(TransQosStatServerTest, QosStatServerTest001, TestSize.Level0) +{ + int32_t ret; + if (g_testWay == 0) { + ret = CreateSessionServer(UDP_TEST_PKG_NAME.c_str(), UDP_TEST_SESSION_NAME.c_str(), &g_hasQosCb); + } else { + ret = CreateSessionServer(UDP_TEST_PKG_NAME.c_str(), UDP_TEST_SESSION_NAME.c_str(), &g_noQosCb); + } + EXPECT_EQ(ret, SOFTBUS_OK); + if (ret == SOFTBUS_OK) { + while (1) { + sleep(3); + } + } +} +} \ No newline at end of file diff --git a/tests/sdk/transmission/trans_channel/qos/trans_qos_test.cpp b/tests/sdk/transmission/trans_channel/qos/trans_qos_test.cpp new file mode 100644 index 000000000..4b8dc233d --- /dev/null +++ b/tests/sdk/transmission/trans_channel/qos/trans_qos_test.cpp @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "session.h" +#include "softbus_errcode.h" + +using namespace testing::ext; + +namespace OHOS { +const int32_t G_VALID_SESSION_ID = 1; +const int32_t G_INVALID_SESSION_ID = 1; +const int32_t G_VALID_APP_TYPE = 1; + +class TransQosTest : public testing::Test { +public: + TransQosTest() + {} + ~TransQosTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp() override + {} + void TearDown() override + {} +}; + +void TransQosTest::SetUpTestCase(void) +{} + +void TransQosTest::TearDownTestCase(void) +{} + +/** + * @tc.name: TransQosTest001 + * @tc.desc: test the wrong parameter. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(TransQosTest, QosReportTest001, TestSize.Level0) +{ + int ret; + ret = QosReport(G_INVALID_SESSION_ID, G_VALID_APP_TYPE, QOS_IMPROVE); + EXPECT_NE(ret, SOFTBUS_OK); + + ret = QosReport(G_VALID_SESSION_ID, G_VALID_APP_TYPE, QOS_RECOVER); + EXPECT_NE(ret, SOFTBUS_OK); + + ret = QosReport(G_VALID_SESSION_ID, G_VALID_APP_TYPE, QOS_IMPROVE); + EXPECT_NE(ret, SOFTBUS_OK); +} +} \ No newline at end of file