diff --git a/services/distributeddataservice/adapter/communicator/src/communicator_context.cpp b/services/distributeddataservice/adapter/communicator/src/communicator_context.cpp index 76f63db9f18f27dedcacf9e5f37ec6601c610d08..b5415a6b7614e4ba8b48af5eb1d51b5f0b0c607c 100644 --- a/services/distributeddataservice/adapter/communicator/src/communicator_context.cpp +++ b/services/distributeddataservice/adapter/communicator/src/communicator_context.cpp @@ -14,13 +14,14 @@ */ #define LOG_TAG "CommunicatorContext" + #include "communicator_context.h" + #include "log_print.h" -#include "kvstore_utils.h" #include "softbus_error_code.h" +#include "utils/anonymous.h" namespace OHOS::DistributedData { -using KvUtils = OHOS::DistributedKv::KvStoreUtils; using Status = OHOS::DistributedKv::Status; CommunicatorContext &CommunicatorContext::GetInstance() @@ -92,7 +93,7 @@ void CommunicatorContext::NotifySessionReady(const std::string &deviceId, int32_ } } ZLOGI("Notify session begin, deviceId:%{public}s, observer count:%{public}zu", - KvUtils::ToBeAnonymous(deviceId).c_str(), observers_.size()); + Anonymous::Change(deviceId).c_str(), observers_.size()); } if (errCode == SOFTBUS_OK) { std::lock_guard sessionLockGard(sessionMutex_); diff --git a/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp b/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp index 817824732148815ffdf85897b8b23e59a58eb449..efd75ab6d1b72eac8a4ffdc1c60172cf76e59042 100644 --- a/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp +++ b/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp @@ -14,18 +14,16 @@ */ #define LOG_TAG "DeviceManagerAdapter" -#include "device_manager_adapter.h" -#include +#include "device_manager_adapter.h" -#include "kvstore_utils.h" #include "log_print.h" #include "serializable/serializable.h" +#include "utils/anonymous.h" namespace OHOS::DistributedData { using namespace OHOS::DistributedHardware; using namespace OHOS::AppDistributedKv; -using KvStoreUtils = OHOS::DistributedKv::KvStoreUtils; constexpr int32_t DM_OK = 0; constexpr const char *PKG_NAME = "ohos.distributeddata.service"; class DataMgrDmStateCall final : public DistributedHardware::DeviceStateCallback { @@ -173,7 +171,7 @@ void DeviceManagerAdapter::Online(const DmDeviceInfo &info) return; } ZLOGI("[online] uuid:%{public}s, name:%{public}s, type:%{public}d, authForm:%{public}d, osType:%{public}d", - KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType, + Anonymous::Change(dvInfo.uuid).c_str(), Anonymous::Change(dvInfo.deviceName).c_str(), dvInfo.deviceType, static_cast(dvInfo.authForm), dvInfo.osType); SaveDeviceInfo(dvInfo, DeviceChangeType::DEVICE_ONLINE); syncTask_.Insert(dvInfo.uuid, dvInfo.uuid); @@ -217,7 +215,7 @@ void DeviceManagerAdapter::NotifyReadyEvent(const std::string &uuid) if (uuid == CLOUD_DEVICE_UUID) { return; } - ZLOGI("[NotifyReadyEvent] uuid:%{public}s", KvStoreUtils::ToBeAnonymous(uuid).c_str()); + ZLOGI("[NotifyReadyEvent] uuid:%{public}s", Anonymous::Change(uuid).c_str()); std::string event = R"({"extra": {"deviceId":")" + uuid + R"(" } })"; DeviceManager::GetInstance().NotifyEvent(PKG_NAME, DmNotifyEvent::DM_NOTIFY_EVENT_ONDEVICEREADY, event); } @@ -242,7 +240,7 @@ void DeviceManagerAdapter::Offline(const DmDeviceInfo &info) } syncTask_.Erase(dvInfo.uuid); ZLOGI("[offline] uuid:%{public}s, name:%{public}s, type:%{public}d, authForm:%{public}d, osType:%{public}d", - KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType, + Anonymous::Change(dvInfo.uuid).c_str(), Anonymous::Change(dvInfo.deviceName).c_str(), dvInfo.deviceType, static_cast(dvInfo.authForm), dvInfo.osType); SaveDeviceInfo(dvInfo, DeviceChangeType::DEVICE_OFFLINE); auto task = [this, dvInfo]() { @@ -264,7 +262,7 @@ void DeviceManagerAdapter::OnChanged(const DmDeviceInfo &info) return; } ZLOGI("[OnChanged] uuid:%{public}s, name:%{public}s, type:%{public}d, authForm:%{public}d osType:%{public}d", - KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType, + Anonymous::Change(dvInfo.uuid).c_str(), Anonymous::Change(dvInfo.deviceName).c_str(), dvInfo.deviceType, static_cast(dvInfo.authForm), dvInfo.osType); } @@ -277,7 +275,7 @@ void DeviceManagerAdapter::OnReady(const DmDeviceInfo &info) } readyDevices_.InsertOrAssign(dvInfo.uuid, std::make_pair(DeviceState::DEVICE_ONREADY, dvInfo)); ZLOGI("[OnReady] uuid:%{public}s, name:%{public}s, type:%{public}d, authForm:%{public}d, osType:%{public}d", - KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType, + Anonymous::Change(dvInfo.uuid).c_str(), Anonymous::Change(dvInfo.deviceName).c_str(), dvInfo.deviceType, static_cast(dvInfo.authForm), dvInfo.osType); auto task = [this, dvInfo]() { observers_.ForEachCopies([&dvInfo](const auto &key, auto &value) { @@ -446,7 +444,7 @@ DeviceInfo DeviceManagerAdapter::GetDeviceInfoFromCache(const std::string &id) deviceInfos_.Get(id, dvInfo); } if (dvInfo.uuid.empty()) { - ZLOGE("invalid id:%{public}s", KvStoreUtils::ToBeAnonymous(id).c_str()); + ZLOGE("invalid id:%{public}s", Anonymous::Change(id).c_str()); } return dvInfo; } @@ -463,7 +461,7 @@ void DeviceManagerAdapter::InitDeviceInfo(bool onlyCache) for (const auto &info : dvInfos) { if (info.networkId.empty() || info.uuid.empty() || info.udid.empty()) { ZLOGE("networkId:%{public}s, uuid:%{public}d, udid:%{public}d", - KvStoreUtils::ToBeAnonymous(info.networkId).c_str(), info.uuid.empty(), info.udid.empty()); + Anonymous::Change(info.networkId).c_str(), info.uuid.empty(), info.udid.empty()); continue; } deviceInfos_.Set(info.networkId, info); @@ -499,7 +497,7 @@ DeviceInfo DeviceManagerAdapter::GetLocalDeviceInfo() return {}; } ZLOGI("[LocalDevice] uuid:%{public}s, name:%{public}s, type:%{public}d, osType:%{public}d", - KvStoreUtils::ToBeAnonymous(uuid).c_str(), info.deviceName, info.deviceTypeId, deviceExtraInfo.OS_TYPE); + Anonymous::Change(uuid).c_str(), info.deviceName, info.deviceTypeId, deviceExtraInfo.OS_TYPE); return { std::move(uuid), std::move(udid), std::move(networkId), std::string(info.deviceName), info.deviceTypeId, deviceExtraInfo.OS_TYPE, static_cast(info.authForm) }; } @@ -519,7 +517,7 @@ std::string DeviceManagerAdapter::GetUuidByNetworkId(const std::string &networkI std::string uuid; auto ret = DeviceManager::GetInstance().GetUuidByNetworkId(PKG_NAME, networkId, uuid); if (ret != DM_OK || uuid.empty()) { - ZLOGE("failed, result:%{public}d, networkId:%{public}s", ret, KvStoreUtils::ToBeAnonymous(networkId).c_str()); + ZLOGE("failed, result:%{public}d, networkId:%{public}s", ret, Anonymous::Change(networkId).c_str()); return ""; } return uuid; @@ -540,7 +538,7 @@ std::string DeviceManagerAdapter::GetUdidByNetworkId(const std::string &networkI std::string udid; auto ret = DeviceManager::GetInstance().GetUdidByNetworkId(PKG_NAME, networkId, udid); if (ret != DM_OK || udid.empty()) { - ZLOGE("failed, result:%{public}d, networkId:%{public}s", ret, KvStoreUtils::ToBeAnonymous(networkId).c_str()); + ZLOGE("failed, result:%{public}d, networkId:%{public}s", ret, Anonymous::Change(networkId).c_str()); return ""; } return udid; diff --git a/services/distributeddataservice/adapter/communicator/src/process_communicator_impl.cpp b/services/distributeddataservice/adapter/communicator/src/process_communicator_impl.cpp index 0e40297fcb6661a1121ec2931d97e5cf7b70317e..09a555c5ae642dbcbd8f0181a6011d9184df420d 100644 --- a/services/distributeddataservice/adapter/communicator/src/process_communicator_impl.cpp +++ b/services/distributeddataservice/adapter/communicator/src/process_communicator_impl.cpp @@ -143,7 +143,15 @@ DBStatus ProcessCommunicatorImpl::SendData(const DeviceInfos &dstDevInfo, const uint32_t totalLength) { PipeInfo pi = {thisProcessLabel_, ""}; - const DataInfo dataInfo = { const_cast(data), length}; + if (dstDevInfo.callee.userId.empty() || dstDevInfo.callee.appId.empty() || dstDevInfo.callee.storeId.empty()) { + ZLOGE("access info is empty, userId:%{public}s, bundleName:%{public}s, storeId:%{public}s", + dstDevInfo.callee.userId.c_str(), dstDevInfo.callee.appId.c_str(), + Anonymous::Change(dstDevInfo.callee.storeId).c_str()); + return DBStatus::DB_ERROR; + } + ExtraDataInfo extraInfo = { .userId = dstDevInfo.callee.userId, .bundleName = dstDevInfo.callee.appId, + .storeId = dstDevInfo.callee.storeId }; + const DataInfo dataInfo = { .data = const_cast(data), .length = length, .extraInfo = extraInfo }; DeviceId destination; destination.deviceId = dstDevInfo.identifier; auto [errCode, softBusErrCode] = diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_adapter.h b/services/distributeddataservice/adapter/communicator/src/softbus_adapter.h index 08c572812639eef7555921feb2c7259d6562c21a..53bba56ba084c6227a0a94e517743f58be0aaacd 100644 --- a/services/distributeddataservice/adapter/communicator/src/softbus_adapter.h +++ b/services/distributeddataservice/adapter/communicator/src/softbus_adapter.h @@ -15,6 +15,7 @@ #ifndef DISTRIBUTEDDATAFWK_SRC_SOFTBUS_ADAPTER_H #define DISTRIBUTEDDATAFWK_SRC_SOFTBUS_ADAPTER_H + #include #include #include @@ -28,23 +29,25 @@ #include "app_data_change_listener.h" #include "app_device_change_listener.h" #include "block_data.h" +#include "executor_pool.h" #include "socket.h" #include "softbus_bus_center.h" #include "softbus_client.h" + namespace OHOS { namespace AppDistributedKv { -class SoftBusAdapter : public AppDistributedKv::AppDeviceChangeListener { +class SoftBusAdapter { public: - SoftBusAdapter(); - ~SoftBusAdapter(); - static std::shared_ptr GetInstance(); - struct ServerSocketInfo { std::string name; /**< Peer socket name */ std::string networkId; /**< Peer network ID */ std::string pkgName; /**< Peer package name */ }; + SoftBusAdapter(); + ~SoftBusAdapter(); + static std::shared_ptr GetInstance(); + // add DataChangeListener to watch data change; Status StartWatchDataChange(const AppDataChangeListener *observer, const PipeInfo &pipeInfo); @@ -63,14 +66,10 @@ public: int RemoveSessionServerAdapter(const std::string &sessionName) const; + void OnBind(int32_t socket, PeerSocketInfo info); void NotifyDataListeners(const uint8_t *data, int size, const std::string &deviceId, const PipeInfo &pipeInfo); - std::string OnClientShutdown(int32_t socket, bool isForce = true); - - void OnBind(int32_t socket, PeerSocketInfo info); - void OnServerShutdown(int32_t socket); - bool GetPeerSocketInfo(int32_t socket, ServerSocketInfo &info); Status Broadcast(const PipeInfo &pipeInfo, const LevelInfo &levelInfo); @@ -81,26 +80,24 @@ public: uint32_t GetMtuSize(const DeviceId &deviceId); uint32_t GetTimeout(const DeviceId &deviceId); - void OnDeviceChanged(const AppDistributedKv::DeviceInfo &info, - const AppDistributedKv::DeviceChangeType &type) const override; - Status ReuseConnect(const PipeInfo &pipeInfo, const DeviceId &deviceId); private: using Time = std::chrono::steady_clock::time_point; using Duration = std::chrono::steady_clock::duration; using Task = ExecutorPool::Task; + std::string DelConnect(int32_t socket, bool isForce); void StartCloseSessionTask(const std::string &deviceId); Task GetCloseSessionTask(); bool CloseSession(const std::string &networkId); void GetExpireTime(std::shared_ptr &conn); std::pair OpenConnect(const std::shared_ptr &conn, const DeviceId &deviceId); - std::shared_ptr GetConnect(const PipeInfo &pipeInfo, const DeviceId &deviceId, uint32_t qosType); - static constexpr const char *PKG_NAME = "distributeddata-default"; + bool ConfigSessionAccessInfo(const ExtraDataInfo &extraInfo, SessionAccessInfo &sessionAccessInfo); + std::shared_ptr GetConnect(const PipeInfo &pipeInfo, const DeviceId &deviceId, + const ExtraDataInfo &extraInfo = {}); + static constexpr Time INVALID_NEXT = std::chrono::steady_clock::time_point::max(); - static constexpr uint32_t QOS_COUNT = 3; - static constexpr QosTV Qos[QOS_COUNT] = { { .qos = QOS_TYPE_MIN_BW, .value = 64 * 1024 }, - { .qos = QOS_TYPE_MAX_LATENCY, .value = 15000 }, { .qos = QOS_TYPE_MIN_LATENCY, .value = 1600 } }; + static std::shared_ptr instance_; ConcurrentMap dataChangeListeners_{}; ConcurrentMap>> connects_; diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp b/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp index 5d8e2cb4d114efcb23f3c13aa48d966aa97fbc16..9b9c56702ec0a28cbc665927c05c1e16d043664b 100644 --- a/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp +++ b/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp @@ -12,37 +12,37 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include -#include -#include +#ifdef LOG_TAG +#undef LOG_TAG +#endif +#define LOG_TAG "SoftBusAdapter" + +#include "softbus_adapter.h" +#include "account/account_delegate.h" #include "communication/connect_manager.h" #include "communicator_context.h" #include "data_level.h" #include "device_manager_adapter.h" -#include "dfx/dfx_types.h" -#include "dfx/reporter.h" -#include "kvstore_utils.h" #include "log_print.h" -#include "securec.h" -#include "session.h" -#include "softbus_adapter.h" -#include "softbus_bus_center.h" +#include "metadata/meta_data_manager.h" +#include "metadata/store_meta_data.h" #include "softbus_error_code.h" -#ifdef LOG_TAG -#undef LOG_TAG -#endif -#define LOG_TAG "SoftBusAdapter" +#include "utils/anonymous.h" namespace OHOS { namespace AppDistributedKv { -using Context = DistributedData::CommunicatorContext; -constexpr uint32_t DEFAULT_MTU_SIZE = 4096 * 1024u; -constexpr uint32_t DEFAULT_TIMEOUT = 30 * 1000; using namespace std; -using namespace OHOS::DistributedDataDfx; using namespace OHOS::DistributedKv; -using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; +using namespace OHOS::DistributedData; + +static constexpr const char *SYSTEM_USERID = "0"; +static constexpr const char *PKG_NAME = "distributeddata-default"; +static constexpr uint32_t DEFAULT_MTU_SIZE = 4096 * 1024u; +static constexpr uint32_t DEFAULT_TIMEOUT = 30 * 1000; +static constexpr uint32_t QOS_COUNT = 3; +static constexpr QosTV Qos[QOS_COUNT] = { { .qos = QOS_TYPE_MIN_BW, .value = 64 * 1024 }, + { .qos = QOS_TYPE_MAX_LATENCY, .value = 15000 }, { .qos = QOS_TYPE_MIN_LATENCY, .value = 1600 } }; class AppDataListenerWrap { public: @@ -55,12 +55,16 @@ public: static void OnServerBind(int32_t socket, PeerSocketInfo info); static void OnServerShutdown(int32_t socket, ShutdownReason reason); static void OnServerBytesReceived(int32_t socket, const void *data, uint32_t dataLen); + static bool OnServerAccessCheck(int32_t socket, PeerSocketInfo info, SocketAccessInfo *peerInfo, + SocketAccessInfo *localInfo); private: // notify all listeners when received message static void NotifyDataListeners(const uint8_t *data, const int size, const std::string &deviceId, const PipeInfo &pipeInfo); static std::string GetPipeId(const std::string &name); + static std::pair LoadMetaData(const std::string &bundleName, const std::string &storeId, + int32_t userId); static SoftBusAdapter *softBusAdapter_; }; @@ -80,7 +84,7 @@ void OnDataLevelChanged(const char* networkId, const DataLevel dataLevel) .switches = dataLevel.switchLevel, .switchesLen = dataLevel.switchLength, }; - auto uuid = DmAdapter::GetInstance().GetUuidByNetworkId(networkId); + auto uuid = DeviceManagerAdapter::GetInstance().GetUuidByNetworkId(networkId); SoftBusAdapter::GetInstance()->OnBroadcast({ uuid }, std::move(level)); } @@ -88,6 +92,7 @@ IDataLevelCb g_callback = { .onDataLevelChanged = OnDataLevelChanged, }; } // namespace + SoftBusAdapter::SoftBusAdapter() { ZLOGI("begin"); @@ -102,23 +107,20 @@ SoftBusAdapter::SoftBusAdapter() serverListener_.OnShutdown = AppDataListenerWrap::OnServerShutdown; serverListener_.OnBytes = AppDataListenerWrap::OnServerBytesReceived; serverListener_.OnMessage = AppDataListenerWrap::OnServerBytesReceived; + serverListener_.OnNegotiate2 = AppDataListenerWrap::OnServerAccessCheck; - auto status = DmAdapter::GetInstance().StartWatchDeviceChange(this, { "softBusAdapter" }); - if (status != Status::SUCCESS) { - ZLOGW("register device change failed, status:%d", static_cast(status)); - } - - Context::GetInstance().SetSessionListener([this](const std::string &deviceId) { + CommunicatorContext::GetInstance().SetSessionListener([this](const std::string &deviceId) { StartCloseSessionTask(deviceId); }); ConnectManager::GetInstance()->RegisterCloseSessionTask([this](const std::string &networkId) { return CloseSession(networkId); }); - ConnectManager::GetInstance()->RegisterSessionCloseListener("context", [](const std::string &networkId) { - auto uuid = DmAdapter::GetInstance().GetUuidByNetworkId(networkId); - Context::GetInstance().NotifySessionClose(uuid); - }); + ConnectManager::GetInstance()->RegisterSessionCloseListener("CommunicatorContext", + [](const std::string &networkId) { + auto uuid = DeviceManagerAdapter::GetInstance().GetUuidByNetworkId(networkId); + CommunicatorContext::GetInstance().NotifySessionClose(uuid); + }); ConnectManager::GetInstance()->OnStart(); } @@ -129,7 +131,9 @@ SoftBusAdapter::~SoftBusAdapter() UnregDataLevelChangeCb(PKG_NAME); } connects_.Clear(); +#ifndef UT_TEST ConnectManager::GetInstance()->OnDestory(); +#endif } std::shared_ptr SoftBusAdapter::GetInstance() @@ -174,7 +178,7 @@ void SoftBusAdapter::GetExpireTime(std::shared_ptr &conn) auto expireTime = conn->GetExpireTime() > now ? conn->GetExpireTime() : now; lock_guard lock(taskMutex_); if (taskId_ != ExecutorPool::INVALID_TASK_ID && expireTime < next_) { - taskId_ = Context::GetInstance().GetThreadPool()->Reset(taskId_, expireTime - now); + taskId_ = CommunicatorContext::GetInstance().GetThreadPool()->Reset(taskId_, expireTime - now); next_ = expireTime; } } @@ -182,9 +186,7 @@ void SoftBusAdapter::GetExpireTime(std::shared_ptr &conn) std::pair SoftBusAdapter::SendData(const PipeInfo &pipeInfo, const DeviceId &deviceId, const DataInfo &dataInfo, uint32_t length, const MessageInfo &info) { - bool isOHOSType = DmAdapter::GetInstance().IsOHOSType(deviceId.deviceId); - uint32_t qosType = isOHOSType ? SoftBusClient::QOS_HML : SoftBusClient::QOS_BR; - std::shared_ptr conn = GetConnect(pipeInfo, deviceId, qosType); + std::shared_ptr conn = GetConnect(pipeInfo, deviceId, dataInfo.extraInfo); if (conn == nullptr) { return std::make_pair(Status::ERROR, 0); } @@ -195,7 +197,7 @@ std::pair SoftBusAdapter::SendData(const PipeInfo &pipeInfo, co if (status != Status::SUCCESS) { return OpenConnect(conn, deviceId); } - status = conn->SendData(dataInfo, &clientListener_); + status = conn->SendData(dataInfo); if ((status != Status::NETWORK_ERROR) && (status != Status::RATE_LIMIT)) { GetExpireTime(conn); } @@ -203,27 +205,77 @@ std::pair SoftBusAdapter::SendData(const PipeInfo &pipeInfo, co return std::make_pair(status, errCode); } +bool SoftBusAdapter::ConfigSessionAccessInfo(const ExtraDataInfo &extraInfo, SessionAccessInfo &sessionAccessInfo) +{ + if (extraInfo.userId.empty() || extraInfo.bundleName.empty() || extraInfo.storeId.empty()) { + ZLOGE("extraInfo is empty, userId:%{public}s, bundleName:%{public}s, storeId:%{public}s", + extraInfo.userId.c_str(), extraInfo.bundleName.c_str(), Anonymous::Change(extraInfo.storeId).c_str()); + return false; + } + StoreMetaData metaData; + metaData.deviceId = DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid; + metaData.user = extraInfo.userId; + metaData.bundleName = extraInfo.bundleName; + metaData.storeId = extraInfo.storeId; + if (!MetaDataManager::GetInstance().LoadMeta(metaData.GetKey(), metaData)) { + ZLOGE("get meta data fail, metaKey:%{public}s", Anonymous::Change(metaData.GetKey()).c_str()); + return false; + } + sessionAccessInfo.bundleName = extraInfo.bundleName; + sessionAccessInfo.storeId = extraInfo.storeId; + sessionAccessInfo.tokenId = metaData.tokenId; + int foregroundUserId = 0; + auto ret = AccountDelegate::GetInstance()->QueryForegroundUserId(foregroundUserId); + if (!ret) { + return false; + } + sessionAccessInfo.userId = foregroundUserId; + auto accountId = AccountDelegate::GetInstance()->GetCurrentAccountId(); + if (accountId.empty()) { + return false; + } + sessionAccessInfo.accountId = accountId; + return true; +} + std::shared_ptr SoftBusAdapter::GetConnect(const PipeInfo &pipeInfo, const DeviceId &deviceId, - uint32_t qosType) + const ExtraDataInfo &extraInfo) { std::shared_ptr conn; - std::string networkId = DmAdapter::GetInstance().ToNetworkID(deviceId.deviceId); - connects_.Compute(deviceId.deviceId, [&pipeInfo, &deviceId, &conn, qosType, &networkId](const auto &key, - std::vector> &connects) -> bool { - for (auto &connect : connects) { - if (connect == nullptr) { - continue; - } - if (connect->GetQoSType() == qosType) { - conn = connect; - return true; + if (deviceId.deviceId.empty()) { + ZLOGE("deviceId is empty"); + return nullptr; + } + auto isOHType = DeviceManagerAdapter::GetInstance().IsOHOSType(deviceId.deviceId); + SessionAccessInfo sessionAccessInfo = { .isOHType = isOHType }; + if (isOHType && !ConfigSessionAccessInfo(extraInfo, sessionAccessInfo)) { + ZLOGE("peer device is not oh device or config accessInfo fail, deviceId:%{public}s", + Anonymous::Change(deviceId.deviceId).c_str()); + return nullptr; + } + std::string networkId = DeviceManagerAdapter::GetInstance().ToNetworkID(deviceId.deviceId); + if (networkId.empty()) { + ZLOGE("networkId is empty, deviceId:%{public}s", Anonymous::Change(deviceId.deviceId).c_str()); + return nullptr; + } + uint32_t qosType = isOHType ? SoftBusClient::QOS_HML : SoftBusClient::QOS_BR; + connects_.Compute(deviceId.deviceId, + [&pipeInfo, &deviceId, &sessionAccessInfo, &conn, qosType, &networkId](const auto &key, + std::vector> &connects) -> bool { + for (auto &connect : connects) { + if (connect == nullptr) { + continue; + } + if (connect->GetQoSType() == qosType) { + conn = connect; + return true; + } } - } - auto connect = std::make_shared(pipeInfo, deviceId, networkId, qosType); - connects.emplace_back(connect); - conn = connect; - return true; - }); + auto connect = std::make_shared(pipeInfo, deviceId, networkId, qosType, sessionAccessInfo); + connects.emplace_back(connect); + conn = connect; + return true; + }); return conn; } @@ -236,7 +288,7 @@ std::pair SoftBusAdapter::OpenConnect(const std::shared_ptrOpenConnect(&clientListener_); } }; - auto networkId = DmAdapter::GetInstance().GetDeviceInfo(deviceId.deviceId).networkId; + auto networkId = DeviceManagerAdapter::GetInstance().ToNetworkID(deviceId.deviceId); ConnectManager::GetInstance()->ApplyConnect(networkId, task); return std::make_pair(Status::RATE_LIMIT, 0); } @@ -244,7 +296,7 @@ std::pair SoftBusAdapter::OpenConnect(const std::shared_ptr conn; - bool isOHOSType = DmAdapter::GetInstance().IsOHOSType(deviceId); + bool isOHOSType = DeviceManagerAdapter::GetInstance().IsOHOSType(deviceId); uint32_t qosType = isOHOSType ? SoftBusClient::QOS_HML : SoftBusClient::QOS_BR; auto connects = connects_.Find(deviceId); if (!connects.first) { @@ -263,8 +315,8 @@ void SoftBusAdapter::StartCloseSessionTask(const std::string &deviceId) auto expireTime = conn->GetExpireTime() > now ? conn->GetExpireTime() : now; lock_guard lock(taskMutex_); if (taskId_ == ExecutorPool::INVALID_TASK_ID) { - ZLOGI("Start close session, deviceId:%{public}s", KvStoreUtils::ToBeAnonymous(deviceId).c_str()); - taskId_ = Context::GetInstance().GetThreadPool()->Schedule(expireTime - now, GetCloseSessionTask()); + ZLOGI("Start close session, deviceId:%{public}s", Anonymous::Change(deviceId).c_str()); + taskId_ = CommunicatorContext::GetInstance().GetThreadPool()->Schedule(expireTime - now, GetCloseSessionTask()); next_ = expireTime; } } @@ -293,7 +345,8 @@ SoftBusAdapter::Task SoftBusAdapter::GetCloseSessionTask() }); connects_.EraseIf([](const auto &key, const auto &conn) -> bool { if (conn.empty()) { - ConnectManager::GetInstance()->OnSessionClose(DmAdapter::GetInstance().GetDeviceInfo(key).networkId); + ConnectManager::GetInstance()->OnSessionClose( + DeviceManagerAdapter::GetInstance().ToNetworkID(key)); } return conn.empty(); }); @@ -315,7 +368,7 @@ SoftBusAdapter::Task SoftBusAdapter::GetCloseSessionTask() taskId_ = ExecutorPool::INVALID_TASK_ID; return; } - taskId_ = Context::GetInstance().GetThreadPool()->Schedule( + taskId_ = CommunicatorContext::GetInstance().GetThreadPool()->Schedule( next > now ? next - now : ExecutorPool::INVALID_DELAY, GetCloseSessionTask()); next_ = next; }; @@ -330,8 +383,8 @@ uint32_t SoftBusAdapter::GetMtuSize(const DeviceId &deviceId) if (conn == nullptr) { continue; } - if (mtu < conn->GetMtuSize()) { - mtu = conn->GetMtuSize(); + if (mtu < conn->GetMtuBuffer()) { + mtu = conn->GetMtuBuffer(); } } if (mtu != 0) { @@ -352,7 +405,7 @@ std::string SoftBusAdapter::DelConnect(int32_t socket, bool isForce) std::string name; std::set closedConnect; connects_.EraseIf([socket, isForce, &name, &closedConnect](const auto &deviceId, auto &connects) -> bool { - if (!isForce && DmAdapter::GetInstance().IsOHOSType(deviceId)) { + if (!isForce && DeviceManagerAdapter::GetInstance().IsOHOSType(deviceId)) { return false; } std::string networkId; @@ -387,13 +440,13 @@ bool SoftBusAdapter::IsSameStartedOnPeer(const struct PipeInfo &pipeInfo, __attribute__((unused)) const struct DeviceId &peer) { ZLOGI("pipeInfo:%{public}s deviceId:%{public}s", pipeInfo.pipeId.c_str(), - KvStoreUtils::ToBeAnonymous(peer.deviceId).c_str()); + Anonymous::Change(peer.deviceId).c_str()); return true; } void SoftBusAdapter::SetMessageTransFlag(const PipeInfo &pipeInfo, bool flag) { - ZLOGI("pipeInfo: %s flag: %d", pipeInfo.pipeId.c_str(), flag); + ZLOGI("pipeInfo:%{public}s, flag:%{public}d", pipeInfo.pipeId.c_str(), flag); flag_ = flag; } @@ -423,11 +476,9 @@ void SoftBusAdapter::NotifyDataListeners(const uint8_t *data, int size, const st auto ret = dataChangeListeners_.ComputeIfPresent(pipeInfo.pipeId, [&data, &size, &deviceId, &pipeInfo](const auto &key, const AppDataChangeListener *&value) { ZLOGD("ready to notify, pipeName:%{public}s, deviceId:%{public}s.", pipeInfo.pipeId.c_str(), - KvStoreUtils::ToBeAnonymous(deviceId).c_str()); - DeviceInfo deviceInfo = DmAdapter::GetInstance().GetDeviceInfo(deviceId); + Anonymous::Change(deviceId).c_str()); + DeviceInfo deviceInfo = DeviceManagerAdapter::GetInstance().GetDeviceInfo(deviceId); value->OnMessage(deviceInfo, data, size, pipeInfo); - TrafficStat ts{ pipeInfo.pipeId, deviceId, 0, size }; - Reporter::GetInstance()->TrafficStatistic()->Report(ts); return true; }); if (!ret) { @@ -447,14 +498,14 @@ Status SoftBusAdapter::Broadcast(const PipeInfo &pipeInfo, const LevelInfo &leve if (status == SOFTBUS_FUNC_NOT_SUPPORT) { return Status::NOT_SUPPORT_BROADCAST; } - return status ? Status::ERROR : Status::SUCCESS; + return status != SOFTBUS_OK ? Status::ERROR : Status::SUCCESS; } void SoftBusAdapter::OnBroadcast(const DeviceId &device, const LevelInfo &levelInfo) { - ZLOGI("device:%{public}s", KvStoreUtils::ToBeAnonymous(device.deviceId).c_str()); + ZLOGI("device:%{public}s", Anonymous::Change(device.deviceId).c_str()); if (!onBroadcast_) { - ZLOGW("no listener device:%{public}s", KvStoreUtils::ToBeAnonymous(device.deviceId).c_str()); + ZLOGW("no listener device:%{public}s", Anonymous::Change(device.deviceId).c_str()); return; } onBroadcast_(device.deviceId, levelInfo); @@ -481,7 +532,7 @@ void AppDataListenerWrap::OnClientShutdown(int32_t socket, ShutdownReason reason // when the local close the session, this callback function will not be triggered; // when the current function is called, soft bus has released the session resource, only connId is valid; std::string name = softBusAdapter_->OnClientShutdown(socket); - ZLOGI("[shutdown] socket:%{public}d, name:%{public}s", socket, KvStoreUtils::ToBeAnonymous(name).c_str()); + ZLOGI("[shutdown] socket:%{public}d, name:%{public}s", socket, Anonymous::Change(name).c_str()); } void AppDataListenerWrap::OnClientBytesReceived(int32_t socket, const void *data, uint32_t dataLen) {} @@ -490,17 +541,17 @@ void AppDataListenerWrap::OnClientSocketChanged(int32_t socket, QoSEvent eventId { if (eventId == QoSEvent::QOS_SATISFIED && qos != nullptr && qos[0].qos == QOS_TYPE_MIN_BW && qosCount == 1) { auto name = softBusAdapter_->OnClientShutdown(socket, false); - ZLOGI("[SocketChanged] socket:%{public}d, name:%{public}s", socket, KvStoreUtils::ToBeAnonymous(name).c_str()); + ZLOGI("[SocketChanged] socket:%{public}d, name:%{public}s", socket, Anonymous::Change(name).c_str()); } } void AppDataListenerWrap::OnServerBind(int32_t socket, PeerSocketInfo info) { softBusAdapter_->OnBind(socket, info); - std::string peerDevUuid = DmAdapter::GetInstance().GetUuidByNetworkId(std::string(info.networkId)); + std::string peerDevUuid = DeviceManagerAdapter::GetInstance().GetUuidByNetworkId(std::string(info.networkId)); ZLOGI("[OnServerBind] socket:%{public}d, peer name:%{public}s, peer devId:%{public}s", socket, info.name, - KvStoreUtils::ToBeAnonymous(peerDevUuid).c_str()); + Anonymous::Change(peerDevUuid).c_str()); } void AppDataListenerWrap::OnServerShutdown(int32_t socket, ShutdownReason reason) @@ -516,9 +567,9 @@ void AppDataListenerWrap::OnServerBytesReceived(int32_t socket, const void *data ZLOGE("Get peer socket info failed, socket id %{public}d", socket); return; }; - std::string peerDevUuid = DmAdapter::GetInstance().GetUuidByNetworkId(std::string(info.networkId)); + std::string peerDevUuid = DeviceManagerAdapter::GetInstance().GetUuidByNetworkId(std::string(info.networkId)); ZLOGD("[OnBytesReceived] socket:%{public}d, peer name:%{public}s, peer devId:%{public}s, data len:%{public}u", - socket, info.name.c_str(), KvStoreUtils::ToBeAnonymous(peerDevUuid).c_str(), dataLen); + socket, info.name.c_str(), Anonymous::Change(peerDevUuid).c_str(), dataLen); std::string pipeId = GetPipeId(info.name); if (pipeId.empty()) { @@ -529,6 +580,71 @@ void AppDataListenerWrap::OnServerBytesReceived(int32_t socket, const void *data NotifyDataListeners(reinterpret_cast(data), dataLen, peerDevUuid, { pipeId, "" }); } +std::pair AppDataListenerWrap::LoadMetaData(const std::string &bundleName, const std::string &storeId, + int32_t userId) +{ + StoreMetaData metaData; + metaData.deviceId = DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid; + metaData.bundleName = bundleName; + metaData.storeId = storeId; + metaData.user = std::to_string(userId); + auto ret = MetaDataManager::GetInstance().LoadMeta(metaData.GetKey(), metaData); + if (!ret) { + metaData.user = SYSTEM_USERID; + ret = MetaDataManager::GetInstance().LoadMeta(metaData.GetKey(), metaData); + } + return { ret, metaData }; +} + +bool AppDataListenerWrap::OnServerAccessCheck(int32_t socket, PeerSocketInfo info, SocketAccessInfo *peerInfo, + SocketAccessInfo *localInfo) +{ + ZLOGI("receive bind request, socket:%{public}d", socket); + if (peerInfo == nullptr || localInfo == nullptr) { + ZLOGE("peerInfo or localInfo is nullptr, peerInfo:%{public}d, localInfo:%{public}d", peerInfo == nullptr, + localInfo == nullptr); + return false; + } + SoftBusClient::AccessExtraInfo peerExtraInfo; + if (!DistributedData::Serializable::Unmarshall(peerInfo->extraAccessInfo, peerExtraInfo)) { + ZLOGE("Unmarshall failed, peer extraAccessInfo:%{public}s", peerInfo->extraAccessInfo); + return false; + } + int foregroundUserId = 0; + if (!AccountDelegate::GetInstance()->QueryForegroundUserId(foregroundUserId)) { + return false; + } + auto localAccountId = AccountDelegate::GetInstance()->GetCurrentAccountId(); + if (localAccountId.empty()) { + return false; + } + auto resultPair = LoadMetaData(peerExtraInfo.bundleName, peerExtraInfo.storeId, foregroundUserId); + if (!resultPair.first) { + ZLOGE("local device has no store, bundleName:%{public}s", peerExtraInfo.bundleName.c_str()); + return false; + } + AclParams aclParams; + aclParams.accCaller.bundleName = peerExtraInfo.bundleName; + aclParams.accCaller.accountId = localAccountId; + aclParams.accCaller.userId = foregroundUserId; + aclParams.accCaller.networkId = DeviceManagerAdapter::GetInstance().GetLocalDevice().networkId; + aclParams.accCallee.accountId = peerExtraInfo.accountId; + aclParams.accCallee.userId = peerInfo->userId; + aclParams.accCallee.networkId = std::string(info.networkId); + bool accessFlag = false; + if (resultPair.second.authType == AuthType::IDENTICAL_ACCOUNT) { + accessFlag = DeviceManagerAdapter::GetInstance().IsSameAccount(aclParams.accCaller, aclParams.accCallee); + } else { + accessFlag = DeviceManagerAdapter::GetInstance().CheckAccessControl(aclParams.accCaller, aclParams.accCallee); + } + if (!accessFlag) { + return false; + } + localInfo->userId = foregroundUserId; + localInfo->localTokenId = resultPair.second.tokenId; + return true; +} + std::string AppDataListenerWrap::GetPipeId(const std::string &name) { auto pos = name.find('_'); @@ -557,9 +673,9 @@ bool SoftBusAdapter::GetPeerSocketInfo(int32_t socket, ServerSocketInfo &info) void SoftBusAdapter::OnBind(int32_t socket, PeerSocketInfo info) { ServerSocketInfo socketInfo; - socketInfo.name = info.name; - socketInfo.networkId = info.networkId; - socketInfo.pkgName = info.pkgName; + socketInfo.name = std::string(info.name); + socketInfo.networkId = std::string(info.networkId); + socketInfo.pkgName = std::string(info.pkgName); peerSocketInfos_.Insert(socket, socketInfo); } @@ -568,15 +684,9 @@ void SoftBusAdapter::OnServerShutdown(int32_t socket) peerSocketInfos_.Erase(socket); } -void SoftBusAdapter::OnDeviceChanged(const AppDistributedKv::DeviceInfo &info, - const AppDistributedKv::DeviceChangeType &type) const -{ - return; -} - bool SoftBusAdapter::CloseSession(const std::string &networkId) { - auto uuid = DmAdapter::GetInstance().GetUuidByNetworkId(networkId); + auto uuid = DeviceManagerAdapter::GetInstance().GetUuidByNetworkId(networkId); auto ret = connects_.Erase(uuid); if (ret != 0) { ConnectManager::GetInstance()->OnSessionClose(networkId); @@ -586,12 +696,11 @@ bool SoftBusAdapter::CloseSession(const std::string &networkId) Status SoftBusAdapter::ReuseConnect(const PipeInfo &pipeInfo, const DeviceId &deviceId) { - bool isOHOSType = DmAdapter::GetInstance().IsOHOSType(deviceId.deviceId); + bool isOHOSType = DeviceManagerAdapter::GetInstance().IsOHOSType(deviceId.deviceId); if (!isOHOSType) { return Status::NOT_SUPPORT; } - uint32_t qosType = SoftBusClient::QOS_HML; - std::shared_ptr conn = GetConnect(pipeInfo, deviceId, qosType); + std::shared_ptr conn = GetConnect(pipeInfo, deviceId); if (conn == nullptr) { return Status::ERROR; } @@ -599,6 +708,7 @@ Status SoftBusAdapter::ReuseConnect(const PipeInfo &pipeInfo, const DeviceId &de if (status != Status::SUCCESS) { return status; } + uint32_t qosType = SoftBusClient::QOS_HML; // Avoid being cleared by scheduled tasks connects_.Compute(deviceId.deviceId, [&conn, qosType](const auto &key, std::vector> &connects) -> bool { diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp b/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp index 23c8c79167f5735c46c620a3d592cda106bede2b..e589e7054b99af344480fd590eacb241792cff32 100644 --- a/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp +++ b/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp @@ -14,30 +14,29 @@ */ #define LOG_TAG "SoftBusClient" + #include "softbus_client.h" #include "communicator_context.h" #include "communication/connect_manager.h" -#include "device_manager_adapter.h" #include "inner_socket.h" -#include "kvstore_utils.h" #include "log_print.h" #include "softbus_error_code.h" +#include "utils/anonymous.h" namespace OHOS::AppDistributedKv { using namespace OHOS::DistributedKv; -using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; -using Context = DistributedData::CommunicatorContext; +using namespace OHOS::DistributedData; SoftBusClient::SoftBusClient(const PipeInfo& pipeInfo, const DeviceId& deviceId, const std::string& networkId, - uint32_t type) : type_(type), pipe_(pipeInfo), device_(deviceId), networkId_(networkId) + uint32_t type, const SessionAccessInfo &accessInfo) : type_(type), pipe_(pipeInfo), device_(deviceId), + networkId_(networkId), accessInfo_(accessInfo) { mtu_ = DEFAULT_MTU_SIZE; } SoftBusClient::~SoftBusClient() { - ZLOGI("Shutdown socket:%{public}d, deviceId:%{public}s", socket_, - KvStoreUtils::ToBeAnonymous(device_.deviceId).c_str()); + ZLOGI("Shutdown socket:%{public}d, deviceId:%{public}s", socket_, Anonymous::Change(device_.deviceId).c_str()); if (socket_ > 0) { Shutdown(socket_); } @@ -53,7 +52,7 @@ bool SoftBusClient::operator==(const std::string &deviceId) const return device_.deviceId == deviceId; } -uint32_t SoftBusClient::GetMtuSize() const +uint32_t SoftBusClient::GetMtuBuffer() const { ZLOGD("get mtu size socket:%{public}d mtu:%{public}d", socket_, mtu_); return mtu_; @@ -64,7 +63,7 @@ uint32_t SoftBusClient::GetTimeout() const return DEFAULT_TIMEOUT; } -Status SoftBusClient::SendData(const DataInfo &dataInfo, const ISocketListener *listener) +Status SoftBusClient::SendData(const DataInfo &dataInfo) { std::lock_guard lock(mutex_); auto result = CheckStatus(); @@ -84,7 +83,7 @@ Status SoftBusClient::SendData(const DataInfo &dataInfo, const ISocketListener * return Status::SUCCESS; } -int32_t SoftBusClient::GetSoftBusError() +int32_t SoftBusClient::GetSoftBusError() const { std::lock_guard lock(mutex_); return softBusError_; @@ -111,12 +110,12 @@ Status SoftBusClient::OpenConnect(const ISocketListener *listener) return; } ZLOGI("Bind Start, device:%{public}s socket:%{public}d type:%{public}u", - KvStoreUtils::ToBeAnonymous(client->device_.deviceId).c_str(), clientSocket, type); + Anonymous::Change(client->device_.deviceId).c_str(), clientSocket, type); int32_t status = client->Open(clientSocket, type, listener); - Context::GetInstance().NotifySessionReady(client->device_.deviceId, status); + CommunicatorContext::GetInstance().NotifySessionReady(client->device_.deviceId, status); client->isOpening_.store(false); }; - Context::GetInstance().GetThreadPool()->Execute(task); + CommunicatorContext::GetInstance().GetThreadPool()->Execute(task); return Status::RATE_LIMIT; } @@ -134,6 +133,26 @@ int32_t SoftBusClient::CreateSocket() const int32_t socket = Socket(socketInfo); if (socket <= 0) { ZLOGE("Create the client Socket:%{public}d failed, peerName:%{public}s", socket, socketInfo.peerName); + return socket; + } + if (accessInfo_.isOHType) { + SocketAccessInfo info; + info.userId = accessInfo_.userId; + info.localTokenId = accessInfo_.tokenId; + AccessExtraInfo extraInfo; + extraInfo.bundleName = accessInfo_.bundleName; + extraInfo.accountId = accessInfo_.accountId; + extraInfo.storeId = accessInfo_.storeId; + std::string extraInfoStr = Serializable::Marshall(extraInfo); + info.extraAccessInfo = const_cast(extraInfoStr.c_str()); + auto status = SetAccessInfo(socket, info); + if (status != 0) { + ZLOGE("SetAccessInfo fail, status:%{public}d, userId:%{public}d, tokenId:%{public}lu," + "bundleName:%{public}s, accountId:%{public}s, storeId:%{public}s", status, info.userId, info.localTokenId, + extraInfo.bundleName.c_str(), Anonymous::Change(extraInfo.accountId).c_str(), + Anonymous::Change(extraInfo.storeId).c_str()); + return -1; + } } return socket; } @@ -154,28 +173,27 @@ Status SoftBusClient::CheckStatus() int32_t SoftBusClient::Open(int32_t socket, uint32_t type, const ISocketListener *listener, bool async) { - int32_t status = ::Bind(socket, QOS_INFOS[type % QOS_BUTT], QOS_COUNTS[type % QOS_BUTT], listener); - ZLOGI("Bind %{public}s,session:%{public}s,socketId:%{public}d", - KvStoreUtils::ToBeAnonymous(device_.deviceId).c_str(), pipe_.pipeId.c_str(), socket); + int32_t status = Bind(socket, QOS_INFOS[type % QOS_BUTT], QOS_COUNTS[type % QOS_BUTT], listener); + ZLOGI("Bind %{public}s,session:%{public}s,socketId:%{public}d", Anonymous::Change(device_.deviceId).c_str(), + pipe_.pipeId.c_str(), socket); if (status != 0) { ZLOGE("[Bind] device:%{public}s socket failed, session:%{public}s,result:%{public}d", - KvStoreUtils::ToBeAnonymous(device_.deviceId).c_str(), pipe_.pipeId.c_str(), status); - ::Shutdown(socket); + Anonymous::Change(device_.deviceId).c_str(), pipe_.pipeId.c_str(), status); + Shutdown(socket); return status; } - UpdateExpireTime(async); uint32_t mtu = 0; std::tie(status, mtu) = GetMtu(socket); - if (status != SOFTBUS_OK) { + if (status != 0) { ZLOGE("GetMtu failed, session:%{public}s, socket:%{public}d, status:%{public}d", pipe_.pipeId.c_str(), socket_, status); - ::Shutdown(socket); + Shutdown(socket); return status; } UpdateBindInfo(socket, mtu, status, async); - ZLOGI("open %{public}s, session:%{public}s success, socket:%{public}d", - KvStoreUtils::ToBeAnonymous(device_.deviceId).c_str(), pipe_.pipeId.c_str(), socket_); + ZLOGI("open %{public}s, session:%{public}s success, socket:%{public}d", Anonymous::Change(device_.deviceId).c_str(), + pipe_.pipeId.c_str(), socket_); ConnectManager::GetInstance()->OnSessionOpen(networkId_); return status; } @@ -191,18 +209,11 @@ int32_t SoftBusClient::GetSocket() const return socket_; } -void SoftBusClient::UpdateExpireTime(bool async) +void SoftBusClient::UpdateExpireTime() { auto expireTime = CalcExpireTime(); - if (async) { - std::lock_guard lock(mutex_); - if (expireTime > expireTime_) { - expireTime_ = expireTime; - } - } else { - if (expireTime > expireTime_) { - expireTime_ = expireTime; - } + if (expireTime > expireTime_) { + expireTime_ = expireTime; } } @@ -223,7 +234,7 @@ void SoftBusClient::UpdateBindInfo(int32_t socket, uint32_t mtu, int32_t status, std::pair SoftBusClient::GetMtu(int32_t socket) { uint32_t mtu = 0; - auto ret = ::GetMtuSize(socket, &mtu); + auto ret = GetMtuSize(socket, &mtu); return { ret, mtu }; } @@ -243,7 +254,7 @@ Status SoftBusClient::ReuseConnect(const ISocketListener *listener) std::lock_guard lock(mutex_); auto checkStatus = CheckStatus(); if (checkStatus == Status::SUCCESS) { - UpdateExpireTime(false); + UpdateExpireTime(); return Status::SUCCESS; } int32_t socket = CreateSocket(); @@ -251,12 +262,12 @@ Status SoftBusClient::ReuseConnect(const ISocketListener *listener) return Status::NETWORK_ERROR; } ZLOGI("Reuse Start, device:%{public}s session:%{public}s socket:%{public}d", - KvStoreUtils::ToBeAnonymous(device_.deviceId).c_str(), pipe_.pipeId.c_str(), socket); + Anonymous::Change(device_.deviceId).c_str(), pipe_.pipeId.c_str(), socket); int32_t status = Open(socket, QOS_REUSE, listener, false); return status == SOFTBUS_OK ? Status::SUCCESS : Status::NETWORK_ERROR; } -const std::string& SoftBusClient::GetNetworkId() const +std::string SoftBusClient::GetNetworkId() const { return networkId_; } diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_client.h b/services/distributeddataservice/adapter/communicator/src/softbus_client.h index a0196c94f3203f1475bb84c3c5c111e4dbc6ee31..77f3ac9c9434331209759c0d8573032bcc7b7430 100644 --- a/services/distributeddataservice/adapter/communicator/src/softbus_client.h +++ b/services/distributeddataservice/adapter/communicator/src/softbus_client.h @@ -17,47 +17,73 @@ #define DISTRIBUTEDDATAMGR_DATAMGR_SERVICE_SOFTBUS_CLIENT_H #include -#include #include #include "commu_types.h" -#include "executor_pool.h" +#include "serializable/serializable.h" #include "socket.h" -#include "softbus_bus_center.h" + namespace OHOS::AppDistributedKv { class SoftBusClient : public std::enable_shared_from_this { public: + struct AccessExtraInfo final : public DistributedData::Serializable { + std::string bundleName = ""; + std::string accountId = ""; + std::string storeId = ""; + + AccessExtraInfo() {}; + ~AccessExtraInfo() {}; + bool Marshal(json &node) const override + { + SetValue(node[GET_NAME(bundleName)], bundleName); + SetValue(node[GET_NAME(accountId)], accountId); + SetValue(node[GET_NAME(storeId)], storeId); + return true; + }; + bool Unmarshal(const json &node) override + { + GetValue(node, GET_NAME(bundleName), bundleName); + GetValue(node, GET_NAME(accountId), accountId); + GetValue(node, GET_NAME(storeId), storeId); + return true; + }; + }; + enum QoSType { QOS_BR, QOS_HML, QOS_REUSE, QOS_BUTT }; + SoftBusClient(const PipeInfo &pipeInfo, const DeviceId &deviceId, const std::string& networkId, - uint32_t type = QOS_HML); + uint32_t type = QOS_HML, const SessionAccessInfo &accessInfo = {}); ~SoftBusClient(); using Time = std::chrono::steady_clock::time_point; using Duration = std::chrono::steady_clock::duration; - Status CheckStatus(); - Status OpenConnect(const ISocketListener *listener); - Status SendData(const DataInfo &dataInfo, const ISocketListener *listener); + bool operator==(int32_t socket) const; bool operator==(const std::string &deviceId) const; - uint32_t GetMtuSize() const; - uint32_t GetTimeout() const; + + Status CheckStatus(); + Status OpenConnect(const ISocketListener *listener); + Status ReuseConnect(const ISocketListener *listener); + Status SendData(const DataInfo &dataInfo); Time GetExpireTime() const; + int32_t GetSocket() const; uint32_t GetQoSType() const; - void UpdateExpireTime(bool async = true); - int32_t GetSoftBusError(); - Status ReuseConnect(const ISocketListener *listener); - const std::string& GetNetworkId() const; + uint32_t GetMtuBuffer() const; + uint32_t GetTimeout() const; + int32_t GetSoftBusError() const; + std::string GetNetworkId() const; private: int32_t Open(int32_t socket, uint32_t type, const ISocketListener *listener, bool async = true); std::pair GetMtu(int32_t socket); Time CalcExpireTime() const; + void UpdateExpireTime(); int32_t CreateSocket() const; void UpdateBindInfo(int32_t socket, uint32_t mtu, int32_t status, bool async = true); @@ -91,14 +117,14 @@ private: uint32_t type_ = QOS_HML; PipeInfo pipe_; DeviceId device_; + std::string networkId_; + SessionAccessInfo accessInfo_; uint32_t mtu_; Time expireTime_ = std::chrono::steady_clock::now() + MAX_DELAY; int32_t socket_ = INVALID_SOCKET_ID; int32_t bindState_ = -1; int32_t softBusError_ = 0; - const std::string networkId_; }; } // namespace OHOS::AppDistributedKv - #endif // DISTRIBUTEDDATAMGR_DATAMGR_SERVICE_SOFTBUS_CLIENT_H \ No newline at end of file diff --git a/services/distributeddataservice/adapter/communicator/test/BUILD.gn b/services/distributeddataservice/adapter/communicator/test/BUILD.gn index a85976697641f91ed1b1c162af428da050e69c34..c0a54f41f54fbc2d740a29838e762bb4a2f668b6 100755 --- a/services/distributeddataservice/adapter/communicator/test/BUILD.gn +++ b/services/distributeddataservice/adapter/communicator/test/BUILD.gn @@ -181,82 +181,88 @@ ohos_unittest("ProcessCommunicatorImplTest") { defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] } -ohos_unittest("SoftbusAdapterStandardTest") { +ohos_unittest("SoftBusAdapterStandardTest") { module_out_path = module_output_path - sources = [ - "../src/app_pipe_handler.cpp", - "../src/app_pipe_mgr.cpp", - "../src/ark_communication_provider.cpp", - "../src/communication_provider.cpp", - "../src/communication_provider_impl.cpp", - "../src/communicator_context.cpp", - "../src/data_buffer.cpp", - "../src/device_manager_adapter.cpp", - "../src/process_communicator_impl.cpp", - "../src/softbus_client.cpp", - "unittest/softbus_adapter_standard_test.cpp", - ] - include_dirs = [ + "${data_service_path}/adapter/communicator/src", + "${data_service_path}/adapter/communicator/test/mock/account_manager", + "${data_service_path}/adapter/communicator/test/mock/device_manager", + "${data_service_path}/adapter/communicator/test/mock/softbus", "${data_service_path}/adapter/include/communicator", - "${data_service_path}/framework/include/dfx", - "../src", - "../../include/communicator", - "../../include/utils", - "${data_service_path}/framework/include/utils", + "${data_service_path}/framework/include", + ] + + sources = [ + "${data_service_path}/adapter/communicator/src/communicator_context.cpp", + "${data_service_path}/adapter/communicator/src/device_manager_adapter.cpp", + "${data_service_path}/adapter/communicator/src/softbus_client.cpp", + "${data_service_path}/adapter/communicator/src/softbus_adapter_standard.cpp", + "${data_service_path}/adapter/communicator/test/mock/account_manager/account_delegate_mock.cpp", + "${data_service_path}/adapter/communicator/test/mock/device_manager/device_manager.cpp", + "${data_service_path}/adapter/communicator/test/mock/softbus/data_level.cpp", + "${data_service_path}/adapter/communicator/test/mock/softbus/inner_socket.cpp", + "${data_service_path}/adapter/communicator/test/mock/softbus/socket.cpp", + "${data_service_path}/adapter/communicator/test/mock/meta_data_manager.cpp", + "${data_service_path}/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp", + "${data_service_path}/framework/account/account_delegate.cpp", + "${data_service_path}/framework/communication/connect_manager.cpp", + "${data_service_path}/framework/metadata/store_meta_data.cpp", + "${data_service_path}/framework/serializable/serializable.cpp", + "${data_service_path}/framework/utils/anonymous.cpp", ] + external_deps = [ - "access_token:libaccesstoken_sdk", - "access_token:libnativetoken", - "access_token:libtoken_setproc", + "cJSON:cjson", "c_utils:utils", - "device_manager:devicemanagersdk", - "dsoftbus:softbus_client", "hilog:libhilog", - "ipc:ipc_core", - "json:nlohmann_json_static", - "kv_store:datamgr_common", "kv_store:distributeddata_inner", - "kv_store:distributeddb", ] + + cflags_cc = [ "-DUT_TEST" ] + cflags = [ "-Dprivate=public", "-Dprotected=public", ] - deps = [ - "${data_service_path}/adapter/utils:distributeddata_utils", - "${data_service_path}/framework:distributeddatasvcfwk", - ] + defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] } -ohos_unittest("SoftbusClientTest") { +ohos_unittest("SoftBusClientTest") { module_out_path = module_output_path - sources = [ "unittest/softbus_client_test.cpp" ] include_dirs = [ - "${data_service_path}/adapter/include/autils", + "${data_service_path}/adapter/communicator/src", + "${data_service_path}/adapter/communicator/test/mock/softbus", "${data_service_path}/adapter/include/communicator", - "${data_service_path}/adapter/include/dfx", - "../src", + "${data_service_path}/framework/include", ] + + sources = [ + "${data_service_path}/adapter/communicator/src/communicator_context.cpp", + "${data_service_path}/adapter/communicator/src/softbus_client.cpp", + "${data_service_path}/adapter/communicator/test/mock/softbus/inner_socket.cpp", + "${data_service_path}/adapter/communicator/test/mock/softbus/socket.cpp", + "${data_service_path}/adapter/communicator/test/unittest/softbus_client_test.cpp", + "${data_service_path}/framework/communication/connect_manager.cpp", + "${data_service_path}/framework/serializable/serializable.cpp", + "${data_service_path}/framework/utils/anonymous.cpp", + ] + external_deps = [ + "cJSON:cjson", "c_utils:utils", - "device_manager:devicemanagersdk", - "dsoftbus:softbus_client", "googletest:gtest_main", "hilog:libhilog", "kv_store:distributeddata_inner", - "kv_store:distributeddb", ] + cflags = [ "-Dprivate=public", "-Dprotected=public", ] - deps = [ - "${data_service_path}/adapter/communicator:distributeddata_communicator", - ] + defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] } @@ -267,7 +273,7 @@ ohos_unittest("AppPipeMgrServiceTest") { "${data_service_path}/adapter/include/communicator", "${data_service_path}/adapter/include/dfx", "${data_service_path}/adapter/include/utils", - "${data_service_path}/framework/include/dfx", + "${data_service_path}/framework/include", "../src", ] sources = [ "unittest/app_pipe_mgr_service_test.cpp" ] @@ -286,6 +292,7 @@ ohos_unittest("AppPipeMgrServiceTest") { ] deps = [ "${data_service_path}/adapter/communicator:distributeddata_communicator", + "${data_service_path}/framework:distributeddatasvcfwk", ] defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] } @@ -303,8 +310,8 @@ group("unittest") { ":CommunicatorDataBufferTest", ":DeviceManagerAdapterTest", ":ProcessCommunicatorImplTest", - ":SoftbusAdapterStandardTest", - ":SoftbusClientTest", + ":SoftBusAdapterStandardTest", + ":SoftBusClientTest", ] } ############################################################################### diff --git a/services/distributeddataservice/adapter/communicator/test/mock/account_manager/account_delegate_mock.cpp b/services/distributeddataservice/adapter/communicator/test/mock/account_manager/account_delegate_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f526174d9435f8bad30c21cfa73a11aa1911fa2a --- /dev/null +++ b/services/distributeddataservice/adapter/communicator/test/mock/account_manager/account_delegate_mock.cpp @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2025 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 "account_delegate_mock.h" + +namespace OHOS::DistributedData { +__attribute__((used)) static bool g_isInit = AccountDelegateMock::Init(); + +static constexpr int FOREGROUND_USERID = 100; +static constexpr const char *LOCAL_ACCOUNT_ID = "local_account"; + +bool AccountDelegateMock::Init() +{ + static AccountDelegateMock accountDelegateMock; + static std::once_flag onceFlag; + std::call_once(onceFlag, [&]() { AccountDelegate::RegisterAccountInstance(&accountDelegateMock); }); + return true; +} + +int32_t AccountDelegateMock::Subscribe(std::shared_ptr observer) +{ + (void)observer; + return 0; +} + +int32_t AccountDelegateMock::Unsubscribe(std::shared_ptr observer) +{ + (void)observer; + return 0; +} + +std::string AccountDelegateMock::GetCurrentAccountId() const +{ + return LOCAL_ACCOUNT_ID; +} + +int32_t AccountDelegateMock::GetUserByToken(uint32_t tokenId) const +{ + (void)tokenId; + return 0; +} + +void AccountDelegateMock::SubscribeAccountEvent() {} + +void AccountDelegateMock::UnsubscribeAccountEvent() {} + +bool AccountDelegateMock::QueryUsers(std::vector &users) +{ + (void)users; + return true; +} + +bool AccountDelegateMock::QueryForegroundUsers(std::vector &users) +{ + (void)users; + return true; +} + +bool AccountDelegateMock::IsLoginAccount() +{ + return true; +} + +bool AccountDelegateMock::QueryForegroundUserId(int &foregroundUserId) +{ + foregroundUserId = FOREGROUND_USERID; + return true; +} + +bool AccountDelegateMock::IsVerified(int userId) +{ + (void)userId; + return true; +} + +bool AccountDelegateMock::RegisterHashFunc(HashFunc hash) +{ + (void)hash; + return true; +} + +bool AccountDelegateMock::IsDeactivating(int userId) +{ + (void)userId; + return true; +} + +void AccountDelegateMock::BindExecutor(std::shared_ptr executors) +{ + (void)executors; +} + +std::string AccountDelegateMock::GetUnencryptedAccountId(int32_t userId) const +{ + (void)userId; + return ""; +} + +bool AccountDelegateMock::IsUserForeground(int32_t userId) +{ + (void)userId; + return true; +} +} // namespace OHOS::DistributedData \ No newline at end of file diff --git a/services/distributeddataservice/adapter/communicator/test/mock/account_manager/account_delegate_mock.h b/services/distributeddataservice/adapter/communicator/test/mock/account_manager/account_delegate_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..59195d6840fc3884c9f76d4308642b97b135fda3 --- /dev/null +++ b/services/distributeddataservice/adapter/communicator/test/mock/account_manager/account_delegate_mock.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2025 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 MOCK_ACCOUNT_DELEGATE_MOCK_H +#define MOCK_ACCOUNT_DELEGATE_MOCK_H + +#include "account/account_delegate.h" + +namespace OHOS::DistributedData { +class AccountDelegateMock final : public AccountDelegate { +public: + static bool Init(); + int32_t Subscribe(std::shared_ptr observer) override; + int32_t Unsubscribe(std::shared_ptr observer) override; + std::string GetCurrentAccountId() const override; + int32_t GetUserByToken(uint32_t tokenId) const override; + void SubscribeAccountEvent() override; + void UnsubscribeAccountEvent() override; + bool QueryUsers(std::vector &users) override; + bool QueryForegroundUsers(std::vector &users) override; + bool IsLoginAccount() override; + bool QueryForegroundUserId(int &foregroundUserId) override; + bool IsVerified(int userId) override; + bool RegisterHashFunc(HashFunc hash) override; + bool IsDeactivating(int userId) override; + void BindExecutor(std::shared_ptr executors) override; + std::string GetUnencryptedAccountId(int32_t userId = 0) const override; + bool IsUserForeground(int32_t userId) override; +}; +} + +#endif // MOCK_ACCOUNT_DELEGATE_MOCK_H diff --git a/services/distributeddataservice/adapter/communicator/test/mock/device_manager/device_manager.cpp b/services/distributeddataservice/adapter/communicator/test/mock/device_manager/device_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0e6a938fa8e7a5b137786809ff0f681ccb572082 --- /dev/null +++ b/services/distributeddataservice/adapter/communicator/test/mock/device_manager/device_manager.cpp @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2025 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 "device_manager.h" + +#include "securec.h" + +namespace OHOS::DistributedHardware { +static constexpr const char *LOCAL_DEVICE_NAME = "local_device_name"; +static constexpr const char *LOCAL_NETWORK_ID = "local_network_id"; +static constexpr const char *LOCAL_UUID = "local_uuid"; +static constexpr const char *LOCAL_UDID = "local_udid"; +static constexpr const char *REMOTE_DEVICE_NAME = "remote_device_name"; +static constexpr const char *REMOTE_NETWORK_ID = "remote_network_id"; +static constexpr const char *REMOTE_UUID = "remote_uuid"; +static constexpr const char *REMOTE_UDID = "remote_udid"; + +DeviceManager &DeviceManager::GetInstance() +{ + static DeviceManager dmManager; + return dmManager; +} + +int32_t DeviceManager::InitDeviceManager(const std::string &pkgName, std::shared_ptr dmInitCallback) +{ + (void)pkgName; + (void)dmInitCallback; + return 0; +} + +int32_t DeviceManager::RegisterDevStateCallback(const std::string &pkgName, const std::string &extra, + std::shared_ptr callback) +{ + (void)pkgName; + (void)extra; + (void)callback; + return 0; +} + +int32_t DeviceManager::NotifyEvent(const std::string &pkgName, const int32_t eventId, const std::string &event) +{ + (void)pkgName; + (void)eventId; + (void)event; + return 0; +} + +int32_t DeviceManager::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, + std::vector &deviceList) +{ + (void)pkgName; + (void)extra; + DeviceExtraInfo extraInfo; + DmDeviceInfo remoteDeviceInfo = { .extraData = DistributedData::Serializable::Marshall(extraInfo) }; + (void)strcpy_s(remoteDeviceInfo.deviceName, DM_MAX_DEVICE_ID_LEN, REMOTE_DEVICE_NAME); + (void)strcpy_s(remoteDeviceInfo.networkId, DM_MAX_DEVICE_ID_LEN, REMOTE_NETWORK_ID); + deviceList.emplace_back(std::move(remoteDeviceInfo)); + return 0; +} + +int32_t DeviceManager::GetLocalDeviceInfo(const std::string &pkgName, DmDeviceInfo &deviceInfo) +{ + (void)pkgName; + (void)strcpy_s(deviceInfo.deviceName, DM_MAX_DEVICE_ID_LEN, LOCAL_DEVICE_NAME); + (void)strcpy_s(deviceInfo.networkId, DM_MAX_DEVICE_ID_LEN, LOCAL_NETWORK_ID); + DeviceExtraInfo extraInfo; + deviceInfo.extraData = DistributedData::Serializable::Marshall(extraInfo); + return 0; +} + +int32_t DeviceManager::GetUuidByNetworkId(const std::string &pkgName, const std::string &networkId, std::string &uuid) +{ + (void)pkgName; + if (networkId == LOCAL_NETWORK_ID) { + uuid = LOCAL_UUID; + } + if (networkId == REMOTE_NETWORK_ID) { + uuid = REMOTE_UUID; + } + return 0; +} + +int32_t DeviceManager::GetUdidByNetworkId(const std::string &pkgName, const std::string &networkId, std::string &udid) +{ + (void)pkgName; + if (networkId == LOCAL_NETWORK_ID) { + udid = LOCAL_UDID; + } + if (networkId == REMOTE_NETWORK_ID) { + udid = REMOTE_UDID; + } + return 0; +} + +int32_t DeviceManager::GenerateEncryptedUuid(const std::string &pkgName, const std::string &uuid, + const std::string &appId, std::string &encryptedUuid) +{ + (void)pkgName; + (void)uuid; + (void)appId; + (void)encryptedUuid; + return 0; +} + +int32_t DeviceManager::GetEncryptedUuidByNetworkId(const std::string &pkgName, const std::string &networkId, + std::string &uuid) +{ + (void)pkgName; + (void)networkId; + (void)uuid; + return 0; +} + +bool DeviceManager::IsSameAccount(const std::string &networkId) +{ + (void)networkId; + return true; +} + +bool DeviceManager::CheckAccessControl(const DmAccessCaller &caller, const DmAccessCallee &callee) +{ + (void)caller; + (void)callee; + return true; +} + +bool DeviceManager::CheckIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee) +{ + (void)caller; + (void)callee; + return true; +} +} // namespace OHOS::DistributedHardware \ No newline at end of file diff --git a/services/distributeddataservice/adapter/communicator/test/mock/device_manager/device_manager.h b/services/distributeddataservice/adapter/communicator/test/mock/device_manager/device_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..874d0bfef0947d4d6ef5c0cf31d6cc5ed2c55119 --- /dev/null +++ b/services/distributeddataservice/adapter/communicator/test/mock/device_manager/device_manager.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 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 MOCK_DEVICE_MANAGER_H +#define MOCK_DEVICE_MANAGER_H + +#include +#include + +#include "device_manager_callback.h" +#include "dm_device_info.h" + +namespace OHOS::DistributedHardware { +class DeviceManager { +public: + static DeviceManager &GetInstance(); + + int32_t InitDeviceManager(const std::string &pkgName, std::shared_ptr dmInitCallback); + int32_t RegisterDevStateCallback(const std::string &pkgName, const std::string &extra, + std::shared_ptr callback); + int32_t NotifyEvent(const std::string &pkgName, const int32_t eventId, const std::string &event); + int32_t GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, + std::vector &deviceList); + int32_t GetLocalDeviceInfo(const std::string &pkgName, DmDeviceInfo &deviceInfo); + int32_t GetUuidByNetworkId(const std::string &pkgName, const std::string &networkId, std::string &uuid); + int32_t GetUdidByNetworkId(const std::string &pkgName, const std::string &networkId, std::string &udid); + int32_t GenerateEncryptedUuid(const std::string &pkgName, const std::string &uuid, const std::string &appId, + std::string &encryptedUuid); + int32_t GetEncryptedUuidByNetworkId(const std::string &pkgName, const std::string &networkId, std::string &uuid); + bool IsSameAccount(const std::string &networkId); + bool CheckAccessControl(const DmAccessCaller &caller, const DmAccessCallee &callee); + bool CheckIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee); + +private: + DeviceManager() = default; + ~DeviceManager() = default; +}; +} // namespace OHOS::DistributedHardware +#endif // MOCK_DEVICE_MANAGER_H \ No newline at end of file diff --git a/services/distributeddataservice/adapter/communicator/test/mock/device_manager/device_manager_callback.h b/services/distributeddataservice/adapter/communicator/test/mock/device_manager/device_manager_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..2ba425aebd2677e22fa175aa9398d1ece5a913c6 --- /dev/null +++ b/services/distributeddataservice/adapter/communicator/test/mock/device_manager/device_manager_callback.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2025 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 MOCK_DEVICE_MANAGER_CALLBACK_H +#define MOCK_DEVICE_MANAGER_CALLBACK_H + +#include "dm_device_info.h" + +namespace OHOS::DistributedHardware { +class DmInitCallback { +public: + virtual ~DmInitCallback() {} + virtual void OnRemoteDied() = 0; +}; + +class DeviceStateCallback { +public: + virtual ~DeviceStateCallback() {} + virtual void OnDeviceOnline(const DmDeviceInfo &deviceInfo) = 0; + virtual void OnDeviceOffline(const DmDeviceInfo &deviceInfo) = 0; + virtual void OnDeviceChanged(const DmDeviceInfo &deviceInfo) = 0; + virtual void OnDeviceReady(const DmDeviceInfo &deviceInfo) = 0; +}; +} // namespace OHOS::DistributedHardware +#endif // MOCK_DEVICE_MANAGER_CALLBACK_H \ No newline at end of file diff --git a/services/distributeddataservice/adapter/communicator/test/mock/device_manager/dm_device_info.h b/services/distributeddataservice/adapter/communicator/test/mock/device_manager/dm_device_info.h new file mode 100644 index 0000000000000000000000000000000000000000..ad9a9de9becce9446b2f4188c14e8ef8688f462a --- /dev/null +++ b/services/distributeddataservice/adapter/communicator/test/mock/device_manager/dm_device_info.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2025 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 MOCK_DM_DEVICE_INFO_H +#define MOCK_DM_DEVICE_INFO_H + +#include "serializable/serializable.h" + +#define DM_MAX_DEVICE_ID_LEN (97) + +namespace OHOS::DistributedHardware { +struct DeviceExtraInfo final : public DistributedData::Serializable { + static constexpr int32_t OH_OS_TYPE = 10; + + int32_t OS_TYPE = OH_OS_TYPE; + + DeviceExtraInfo() {}; + ~DeviceExtraInfo() {}; + bool Marshal(json &node) const override + { + return SetValue(node[GET_NAME(OS_TYPE)], OS_TYPE); + }; + bool Unmarshal(const json &node) override + { + return GetValue(node, GET_NAME(OS_TYPE), OS_TYPE); + }; +}; + +struct DmDeviceInfo { + char deviceId[DM_MAX_DEVICE_ID_LEN] = {0}; + char deviceName[DM_MAX_DEVICE_ID_LEN] = {0}; + uint16_t deviceTypeId; + char networkId[DM_MAX_DEVICE_ID_LEN] = {0}; + int32_t range; + int32_t networkType; + int32_t authForm; + std::string extraData; +}; + +struct DmAccessCaller { + std::string accountId; + std::string pkgName; + std::string networkId; + int32_t userId; + uint64_t tokenId = 0; + std::string extra; +}; + +struct DmAccessCallee { + std::string accountId; + std::string networkId; + std::string peerId; + std::string pkgName; + int32_t userId; + uint64_t tokenId = 0; + std::string extra; +}; + +enum DmNotifyEvent { + DM_NOTIFY_EVENT_ONDEVICEREADY, +}; +} // namespace OHOS::DistributedHardware +#endif // MOCK_DM_DEVICE_INFO_H \ No newline at end of file diff --git a/services/distributeddataservice/adapter/communicator/test/mock/meta_data_manager.cpp b/services/distributeddataservice/adapter/communicator/test/mock/meta_data_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5ff53cd3c06eb0041022c8b6c0a70e8f2c1bb764 --- /dev/null +++ b/services/distributeddataservice/adapter/communicator/test/mock/meta_data_manager.cpp @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2025 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 "metadata/meta_data_manager.h" +#include "metadata/store_meta_data.h" + +namespace OHOS::DistributedData { +ConcurrentMap storeMetaList_; +MetaDataManager &MetaDataManager::GetInstance() +{ + static MetaDataManager instance; + return instance; +} + +MetaDataManager::MetaDataManager() = default; + +MetaDataManager::~MetaDataManager() = default; + +void MetaDataManager::Initialize(std::shared_ptr metaStore, const Backup &backup, + const std::string &storeId) +{ + (void)metaStore; + (void)backup; + (void)storeId; +} + +void MetaDataManager::SetSyncer(const Syncer &syncer) +{ + (void)syncer; +} + +void MetaDataManager::SetCloudSyncer(const CloudSyncer &cloudSyncer) +{ + (void)cloudSyncer; +} + +bool MetaDataManager::SaveMeta(const std::string &key, const Serializable &value, bool isLocal) +{ + (void)isLocal; + auto data = Serializable::Marshall(value); + StoreMetaData metaData; + Serializable::Unmarshall({ data.begin(), data.end() }, metaData); + storeMetaList_.InsertOrAssign(key, metaData); + return true; +} + +bool MetaDataManager::LoadMeta(const std::string &key, Serializable &value, bool isLocal) +{ + (void)isLocal; + auto index = storeMetaList_.Find(key); + if (index.first) { + value = index.second; + return true; + } + return false; +} + +bool MetaDataManager::DelMeta(const std::string &key, bool isLocal) +{ + (void)isLocal; + storeMetaList_.Erase(key); + return true; +} + +bool MetaDataManager::GetEntries(const std::string &prefix, std::vector &entries, bool isLocal) +{ + (void)prefix; + (void)entries; + (void)isLocal; + return true; +} + +bool MetaDataManager::Sync(const std::vector &devices, OnComplete complete, bool wait) +{ + (void)devices; + (void)complete; + (void)wait; + return true; +} + +bool MetaDataManager::Subscribe(std::shared_ptr filter, Observer observer) +{ + (void)filter; + (void)observer; + return true; +} + +bool MetaDataManager::Subscribe(std::string prefix, Observer observer, bool isLocal) +{ + (void)prefix; + (void)observer; + (void)isLocal; + return true; +} + +bool MetaDataManager::Unsubscribe(std::string filter) +{ + (void)filter; + return true; +} + +void MetaDataManager::StopSA() +{ +} +} // namespace OHOS::DistributedData \ No newline at end of file diff --git a/services/distributeddataservice/adapter/communicator/test/mock/softbus/data_level.cpp b/services/distributeddataservice/adapter/communicator/test/mock/softbus/data_level.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7b778b84fbbff86b74b2d74dc3b9dd891ca06ee5 --- /dev/null +++ b/services/distributeddataservice/adapter/communicator/test/mock/softbus/data_level.cpp @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 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 "data_level.h" + +static constexpr const char *REMOTE_NETWORK_ID = "remote_network_id"; + +SoftBusErrNo errCode_; +IDataLevelCb *callback_ = nullptr; + +void ConfigReturnCode(SoftBusErrNo errorCode) +{ + errCode_ = errorCode; +} + +int32_t RegDataLevelChangeCb(const char *pkgName, IDataLevelCb *callback) +{ + (void)pkgName; + if (callback_ != nullptr) { + return SoftBusErrNo::SOFTBUS_ALREADY_EXISTED; + } + callback_ = callback; + return 0; +} + +int32_t UnregDataLevelChangeCb(const char *pkgName) +{ + (void)pkgName; + callback_ = nullptr; + return 0; +} + +int32_t SetDataLevel(const DataLevel *dataLevel) +{ + if (errCode_ == SoftBusErrNo::SOFTBUS_OK && callback_ != nullptr) { + callback_->onDataLevelChanged(REMOTE_NETWORK_ID, *dataLevel); + } + return errCode_; +} \ No newline at end of file diff --git a/services/distributeddataservice/adapter/communicator/test/mock/softbus/data_level.h b/services/distributeddataservice/adapter/communicator/test/mock/softbus/data_level.h new file mode 100644 index 0000000000000000000000000000000000000000..fdd246507c5275458ba82c469978f2b679de7d6e --- /dev/null +++ b/services/distributeddataservice/adapter/communicator/test/mock/softbus/data_level.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2025 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 MOCK_SOFTBUS_DATA_LEVEL_H +#define MOCK_SOFTBUS_DATA_LEVEL_H + +#include + +#include "softbus_error_code.h" + +struct DataLevel { + uint16_t dynamicLevel; + uint16_t staticLevel; + uint32_t switchLevel; + uint16_t switchLength; +}; + +struct IDataLevelCb { + void (*onDataLevelChanged)(const char *networkId, const DataLevel dataLevel); +}; + +void ConfigReturnCode(SoftBusErrNo errorCode); + +int32_t RegDataLevelChangeCb(const char *pkgName, IDataLevelCb *callback); + +int32_t UnregDataLevelChangeCb(const char *pkgName); + +int32_t SetDataLevel(const DataLevel *dataLevel); + +#endif // MOCK_SOFTBUS_DATA_LEVEL_H \ No newline at end of file diff --git a/services/distributeddataservice/adapter/communicator/test/mock/softbus/inner_socket.cpp b/services/distributeddataservice/adapter/communicator/test/mock/softbus/inner_socket.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a2bc12a6d4af75258ffeefd04d9e182d7582f1a3 --- /dev/null +++ b/services/distributeddataservice/adapter/communicator/test/mock/softbus/inner_socket.cpp @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2025 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 "inner_socket.h" + +#include "socket.h" + +static constexpr uint32_t MTU_SIZE = 4 * 1024u; + +int32_t GetMtuSize(int32_t socket, uint32_t *mtuSize) +{ + if (socket <= INVALID_MTU_SOCKET) { + return -1; + } + *mtuSize = MTU_SIZE; + return 0; +} \ No newline at end of file diff --git a/services/distributeddataservice/adapter/communicator/test/mock/softbus/inner_socket.h b/services/distributeddataservice/adapter/communicator/test/mock/softbus/inner_socket.h new file mode 100644 index 0000000000000000000000000000000000000000..5db024db30d14ec5dca4ffe97fd1fb194915d2d7 --- /dev/null +++ b/services/distributeddataservice/adapter/communicator/test/mock/softbus/inner_socket.h @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2025 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 MOCK_SOFTBUS_INNER_SESSION_SOCKET_H +#define MOCK_SOFTBUS_INNER_SESSION_SOCKET_H + +#include + +int32_t GetMtuSize(int32_t socket, uint32_t *mtuSize); + +#endif // MOCK_SOFTBUS_INNER_SESSION_SOCKET_H \ No newline at end of file diff --git a/services/distributeddataservice/adapter/communicator/test/mock/softbus/socket.cpp b/services/distributeddataservice/adapter/communicator/test/mock/softbus/socket.cpp new file mode 100644 index 0000000000000000000000000000000000000000..560df44d2fdfaf55b22be923f120f416e4f0e317 --- /dev/null +++ b/services/distributeddataservice/adapter/communicator/test/mock/softbus/socket.cpp @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2025 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 "socket.h" + +#include "securec.h" + +static constexpr uint32_t EXTRA_INFO_LENGTH = 100; +static constexpr const char *SOCKET_NAME = "socket_test"; +static constexpr const char *PKG_NAME = "ddms_test"; +static constexpr const char *REMOTE_NETWORK_ID = "remote_network_id"; + +int32_t socketId_ = -1; +ISocketListener *clientListener_ = nullptr; +ISocketListener *serverListener_ = nullptr; +SocketAccessInfo accessInfo_; + +void ConfigSocketId(int32_t socketId) +{ + socketId_ = socketId; +} + +int32_t Socket(SocketInfo info) +{ + (void)info; + return socketId_; +} + +int32_t SetAccessInfo(int32_t socket, SocketAccessInfo accessInfo) +{ + if (socket == INVALID_BIND_SOCKET) { + return -1; + } + accessInfo_.userId = accessInfo.userId; + accessInfo_.localTokenId = accessInfo.localTokenId; + accessInfo_.extraAccessInfo = new char[EXTRA_INFO_LENGTH]; + (void)strcpy_s(accessInfo_.extraAccessInfo, EXTRA_INFO_LENGTH, accessInfo.extraAccessInfo); + return 0; +} + +int32_t Bind(int32_t socket, const QosTV qos[], uint32_t qosCount, const ISocketListener *listener) +{ + (void)qos; + (void)qosCount; + if (socket <= INVALID_OPEN_SOCKET) { + return -1; + } + if (serverListener_ != nullptr) { + PeerSocketInfo info; + info.name = const_cast(SOCKET_NAME); + info.pkgName = const_cast(PKG_NAME); + info.networkId = const_cast(REMOTE_NETWORK_ID); + SocketAccessInfo localInfo; + if (!serverListener_->OnNegotiate2(socket, info, &accessInfo_, &localInfo)) { + return -1; + } + serverListener_->OnBind(socket, info); + } + clientListener_ = const_cast(listener); + return 0; +} + +void Shutdown(int32_t socket) +{ + if (socket <= INVALID_MTU_SOCKET) { + return; + } + ShutdownReason reason = ShutdownReason::UN_KNOWN; + if (clientListener_ != nullptr && clientListener_->OnShutdown != nullptr) { + clientListener_->OnShutdown(socket, reason); + } + if (serverListener_ != nullptr && serverListener_->OnShutdown != nullptr) { + serverListener_->OnShutdown(socket, reason); + } +} + +int32_t SendBytes(int32_t socket, const void *data, uint32_t len) +{ + if (clientListener_ == nullptr) { + return 0; + } + if (clientListener_->OnBytes != nullptr) { + clientListener_->OnBytes(socket, data, len); + } + if (clientListener_->OnMessage != nullptr) { + clientListener_->OnMessage(socket, data, len); + } + return 0; +} + +int32_t Listen(int32_t socket, const QosTV qos[], uint32_t qosCount, const ISocketListener *listener) +{ + (void)socket; + (void)qos; + (void)qosCount; + serverListener_ = const_cast(listener); + return 0; +} \ No newline at end of file diff --git a/services/distributeddataservice/adapter/communicator/test/mock/softbus/socket.h b/services/distributeddataservice/adapter/communicator/test/mock/softbus/socket.h new file mode 100644 index 0000000000000000000000000000000000000000..0fc12020114a894ada628bb0af378cb1fe45eb09 --- /dev/null +++ b/services/distributeddataservice/adapter/communicator/test/mock/softbus/socket.h @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2025 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 MOCK_SOFTBUS_SESSION_SOCKET_H +#define MOCK_SOFTBUS_SESSION_SOCKET_H + +#include + +enum TransDataType { + DATA_TYPE_BYTES, +}; + +enum ShutdownReason { + UN_KNOWN, +}; + +enum QoSEvent { + QOS_SATISFIED, + QOS_NOT_SATISFIED, +}; + +enum QosType { + QOS_TYPE_MIN_BW, + QOS_TYPE_MAX_LATENCY, + QOS_TYPE_MIN_LATENCY, + QOS_TYPE_REUSE_BE, +}; + +struct QosTV { + QosType qos; + int32_t value; +}; + +struct PeerSocketInfo { + char *name; + char *networkId; + char *pkgName; + TransDataType dataType = TransDataType::DATA_TYPE_BYTES; +}; + +struct SocketInfo { + char *name; + char *peerName; + char *peerNetworkId; + char *pkgName; + TransDataType dataType; +}; + +struct SocketAccessInfo { + int32_t userId; + uint64_t localTokenId; + char *businessAccountId; + char *extraAccessInfo; +}; + +struct ISocketListener { + void (*OnBind)(int32_t socket, PeerSocketInfo info); + void (*OnShutdown)(int32_t socket, ShutdownReason reason); + void (*OnBytes)(int32_t socket, const void *data, uint32_t dataLen); + void (*OnMessage)(int32_t socket, const void *data, uint32_t dataLen); + void (*OnQos)(int32_t socket, QoSEvent eventId, const QosTV *qos, uint32_t qosCount); + bool (*OnNegotiate2)(int32_t socket, PeerSocketInfo info, SocketAccessInfo *peerInfo, SocketAccessInfo *localInfo); +}; + +static constexpr int32_t INVALID_SOCKET = 0; +static constexpr int32_t INVALID_BIND_SOCKET = 1; +static constexpr int32_t INVALID_OPEN_SOCKET = 2; +static constexpr int32_t INVALID_MTU_SOCKET = 3; +static constexpr int32_t VALID_SOCKET = 4; + +void ConfigSocketId(int32_t socketId); + +int32_t Socket(SocketInfo info); + +int32_t Listen(int32_t socket, const QosTV qos[], uint32_t qosCount, const ISocketListener *listener); + +int32_t SetAccessInfo(int32_t socket, SocketAccessInfo accessInfo); + +int32_t Bind(int32_t socket, const QosTV qos[], uint32_t qosCount, const ISocketListener *listener); + +void Shutdown(int32_t socket); + +int32_t SendBytes(int32_t socket, const void *data, uint32_t len); +#endif // MOCK_SOFTBUS_SESSION_SOCKET_H \ No newline at end of file diff --git a/services/distributeddataservice/adapter/communicator/test/mock/softbus/softbus_error_code.h b/services/distributeddataservice/adapter/communicator/test/mock/softbus/softbus_error_code.h new file mode 100644 index 0000000000000000000000000000000000000000..7925f943854f804e07abf1903fc7b3e79298d380 --- /dev/null +++ b/services/distributeddataservice/adapter/communicator/test/mock/softbus/softbus_error_code.h @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2025 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 MOCK_SOFTBUS_ERROR_CODE_H +#define MOCK_SOFTBUS_ERROR_CODE_H + +enum SoftBusErrNo { + SOFTBUS_OK = 0, + SOFTBUS_ERROR = 1, + SOFTBUS_FUNC_NOT_SUPPORT = 2, + SOFTBUS_ALREADY_EXISTED = 3, +}; +#endif // MOCK_SOFTBUS_ERROR_CODE_H \ No newline at end of file diff --git a/services/distributeddataservice/adapter/communicator/test/unittest/app_pipe_mgr_service_test.cpp b/services/distributeddataservice/adapter/communicator/test/unittest/app_pipe_mgr_service_test.cpp index 0d2a4fab8e99cc5523192f629366b85c5633a95c..3f6b872499fa83804f6691ccf36c2482842f85ff 100644 --- a/services/distributeddataservice/adapter/communicator/test/unittest/app_pipe_mgr_service_test.cpp +++ b/services/distributeddataservice/adapter/communicator/test/unittest/app_pipe_mgr_service_test.cpp @@ -17,7 +17,6 @@ #include "app_pipe_mgr.h" #include "kvstore_utils.h" #include "log_print.h" -#include "reporter.h" #include "types.h" #include diff --git a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp index 842b4777781ad6790ac9be831e7dd4e66cb5d72a..269f2e42d961219ca805306fbaa2c488340561d4 100644 --- a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp +++ b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp @@ -12,642 +12,345 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "app_device_change_listener.h" -#include -#include "gtest/gtest.h" -#include + #include "softbus_adapter.h" -#include "softbus_adapter_standard.cpp" -#include "softbus_error_code.h" + +#include + +#include "account/account_delegate.h" +#include "app_data_change_listener.h" +#include "app_device_change_listener.h" +#include "communication/connect_manager.h" +#include "communicator_context.h" +#include "data_level.h" +#include "device_manager_adapter.h" +#include "executor_pool.h" +#include "inner_socket.h" +#include "metadata/meta_data_manager.h" +#include "metadata/store_meta_data.h" #include "types.h" -#include -#include namespace OHOS::Test { using namespace testing::ext; using namespace OHOS::AppDistributedKv; using namespace OHOS::DistributedData; -using DeviceInfo = OHOS::AppDistributedKv::DeviceInfo; -class AppDataChangeListenerImpl : public AppDataChangeListener { - struct ServerSocketInfo { - std::string name; /**< Peer socket name */ - std::string networkId; /**< Peer network ID */ - std::string pkgName; /**< Peer package name */ - }; - - void OnMessage(const OHOS::AppDistributedKv::DeviceInfo &info, const uint8_t *ptr, const int size, - const struct PipeInfo &id) const override; -}; -void AppDataChangeListenerImpl::OnMessage(const OHOS::AppDistributedKv::DeviceInfo &info, - const uint8_t *ptr, const int size, const struct PipeInfo &id) const -{} +static constexpr size_t THREAD_MIN = 0; +static constexpr size_t THREAD_MAX = 3; +static constexpr const char *TEST_BUNDLE_NAME = "TestApplication"; +static constexpr const char *TEST_STORE_NAME = "TestStore"; +static constexpr uint16_t DYNAMIC_LEVEL = 0xFFFF; +static constexpr uint16_t STATIC_LEVEL = 0x1111; +static constexpr uint32_t SWITCH_VALUE = 0x00000001; +static constexpr uint16_t SWITCH_LENGTH = 1; -class SoftbusAdapterStandardTest : public testing::Test { +class DeviceChangeListenerTest : public AppDeviceChangeListener { public: - static void SetUpTestCase(void) {} - static void TearDownTestCase(void) {} - void SetUp() {} - void TearDown() {} -protected: - static constexpr uint32_t DEFAULT_MTU_SIZE = 4096 * 1024u; - static constexpr uint32_t DEFAULT_TIMEOUT = 30 * 1000; + void OnDeviceChanged(const DeviceInfo &info, const DeviceChangeType &type) const override {} + void OnSessionReady(const DeviceInfo &info, int32_t errCode) const override; + void ResetReadyFlag(); + + mutable int32_t bindResult_; + mutable bool isReady_ = false; }; -/** -* @tc.name: StartWatchDeviceChange -* @tc.desc: start watch data change -* @tc.type: FUNC -* @tc.require: -* @tc.author: nhj - */ -HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange, TestSize.Level0) +void DeviceChangeListenerTest::OnSessionReady(const DeviceInfo &info, int32_t errCode) const { - ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); - auto status = SoftBusAdapter::GetInstance()->StartWatchDataChange(nullptr, {}); - EXPECT_EQ(status, Status::INVALID_ARGUMENT); + (void)info; + bindResult_ = errCode; + isReady_ = true; } -/** -* @tc.name: StartWatchDeviceChange -* @tc.desc: start watch data change -* @tc.type: FUNC -* @tc.require: -* @tc.author: nhj - */ -HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange01, TestSize.Level0) +void DeviceChangeListenerTest::ResetReadyFlag() { - ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); - PipeInfo appId; - appId.pipeId = "appId"; - appId.userId = "groupId"; - const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); - auto status = SoftBusAdapter::GetInstance()->StartWatchDataChange(dataListener, appId); - EXPECT_EQ(status, Status::SUCCESS); - status = SoftBusAdapter::GetInstance()->StartWatchDataChange(dataListener, appId); - delete dataListener; - EXPECT_EQ(status, Status::ERROR); + isReady_ = false; } -/** -* @tc.name: StartWatchDeviceChange -* @tc.desc: start watch data change -* @tc.type: FUNC -* @tc.require: -* @tc.author: nhj - */ -HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange02, TestSize.Level0) -{ - ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); - PipeInfo appId; - appId.pipeId = ""; - appId.userId = "groupId"; - const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); - auto status = SoftBusAdapter::GetInstance()->StartWatchDataChange(dataListener, appId); - delete dataListener; - EXPECT_EQ(status, Status::SUCCESS); -} +class AppDataChangeListenerTest : public AppDataChangeListener { +public: + void OnMessage(const DeviceInfo &info, const uint8_t *ptr, const int size, const PipeInfo &pipeInfo) const override + { + } +}; -/** -* @tc.name: StartWatchDeviceChange03 -* @tc.desc:the observer is nullptr -* @tc.type: FUNC -* @tc.author: nhj -*/ -HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange03, TestSize.Level1) -{ - PipeInfo appId; - appId.pipeId = "appId06"; - appId.userId = "groupId06"; - auto flag = SoftBusAdapter::GetInstance(); - ASSERT_NE(flag, nullptr); - SoftBusAdapter::GetInstance()->StartWatchDataChange(nullptr, appId); - auto status = SoftBusAdapter::GetInstance()->StartWatchDataChange(nullptr, appId); - EXPECT_EQ(Status::INVALID_ARGUMENT, status); -} +class SoftBusAdapterStandardTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp() {} + void TearDown() {}; + + void ConfigSendParameters(); + void ProcessBroadcastMsg(const std::string &device, const LevelInfo &levelInfo); + + mutable bool dataLevelResult_ = false; + + static std::shared_ptr executors_; + static std::shared_ptr softBusAdapter_; + static DeviceChangeListenerTest deviceListener_; + static AppDataChangeListenerTest dataChangeListener_; + static PipeInfo pipeInfo_; + static DeviceId deviceId_; + static DataInfo dataInfo_; + static MessageInfo msgInfo_; + static LevelInfo sendLevelInfo_; + static LevelInfo receiveLevelInfo_; + static std::string foregroundUserId_; + static DeviceInfo localDeviceInfo_; + static DeviceInfo remoteDeviceInfo_; +}; -/** -* @tc.name: StopWatchDataChange -* @tc.desc: stop watch data change -* @tc.type: FUNC -* @tc.require: -* @tc.author: nhj - */ -HWTEST_F(SoftbusAdapterStandardTest, StopWatchDataChange, TestSize.Level0) +std::shared_ptr SoftBusAdapterStandardTest::executors_; +std::shared_ptr SoftBusAdapterStandardTest::softBusAdapter_; +DeviceChangeListenerTest SoftBusAdapterStandardTest::deviceListener_; +AppDataChangeListenerTest SoftBusAdapterStandardTest::dataChangeListener_; +PipeInfo SoftBusAdapterStandardTest::pipeInfo_; +DeviceId SoftBusAdapterStandardTest::deviceId_; +DataInfo SoftBusAdapterStandardTest::dataInfo_; +MessageInfo SoftBusAdapterStandardTest::msgInfo_; +LevelInfo SoftBusAdapterStandardTest::sendLevelInfo_; +LevelInfo SoftBusAdapterStandardTest::receiveLevelInfo_; +std::string SoftBusAdapterStandardTest::foregroundUserId_; +DeviceInfo SoftBusAdapterStandardTest::localDeviceInfo_; +DeviceInfo SoftBusAdapterStandardTest::remoteDeviceInfo_; + +void SoftBusAdapterStandardTest::SetUpTestCase(void) { - PipeInfo appId; - appId.pipeId = "appId"; - appId.userId = "groupId"; - auto flag = SoftBusAdapter::GetInstance(); - ASSERT_NE(flag, nullptr); - const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); - auto status = SoftBusAdapter::GetInstance()->StopWatchDataChange(dataListener, appId); - EXPECT_EQ(status, Status::SUCCESS); - status = SoftBusAdapter::GetInstance()->StopWatchDataChange(dataListener, appId); - delete dataListener; - EXPECT_EQ(status, Status::ERROR); + softBusAdapter_ = SoftBusAdapter::GetInstance(); + CommunicatorContext::GetInstance().RegSessionListener(&deviceListener_); + executors_ = std::make_shared(THREAD_MAX, THREAD_MIN); + CommunicatorContext::GetInstance().SetThreadPool(executors_); + int userId = 0; + AccountDelegate::GetInstance()->QueryForegroundUserId(userId); + foregroundUserId_ = std::to_string(userId); + localDeviceInfo_ = DeviceManagerAdapter::GetInstance().GetLocalDevice(); + auto remoteDeviceInfos = DeviceManagerAdapter::GetInstance().GetRemoteDevices(); + if (!remoteDeviceInfos.empty()) { + remoteDeviceInfo_ = remoteDeviceInfos[0]; + } } -/** -* @tc.name: StopWatchDataChange -* @tc.desc: stop watch data change -* @tc.type: FUNC -* @tc.require: -* @tc.author: nhj - */ -HWTEST_F(SoftbusAdapterStandardTest, StopWatchDataChange01, TestSize.Level0) +void SoftBusAdapterStandardTest::TearDownTestCase(void) { - ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); - PipeInfo appId; - appId.pipeId = ""; - appId.userId = "groupId"; - const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); - auto status = SoftBusAdapter::GetInstance()->StopWatchDataChange(dataListener, appId); - delete dataListener; - EXPECT_EQ(status, Status::SUCCESS); + CommunicatorContext::GetInstance().UnRegSessionListener(&deviceListener_); } -/** -* @tc.name: GetExpireTime -* @tc.desc: GetExpireTime Test -* @tc.type: FUNC -* @tc.require: -* @tc.author: wangbin - */ -HWTEST_F(SoftbusAdapterStandardTest, GetExpireTime, TestSize.Level0) +void SoftBusAdapterStandardTest::ConfigSendParameters() { - ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); - PipeInfo appId; - appId.pipeId = "appId"; - appId.userId = "groupId"; - DeviceId id = {"DeviceId"}; - std::shared_ptr conn = std::make_shared( - appId, id, "", SoftBusClient::QoSType::QOS_HML); - EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->GetExpireTime(conn)); + deviceId_.deviceId = remoteDeviceInfo_.uuid; + dataInfo_.extraInfo.userId = foregroundUserId_; + dataInfo_.extraInfo.bundleName = TEST_BUNDLE_NAME; + dataInfo_.extraInfo.storeId = TEST_STORE_NAME; + + StoreMetaData localMetaData; + localMetaData.deviceId = localDeviceInfo_.uuid; + localMetaData.user = foregroundUserId_; + localMetaData.bundleName = TEST_BUNDLE_NAME; + localMetaData.storeId = TEST_STORE_NAME; + MetaDataManager::GetInstance().SaveMeta(localMetaData.GetKey(), localMetaData); + + StoreMetaData remoteMetaData; + remoteMetaData.deviceId = remoteDeviceInfo_.uuid; + remoteMetaData.user = foregroundUserId_; + remoteMetaData.bundleName = TEST_BUNDLE_NAME; + remoteMetaData.storeId = TEST_STORE_NAME; + MetaDataManager::GetInstance().SaveMeta(remoteMetaData.GetKey(), remoteMetaData); } -/** -* @tc.name: SendData -* @tc.desc: parse sent data -* @tc.type: FUNC -* @tc.author: nhj -*/ -HWTEST_F(SoftbusAdapterStandardTest, SendData, TestSize.Level1) +void SoftBusAdapterStandardTest::ProcessBroadcastMsg(const std::string &device, const LevelInfo &levelInfo) { - ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); - const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); - PipeInfo id; - id.pipeId = "appId"; - id.userId = "groupId"; - auto secRegister = SoftBusAdapter::GetInstance()->StartWatchDataChange(dataListener, id); - EXPECT_EQ(Status::SUCCESS, secRegister); - std::string content = "Helloworlds"; - const uint8_t *t = reinterpret_cast(content.c_str()); - DeviceId di = {"DeviceId"}; - DataInfo data = { const_cast(t), static_cast(content.length())}; - auto status = SoftBusAdapter::GetInstance()->SendData(id, di, data, 11, { MessageType::DEFAULT }); - EXPECT_NE(status.first, Status::SUCCESS); - SoftBusAdapter::GetInstance()->StopWatchDataChange(dataListener, id); - delete dataListener; + (void)device; + receiveLevelInfo_ = levelInfo; + dataLevelResult_ = true; } /** -* @tc.name: SendData01 -* @tc.desc: parse sent data +* @tc.name: SessionServerTest001 +* @tc.desc: create and remove session server * @tc.type: FUNC -* @tc.author: */ -HWTEST_F(SoftbusAdapterStandardTest, SendData01, TestSize.Level1) +HWTEST_F(SoftBusAdapterStandardTest, SessionServerTest001, TestSize.Level1) { - const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); - PipeInfo pipe01; - pipe01.pipeId = "appId"; - pipe01.userId = "groupId"; - auto flag = SoftBusAdapter::GetInstance(); - ASSERT_NE(flag, nullptr); - auto secRegister = SoftBusAdapter::GetInstance()->StartWatchDataChange(dataListener, pipe01); - EXPECT_EQ(Status::SUCCESS, secRegister); - std::string content = ""; - const uint8_t *t = reinterpret_cast(content.c_str()); - DeviceId di = {"DeviceId"}; - DataInfo data = { const_cast(t), static_cast(content.length())}; - auto status = SoftBusAdapter::GetInstance()->SendData(pipe01, di, data, 10, { MessageType::FILE }); - EXPECT_NE(status.first, Status::ERROR); - EXPECT_EQ(status.first, Status::RATE_LIMIT); - SoftBusAdapter::GetInstance()->StopWatchDataChange(dataListener, pipe01); - delete dataListener; -} + ConfigSocketId(VALID_SOCKET); -/** -* @tc.name: StartCloseSessionTask -* @tc.desc: StartCloseSessionTask tests -* @tc.type: FUNC -* @tc.author: -*/ -HWTEST_F(SoftbusAdapterStandardTest, StartCloseSessionTask, TestSize.Level1) -{ - ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); - std::shared_ptr conn = nullptr; - std::vector> clients; - clients.emplace_back(conn); - auto status = SoftBusAdapter::GetInstance()->connects_.Insert("deviceId01", clients); - EXPECT_EQ(status, true); - SoftBusAdapter::GetInstance()->connects_.Clear(); - EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->StartCloseSessionTask("deviceId02")); -} + auto result = softBusAdapter_->CreateSessionServerAdapter(""); + ASSERT_EQ(result, 0); -/** -* @tc.name: OnClientShutdown -* @tc.desc: DelConnect tests -* @tc.type: FUNC -* @tc.author: -*/ -HWTEST_F(SoftbusAdapterStandardTest, OnClientShutdown, TestSize.Level1) -{ - ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); - PipeInfo appId; - appId.pipeId = "appId"; - appId.userId = "groupId"; - DeviceId id = {"DeviceId"}; - std::shared_ptr conn1 = std::make_shared( - appId, id, "", SoftBusClient::QoSType::QOS_HML); - std::shared_ptr conn2 = nullptr; - std::vector> clients; - clients.emplace_back(conn1); - clients.emplace_back(conn2); - auto status = SoftBusAdapter::GetInstance()->connects_.Insert("deviceId01", clients); - EXPECT_EQ(status, true); - status = SoftBusAdapter::GetInstance()->connects_.Insert("deviceId02", {}); - EXPECT_EQ(status, true); - auto name = SoftBusAdapter::GetInstance()->OnClientShutdown(-1, true); - EXPECT_EQ(name, "deviceId01 "); - name = SoftBusAdapter::GetInstance()->OnClientShutdown(-1, false); - EXPECT_EQ(name, ""); - name = SoftBusAdapter::GetInstance()->OnClientShutdown(1, true); - SoftBusAdapter::GetInstance()->connects_.Clear(); - EXPECT_EQ(name, ""); + result = softBusAdapter_->RemoveSessionServerAdapter(""); + ASSERT_EQ(result, 0); } /** -* @tc.name: NotifyDataListeners -* @tc.desc: NotifyDataListeners tests +* @tc.name: WatchDataChangeTest001 +* @tc.desc: watch and unwatch data change * @tc.type: FUNC -* @tc.author: */ -HWTEST_F(SoftbusAdapterStandardTest, NotifyDataListeners, TestSize.Level1) +HWTEST_F(SoftBusAdapterStandardTest, WatchDataChangeTest001, TestSize.Level1) { - ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); - PipeInfo appId; - appId.pipeId = "appId"; - appId.userId = "groupId"; - std::string content = "Helloworlds"; - const uint8_t *t = reinterpret_cast(content.c_str()); - SoftBusAdapter::GetInstance()->dataChangeListeners_.Clear(); - EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->NotifyDataListeners(t, 1, "deviceId", appId)); - const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); - SoftBusAdapter::GetInstance()->dataChangeListeners_.Insert(appId.pipeId, dataListener); - delete dataListener; - SoftBusAdapter::GetInstance()->dataChangeListeners_.Clear(); - EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->NotifyDataListeners(t, 1, "deviceId", appId)); -} + auto status = softBusAdapter_->StartWatchDataChange(nullptr, pipeInfo_); + ASSERT_EQ(status, Status::INVALID_ARGUMENT); -/** -* @tc.name: ListenBroadcastMsg -* @tc.desc: ListenBroadcastMsg tests -* @tc.type: FUNC -* @tc.author: -*/ -HWTEST_F(SoftbusAdapterStandardTest, ListenBroadcastMsg, TestSize.Level1) -{ - ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); - SoftBusAdapter::GetInstance()->onBroadcast_= nullptr; - PipeInfo appId; - appId.pipeId = "appId"; - appId.userId = "groupId"; - auto result = SoftBusAdapter::GetInstance()->ListenBroadcastMsg(appId, nullptr); - EXPECT_EQ(result, SoftBusErrNo::SOFTBUS_INVALID_PARAM); - - auto listener = [](const std::string &message, const LevelInfo &info) {}; - result = SoftBusAdapter::GetInstance()->ListenBroadcastMsg(appId, listener); - EXPECT_EQ(result, SoftBusErrNo::SOFTBUS_INVALID_PARAM); - result = SoftBusAdapter::GetInstance()->ListenBroadcastMsg(appId, listener); - EXPECT_EQ(result, SoftBusErrNo::SOFTBUS_ALREADY_EXISTED); -} + status = softBusAdapter_->StartWatchDataChange(&dataChangeListener_, pipeInfo_); + ASSERT_EQ(status, Status::SUCCESS); -/** -* @tc.name: OnBroadcast -* @tc.desc: OnBroadcast tests -* @tc.type: FUNC -* @tc.author: -*/ -HWTEST_F(SoftbusAdapterStandardTest, OnBroadcast, TestSize.Level1) -{ - ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); - DeviceId id = {"DeviceId"}; - LevelInfo level; - level.dynamic = 1; - level.statics = 1; - level.switches = 1; - level.switchesLen = 1; - EXPECT_NE(SoftBusAdapter::GetInstance()->onBroadcast_, nullptr); - EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->OnBroadcast(id, level)); - SoftBusAdapter::GetInstance()->onBroadcast_ = nullptr; - EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->OnBroadcast(id, level)); -} + status = softBusAdapter_->StartWatchDataChange(&dataChangeListener_, pipeInfo_); + ASSERT_EQ(status, Status::ERROR); -/** -* @tc.name: OnClientSocketChanged -* @tc.desc: OnClientSocketChanged tests -* @tc.type: FUNC -* @tc.author: -*/ -HWTEST_F(SoftbusAdapterStandardTest, OnClientSocketChanged, TestSize.Level1) -{ - QosTV qosTv; - qosTv.qos = QosType::QOS_TYPE_MIN_BW; - qosTv.value = 1; - EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnClientSocketChanged(1, QoSEvent::QOS_SATISFIED, &qosTv, 1)); - EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnClientSocketChanged(1, QoSEvent::QOS_SATISFIED, &qosTv, 0)); - qosTv.qos = QosType::QOS_TYPE_MAX_WAIT_TIMEOUT; - EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnClientSocketChanged(1, QoSEvent::QOS_SATISFIED, &qosTv, 0)); - EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnClientSocketChanged(1, QoSEvent::QOS_SATISFIED, nullptr, 0)); - EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnClientSocketChanged(1, QoSEvent::QOS_NOT_SATISFIED, nullptr, 0)); -} + status = softBusAdapter_->StopWatchDataChange(nullptr, pipeInfo_); + ASSERT_EQ(status, Status::SUCCESS); -/** -* @tc.name: OnServerBytesReceived -* @tc.desc: OnServerBytesReceived tests -* @tc.type: FUNC -* @tc.author: -*/ -HWTEST_F(SoftbusAdapterStandardTest, OnServerBytesReceived, TestSize.Level1) -{ - ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); - PeerSocketInfo info; - info.name = strdup(""); - info.networkId = strdup("peertest01"); - info.pkgName = strdup("ohos.kv.test"); - info.dataType = TransDataType::DATA_TYPE_MESSAGE; - AppDistributedKv::SoftBusAdapter::ServerSocketInfo serinfo; - auto result = SoftBusAdapter::GetInstance()->GetPeerSocketInfo(1, serinfo); - EXPECT_EQ(result, false); - char str[] = "Hello"; - const void* data = static_cast(str); - EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnServerBytesReceived(1, data, 10)); - SoftBusAdapter::GetInstance()->OnBind(1, info); - result = SoftBusAdapter::GetInstance()->GetPeerSocketInfo(1, serinfo); - EXPECT_EQ(result, true); - EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnServerBytesReceived(1, data, 10)); - info.name = strdup("name"); - SoftBusAdapter::GetInstance()->OnBind(2, info); - result = SoftBusAdapter::GetInstance()->GetPeerSocketInfo(2, serinfo); - EXPECT_EQ(result, true); - EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnServerBytesReceived(2, data, 10)); + status = softBusAdapter_->StopWatchDataChange(nullptr, pipeInfo_); + ASSERT_EQ(status, Status::ERROR); } /** -* @tc.name: GetPipeId -* @tc.desc: GetPipeId tests +* @tc.name: SendDataTest001 +* @tc.desc: send data with invalid param * @tc.type: FUNC -* @tc.author: */ -HWTEST_F(SoftbusAdapterStandardTest, GetPipeId, TestSize.Level1) +HWTEST_F(SoftBusAdapterStandardTest, SendDataTest001, TestSize.Level1) { - std::string names = "GetPipeId"; - auto name = AppDataListenerWrap::GetPipeId(names); - EXPECT_EQ(name, names); - names = "test01_GetPipeId"; - name = AppDataListenerWrap::GetPipeId(names); - EXPECT_EQ(name, "test01"); -} + auto result = softBusAdapter_->SendData(pipeInfo_, deviceId_, dataInfo_, 0, msgInfo_); + ASSERT_EQ(result.first, Status::ERROR); -/** -* @tc.name: GetMtuSize -* @tc.desc: get size -* @tc.type: FUNC -* @tc.author: nhj -*/ -HWTEST_F(SoftbusAdapterStandardTest, GetMtuSize, TestSize.Level1) -{ - ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); - const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); - PipeInfo id; - id.pipeId = "appId"; - id.userId = "groupId"; - SoftBusAdapter::GetInstance()->StartWatchDataChange(dataListener, id); - DeviceId di = {"DeviceId"}; - auto size = SoftBusAdapter::GetInstance()->GetMtuSize(di); - EXPECT_EQ(size, DEFAULT_MTU_SIZE); - SoftBusAdapter::GetInstance()->GetCloseSessionTask(); - SoftBusAdapter::GetInstance()->StopWatchDataChange(dataListener, id); - delete dataListener; -} + deviceId_.deviceId = remoteDeviceInfo_.uuid; + result = softBusAdapter_->SendData(pipeInfo_, deviceId_, dataInfo_, 0, msgInfo_); + ASSERT_EQ(result.first, Status::ERROR); -/** -* @tc.name: GetTimeout -* @tc.desc: get timeout -* @tc.type: FUNC -* @tc.author: nhj -*/ -HWTEST_F(SoftbusAdapterStandardTest, GetTimeout, TestSize.Level1) -{ - ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); - const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); - PipeInfo id; - id.pipeId = "appId01"; - id.userId = "groupId01"; - SoftBusAdapter::GetInstance()->StartWatchDataChange(dataListener, id); - DeviceId di = {"DeviceId"}; - auto time = SoftBusAdapter::GetInstance()->GetTimeout(di); - EXPECT_EQ(time, DEFAULT_TIMEOUT); - SoftBusAdapter::GetInstance()->StopWatchDataChange(dataListener, id); - delete dataListener; -} + dataInfo_.extraInfo.userId = foregroundUserId_; + result = softBusAdapter_->SendData(pipeInfo_, deviceId_, dataInfo_, 0, msgInfo_); + ASSERT_EQ(result.first, Status::ERROR); -/** -* @tc.name: IsSameStartedOnPeer -* @tc.desc: get size -* @tc.type: FUNC -* @tc.author: nhj -*/ -HWTEST_F(SoftbusAdapterStandardTest, IsSameStartedOnPeer, TestSize.Level1) -{ - ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); - PipeInfo id; - id.pipeId = "appId01"; - id.userId = "groupId01"; - DeviceId di = {"DeviceId"}; - SoftBusAdapter::GetInstance()->SetMessageTransFlag(id, true); - auto status = SoftBusAdapter::GetInstance()->IsSameStartedOnPeer(id, di); - EXPECT_EQ(status, true); -} + dataInfo_.extraInfo.bundleName = TEST_BUNDLE_NAME; + result = softBusAdapter_->SendData(pipeInfo_, deviceId_, dataInfo_, 0, msgInfo_); + ASSERT_EQ(result.first, Status::ERROR); -/** -* @tc.name: ReuseConnect -* @tc.desc: reuse connect -* @tc.type: FUNC -* @tc.author: nhj -*/ -HWTEST_F(SoftbusAdapterStandardTest, ReuseConnect, TestSize.Level1) -{ - const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); - PipeInfo pipe; - pipe.pipeId = "appId"; - pipe.userId = "groupId"; - auto flag = SoftBusAdapter::GetInstance(); - ASSERT_NE(flag, nullptr); - SoftBusAdapter::GetInstance()->StartWatchDataChange(dataListener, pipe); - DeviceId device = {"DeviceId"}; - auto reuse = SoftBusAdapter::GetInstance()->ReuseConnect(pipe, device); - EXPECT_EQ(reuse, Status::NOT_SUPPORT); - SoftBusAdapter::GetInstance()->StopWatchDataChange(dataListener, pipe); - delete dataListener; + dataInfo_.extraInfo.storeId = TEST_STORE_NAME; + result = softBusAdapter_->SendData(pipeInfo_, deviceId_, dataInfo_, 0, msgInfo_); + ASSERT_EQ(result.first, Status::ERROR); } /** -* @tc.name: ReuseConnect01 -* @tc.desc: reuse connect +* @tc.name: SendDataTest002 +* @tc.desc: send data with bind fail * @tc.type: FUNC -* @tc.author: wangbin */ -HWTEST_F(SoftbusAdapterStandardTest, ReuseConnect01, TestSize.Level1) +HWTEST_F(SoftBusAdapterStandardTest, SendDataTest002, TestSize.Level1) { - ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr); - PipeInfo pipe; - pipe.pipeId = "appId"; - pipe.userId = "groupId"; - DeviceId device = {"DeviceId"}; - auto status = SoftBusAdapter::GetInstance()->ReuseConnect(pipe, device); - EXPECT_EQ(status, Status::NOT_SUPPORT); + ConfigSendParameters(); + ConfigSocketId(INVALID_MTU_SOCKET); + + auto res = softBusAdapter_->CreateSessionServerAdapter(""); + ASSERT_EQ(res, 0); + + auto result = softBusAdapter_->SendData(pipeInfo_, deviceId_, dataInfo_, 0, msgInfo_); + ASSERT_EQ(result.first, Status::RATE_LIMIT); + while (!(deviceListener_.isReady_)) { + std::this_thread::sleep_for(std::chrono::seconds(1)); + } + res = deviceListener_.bindResult_; + ASSERT_NE(res, 0); + + deviceListener_.ResetReadyFlag(); + ConnectManager::GetInstance()->CloseSession(remoteDeviceInfo_.uuid); } /** -* @tc.name: GetConnect -* @tc.desc: get connect +* @tc.name: SendDataTest003 +* @tc.desc: send data with bind success * @tc.type: FUNC -* @tc.author: nhj */ -HWTEST_F(SoftbusAdapterStandardTest, GetConnect, TestSize.Level1) +HWTEST_F(SoftBusAdapterStandardTest, SendDataTest003, TestSize.Level1) { - const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl(); - PipeInfo pipe; - pipe.pipeId = "appId01"; - pipe.userId = "groupId01"; - auto flag = SoftBusAdapter::GetInstance(); - ASSERT_NE(flag, nullptr); - SoftBusAdapter::GetInstance()->StartWatchDataChange(dataListener, pipe); - DeviceId device = {"DeviceId01"}; - std::shared_ptr conn = nullptr; - auto reuse = SoftBusAdapter::GetInstance()->GetConnect(pipe, device, 1); - EXPECT_NE(reuse, nullptr); - SoftBusAdapter::GetInstance()->StopWatchDataChange(dataListener, pipe); - delete dataListener; + ConfigSendParameters(); + ConfigSocketId(VALID_SOCKET); + + auto res = softBusAdapter_->CreateSessionServerAdapter(""); + ASSERT_EQ(res, 0); + + auto result = softBusAdapter_->SendData(pipeInfo_, deviceId_, dataInfo_, 0, msgInfo_); + ASSERT_EQ(result.first, Status::RATE_LIMIT); + while (!(deviceListener_.isReady_)) { + std::this_thread::sleep_for(std::chrono::seconds(1)); + } + res = deviceListener_.bindResult_; + ASSERT_EQ(res, 0); + + uint32_t mtuBuffer; + GetMtuSize(VALID_SOCKET, &mtuBuffer); + auto mtuSize = softBusAdapter_->GetMtuSize(deviceId_); + ASSERT_EQ(mtuSize, mtuBuffer); + + auto timeOut = softBusAdapter_->GetTimeout(deviceId_); + ASSERT_NE(timeOut, 0); + + result = softBusAdapter_->SendData(pipeInfo_, deviceId_, dataInfo_, 0, msgInfo_); + ASSERT_EQ(result.first, Status::SUCCESS); + + std::this_thread::sleep_for(std::chrono::seconds(10)); + mtuSize = softBusAdapter_->GetMtuSize(deviceId_); + ASSERT_NE(mtuSize, mtuBuffer); } /** -* @tc.name: Broadcast -* @tc.desc: broadcast +* @tc.name: IsSameStartedOnPeerTest001 +* @tc.desc: test IsSameStartedOnPeer * @tc.type: FUNC -* @tc.author: nhj */ -HWTEST_F(SoftbusAdapterStandardTest, Broadcast, TestSize.Level1) +HWTEST_F(SoftBusAdapterStandardTest, IsSameStartedOnPeerTest001, TestSize.Level1) { - PipeInfo id; - id.pipeId = "appId"; - id.userId = "groupId"; - LevelInfo level; - level.dynamic = 1; - level.statics = 1; - level.switches = 1; - level.switchesLen = 1; - auto flag = SoftBusAdapter::GetInstance(); - ASSERT_NE(flag, nullptr); - SoftBusAdapter::GetInstance()->SetMessageTransFlag(id, true); - auto status = SoftBusAdapter::GetInstance()->Broadcast(id, level); - EXPECT_EQ(status, Status::ERROR); + auto result = softBusAdapter_->IsSameStartedOnPeer(pipeInfo_, deviceId_); + ASSERT_TRUE(result); } /** -* @tc.name: OpenConnect -* @tc.desc: open connect +* @tc.name: BroadcastTest001 +* @tc.desc: broadcast msg fail * @tc.type: FUNC -* @tc.author: nhj */ -HWTEST_F(SoftbusAdapterStandardTest, OpenConnect, TestSize.Level1) +HWTEST_F(SoftBusAdapterStandardTest, BroadcastTest001, TestSize.Level1) { - DeviceId device = {"DeviceId"}; - std::shared_ptr conn = nullptr; - auto flag = SoftBusAdapter::GetInstance(); - ASSERT_NE(flag, nullptr); - auto status = SoftBusAdapter::GetInstance()->OpenConnect(conn, device); - EXPECT_NE(status.first, Status::SUCCESS); - EXPECT_EQ(status.first, Status::RATE_LIMIT); - EXPECT_EQ(status.second, 0); -} + ConfigReturnCode(SoftBusErrNo::SOFTBUS_FUNC_NOT_SUPPORT); + auto status = softBusAdapter_->Broadcast(pipeInfo_, sendLevelInfo_); + ASSERT_EQ(status, Status::NOT_SUPPORT_BROADCAST); -/** -* @tc.name: CloseSession -* @tc.desc: close session -* @tc.type: FUNC -* @tc.author: nhj -*/ -HWTEST_F(SoftbusAdapterStandardTest, CloseSession, TestSize.Level1) -{ - std::string networkId = "networkId"; - auto flag = SoftBusAdapter::GetInstance(); - ASSERT_NE(flag, nullptr); - auto status = SoftBusAdapter::GetInstance()->CloseSession(networkId); - EXPECT_EQ(status, false); + ConfigReturnCode(SoftBusErrNo::SOFTBUS_ERROR); + status = softBusAdapter_->Broadcast(pipeInfo_, sendLevelInfo_); + ASSERT_EQ(status, Status::ERROR); } /** -* @tc.name: CloseSession01 -* @tc.desc: close session +* @tc.name: BroadcastTest002 +* @tc.desc: broadcast msg success and receive msg * @tc.type: FUNC -* @tc.author: nhj */ -HWTEST_F(SoftbusAdapterStandardTest, CloseSession01, TestSize.Level1) +HWTEST_F(SoftBusAdapterStandardTest, BroadcastTest002, TestSize.Level1) { - std::string networkId = ""; - auto flag = SoftBusAdapter::GetInstance(); - ASSERT_NE(flag, nullptr); - auto status = SoftBusAdapter::GetInstance()->CloseSession(networkId); - EXPECT_EQ(status, false); -} + auto dataLevelListener = [this](const std::string &device, const LevelInfo &levelInfo) { + ProcessBroadcastMsg(device, levelInfo); + }; -/** -* @tc.name: GetPeerSocketInfo -* @tc.desc: get socket info -* @tc.type: FUNC -* @tc.author: nhj -*/ -HWTEST_F(SoftbusAdapterStandardTest, GetPeerSocketInfo, TestSize.Level1) -{ - AppDistributedKv::SoftBusAdapter::ServerSocketInfo info; - info.name = "kv"; - info.networkId= "192.168.1.1"; - info.pkgName = "test"; - auto flag = SoftBusAdapter::GetInstance(); - ASSERT_NE(flag, nullptr); - auto status = SoftBusAdapter::GetInstance()->GetPeerSocketInfo(-1, info); - EXPECT_EQ(status, false); -} + auto status = softBusAdapter_->ListenBroadcastMsg(pipeInfo_, dataLevelListener); + ASSERT_EQ(status, Status::SUCCESS); -/** -* @tc.name: GetPeerSocketInfo -* @tc.desc: get socket info -* @tc.type: FUNC -* @tc.author: nhj -*/ -HWTEST_F(SoftbusAdapterStandardTest, GetPeerSocketInfo01, TestSize.Level1) -{ - AppDistributedKv::SoftBusAdapter::ServerSocketInfo info; - info.name = "service"; - info.networkId= "192.168.1.1"; - info.pkgName = "test"; - auto flag = SoftBusAdapter::GetInstance(); - ASSERT_NE(flag, nullptr); - auto status = SoftBusAdapter::GetInstance()->GetPeerSocketInfo(1, info); - EXPECT_EQ(status, true); + status = softBusAdapter_->ListenBroadcastMsg(pipeInfo_, dataLevelListener); + ASSERT_NE(status, Status::SUCCESS); + + ConfigReturnCode(SoftBusErrNo::SOFTBUS_OK); + sendLevelInfo_.dynamic = DYNAMIC_LEVEL; + sendLevelInfo_.statics = STATIC_LEVEL; + sendLevelInfo_.switches = SWITCH_VALUE; + sendLevelInfo_.switchesLen = SWITCH_LENGTH; + + status = softBusAdapter_->Broadcast(pipeInfo_, sendLevelInfo_); + ASSERT_EQ(status, Status::SUCCESS); + + while (!(dataLevelResult_)) { + std::this_thread::sleep_for(std::chrono::seconds(1)); + } + ASSERT_EQ(receiveLevelInfo_.dynamic, sendLevelInfo_.dynamic); + ASSERT_EQ(receiveLevelInfo_.statics, sendLevelInfo_.statics); + ASSERT_EQ(receiveLevelInfo_.switches, sendLevelInfo_.switches); + ASSERT_EQ(receiveLevelInfo_.switchesLen, sendLevelInfo_.switchesLen); } } // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_client_test.cpp b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_client_test.cpp index 3f1d713deb0fc7b2b05b72ae2cde2ac687dd6375..0658174a23e818498b12de929b886280c10194a1 100644 --- a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_client_test.cpp +++ b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_client_test.cpp @@ -13,177 +13,198 @@ * limitations under the License. */ -#include -#include -#include -#include -#include #include "softbus_client.h" -#include "types.h" +#include + +#include "app_device_change_listener.h" +#include "communicator_context.h" +#include "executor_pool.h" namespace OHOS::Test { using namespace testing::ext; using namespace OHOS::AppDistributedKv; -using PipeInfo = OHOS::AppDistributedKv::PipeInfo; -constexpr int32_t SOFTBUS_OK = 0; +using namespace OHOS::DistributedData; + +static constexpr const char* PIP_ID = "SoftBusClientTest"; +static constexpr const char* UUID = "0123456789"; +static constexpr const char* NETWORK_ID = "ABCDEFGHI"; +static constexpr size_t THREAD_MIN = 0; +static constexpr size_t THREAD_MAX = 1; -class SoftbusClientTest : public testing::Test { +class DeviceChangeListenerTest : public AppDeviceChangeListener { +public: + void OnDeviceChanged(const DeviceInfo &info, const DeviceChangeType &type) const override {} + void OnSessionReady(const DeviceInfo &info, int32_t errCode) const override; + void ResetReadyFlag(); + + mutable int32_t bindResult_; + mutable bool isReady_ = false; +}; + +void DeviceChangeListenerTest::OnSessionReady(const DeviceInfo &info, int32_t errCode) const +{ + (void)info; + bindResult_ = errCode; + isReady_ = true; +} + +void DeviceChangeListenerTest::ResetReadyFlag() +{ + isReady_ = false; +} + +class SoftBusClientTest : public testing::Test { public: static void SetUpTestCase(void); static void TearDownTestCase(void); void SetUp() {} void TearDown() {} - static std::shared_ptr client; + static PipeInfo pipeInfo_; + static DeviceId deviceId_; + static SessionAccessInfo accessInfo_; + static ISocketListener clientListener_; + static DeviceChangeListenerTest deviceListener_; + static std::shared_ptr executors_; }; -std::shared_ptr SoftbusClientTest::client = nullptr; +PipeInfo SoftBusClientTest::pipeInfo_; +DeviceId SoftBusClientTest::deviceId_; +SessionAccessInfo SoftBusClientTest::accessInfo_; +ISocketListener SoftBusClientTest::clientListener_; +DeviceChangeListenerTest SoftBusClientTest::deviceListener_; +std::shared_ptr SoftBusClientTest::executors_; -void SoftbusClientTest::SetUpTestCase(void) +void SoftBusClientTest::SetUpTestCase(void) { - PipeInfo pipeInfo; - pipeInfo.pipeId = "pipeId"; - pipeInfo.userId = "userId"; - DeviceId id = {"DeviceId"}; - client = std::make_shared(pipeInfo, id, ""); + pipeInfo_.pipeId = PIP_ID; + deviceId_.deviceId = UUID; + CommunicatorContext::GetInstance().RegSessionListener(&deviceListener_); + executors_ = std::make_shared(THREAD_MAX, THREAD_MIN); + CommunicatorContext::GetInstance().SetThreadPool(executors_); } -void SoftbusClientTest::TearDownTestCase(void) +void SoftBusClientTest::TearDownTestCase(void) { - client = nullptr; + CommunicatorContext::GetInstance().UnRegSessionListener(&deviceListener_); } /** -* @tc.name: SendData -* @tc.desc: SendData test +* @tc.name: OpenConnectTest001 +* @tc.desc: bind socket fail and socketId is invalid * @tc.type: FUNC -* @tc.require: -* @tc.author: wangbin - */ -HWTEST_F(SoftbusClientTest, SendData, TestSize.Level0) +*/ +HWTEST_F(SoftBusClientTest, OpenConnectTest001, TestSize.Level1) { - ASSERT_NE(client, nullptr); - std::string content = "Helloworlds"; - const uint8_t *data = reinterpret_cast(content.c_str()); - DataInfo info = { const_cast(data), static_cast(content.length())}; - ISocketListener *listener = nullptr; - auto status = client->SendData(info, listener); - EXPECT_EQ(status, Status::ERROR); - client->bindState_ = 0; - status = client->SendData(info, listener); - EXPECT_EQ(status, Status::ERROR); + ConfigSocketId(INVALID_SOCKET); + accessInfo_.isOHType = true; + auto connect = std::make_shared(pipeInfo_, deviceId_, NETWORK_ID, SoftBusClient::QOS_HML, + accessInfo_); + auto status = connect->OpenConnect(&clientListener_); + ASSERT_EQ(status, Status::NETWORK_ERROR); } /** -* @tc.name: OpenConnect -* @tc.desc: OpenConnect test +* @tc.name: OpenConnectTest002 +* @tc.desc: bind socket fail and socket is valid and SetAccessInfo fail * @tc.type: FUNC -* @tc.require: -* @tc.author: wangbin - */ -HWTEST_F(SoftbusClientTest, OpenConnect, TestSize.Level0) +*/ +HWTEST_F(SoftBusClientTest, OpenConnectTest002, TestSize.Level1) { - ASSERT_NE(client, nullptr); - ISocketListener *listener = nullptr; - client->bindState_ = 0; - auto status = client->OpenConnect(listener); - EXPECT_EQ(status, Status::SUCCESS); - client->bindState_ = 1; - client->isOpening_.store(true); - status = client->OpenConnect(listener); - EXPECT_EQ(status, Status::RATE_LIMIT); - client->isOpening_.store(false); - status = client->OpenConnect(listener); - EXPECT_EQ(status, Status::NETWORK_ERROR); + ConfigSocketId(INVALID_BIND_SOCKET); + accessInfo_.isOHType = true; + auto connect = std::make_shared(pipeInfo_, deviceId_, NETWORK_ID, SoftBusClient::QOS_HML, + accessInfo_); + auto status = connect->OpenConnect(&clientListener_); + ASSERT_EQ(status, Status::RATE_LIMIT); + while (!(deviceListener_.isReady_)) { + sleep(1); + } + deviceListener_.ResetReadyFlag(); + status = connect->CheckStatus(); + ASSERT_EQ(status, Status::NETWORK_ERROR); } /** -* @tc.name: CheckStatus -* @tc.desc: CheckStatus test +* @tc.name: OpenConnectTest003 +* @tc.desc: bind socket fail and socket is valid and open fail * @tc.type: FUNC -* @tc.require: -* @tc.author: wangbin - */ -HWTEST_F(SoftbusClientTest, CheckStatus, TestSize.Level0) +*/ +HWTEST_F(SoftBusClientTest, OpenConnectTest003, TestSize.Level1) { - ASSERT_NE(client, nullptr); - client->bindState_ = 0; - auto status = client->CheckStatus(); - EXPECT_EQ(status, Status::SUCCESS); - client->bindState_ = -1; - client->isOpening_.store(true); - status = client->CheckStatus(); - EXPECT_EQ(status, Status::RATE_LIMIT); - client->isOpening_.store(false); - status = client->CheckStatus(); - EXPECT_EQ(status, Status::ERROR); -} + ConfigSocketId(INVALID_BIND_SOCKET); + accessInfo_.isOHType = false; + auto connect = std::make_shared(pipeInfo_, deviceId_, NETWORK_ID, SoftBusClient::QOS_BR, + accessInfo_); + auto status = connect->OpenConnect(&clientListener_); + ASSERT_EQ(status, Status::RATE_LIMIT); + while (!(deviceListener_.isReady_)) { + sleep(1); + } + deviceListener_.ResetReadyFlag(); + auto result = deviceListener_.bindResult_; + ASSERT_NE(result, 0); -/** -* @tc.name: Open -* @tc.desc: Open test -* @tc.type: FUNC -* @tc.require: -* @tc.author: wangbin - */ -HWTEST_F(SoftbusClientTest, Open, TestSize.Level0) -{ - ASSERT_NE(client, nullptr); - ISocketListener *listener = nullptr; - auto status = client->Open(1, AppDistributedKv::SoftBusClient::QOS_BR, listener, false); - EXPECT_NE(status, SOFTBUS_OK); + accessInfo_.isOHType = true; + auto ohConnect = std::make_shared(pipeInfo_, deviceId_, NETWORK_ID, SoftBusClient::QOS_HML, + accessInfo_); + status = connect->OpenConnect(&clientListener_); + ASSERT_EQ(status, Status::RATE_LIMIT); + while (!(deviceListener_.isReady_)) { + sleep(1); + } + deviceListener_.ResetReadyFlag(); + result = deviceListener_.bindResult_; + ASSERT_NE(result, 0); } /** -* @tc.name: UpdateExpireTime -* @tc.desc: UpdateExpireTime test +* @tc.name: OpenConnectTest004 +* @tc.desc: bind socket success but get mtu fail * @tc.type: FUNC -* @tc.require: -* @tc.author: wangbin - */ -HWTEST_F(SoftbusClientTest, UpdateExpireTime, TestSize.Level0) +*/ +HWTEST_F(SoftBusClientTest, OpenConnectTest004, TestSize.Level1) { - ASSERT_NE(client, nullptr); - client->type_ = AppDistributedKv::SoftBusClient::QOS_BR; - auto expireTime = client->CalcExpireTime(); - EXPECT_NO_FATAL_FAILURE(client->UpdateExpireTime(true)); - EXPECT_LT(expireTime, client->expireTime_); - EXPECT_NO_FATAL_FAILURE(client->UpdateExpireTime(false)); - EXPECT_LT(expireTime, client->expireTime_); + ConfigSocketId(INVALID_MTU_SOCKET); + accessInfo_.isOHType = true; + auto connect = std::make_shared(pipeInfo_, deviceId_, NETWORK_ID, SoftBusClient::QOS_HML, + accessInfo_); + auto status = connect->OpenConnect(&clientListener_); + ASSERT_EQ(status, Status::RATE_LIMIT); + while (!(deviceListener_.isReady_)) { + sleep(1); + } + deviceListener_.ResetReadyFlag(); + auto result = deviceListener_.bindResult_; + ASSERT_NE(result, 0); } /** -* @tc.name: UpdateBindInfo -* @tc.desc: UpdateBindInfo test +* @tc.name: OpenConnectTest005 +* @tc.desc: bind socket success and send data success * @tc.type: FUNC -* @tc.require: -* @tc.author: wangbin - */ -HWTEST_F(SoftbusClientTest, UpdateBindInfo, TestSize.Level0) +*/ +HWTEST_F(SoftBusClientTest, OpenConnectTest005, TestSize.Level1) { - ASSERT_NE(client, nullptr); - EXPECT_NO_FATAL_FAILURE(client->UpdateBindInfo(1, 1, AppDistributedKv::SoftBusClient::QOS_BR, false)); - EXPECT_NO_FATAL_FAILURE(client->UpdateBindInfo(1, 1, AppDistributedKv::SoftBusClient::QOS_BR, true)); -} + ConfigSocketId(VALID_SOCKET); + accessInfo_.isOHType = true; + auto connect = std::make_shared(pipeInfo_, deviceId_, NETWORK_ID, SoftBusClient::QOS_HML, + accessInfo_); + auto status = connect->OpenConnect(&clientListener_); + ASSERT_EQ(status, Status::RATE_LIMIT); + while (!(deviceListener_.isReady_)) { + sleep(1); + } + deviceListener_.ResetReadyFlag(); + auto result = deviceListener_.bindResult_; + ASSERT_EQ(result, 0); + status = connect->CheckStatus(); + ASSERT_EQ(status, Status::SUCCESS); + ASSERT_TRUE(*connect == UUID); -/** -* @tc.name: ReuseConnect -* @tc.desc: ReuseConnect test -* @tc.type: FUNC -* @tc.require: -* @tc.author: wangbin - */ -HWTEST_F(SoftbusClientTest, ReuseConnect, TestSize.Level0) -{ - ASSERT_NE(client, nullptr); - ISocketListener *listener = nullptr; - client->bindState_ = 0; - auto status = client->ReuseConnect(listener); - EXPECT_EQ(status, Status::SUCCESS); - client->bindState_ = -1; - client->isOpening_.store(true); - status = client->ReuseConnect(listener); - EXPECT_EQ(status, Status::NETWORK_ERROR); + DataInfo dataInfo; + status = connect->SendData(dataInfo); + ASSERT_EQ(status, Status::SUCCESS); } } // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/adapter/include/communicator/commu_types.h b/services/distributeddataservice/adapter/include/communicator/commu_types.h index 6b1f1af696dcb9482181dea2df903ce5f51913a8..b7413703348fe817ae28d319e51ed1761da19cb9 100644 --- a/services/distributeddataservice/adapter/include/communicator/commu_types.h +++ b/services/distributeddataservice/adapter/include/communicator/commu_types.h @@ -59,9 +59,16 @@ enum RouteType : int32_t { BUTT, }; +struct ExtraDataInfo { + std::string userId; + std::string bundleName; + std::string storeId; +}; + struct DataInfo { uint8_t *data; uint32_t length; + ExtraDataInfo extraInfo; }; struct API_EXPORT PipeInfo { @@ -99,5 +106,14 @@ struct API_EXPORT LevelInfo { uint32_t switches; uint16_t switchesLen; }; + +struct API_EXPORT SessionAccessInfo { + int32_t userId; + std::string bundleName; + std::string storeId; + std::string accountId; + uint32_t tokenId; + bool isOHType = true; +}; } #endif // OHOS_DISTRIBUTED_DATA_ADAPTER_COMMUNICATOR_COMMU_TYPES_H diff --git a/services/distributeddataservice/adapter/include/communicator/communicator_context.h b/services/distributeddataservice/adapter/include/communicator/communicator_context.h index ce09ab58a92c4e58d37bf62b8f497cbb7af93ecb..7b9ea464183ec8f5b2bdc6be27416bac69079909 100644 --- a/services/distributeddataservice/adapter/include/communicator/communicator_context.h +++ b/services/distributeddataservice/adapter/include/communicator/communicator_context.h @@ -21,7 +21,6 @@ #include "commu_types.h" #include "concurrent_map.h" #include "visibility.h" -#include "iprocess_communicator.h" namespace OHOS::DistributedData { class API_EXPORT CommunicatorContext {