diff --git a/frameworks/native/distributed_file_inner/src/asset/asset_adapter_sa_client.cpp b/frameworks/native/distributed_file_inner/src/asset/asset_adapter_sa_client.cpp index bfcd6677ebc1fb0fb6a919f2fd7dee064c4303f7..2f27417cd61f07e5861f748dd1586ce8a7670e9f 100644 --- a/frameworks/native/distributed_file_inner/src/asset/asset_adapter_sa_client.cpp +++ b/frameworks/native/distributed_file_inner/src/asset/asset_adapter_sa_client.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2024 Huawei Device Co., Ltd. +* Copyright (c) 2024-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 @@ -111,6 +111,11 @@ int32_t AssetAdapterSaClient::RemoveListener(const sptr &lis LOGI("Sa client remove listener enter."); std::lock_guard lock(eventMutex_); for (auto iter = listeners_.begin(); iter != listeners_.end();) { + if (*iter == nullptr) { + LOGE("*iter is nullptr"); + ++iter; + continue; + } if ((*iter)->AsObject() == listener->AsObject()) { iter = listeners_.erase(iter); } else { diff --git a/frameworks/native/distributed_file_inner/src/asset/asset_recv_callback_stub.cpp b/frameworks/native/distributed_file_inner/src/asset/asset_recv_callback_stub.cpp index 78dfe4a660f0327a30bca3eb673c89ddb7340904..faedde487bb28c6b798dd1765b87a143407d915e 100644 --- a/frameworks/native/distributed_file_inner/src/asset/asset_recv_callback_stub.cpp +++ b/frameworks/native/distributed_file_inner/src/asset/asset_recv_callback_stub.cpp @@ -43,7 +43,7 @@ int32_t AssetRecvCallbackStub::OnRemoteRequest(uint32_t code, } auto interfaceIndex = opToInterfaceMap_.find(code); if (interfaceIndex == opToInterfaceMap_.end() || !interfaceIndex->second) { - LOGE("Cannot response request %{public}d: unknown tranction", code); + LOGE("Cannot response request %{public}d: unknown transaction", code); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } return (this->*(interfaceIndex->second))(data, reply); diff --git a/services/distributedfiledaemon/include/device/device_manager_agent.h b/services/distributedfiledaemon/include/device/device_manager_agent.h index ded3f380ba735ada06a0433e7455750a365fa22d..da95af0c3309e3987670ab46692a2682fb371c24 100644 --- a/services/distributedfiledaemon/include/device/device_manager_agent.h +++ b/services/distributedfiledaemon/include/device/device_manager_agent.h @@ -132,8 +132,7 @@ private: bool MountDfsCountOnly(const std::string &deviceId); bool UMountDfsCountOnly(const std::string &deviceId, bool needClear); int32_t GetCurrentUserId(); - void GetStorageManager(); - sptr storageMgrProxy_; + sptr GetStorageManager(); std::mutex mountDfsCountMutex_; std::unordered_map mountDfsCount_; std::mutex networkIdMapMutex_; diff --git a/services/distributedfiledaemon/include/ipc/daemon_execute.h b/services/distributedfiledaemon/include/ipc/daemon_execute.h index d96528d3308ed2f920745ceeecaefd9b51403f99..91fdba6dc7095a61050b5e9402091727cd17555d 100644 --- a/services/distributedfiledaemon/include/ipc/daemon_execute.h +++ b/services/distributedfiledaemon/include/ipc/daemon_execute.h @@ -44,7 +44,7 @@ private: const std::string &sessionName); void ExecutePrepareSession(const AppExecFwk::InnerEvent::Pointer &event); int32_t PrepareSessionInner(const std::string &srcUri, - std::string &physicalPath, + const std::string &physicalPath, const std::string &sessionName, const sptr &daemon, HmdfsInfo &info); diff --git a/services/distributedfiledaemon/include/multiuser/os_account_observer.h b/services/distributedfiledaemon/include/multiuser/os_account_observer.h index 2079917e8e523ec7e3772106d9d7dbe7d4e7230e..a1c8be515901a84ceb2b0cbbb7746ccb6f0096df 100644 --- a/services/distributedfiledaemon/include/multiuser/os_account_observer.h +++ b/services/distributedfiledaemon/include/multiuser/os_account_observer.h @@ -39,7 +39,8 @@ private: void RemoveMPInfo(const int id); void AddMPInfo(const int id, const std::string &relativePath); int32_t GetCurrentUserId(); - + void OnEventUserSwitched(int32_t userId); + void OnEventUserUnlocked(int32_t userId); std::mutex serializer_; std::unordered_map>> mountPoints_; int curUsrId_ { -1 }; diff --git a/services/distributedfiledaemon/include/network/network_agent_template.h b/services/distributedfiledaemon/include/network/network_agent_template.h index c5802c7bf64a5ad91c32b5a14ffacd54c198f941..d970f1371eb7ec9a53aaff401009a068f73437f7 100644 --- a/services/distributedfiledaemon/include/network/network_agent_template.h +++ b/services/distributedfiledaemon/include/network/network_agent_template.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -58,8 +58,8 @@ public: void Stop(); void ConnectOnlineDevices(); void DisconnectAllDevices(); - void DisconnectDeviceByP2P(const DeviceInfo info); - void DisconnectDeviceByP2PHmdfs(const DeviceInfo info); + void DisconnectDeviceByP2P(const std::string networkId); + void DisconnectDeviceByP2PHmdfs(const std::string networkId); void AcceptSession(std::shared_ptr session, const std::string backStage); void ConnectDeviceByP2PAsync(const DeviceInfo info); bool FindSocketId(int32_t socketId); diff --git a/services/distributedfiledaemon/include/network/softbus/softbus_asset_recv_listener.h b/services/distributedfiledaemon/include/network/softbus/softbus_asset_recv_listener.h index 67916b50ae756cf58a566ad8846bbdaddf0d5df5..13cbcaa1125acd8046bf77f13848d2409609eec4 100644 --- a/services/distributedfiledaemon/include/network/softbus/softbus_asset_recv_listener.h +++ b/services/distributedfiledaemon/include/network/softbus/softbus_asset_recv_listener.h @@ -49,9 +49,9 @@ private: static int32_t GetCurrentUserId(); static bool MoveAsset(const std::vector &fileList, bool isSingleFile); static bool RemoveAsset(const std::string &file); - static inline const std::string SERVICE_NAME{"ohos.storage.distributedfile.daemon"}; + static constexpr char SERVICE_NAME[] = "ohos.storage.distributedfile.daemon"; static inline std::string path_; - static inline std::mutex mtx_; + static std::mutex mtx_; }; } // namespace DistributedFile } // namespace Storage diff --git a/services/distributedfiledaemon/include/network/softbus/softbus_asset_send_listener.h b/services/distributedfiledaemon/include/network/softbus/softbus_asset_send_listener.h index 7d12c7e76747c02c70ec3a20637aee98e8677700..701b68df2c4ad5ad82f08f79982489476de2c76f 100644 --- a/services/distributedfiledaemon/include/network/softbus/softbus_asset_send_listener.h +++ b/services/distributedfiledaemon/include/network/softbus/softbus_asset_send_listener.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2024 Huawei Device Co., Ltd. +* Copyright (c) 2024-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 @@ -42,7 +42,7 @@ public: static void DisConnectByAllConnect(const std::string &peerNetworkId); private: - static inline std::recursive_mutex mtx_; + static std::recursive_mutex mtx_; static std::map> taskIsSingleFileMap_; static inline const std::string SERVICE_NAME{"ohos.storage.distributedfile.daemon"}; }; diff --git a/services/distributedfiledaemon/include/network/softbus/softbus_file_receive_listener.h b/services/distributedfiledaemon/include/network/softbus/softbus_file_receive_listener.h index 28c77d0eea6d8fce9e4151c70073967c13ef0ea2..a52039692bf04298443d9fdf81f93b1000878e2c 100644 --- a/services/distributedfiledaemon/include/network/softbus/softbus_file_receive_listener.h +++ b/services/distributedfiledaemon/include/network/softbus/softbus_file_receive_listener.h @@ -45,7 +45,7 @@ public: private: static inline const std::string SERVICE_NAME{"ohos.storage.distributedfile.daemon"}; static std::string path_; - static inline std::atomic_bool bindSuccess { false }; + static inline std::atomic_bool bindSuccess_ { false }; static std::shared_mutex rwMtx_; static std::condition_variable_any cv_; }; diff --git a/services/distributedfiledaemon/include/network/softbus/softbus_handler.h b/services/distributedfiledaemon/include/network/softbus/softbus_handler.h index d8d820cacb6304aac2424c899a0342171ad99c28..552dce9ed9823dcd59eddd778ed457e9c570737c 100644 --- a/services/distributedfiledaemon/include/network/softbus/softbus_handler.h +++ b/services/distributedfiledaemon/include/network/softbus/softbus_handler.h @@ -38,7 +38,7 @@ public: ~SoftBusHandler(); static SoftBusHandler &GetInstance(); int32_t CreateSessionServer(const std::string &packageName, const std::string &sessionName, - DFS_CHANNEL_ROLE role, const std::string physicalPath); + DFS_CHANNEL_ROLE role, const std::string &physicalPath); int32_t OpenSession(const std::string &mySessionName, const std::string &peerSessionName, const std::string &peerDevId, int32_t &socketId); int32_t CopySendFile(int32_t socketId, diff --git a/services/distributedfiledaemon/include/network/softbus/softbus_handler_asset.h b/services/distributedfiledaemon/include/network/softbus/softbus_handler_asset.h index e3bfea9f87c33a6d2d6972ff837aca577aba80ce..9caf5cd6811a3166cb3a966699318bc057dddadd 100644 --- a/services/distributedfiledaemon/include/network/softbus/softbus_handler_asset.h +++ b/services/distributedfiledaemon/include/network/softbus/softbus_handler_asset.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2024 Huawei Device Co., Ltd. +* Copyright (c) 2024-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 @@ -48,7 +48,7 @@ public: int32_t AssetBind(const std::string &dstNetworkId, int32_t &socketId); int32_t AssetSendFile(int32_t socketId, const std::string& sendFile, bool isSingleFile); - void closeAssetBind(int32_t socketId); + void CloseAssetBind(int32_t socketId); void OnAssetRecvBind(int32_t socketId, const std::string &srcNetWorkId); std::string GetClientInfo(int32_t socketId); diff --git a/services/distributedfiledaemon/src/all_connect/all_connect_manager.cpp b/services/distributedfiledaemon/src/all_connect/all_connect_manager.cpp index 37c62d08bb61b29ac495e83ea08fa62a7b3c13f9..36f4f67a37311aaa1b3abeb309442c86a620ab8b 100644 --- a/services/distributedfiledaemon/src/all_connect/all_connect_manager.cpp +++ b/services/distributedfiledaemon/src/all_connect/all_connect_manager.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2024 Huawei Device Co., Ltd. +* Copyright (c) 2024-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 diff --git a/services/distributedfiledaemon/src/device/device_manager_agent.cpp b/services/distributedfiledaemon/src/device/device_manager_agent.cpp index 7c0bba179b97f88ddac012273f27a4c8bf1387f7..c88c4a73bdcabf0942c7ca890e25e5f19b5c93ac 100644 --- a/services/distributedfiledaemon/src/device/device_manager_agent.cpp +++ b/services/distributedfiledaemon/src/device/device_manager_agent.cpp @@ -134,7 +134,11 @@ void DeviceManagerAgent::QuitGroup(shared_ptr smp) throw runtime_error(ss.str()); } - it->second->StopActor(); + if (it->second != nullptr) { + it->second->StopActor(); + } else { + LOGE("QuitGroup it->second is nullptr"); + } mpToNetworks_.erase(smp->GetID()); LOGI("quit group end, id : %{public}d, account : %{public}s", smp->GetID(), smp->isAccountLess() ? "no" : "yes"); } @@ -211,15 +215,13 @@ void DeviceManagerAgent::OnDeviceOffline(const DistributedHardware::DmDeviceInfo unique_lock lock(mpToNetworksMutex_); auto it = cidNetTypeRecord_.find(info.cid_); if (it == cidNetTypeRecord_.end()) { - LOGE("cid %{public}s network is null!", Utils::GetAnonyString(info.cid_).c_str()); - LOGI("OnDeviceOffline end"); + LOGE("OnDeviceOffline end, cid %{public}s network is null!", Utils::GetAnonyString(info.cid_).c_str()); return; } auto type_ = cidNetworkType_.find(info.cid_); if (type_ == cidNetworkType_.end()) { - LOGE("cid %{public}s network type is null!", Utils::GetAnonyString(info.cid_).c_str()); - LOGI("OnDeviceOffline end"); + LOGE("OnDeviceOffline end, cid %{public}s network type is null!", Utils::GetAnonyString(info.cid_).c_str()); return; } @@ -232,9 +234,14 @@ void DeviceManagerAgent::OnDeviceOffline(const DistributedHardware::DmDeviceInfo UMountDfsDocs(networkId, deviceId, true); } - auto cmd2 = make_unique>( - &NetworkAgentTemplate::DisconnectDeviceByP2PHmdfs, info); - it->second->Recv(move(cmd2)); + auto cmd2 = make_unique>( + &NetworkAgentTemplate::DisconnectDeviceByP2PHmdfs, info.cid_); + if (it->second != nullptr) { + it->second->Recv(move(cmd2)); + } else { + LOGE("OnDeviceOffline it->second is nullptr"); + return; + } cidNetTypeRecord_.erase(info.cid_); cidNetworkType_.erase(info.cid_); @@ -244,16 +251,16 @@ void DeviceManagerAgent::OnDeviceOffline(const DistributedHardware::DmDeviceInfo auto localNetworkId = GetLocalDeviceInfo().GetCid(); if (userId == INVALID_USER_ID) { LOGE("DeviceManagerAgent::GetCurrentUserId Fail"); + return; } - GetStorageManager(); - if (storageMgrProxy_ == nullptr) { - LOGE("storageMgrProxy_ is null"); + auto storageMgrProxy = GetStorageManager(); + if (storageMgrProxy == nullptr) { + LOGE("storageMgrProxy is null"); + return; } - ret = storageMgrProxy_->UMountDisShareFile(userId, localNetworkId); + ret = storageMgrProxy->UMountDisShareFile(userId, localNetworkId); if (ret != NO_ERROR) { LOGE("UMountDisShareFile failed, ret =%{public}d", ret); - } else { - LOGI("UMountDisShareFile success"); } LOGI("OnDeviceOffline end"); @@ -269,7 +276,11 @@ void DeviceManagerAgent::ClearCount(const DistributedHardware::DmDeviceInfo &dev LOGE("cid %{public}s network is null!", Utils::GetAnonyString(info.cid_).c_str()); return; } - it->second->DisconnectDeviceByP2P(info); + if (it->second != nullptr) { + it->second->DisconnectDeviceByP2P(info.cid_); + } else { + LOGE("ClearCount it->second is nullptr"); + } } int32_t DeviceManagerAgent::OnDeviceP2POnline(const DistributedHardware::DmDeviceInfo &deviceInfo) @@ -298,7 +309,12 @@ int32_t DeviceManagerAgent::OnDeviceP2POnline(const DistributedHardware::DmDevic auto cmd = make_unique>( &NetworkAgentTemplate::ConnectDeviceByP2PAsync, info); cmd->UpdateOption({.tryTimes_ = MAX_RETRY_COUNT}); - it->second->Recv(move(cmd)); + if (it->second != nullptr) { + it->second->Recv(move(cmd)); + } else { + LOGE("OnDeviceP2POnline it->second is nullptr"); + return P2P_FAILED; + } LOGI("OnDeviceP2POnline end networkId %{public}s", Utils::GetAnonyString(deviceInfo.networkId).c_str()); return P2P_SUCCESS; } @@ -319,9 +335,14 @@ int32_t DeviceManagerAgent::OnDeviceP2POffline(const DistributedHardware::DmDevi LOGE("cid %{public}s network type is null!", Utils::GetAnonyString(info.cid_).c_str()); return P2P_FAILED; } - auto cmd = make_unique>( - &NetworkAgentTemplate::DisconnectDeviceByP2P, info); - it->second->Recv(move(cmd)); + auto cmd = make_unique>( + &NetworkAgentTemplate::DisconnectDeviceByP2P, info.cid_); + if (it->second != nullptr) { + it->second->Recv(move(cmd)); + } else { + LOGE("OnDeviceP2POffline it->second is nullptr"); + return P2P_FAILED; + } cidNetTypeRecord_.erase(info.cid_); cidNetworkType_.erase(info.cid_); LOGI("OnDeviceP2POffline end"); @@ -388,28 +409,22 @@ int32_t DeviceManagerAgent::GetCurrentUserId() return userIds[0]; } -void DeviceManagerAgent::GetStorageManager() +sptr DeviceManagerAgent::GetStorageManager() { auto saMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (saMgr == nullptr) { LOGE("GetSystemAbilityManager filed"); - return; + return nullptr; } auto storageObj = saMgr->GetSystemAbility(STORAGE_MANAGER_MANAGER_ID); if (storageObj == nullptr) { LOGE("filed to get STORAGE_MANAGER_MANAGER_ID proxy"); - return; - } - - storageMgrProxy_ = iface_cast(storageObj); - if (storageMgrProxy_ == nullptr) { - LOGE("filed to get STORAGE_MANAGER_MANAGER_ID proxy!"); - return; + return nullptr; } LOGI("GetStorageManager end."); - return; + return iface_cast(storageObj); } void DeviceManagerAgent::AddNetworkId(uint32_t tokenId, const std::string &networkId) @@ -476,7 +491,7 @@ int32_t DeviceManagerAgent::MountDfsDocs(const std::string &networkId, const std LOGI("MountDfsDocs start"); if (networkId.empty() || deviceId.empty()) { LOGE("NetworkId or DeviceId is empty"); - return INVALID_USER_ID; + return FileManagement::ERR_BAD_VALUE; } int32_t ret = NO_ERROR; if (MountDfsCountOnly(deviceId)) { @@ -487,14 +502,14 @@ int32_t DeviceManagerAgent::MountDfsDocs(const std::string &networkId, const std int32_t userId = GetCurrentUserId(); if (userId == INVALID_USER_ID) { LOGE("GetCurrentUserId Fail"); - return INVALID_USER_ID; + return FileManagement::ERR_BAD_VALUE; } - GetStorageManager(); - if (storageMgrProxy_ == nullptr) { - LOGE("storageMgrProxy_ is null"); - return INVALID_USER_ID; + auto storageMgrProxy = GetStorageManager(); + if (storageMgrProxy == nullptr) { + LOGE("storageMgrProxy is null"); + return FileManagement::ERR_BAD_VALUE; } - ret = storageMgrProxy_->MountDfsDocs(userId, "account", networkId, deviceId); + ret = storageMgrProxy->MountDfsDocs(userId, "account", networkId, deviceId); if (ret != NO_ERROR) { LOGE("MountDfsDocs fail, ret = %{public}d", ret); } else { @@ -512,28 +527,28 @@ int32_t DeviceManagerAgent::UMountDfsDocs(const std::string &networkId, const st Utils::GetAnonyString(networkId).c_str(), Utils::GetAnonyString(deviceId).c_str()); if (networkId.empty() || deviceId.empty()) { LOGE("NetworkId or DeviceId is empty"); - return INVALID_USER_ID; + return FileManagement::ERR_BAD_VALUE; } int32_t ret = NO_ERROR; if (UMountDfsCountOnly(deviceId, needClear)) { - LOGE("do not need umount"); + LOGW("do not need umount"); return ret; } int32_t userId = GetCurrentUserId(); if (userId == INVALID_USER_ID) { LOGE("GetCurrentUserId Fail"); - return INVALID_USER_ID; + return FileManagement::ERR_BAD_VALUE; } - GetStorageManager(); - if (storageMgrProxy_ == nullptr) { - LOGE("storageMgrProxy_ is null"); - return INVALID_USER_ID; + auto storageMgrProxy = GetStorageManager(); + if (storageMgrProxy == nullptr) { + LOGE("storageMgrProxy is null"); + return FileManagement::ERR_BAD_VALUE; } - ret = storageMgrProxy_->UMountDfsDocs(userId, "account", networkId, deviceId); + ret = storageMgrProxy->UMountDfsDocs(userId, "account", networkId, deviceId); if (ret != NO_ERROR) { LOGE("UMountDfsDocs fail, ret = %{public}d", ret); } else { - LOGE("UMountDfsDocs success, deviceId %{public}s erase count", + LOGI("UMountDfsDocs success, deviceId %{public}s erase count", Utils::GetAnonyString(deviceId).c_str()); RemoveMountDfsCount(deviceId); } diff --git a/services/distributedfiledaemon/src/ipc/connection_detector.cpp b/services/distributedfiledaemon/src/ipc/connection_detector.cpp index 625c317a4e595205a290da07594eeb297409df4f..159208f659b2bf952d0a19cc0cf5f52356e9f6b4 100644 --- a/services/distributedfiledaemon/src/ipc/connection_detector.cpp +++ b/services/distributedfiledaemon/src/ipc/connection_detector.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2023-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 @@ -160,7 +160,7 @@ bool ConnectionDetector::GetConnectionStatus(const std::string &targetDir, const } int num = scandir(SYS_HMDFS_PATH.c_str(), &(pNameList->namelist), FilterFunc, alphasort); if (num < 0) { - LOGE("Failed to scandir."); + LOGE("Failed to scandir, errno = %{public}d", errno); return false; } pNameList->direntNum = num; diff --git a/services/distributedfiledaemon/src/ipc/daemon.cpp b/services/distributedfiledaemon/src/ipc/daemon.cpp index 333ee17fcbb761405fc84a09c3bb1742a573bacd..0a03a4124759a51b1c12d2d81fb8ffea3b226249 100644 --- a/services/distributedfiledaemon/src/ipc/daemon.cpp +++ b/services/distributedfiledaemon/src/ipc/daemon.cpp @@ -326,7 +326,7 @@ int32_t Daemon::OpenP2PConnectionEx(const std::string &networkId, sptrrequestSendFileBlock_; + auto requestSendFileBlock = requestSendFileData->requestSendFileBlock_; if (requestSendFileBlock == nullptr) { LOGE("requestSendFileBlock is nullptr."); return; } std::string srcUri = requestSendFileData->srcUri_; - std::string dstPath = requestSendFileData->dstPath_; - std::string dstDeviceId = requestSendFileData->dstDeviceId_; - std::string sessionName = requestSendFileData->sessionName_; + std::string dstPath = requestSendFileData->dstPath_; + std::string dstDeviceId = requestSendFileData->dstDeviceId_; + std::string sessionName = requestSendFileData->sessionName_; if (srcUri.empty() || dstDeviceId.empty() || sessionName.empty()) { LOGE("params empty. %{public}s, %{public}s", sessionName.c_str(), Utils::GetAnonyString(dstDeviceId).c_str()); requestSendFileBlock->SetValue(ERR_BAD_VALUE); @@ -216,17 +216,15 @@ void DaemonExecute::ExecutePrepareSession(const AppExecFwk::InnerEvent::Pointer LOGE("prepareSessionBlock is nullptr."); return; } - std::string srcUri = prepareSessionData->srcUri_; - std::string physicalPath = prepareSessionData->physicalPath_; - std::string sessionName = prepareSessionData->sessionName_; - sptr daemon = prepareSessionData->daemon_; - HmdfsInfo &info = prepareSessionData->info_; - - prepareSessionBlock->SetValue(PrepareSessionInner(srcUri, physicalPath, sessionName, daemon, info)); + prepareSessionBlock->SetValue(PrepareSessionInner(prepareSessionData->srcUri_, + prepareSessionData->physicalPath_, + prepareSessionData->sessionName_, + prepareSessionData->daemon_, + prepareSessionData->info_)); } int32_t DaemonExecute::PrepareSessionInner(const std::string &srcUri, - std::string &physicalPath, + const std::string &physicalPath, const std::string &sessionName, const sptr &daemon, HmdfsInfo &info) @@ -238,12 +236,12 @@ int32_t DaemonExecute::PrepareSessionInner(const std::string &srcUri, LOGE("CreateSessionServer failed, socketId = %{public}d", socketId); return E_SOFTBUS_SESSION_FAILED; } - physicalPath.clear(); + std::string tmpPhysicalPath; if (info.authority == FILE_MANAGER_AUTHORITY || info.authority == MEDIA_AUTHORITY) { LOGI("authority is media or docs"); - physicalPath = "??" + info.dstPhysicalPath; + tmpPhysicalPath = "??" + info.dstPhysicalPath; } - auto ret = Daemon::Copy(srcUri, physicalPath, daemon, sessionName); + auto ret = Daemon::Copy(srcUri, tmpPhysicalPath, daemon, sessionName); if (ret != E_OK) { LOGE("Remote copy failed,ret = %{public}d", ret); SoftBusHandler::GetInstance().CloseSession(socketId, sessionName); @@ -335,7 +333,7 @@ void DaemonExecute::HandlePushAssetFail(int32_t socketId, const sptr & { auto taskId = assetObj->srcBundleName_ + assetObj->sessionId_; AssetCallbackManager::GetInstance().NotifyAssetSendResult(taskId, assetObj, FileManagement::E_EVENT_HANDLER); - SoftBusHandlerAsset::GetInstance().closeAssetBind(socketId); + SoftBusHandlerAsset::GetInstance().CloseAssetBind(socketId); AssetCallbackManager::GetInstance().RemoveSendCallback(taskId); SoftBusAssetSendListener::RemoveFileMap(taskId); } diff --git a/services/distributedfiledaemon/src/ipc/daemon_stub.cpp b/services/distributedfiledaemon/src/ipc/daemon_stub.cpp index acf73d0a595a1a468ad12acdc113aa5b53e9c6d8..fde899ceb1a394e09cdc11e0d3e04d55aac1da3a 100644 --- a/services/distributedfiledaemon/src/ipc/daemon_stub.cpp +++ b/services/distributedfiledaemon/src/ipc/daemon_stub.cpp @@ -100,7 +100,7 @@ int32_t DaemonStub::HandleOpenP2PConnection(MessageParcel &data, MessageParcel & { LOGI("Begin OpenP2PConnection"); if (!DfsuAccessTokenHelper::CheckCallerPermission(PERM_DISTRIBUTED_DATASYNC)) { - LOGE("[HandleOpenP2PConnection] DATASYNC permission denied"); + LOGE("DATASYNC permission denied"); return E_PERMISSION_DENIED; } DistributedHardware::DmDeviceInfo deviceInfo; @@ -133,7 +133,7 @@ int32_t DaemonStub::HandleCloseP2PConnection(MessageParcel &data, MessageParcel { LOGI("Begin CloseP2PConnection"); if (!DfsuAccessTokenHelper::CheckCallerPermission(PERM_DISTRIBUTED_DATASYNC)) { - LOGE("[HandleCloseP2PConnection] DATASYNC permission denied"); + LOGE("DATASYNC permission denied"); return E_PERMISSION_DENIED; } DistributedHardware::DmDeviceInfo deviceInfo; diff --git a/services/distributedfiledaemon/src/multiuser/os_account_observer.cpp b/services/distributedfiledaemon/src/multiuser/os_account_observer.cpp index f499eae53e31d83c882a270cbe7b51ea095586fe..b53ad3bbd2a59d835bec8487f9fc968725fdac83 100644 --- a/services/distributedfiledaemon/src/multiuser/os_account_observer.cpp +++ b/services/distributedfiledaemon/src/multiuser/os_account_observer.cpp @@ -69,31 +69,12 @@ void OsAccountObserver::OnReceiveEvent(const EventFwk::CommonEventData &eventDat { const AAFwk::Want& want = eventData.GetWant(); std::string action = want.GetAction(); + int32_t userId = eventData.GetCode(); LOGI("AccountSubscriber: OnReceiveEvent action:%{public}s.", action.c_str()); if (action == EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { - int32_t id = eventData.GetCode(); - LOGI("user id changed to %{public}d", id); - lock_guard lock(serializer_); - if (curUsrId_ != -1 && curUsrId_ != id) { - // first stop curUsrId_ network - RemoveMPInfo(curUsrId_); - } else if (curUsrId_ != -1 && curUsrId_ == id) { - return; - } - - // then start new network - curUsrId_ = id; - AddMPInfo(id, SAME_ACCOUNT); - LOGI("user id %{public}d, add network done", curUsrId_); + OnEventUserSwitched(userId); } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED) { - int32_t id = eventData.GetCode(); - LOGI("user id: %{public}d unlocked", id); - lock_guard lock(serializer_); - if (needAddUserId_.load() == id) { - LOGI("user id: %{public}d now begin to join group", id); - AddMPInfo(id, SAME_ACCOUNT); - } - needAddUserId_.store(-1); + OnEventUserUnlocked(userId); } else { LOGE("no expect action"); } @@ -126,6 +107,34 @@ int32_t OsAccountObserver::GetCurrentUserId() } return userIds[0]; } + +void OsAccountObserver::OnEventUserSwitched(const int32_t userId) +{ + LOGI("user id changed to %{public}d", userId); + lock_guard lock(serializer_); + if (curUsrId_ != -1 && curUsrId_ != userId) { + // first stop curUsrId_ network + RemoveMPInfo(curUsrId_); + } else if (curUsrId_ != -1 && curUsrId_ == userId) { + return; + } + + // then start new network + curUsrId_ = userId; + AddMPInfo(userId, SAME_ACCOUNT); + LOGI("user id %{public}d, add network done", curUsrId_); +} + +void OsAccountObserver::OnEventUserUnlocked(const int32_t userId) +{ + LOGI("user id: %{public}d unlocked", userId); + lock_guard lock(serializer_); + if (needAddUserId_.load() == userId) { + LOGI("user id: %{public}d now begin to join group", userId); + AddMPInfo(userId, SAME_ACCOUNT); + } + needAddUserId_.store(-1); +} } // namespace DistributedFile } // namespace Storage } // namespace OHOS diff --git a/services/distributedfiledaemon/src/network/network_agent_template.cpp b/services/distributedfiledaemon/src/network/network_agent_template.cpp index 792b3a0df04870196bb47de97bc1e4dafa2ea381..0c983e9b062b933c3d87cb7173ccc02cd591ae77 100644 --- a/services/distributedfiledaemon/src/network/network_agent_template.cpp +++ b/services/distributedfiledaemon/src/network/network_agent_template.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -112,18 +112,18 @@ void NetworkAgentTemplate::DisconnectAllDevices() ConnectCount::GetInstance()->RemoveAllConnect(); } -void NetworkAgentTemplate::DisconnectDeviceByP2P(const DeviceInfo info) +void NetworkAgentTemplate::DisconnectDeviceByP2P(const std::string networkId) { - LOGI("CloseP2P, cid:%{public}s", Utils::GetAnonyString(info.GetCid()).c_str()); - sessionPool_.ReleaseSession(info.GetCid(), false); + LOGI("CloseP2P, cid:%{public}s", Utils::GetAnonyString(networkId).c_str()); + sessionPool_.ReleaseSession(networkId, false); } -void NetworkAgentTemplate::DisconnectDeviceByP2PHmdfs(const DeviceInfo info) +void NetworkAgentTemplate::DisconnectDeviceByP2PHmdfs(const std::string networkId) { - LOGI("DeviceOffline, cid:%{public}s", Utils::GetAnonyString(info.GetCid()).c_str()); - sessionPool_.ReleaseSession(info.GetCid(), true); - ConnectCount::GetInstance()->NotifyRemoteReverseObj(info.GetCid(), ON_STATUS_OFFLINE); - ConnectCount::GetInstance()->RemoveConnect(info.GetCid()); + LOGI("DeviceOffline, cid:%{public}s", Utils::GetAnonyString(networkId).c_str()); + sessionPool_.ReleaseSession(networkId, true); + ConnectCount::GetInstance()->NotifyRemoteReverseObj(networkId, ON_STATUS_OFFLINE); + ConnectCount::GetInstance()->RemoveConnect(networkId); } void NetworkAgentTemplate::CloseSessionForOneDevice(const string &cid) diff --git a/services/distributedfiledaemon/src/network/session_pool.cpp b/services/distributedfiledaemon/src/network/session_pool.cpp index 76e6e715fed48232303032cc2e621709f7261227..1b02fd9011738c10d4f905ed1796d8bc1d3e6b19 100644 --- a/services/distributedfiledaemon/src/network/session_pool.cpp +++ b/services/distributedfiledaemon/src/network/session_pool.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -40,7 +40,7 @@ void SessionPool::ReleaseSession(const int32_t fd) lock_guard lock(sessionPoolLock_); LOGI("ReleaseSession start, fd=%{public}d", fd); for (auto iter = usrSpaceSessionPool_.begin(); iter != usrSpaceSessionPool_.end(); ++iter) { - if ((*iter)->GetHandle() == fd) { + if ((*iter) != nullptr && (*iter)->GetHandle() == fd) { (*iter)->Release(); iter = usrSpaceSessionPool_.erase(iter); break; @@ -53,7 +53,7 @@ bool SessionPool::CheckIfGetSession(const int32_t fd) lock_guard lock(sessionPoolLock_); std::shared_ptr session = nullptr; for (auto iter = usrSpaceSessionPool_.begin(); iter != usrSpaceSessionPool_.end(); ++iter) { - if ((*iter)->GetHandle() == fd) { + if ((*iter) != nullptr && (*iter)->GetHandle() == fd) { session = *iter; break; } @@ -76,7 +76,7 @@ bool SessionPool::FindSocketId(int32_t socketId) { lock_guard lock(sessionPoolLock_); for (auto iter = usrSpaceSessionPool_.begin(); iter != usrSpaceSessionPool_.end(); ++iter) { - if ((*iter)->GetSessionId() == socketId) { + if ((*iter) != nullptr && (*iter)->GetSessionId() == socketId) { return true; } } @@ -89,7 +89,12 @@ void SessionPool::ReleaseSession(const std::string &cid, bool isReleaseAll) std::vector> sessions; LOGI("ReleaseSession, cid:%{public}s", Utils::GetAnonyString(cid).c_str()); for (auto iter = usrSpaceSessionPool_.begin(); iter != usrSpaceSessionPool_.end();) { - if ((*iter)->GetCid() != cid || ((*iter)->IsFromServer() && !isReleaseAll)) { + if ((*iter) == nullptr) { + LOGE("Value is nullptr"); + ++iter; + continue; + } + if (((*iter)->GetCid() != cid || ((*iter)->IsFromServer() && !isReleaseAll))) { ++iter; continue; } @@ -112,7 +117,7 @@ void SessionPool::ReleaseSession(const std::string &cid, bool isReleaseAll) bool SessionPool::FindCid(const std::string &cid) { for (auto iter = usrSpaceSessionPool_.begin(); iter != usrSpaceSessionPool_.end(); ++iter) { - if ((*iter)->GetCid() == cid) { + if ((*iter) != nullptr && (*iter)->GetCid() == cid) { return true; } } @@ -127,7 +132,9 @@ void SessionPool::ReleaseAllSession() } lock_guard lock(sessionPoolLock_); for (auto iter = usrSpaceSessionPool_.begin(); iter != usrSpaceSessionPool_.end();) { - talker_->SinkOfflineCmdToKernel((*iter)->GetCid()); + if (*iter != nullptr) { + talker_->SinkOfflineCmdToKernel((*iter)->GetCid()); + } /* device offline, session release by softbus */ iter = usrSpaceSessionPool_.erase(iter); } diff --git a/services/distributedfiledaemon/src/network/softbus/softbus_asset_recv_listener.cpp b/services/distributedfiledaemon/src/network/softbus/softbus_asset_recv_listener.cpp index ca3f390d7862e0a6b516cf770afecc4cc1672e61..1eb3b4aba6cc78fd238ff0f8886d36f1390ee107 100644 --- a/services/distributedfiledaemon/src/network/softbus/softbus_asset_recv_listener.cpp +++ b/services/distributedfiledaemon/src/network/softbus/softbus_asset_recv_listener.cpp @@ -33,6 +33,8 @@ namespace OHOS { namespace Storage { namespace DistributedFile { + +std::mutex SoftbusAssetRecvListener::mtx_; const std::string HMDFS_PATH = "/mnt/hmdfs/{userId}/account/device_view/local/data/"; const std::string USRT_ID_FLAG = "{userId}"; const std::string TEMP_DIR = "ASSET_TEMP/"; @@ -384,7 +386,7 @@ void SoftbusAssetRecvListener::DisConnectByAllConnect(const std::string &peerNet for (auto socketId : socketIds) { auto assetObj = SoftBusHandlerAsset::GetInstance().GetAssetObj(socketId); if (assetObj == nullptr) { - LOGE("OnSendAssetError get assetObj is nullptr"); + LOGE("OnSendAssetError get assetObj is nullptr, socket: %{public}d", socketId); continue; } AssetCallbackManager::GetInstance().NotifyAssetRecvFinished( diff --git a/services/distributedfiledaemon/src/network/softbus/softbus_asset_send_listener.cpp b/services/distributedfiledaemon/src/network/softbus/softbus_asset_send_listener.cpp index 287263ee5bd4ad26f131859146d88f536561a4b6..0698c514a04286515908f13d5a366ad55d6dda7c 100644 --- a/services/distributedfiledaemon/src/network/softbus/softbus_asset_send_listener.cpp +++ b/services/distributedfiledaemon/src/network/softbus/softbus_asset_send_listener.cpp @@ -24,6 +24,8 @@ namespace OHOS { namespace Storage { namespace DistributedFile { +std::recursive_mutex SoftBusAssetSendListener::mtx_; + std::map> SoftBusAssetSendListener::taskIsSingleFileMap_; void SoftBusAssetSendListener::OnFile(int32_t socket, FileEvent *event) { @@ -59,7 +61,7 @@ void SoftBusAssetSendListener::OnSendAssetFinished(int32_t socketId, const char } auto taskId = assetObj->srcBundleName_ + assetObj->sessionId_; AssetCallbackManager::GetInstance().NotifyAssetSendResult(taskId, assetObj, FileManagement::E_OK); - SoftBusHandlerAsset::GetInstance().closeAssetBind(socketId); + SoftBusHandlerAsset::GetInstance().CloseAssetBind(socketId); AssetCallbackManager::GetInstance().RemoveSendCallback(taskId); SoftBusHandlerAsset::GetInstance().RemoveFile(fileList[0], GetIsZipFile(taskId)); RemoveFileMap(taskId); @@ -83,7 +85,7 @@ void SoftBusAssetSendListener::OnSendAssetError(int32_t socketId, } auto taskId = assetObj->srcBundleName_ + assetObj->sessionId_; AssetCallbackManager::GetInstance().NotifyAssetSendResult(taskId, assetObj, FileManagement::E_SEND_FILE); - SoftBusHandlerAsset::GetInstance().closeAssetBind(socketId); + SoftBusHandlerAsset::GetInstance().CloseAssetBind(socketId); AssetCallbackManager::GetInstance().RemoveSendCallback(taskId); SoftBusHandlerAsset::GetInstance().RemoveFile(fileList[0], GetIsZipFile(taskId)); RemoveFileMap(taskId); @@ -101,7 +103,7 @@ void SoftBusAssetSendListener::DisConnectByAllConnect(const std::string &peerNet } auto taskId = assetObj->srcBundleName_ + assetObj->sessionId_; AssetCallbackManager::GetInstance().NotifyAssetSendResult(taskId, assetObj, FileManagement::E_SEND_FILE); - SoftBusHandlerAsset::GetInstance().closeAssetBind(socketId); + SoftBusHandlerAsset::GetInstance().CloseAssetBind(socketId); AssetCallbackManager::GetInstance().RemoveSendCallback(taskId); auto it = taskIsSingleFileMap_.find(taskId); if (it != taskIsSingleFileMap_.end()) { @@ -122,7 +124,7 @@ void SoftBusAssetSendListener::OnSendShutdown(int32_t sessionId, ShutdownReason } auto taskId = assetObj->srcBundleName_ + assetObj->sessionId_; AssetCallbackManager::GetInstance().NotifyAssetSendResult(taskId, assetObj, FileManagement::E_SEND_FILE); - SoftBusHandlerAsset::GetInstance().closeAssetBind(sessionId); + SoftBusHandlerAsset::GetInstance().CloseAssetBind(sessionId); AssetCallbackManager::GetInstance().RemoveSendCallback(taskId); auto it = taskIsSingleFileMap_.find(taskId); if (it != taskIsSingleFileMap_.end()) { diff --git a/services/distributedfiledaemon/src/network/softbus/softbus_file_receive_listener.cpp b/services/distributedfiledaemon/src/network/softbus/softbus_file_receive_listener.cpp index 84bfef243867d7c162034bcbeb1fbff8523589da..4a48141662e2c22556893753b0e79f4ff53ff3e4 100644 --- a/services/distributedfiledaemon/src/network/softbus/softbus_file_receive_listener.cpp +++ b/services/distributedfiledaemon/src/network/softbus/softbus_file_receive_listener.cpp @@ -94,10 +94,10 @@ void SoftBusFileReceiveListener::SetRecvPath(const std::string &physicalPath) void SoftBusFileReceiveListener::OnCopyReceiveBind(int32_t socketId, PeerSocketInfo info) { LOGI("OnCopyReceiveBind begin, socketId %{public}d", socketId); - bindSuccess.store(false); + bindSuccess_.store(false); SoftBusHandler::OnSinkSessionOpened(socketId, info); std::unique_lock lock(rwMtx_); - bindSuccess.store(true); + bindSuccess_.store(true); cv_.notify_all(); } @@ -119,7 +119,7 @@ void SoftBusFileReceiveListener::OnReceiveFileProcess(int32_t sessionId, uint64_ "bytesTotal = %{public}" PRIu64 "", sessionId, bytesUpload, bytesTotal); std::shared_lock lock(rwMtx_); cv_.wait_for(lock, std::chrono::milliseconds(WAIT_TIME_MS), - [] { return SoftBusFileReceiveListener::bindSuccess.load(); }); + [] { return SoftBusFileReceiveListener::bindSuccess_.load(); }); std::string sessionName = GetLocalSessionName(sessionId); if (sessionName.empty()) { LOGE("sessionName is empty"); diff --git a/services/distributedfiledaemon/src/network/softbus/softbus_handler.cpp b/services/distributedfiledaemon/src/network/softbus/softbus_handler.cpp index 07a5f1b90c2924c6e93724e7caa81a1da6e8bb79..f865d5b037ffbb27feda0a2b6fef9a678dbc9d3d 100644 --- a/services/distributedfiledaemon/src/network/softbus/softbus_handler.cpp +++ b/services/distributedfiledaemon/src/network/softbus/softbus_handler.cpp @@ -117,7 +117,7 @@ SoftBusHandler &SoftBusHandler::GetInstance() } int32_t SoftBusHandler::CreateSessionServer(const std::string &packageName, const std::string &sessionName, - DFS_CHANNEL_ROLE role, const std::string physicalPath) + DFS_CHANNEL_ROLE role, const std::string &physicalPath) { if (packageName.empty() || sessionName.empty() || physicalPath.empty()) { LOGI("The parameter is empty"); @@ -248,8 +248,12 @@ int32_t SoftBusHandler::CopySendFile(int32_t socketId, LOGE("remote device cannot read this files"); return FileManagement::ERR_BAD_VALUE; } + if (fileList.size() > MAX_SIZE) { + LOGE("The length of src file lists is more than 500"); + return FileManagement::ERR_BAD_VALUE; + } const char *src[MAX_SIZE] = {}; - for (size_t i = 0; i < fileList.size() && fileList.size() < MAX_SIZE; i++) { + for (size_t i = 0; i < fileList.size(); i++) { src[i] = fileList.at(i).c_str(); } @@ -259,7 +263,7 @@ int32_t SoftBusHandler::CopySendFile(int32_t socketId, return FileManagement::ERR_BAD_VALUE; } const char *dst[MAX_SIZE] = {}; - for (size_t i = 0; i < fileNameList.size() && fileList.size() < MAX_SIZE; i++) { + for (size_t i = 0; i < fileNameList.size(); i++) { dst[i] = fileNameList.at(i).c_str(); } diff --git a/services/distributedfiledaemon/src/network/softbus/softbus_handler_asset.cpp b/services/distributedfiledaemon/src/network/softbus/softbus_handler_asset.cpp index f68d89b255ab123fc248f6ea0423035e584a0837..e3210ead2702cf88870318431016e4b0c0934631 100644 --- a/services/distributedfiledaemon/src/network/softbus/softbus_handler_asset.cpp +++ b/services/distributedfiledaemon/src/network/softbus/softbus_handler_asset.cpp @@ -225,9 +225,9 @@ int32_t SoftBusHandlerAsset::AssetSendFile(int32_t socketId, const std::string& return E_OK; } -void SoftBusHandlerAsset::closeAssetBind(int32_t socketId) +void SoftBusHandlerAsset::CloseAssetBind(int32_t socketId) { - LOGI("closeAssetBind Enter."); + LOGI("CloseAssetBind Enter."); Shutdown(socketId); auto assetObj = GetAssetObj(socketId); if (assetObj == nullptr) { @@ -279,6 +279,10 @@ std::vector SoftBusHandlerAsset::GetSocketIdFromAssetObj(const std::str std::vector socketIdVec; std::lock_guard lock(assetObjMapMutex_); for (auto iter = assetObjMap_.begin(); iter != assetObjMap_.end(); ++iter) { + if (iter->second == nullptr) { + LOGE("AssetObj is nullptr"); + continue; + } if (iter->second->dstNetworkId_ == peerNetworkId) { socketIdVec.push_back(iter->first); } diff --git a/services/distributedfiledaemon/test/mock/device_manager_agent_mock.cpp b/services/distributedfiledaemon/test/mock/device_manager_agent_mock.cpp index 82f2fe2740a5319dcb056411ee68e42b73f29df6..a8cd93742ebcc16bd3f137754896a7eb74b99a27 100644 --- a/services/distributedfiledaemon/test/mock/device_manager_agent_mock.cpp +++ b/services/distributedfiledaemon/test/mock/device_manager_agent_mock.cpp @@ -129,9 +129,9 @@ int32_t DeviceManagerAgent::GetCurrentUserId() return 0; } -void DeviceManagerAgent::GetStorageManager() +sptr DeviceManagerAgent::GetStorageManager() { - return; + return nullptr; } void DeviceManagerAgent::AddNetworkId(uint32_t tokenId, const std::string &networkId) @@ -297,9 +297,8 @@ void DeviceManagerAgent::OnRemoteDied() DeviceInfo &DeviceManagerAgent::GetLocalDeviceInfo() { - DeviceInfo deviceInfo; if (IDeviceManagerAgentMock::iDeviceManagerAgentMock_ == nullptr) { - return deviceInfo; + return localDeviceInfo_; } return IDeviceManagerAgentMock::iDeviceManagerAgentMock_->GetLocalDeviceInfo(); } diff --git a/services/distributedfiledaemon/test/mock/include/softbus_handler_mock.h b/services/distributedfiledaemon/test/mock/include/softbus_handler_mock.h index 6f62ea91fad124eee3db744c4fb482e348e1799f..21c44f3aac42a913dbafb7d582e98bbae170c614 100644 --- a/services/distributedfiledaemon/test/mock/include/softbus_handler_mock.h +++ b/services/distributedfiledaemon/test/mock/include/softbus_handler_mock.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2024 Huawei Device Co., Ltd. +* Copyright (c) 2024-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 @@ -27,7 +27,7 @@ public: virtual ~ISoftBusHandlerMock() = default; virtual int32_t CreateSessionServer(const std::string &packageName, const std::string &sessionName, - DFS_CHANNEL_ROLE role, const std::string physicalPath) = 0; + DFS_CHANNEL_ROLE role, const std::string &physicalPath) = 0; virtual int32_t OpenSession(const std::string &mySessionName, const std::string &peerSessionName, const std::string &peerDevId, int32_t &socketId) = 0; virtual int32_t CopySendFile(int32_t socketId, @@ -44,7 +44,7 @@ public: class SoftBusHandlerMock : public ISoftBusHandlerMock { public: MOCK_METHOD4(CreateSessionServer, int32_t(const std::string &packageName, const std::string &sessionName, - DFS_CHANNEL_ROLE role, const std::string physicalPath)); + DFS_CHANNEL_ROLE role, const std::string &physicalPath)); MOCK_METHOD4(OpenSession, int32_t(const std::string &mySessionName, const std::string &peerSessionName, const std::string &peerDevId, int32_t &socketId)); MOCK_METHOD4(CopySendFile, int32_t(int32_t socketId, diff --git a/services/distributedfiledaemon/test/mock/softbus_handler_asset_mock.cpp b/services/distributedfiledaemon/test/mock/softbus_handler_asset_mock.cpp index b21e11096605b9f0ae95e1479fb25d58bdc9b151..b1707b806b1b7abed6a2f327d1e6324428c0872a 100644 --- a/services/distributedfiledaemon/test/mock/softbus_handler_asset_mock.cpp +++ b/services/distributedfiledaemon/test/mock/softbus_handler_asset_mock.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2024 Huawei Device Co., Ltd. +* Copyright (c) 2024-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 @@ -53,7 +53,7 @@ int32_t SoftBusHandlerAsset::AssetSendFile(int32_t socketId, const std::string & return ISoftBusHandlerAssetMock::iSoftBusHandlerAssetMock_->AssetSendFile(socketId, sendFile, isSingleFile); } -void SoftBusHandlerAsset::closeAssetBind(int32_t socketId) +void SoftBusHandlerAsset::CloseAssetBind(int32_t socketId) { return; } diff --git a/services/distributedfiledaemon/test/mock/softbus_handler_mock.cpp b/services/distributedfiledaemon/test/mock/softbus_handler_mock.cpp index c5b7d276c4faaba267af30c32e2869ae01ed80be..686c3318a789d7b49fcb993e0258500a2bb610e9 100644 --- a/services/distributedfiledaemon/test/mock/softbus_handler_mock.cpp +++ b/services/distributedfiledaemon/test/mock/softbus_handler_mock.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2024 Huawei Device Co., Ltd. +* Copyright (c) 2024-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 @@ -38,7 +38,7 @@ std::string SoftBusHandler::GetSessionName(int32_t sessionId) } int32_t SoftBusHandler::CreateSessionServer(const std::string &packageName, const std::string &sessionName, - DFS_CHANNEL_ROLE role, const std::string physicalPath) + DFS_CHANNEL_ROLE role, const std::string &physicalPath) { if (ISoftBusHandlerMock::iSoftBusHandlerMock_ == nullptr) { return -1; diff --git a/services/distributedfiledaemon/test/unittest/BUILD.gn b/services/distributedfiledaemon/test/unittest/BUILD.gn index f6c8f2bf365f945ea908ae59471ddd8bb93385fe..cf9a38ffb02e7226baea17290daddc4d9adcd745 100644 --- a/services/distributedfiledaemon/test/unittest/BUILD.gn +++ b/services/distributedfiledaemon/test/unittest/BUILD.gn @@ -76,12 +76,16 @@ ohos_unittest("device_manager_agent_sup_test") { module_out_path = module_output_path - include_dirs = [ "device/include/" ] + include_dirs = [ + "device/include/", + "${distributedfile_path}/test/mock/" + ] sources = [ "${distributedfile_path}/test/mock/device_manager_impl_mock.cpp", "${distributedfile_path}/test/mock/device_manager_mock.cpp", "${distributedfile_path}/test/mock/softbus_bus_center_mock.cpp", + "${distributedfile_path}/test/mock/system_ability_manager_client_mock.cpp", "device/device_manager_agent_sup_test.cpp", "device/mock_other_method.cpp", ] @@ -1367,6 +1371,7 @@ group("unittest") { ":devsl_dispatcher_test", ":kernel_talker_test", ":os_account_observer_test", + ":session_pool_test", ":softbus_agent_sup_test", ":softbus_agent_test", ":softbus_asset_recv_listener_test", diff --git a/services/distributedfiledaemon/test/unittest/device/device_manager_agent_test.cpp b/services/distributedfiledaemon/test/unittest/device/device_manager_agent_test.cpp index 727401819d32236bdca362432dc055753e86d0af..0733c85d61e8212fa2bd5bf51014b5c159f32eab 100644 --- a/services/distributedfiledaemon/test/unittest/device/device_manager_agent_test.cpp +++ b/services/distributedfiledaemon/test/unittest/device/device_manager_agent_test.cpp @@ -47,7 +47,7 @@ DistributedHardware::DmDeviceInfo deviceInfo = { .deviceId = "testdevid", .deviceName = "testdevname", .deviceTypeId = 1, - .networkId = "testNetWork", + .networkId = "testNetwork", .extraData = R"({"OS_TYPE":10})", }; @@ -218,6 +218,14 @@ HWTEST_F(DeviceManagerAgentTest, DeviceManagerAgentTest_OnDeviceOffline_0300, Te DeviceManagerAgent::GetInstance()->OnDeviceOffline(deviceInfo); DeviceManagerAgent::GetInstance()->cidNetTypeRecord_.erase(NETWORKID_TWO); DeviceManagerAgent::GetInstance()->cidNetworkType_.erase(NETWORKID_TWO); + + DeviceManagerAgent::GetInstance()->cidNetTypeRecord_.insert({ NETWORKID_TWO, nullptr }); + DeviceManagerAgent::GetInstance()->cidNetworkType_.insert({ NETWORKID_TWO, NETWORKTYPE_NONE_WIFI }); + DeviceManagerAgent::GetInstance()->OnDeviceOffline(deviceInfo); + EXPECT_NE(DeviceManagerAgent::GetInstance()->cidNetTypeRecord_.size(), 0); + EXPECT_NE(DeviceManagerAgent::GetInstance()->cidNetworkType_.size(), 0); + DeviceManagerAgent::GetInstance()->cidNetTypeRecord_.clear(); + DeviceManagerAgent::GetInstance()->cidNetworkType_.clear(); } catch (const exception &e) { GTEST_LOG_(INFO) << e.what(); res = false; @@ -433,6 +441,14 @@ HWTEST_F(DeviceManagerAgentTest, DeviceManagerAgentTest_OnDeviceP2POnline_0200, devicePtr->cidNetworkType_.insert({ testNetWorkId, NETWORKTYPE_NONE_WIFI }); ret = devicePtr->OnDeviceP2POnline(deviceInfo); EXPECT_EQ(ret, 0); + + EXPECT_CALL(*deviceManagerImplMock_, GetTrustedDeviceList(_, _, _)) + .WillOnce(DoAll(SetArgReferee<2>(deviceList), Return(0))).WillRepeatedly(Return(0)); + devicePtr->cidNetTypeRecord_[testNetWorkId] = nullptr; + ret = devicePtr->OnDeviceP2POnline(deviceInfo); + EXPECT_EQ(ret, DeviceManagerAgent::P2PErrCode::P2P_FAILED); + EXPECT_EQ(devicePtr->cidNetTypeRecord_.size(), 1); + EXPECT_EQ(devicePtr->cidNetworkType_.size(), 1); devicePtr->cidNetTypeRecord_.erase(testNetWorkId); devicePtr->cidNetworkType_.erase(testNetWorkId); } catch (const exception &e) { @@ -524,6 +540,15 @@ HWTEST_F(DeviceManagerAgentTest, DeviceManagerAgentTest_OnDeviceP2POffline_0300, if (iterType != devicePtr->cidNetworkType_.end()) { res = false; } + + devicePtr->cidNetTypeRecord_.insert({NETWORKID_TWO, nullptr}); + devicePtr->cidNetworkType_.insert({ NETWORKID_TWO, NETWORKTYPE_NONE_WIFI }); + ret = devicePtr->OnDeviceP2POffline(deviceInfo); + EXPECT_EQ(ret, DeviceManagerAgent::P2PErrCode::P2P_FAILED); + EXPECT_NE(devicePtr->cidNetTypeRecord_.size(), 0); + EXPECT_NE(devicePtr->cidNetworkType_.size(), 0); + devicePtr->cidNetTypeRecord_.clear(); + devicePtr->cidNetworkType_.clear(); } catch (const exception &e) { GTEST_LOG_(INFO) << e.what(); res = false; @@ -649,14 +674,13 @@ HWTEST_F(DeviceManagerAgentTest, DeviceManagerAgentTest_JoinGroup_0300, TestSize { GTEST_LOG_(INFO) << "DeviceManagerAgentTest_JoinGroup_0300 start"; bool res = true; - + auto smp = make_shared(Utils::DfsuMountArgumentDescriptors::Alpha(100, "relativePath")); try { - auto smp = make_shared(Utils::DfsuMountArgumentDescriptors::Alpha(100, "relativePath")); DeviceManagerAgent::GetInstance()->JoinGroup(smp); DeviceManagerAgent::GetInstance()->JoinGroup(smp); - DeviceManagerAgent::GetInstance()->QuitGroup(smp); } catch (const exception &e) { EXPECT_EQ(string(e.what()), "Failed to join group: Mountpoint existed"); + DeviceManagerAgent::GetInstance()->QuitGroup(smp); res = false; } @@ -699,8 +723,14 @@ HWTEST_F(DeviceManagerAgentTest, DeviceManagerAgentTest_QuitGroup_0200, TestSize bool res = true; try { - shared_ptr nullwmp; - DeviceManagerAgent::GetInstance()->QuitGroup(nullwmp); + DeviceManagerAgent::GetInstance()->mpToNetworks_.clear(); + auto smp = make_shared(Utils::DfsuMountArgumentDescriptors::Alpha(100, "relativePath")); + DeviceManagerAgent::GetInstance()->mpToNetworks_.emplace(smp->GetID(), nullptr); + DeviceManagerAgent::GetInstance()->QuitGroup(smp); + EXPECT_EQ(DeviceManagerAgent::GetInstance()->mpToNetworks_.size(), 0); + + shared_ptr nullsmp; + DeviceManagerAgent::GetInstance()->QuitGroup(nullsmp); } catch (const exception &e) { EXPECT_EQ(string(e.what()), "Failed to quit group: Received empty mountpoint"); res = false; @@ -1385,6 +1415,38 @@ HWTEST_F(DeviceManagerAgentTest, DeviceManagerAgentTest_QueryRelatedGroups_0100, EXPECT_TRUE(res == true); GTEST_LOG_(INFO) << "DeviceManagerAgentTest_QueryRelatedGroups_0100 end"; } + +/** + * @tc.name: DeviceManagerAgentTest_ClearCount_0100 + * @tc.desc: Verify the ClearCount function. + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(DeviceManagerAgentTest, DeviceManagerAgentTest_ClearCount_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DeviceManagerAgentTest_ClearCount_0100 start"; + bool res = true; + + try { + std::string networkId(deviceInfo.networkId); + DeviceManagerAgent::GetInstance()->cidNetTypeRecord_.insert({ networkId, nullptr }); + DeviceManagerAgent::GetInstance()->ClearCount(deviceInfo); + EXPECT_EQ(DeviceManagerAgent::GetInstance()->cidNetTypeRecord_.size(), 1); + + auto smp = make_shared(Utils::DfsuMountArgumentDescriptors::Alpha(100, "relativePath")); + auto agent1 = make_shared(smp); + DeviceManagerAgent::GetInstance()->cidNetTypeRecord_[networkId] = agent1; + DeviceManagerAgent::GetInstance()->ClearCount(deviceInfo); + EXPECT_EQ(DeviceManagerAgent::GetInstance()->cidNetTypeRecord_.size(), 1); + DeviceManagerAgent::GetInstance()->cidNetTypeRecord_.clear(); + } catch (const exception &e) { + LOGE("Error:%{public}s", e.what()); + res = false; + } + + EXPECT_TRUE(res == true); + GTEST_LOG_(INFO) << "DeviceManagerAgentTest_ClearCount_0100 end"; +} } // namespace Test } // namespace DistributedFile } // namespace Storage diff --git a/services/distributedfiledaemon/test/unittest/multiuser/os_account_observer_test.cpp b/services/distributedfiledaemon/test/unittest/multiuser/os_account_observer_test.cpp index 07f3b79a4ab42a0c710b6c888afd3e38615e39ca..991f8072a4097522903cbd64bedae73ff0d6bb36 100644 --- a/services/distributedfiledaemon/test/unittest/multiuser/os_account_observer_test.cpp +++ b/services/distributedfiledaemon/test/unittest/multiuser/os_account_observer_test.cpp @@ -89,10 +89,22 @@ HWTEST_F(OsAccountObserverTest, OsAccountObserverTest_OnReceiveEvent_0100, TestS std::string data(EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED); EventFwk::CommonEventData eventData(want, code, data); g_subScriber->OnReceiveEvent(eventData); + EXPECT_EQ(g_subScriber->curUsrId_, USER_ID); + g_subScriber->curUsrId_ = USER_ID; + g_subScriber->OnReceiveEvent(eventData); + EXPECT_EQ(g_subScriber->curUsrId_, USER_ID); + + g_subScriber->needAddUserId_.store(-1); // -1: default value std::string data1(EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED); - EventFwk::CommonEventData eventData1(want, code, data); + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED); + EventFwk::CommonEventData eventData1(want, code, data1); + g_subScriber->OnReceiveEvent(eventData1); + EXPECT_EQ(g_subScriber->needAddUserId_.load(), -1); // -1: default value + + g_subScriber->needAddUserId_.store(USER_ID); g_subScriber->OnReceiveEvent(eventData1); + EXPECT_EQ(g_subScriber->needAddUserId_.load(), -1); // -1: default value } } catch (const std::exception &e) { res = false; diff --git a/services/distributedfiledaemon/test/unittest/network/network_agent_template_test.cpp b/services/distributedfiledaemon/test/unittest/network/network_agent_template_test.cpp index 09ebf9857d41672ae1538f8a1654715006bb850a..1edb8c4be6983b9141ad5b829cfdd76b7220b45d 100644 --- a/services/distributedfiledaemon/test/unittest/network/network_agent_template_test.cpp +++ b/services/distributedfiledaemon/test/unittest/network/network_agent_template_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-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 @@ -193,7 +193,7 @@ HWTEST_F(NetworkAgentTemplateTest, NetworkAgentTemplateTest_DisconnectDeviceByP2 DeviceInfo devInfo(info); bool res = true; try { - NetworkAgentTemplate::DisconnectDeviceByP2P(devInfo); + NetworkAgentTemplate::DisconnectDeviceByP2P(devInfo.GetCid()); } catch (const exception &e) { res = false; LOGE("%{public}s", e.what()); diff --git a/services/distributedfiledaemon/test/unittest/network/session_pool_test.cpp b/services/distributedfiledaemon/test/unittest/network/session_pool_test.cpp index f5ece8cc16b89633064081173d07217cba74204b..94cf70b434727e65fcbd2a728bc71500a23dd0b6 100644 --- a/services/distributedfiledaemon/test/unittest/network/session_pool_test.cpp +++ b/services/distributedfiledaemon/test/unittest/network/session_pool_test.cpp @@ -164,7 +164,7 @@ HWTEST_F(SessionPoolTest, SessionPoolTest_HoldSession_0101, TestSize.Level1) auto size = pool->usrSpaceSessionPool_.size(); pool->talker_ = nullptr; pool->HoldSession(session, "Server"); - EXPECT_EQ(pool->usrSpaceSessionPool_.size(), size + 1); + EXPECT_EQ(pool->usrSpaceSessionPool_.size(), size); } catch (const exception &e) { res = false; LOGE("%{public}s", e.what()); @@ -189,12 +189,20 @@ HWTEST_F(SessionPoolTest, SessionPoolTest_ReleaseSession_Fd_0100, TestSize.Level shared_ptr pool = make_shared(kernelTalker); std::string peerDeviceId = "f6d4c0864707aefte7a78f09473aa122ff57fc8"; auto session = make_shared(TEST_SESSION_ID, peerDeviceId); - pool->usrSpaceSessionPool_.push_back(session); + pool->usrSpaceSessionPool_.push_back(nullptr); pool->ReleaseSession(0); EXPECT_EQ(pool->usrSpaceSessionPool_.size(), 1); // 1: session size pool->ReleaseSession(-1); // -1: session fd - EXPECT_EQ(pool->usrSpaceSessionPool_.size(), 0); // 0: session size + EXPECT_EQ(pool->usrSpaceSessionPool_.size(), 1); // 1: session size + + pool->usrSpaceSessionPool_.push_back(session); + pool->ReleaseSession(0); + EXPECT_EQ(pool->usrSpaceSessionPool_.size(), 2); // 2: session size + + pool->ReleaseSession(-1); // -1: session fd + EXPECT_EQ(pool->usrSpaceSessionPool_.size(), 1); // 1: session size + pool->usrSpaceSessionPool_.clear(); GTEST_LOG_(INFO) << "SessionPoolTest_ReleaseSession_Fd_0100 end"; } @@ -211,6 +219,7 @@ HWTEST_F(SessionPoolTest, SessionPoolTest_ReleaseSession_Cid_0100, TestSize.Leve weak_ptr wmp = smp; auto kernelTalker = std::make_shared(wmp, [](NotifyParam ¶m) {}, [](const std::string &) {}); shared_ptr pool = make_shared(kernelTalker); + pool->usrSpaceSessionPool_.push_back(nullptr); std::string peerDeviceId = "f6d4c0864707aefte7a78f09473aa122ff57fc8"; auto session = make_shared(TEST_SESSION_ID, peerDeviceId); @@ -226,7 +235,7 @@ HWTEST_F(SessionPoolTest, SessionPoolTest_ReleaseSession_Cid_0100, TestSize.Leve session2->SetFromServer(false); pool->usrSpaceSessionPool_.push_back(session2); bool ifReleaseService = false; - size_t len = 3; // 3: session size; + size_t len = 4; // 4: session size; pool->ReleaseSession("test", ifReleaseService); EXPECT_EQ(pool->usrSpaceSessionPool_.size(), len); @@ -239,10 +248,11 @@ HWTEST_F(SessionPoolTest, SessionPoolTest_ReleaseSession_Cid_0100, TestSize.Leve ifReleaseService = true; pool->ReleaseSession(peerDeviceId, ifReleaseService); - EXPECT_EQ(pool->usrSpaceSessionPool_.size(), 0); // 1: remove one + EXPECT_EQ(pool->usrSpaceSessionPool_.size(), 1); // 1: sessionId size pool->talker_ = nullptr; pool->ReleaseSession(peerDeviceId, ifReleaseService); - EXPECT_EQ(pool->usrSpaceSessionPool_.size(), 0); + EXPECT_EQ(pool->usrSpaceSessionPool_.size(), 1); // 1: sessionId size + pool->usrSpaceSessionPool_.clear(); GTEST_LOG_(INFO) << "SessionPoolTest_ReleaseSession_Cid_0100 end"; } @@ -262,6 +272,7 @@ HWTEST_F(SessionPoolTest, SessionPoolTest_ReleaseAllSession_0100, TestSize.Level std::string peerDeviceId = "f6d4c0864707aefte7a78f09473aa122ff57fc8"; auto session = make_shared(TEST_SESSION_ID, peerDeviceId); pool->usrSpaceSessionPool_.push_back(session); + pool->usrSpaceSessionPool_.push_back(nullptr); bool res = true; try { @@ -272,6 +283,7 @@ HWTEST_F(SessionPoolTest, SessionPoolTest_ReleaseAllSession_0100, TestSize.Level } EXPECT_TRUE(res == true); + EXPECT_TRUE(pool->usrSpaceSessionPool_.size() == 0); GTEST_LOG_(INFO) << "SessionPoolTest_ReleaseAllSession_0100 end"; } @@ -319,12 +331,17 @@ HWTEST_F(SessionPoolTest, SessionPoolTest_CheckIfGetSession_0100, TestSize.Level auto kernelTalker = std::make_shared(wmp, [](NotifyParam ¶m) {}, [](const std::string &) {}); shared_ptr pool = make_shared(kernelTalker); int32_t fd = -1; // -1: fd + pool->usrSpaceSessionPool_.push_back(nullptr); bool ret = pool->CheckIfGetSession(fd); EXPECT_EQ(ret, false); pool->usrSpaceSessionPool_.push_back(session); + ret = pool->CheckIfGetSession(1); // 1: test fd + EXPECT_EQ(ret, false); + ret = pool->CheckIfGetSession(fd); EXPECT_EQ(ret, true); + pool->usrSpaceSessionPool_.clear(); GTEST_LOG_(INFO) << "SessionPoolTest_CheckIfGetSession_0100 end"; } @@ -386,14 +403,43 @@ HWTEST_F(SessionPoolTest, SessionPoolTest_FindSocketId_0100, TestSize.Level1) weak_ptr wmp = smp; auto kernelTalker = std::make_shared(wmp, [](NotifyParam ¶m) {}, [](const std::string &) {}); shared_ptr pool = make_shared(kernelTalker); + pool->usrSpaceSessionPool_.push_back(nullptr); + bool ret = pool->FindSocketId(TEST_SESSION_ID); + EXPECT_EQ(ret, false); + pool->usrSpaceSessionPool_.push_back(session); - bool ret = pool->FindSocketId(-1); // -1: session id + ret = pool->FindSocketId(-1); // -1: session id EXPECT_EQ(ret, false); ret = pool->FindSocketId(TEST_SESSION_ID); EXPECT_EQ(ret, true); GTEST_LOG_(INFO) << "SessionPoolTest_FindSocketId_0100 end"; } + +/** + * @tc.name: SessionPoolTest_FindCid_0100 + * @tc.desc: Verify the FindCid function. + * @tc.type: FUNC + * @tc.require: SR000H0387 + */ +HWTEST_F(SessionPoolTest, SessionPoolTest_FindCid_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SessionPoolTest_FindCid_0100 start"; + std::string peerDeviceId = "f6d4c0864707aefte7a78f09473aa122ff57fc8"; + auto session = make_shared(TEST_SESSION_ID, peerDeviceId); + auto smp = make_shared(Utils::DfsuMountArgumentDescriptors::Alpha(USER_ID, "account")); + weak_ptr wmp = smp; + auto kernelTalker = std::make_shared(wmp, [](NotifyParam ¶m) {}, [](const std::string &) {}); + shared_ptr pool = make_shared(kernelTalker); + pool->usrSpaceSessionPool_.push_back(nullptr); + pool->usrSpaceSessionPool_.push_back(session); + bool ret = pool->FindCid("test"); + EXPECT_EQ(ret, false); + + ret = pool->FindCid(peerDeviceId); + EXPECT_EQ(ret, true); + GTEST_LOG_(INFO) << "SessionPoolTest_FindCid_0100 end"; +} } // namespace Test } // namespace DistributedFile } // namespace Storage diff --git a/services/distributedfiledaemon/test/unittest/network/softbus/softbus_file_receive_listener_test.cpp b/services/distributedfiledaemon/test/unittest/network/softbus/softbus_file_receive_listener_test.cpp index bebaaade0f11a0575db17f01caa28e846593bc94..910855cd8fd586cbbbce01ed96616cbe4f4bcddd 100644 --- a/services/distributedfiledaemon/test/unittest/network/softbus/softbus_file_receive_listener_test.cpp +++ b/services/distributedfiledaemon/test/unittest/network/softbus/softbus_file_receive_listener_test.cpp @@ -116,7 +116,7 @@ HWTEST_F(SoftBusFileReceiveListenerTest, SoftBusFileReceiveListenerTest_OnFile_0 .bytesProcessed = 0, .bytesTotal = 0}; int32_t socket = 0; - SoftBusFileReceiveListener::bindSuccess.store(true); + SoftBusFileReceiveListener::bindSuccess_.store(true); SoftBusFileReceiveListener::OnFile(socket, nullptr); SoftBusFileReceiveListener::OnFile(socket, &event); diff --git a/services/distributedfiledaemon/test/unittest/network/softbus/softbus_handler_asset_test.cpp b/services/distributedfiledaemon/test/unittest/network/softbus/softbus_handler_asset_test.cpp index c923c93b64983ce5179a36636f4c4ebf52c16d70..c9d3ea39f73dfc32db9421a2a861bb7e7bdd2de7 100644 --- a/services/distributedfiledaemon/test/unittest/network/softbus/softbus_handler_asset_test.cpp +++ b/services/distributedfiledaemon/test/unittest/network/softbus/softbus_handler_asset_test.cpp @@ -25,7 +25,6 @@ #include "mock_other_method.h" #include "network/softbus/softbus_session_pool.h" #include "socket_mock.h" - namespace OHOS { namespace Storage { namespace DistributedFile { @@ -647,6 +646,33 @@ HWTEST_F(SoftBusHandlerAssetTest, SoftBusHandlerAssetTest_RemoveFile_0100, TestS softBusHandlerAsset.RemoveFile(fileName, true); GTEST_LOG_(INFO) << "SoftBusHandlerAssetTest_RemoveFile_0100 end"; } + +/** + * @tc.name: SoftBusHandlerAssetTest_GetSocketIdFromAssetObj_0100 + * @tc.desc: Verify the GetSocketIdFromAssetObj function. + * @tc.type: FUNC + * @tc.require: I9JXPR + */ +HWTEST_F(SoftBusHandlerAssetTest, SoftBusHandlerAssetTest_GetSocketIdFromAssetObj_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SoftBusHandlerAssetTest_GetSocketIdFromAssetObj_0100 start"; + auto &&softBusHandlerAsset = SoftBusHandlerAsset::GetInstance(); + std::string peerNetworkId = "test"; + + sptr assetObj (new (std::nothrow) AssetObj()); + ASSERT_TRUE(assetObj != nullptr) << "assetObj assert failed!"; + assetObj->dstNetworkId_ = peerNetworkId; + softBusHandlerAsset.assetObjMap_.emplace(0, nullptr); + auto ret = softBusHandlerAsset.GetSocketIdFromAssetObj(peerNetworkId); + EXPECT_EQ(ret.size(), 0); + + softBusHandlerAsset.assetObjMap_.emplace(1, assetObj); + ret = softBusHandlerAsset.GetSocketIdFromAssetObj(peerNetworkId); + EXPECT_EQ(ret.size(), 1); + ASSERT_TRUE(ret.size() == 1) << "GetSocketIdFromAssetObj size failed!"; + EXPECT_EQ(ret[0], 1); + GTEST_LOG_(INFO) << "SoftBusHandlerAssetTest_GetSocketIdFromAssetObj_0100 end"; +} } // namespace Test } // namespace DistributedFile } // namespace Storage diff --git a/services/distributedfiledaemon/test/unittest/network/softbus/softbus_handler_test.cpp b/services/distributedfiledaemon/test/unittest/network/softbus/softbus_handler_test.cpp index 3202f996ce15603e30236b21453fd61c6ba34d93..1ba9f742350c83a55e6237598edd1f533f8ccb25 100644 --- a/services/distributedfiledaemon/test/unittest/network/softbus/softbus_handler_test.cpp +++ b/services/distributedfiledaemon/test/unittest/network/softbus/softbus_handler_test.cpp @@ -25,7 +25,9 @@ #include "dfs_error.h" #include "mock_other_method.h" +#include "network/devsl_dispatcher.h" #include "network/softbus/softbus_file_receive_listener.h" +#include "network/softbus/softbus_session_listener.h" #include "network/softbus/softbus_session_pool.h" #include "socket_mock.h" #include "utils_directory.h" @@ -41,6 +43,33 @@ const string TEST_NETWORKID_TWO = "45656596896323232"; const string TEST_NETWORKID_THREE = "45656596896323233"; constexpr int SESSION_ID_ONE = 1; constexpr int UID_ONE = 1; +std::string g_getRealPath = ""; +std::vector g_fileList = {}; +bool g_compareTrue = false; +std::vector g_fileNameList = {}; +} +namespace OHOS::Storage::DistributedFile { + std::string SoftBusSessionListener::GetRealPath(const std::string &srcUri) + { + return g_getRealPath; + } + bool DevslDispatcher::CompareDevslWithLocal(const std::string &peerNetworkId, const std::vector &paths) + { + return g_compareTrue; + } + + std::vector SoftBusSessionListener::GetFileName(const std::vector &fileList, + const std::string &path, const std::string &dstPath) + { + return g_fileNameList; + } +} + +namespace OHOS::Storage::DistributedFile::Utils { +std::vector GetFilePath(const std::string &name) +{ + return g_fileList; +} } namespace OHOS { @@ -652,6 +681,38 @@ HWTEST_F(SoftbusHandlerTest, SoftbusHandlerTest_CloseSessionWithSessionName_0200 } GTEST_LOG_(INFO) << "SoftbusHandlerTest_CloseSessionWithSessionName_0200 end"; } + +/** + * @tc.name: SoftbusHandlerTest_CopySendFile_0100 + * @tc.desc: Verify the CloseSession. + * @tc.type: FUNC + * @tc.require: I9JXPR + */ +HWTEST_F(SoftbusHandlerTest, SoftbusHandlerTest_CopySendFile_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SoftbusHandlerTest_CopySendFile_0100 start"; + auto ret = SoftBusHandler::GetInstance().CopySendFile(0, "", "", ""); + EXPECT_EQ(ret, FileManagement::ERR_BAD_VALUE); + + g_getRealPath = "test"; + ret = SoftBusHandler::GetInstance().CopySendFile(0, "", "", ""); + EXPECT_EQ(ret, FileManagement::ERR_BAD_VALUE); + + g_fileList.emplace_back("realpath"); + ret = SoftBusHandler::GetInstance().CopySendFile(0, "", "", ""); + EXPECT_EQ(ret, FileManagement::ERR_BAD_VALUE); + + g_compareTrue = true; + std::vector testVec(501, "test"); + g_fileList = testVec; + ret = SoftBusHandler::GetInstance().CopySendFile(0, "", "", ""); + EXPECT_EQ(ret, FileManagement::ERR_BAD_VALUE); + + g_fileList.resize(1); // 1: file count + ret = SoftBusHandler::GetInstance().CopySendFile(0, "", "", ""); + EXPECT_EQ(ret, FileManagement::ERR_BAD_VALUE); + GTEST_LOG_(INFO) << "SoftbusHandlerTest_CopySendFile_0100 end"; +} } // namespace Test } // namespace DistributedFile } // namespace Storage diff --git a/test/unittests/distributed_file_inner/BUILD.gn b/test/unittests/distributed_file_inner/BUILD.gn index 9257f8ef54cc8452694adf59390db22f956e629b..404229f17bb530c3e65e661249f35863dd845ba0 100644 --- a/test/unittests/distributed_file_inner/BUILD.gn +++ b/test/unittests/distributed_file_inner/BUILD.gn @@ -209,6 +209,56 @@ ohos_unittest("asset_recv_callback_stub_test") { subsystem_name = "filemanagement" } +ohos_unittest("asset_adapter_sa_client_test") { + branch_protector_ret = "pac_ret" + sanitize = { + integer_overflow = true + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "${distributedfile_path}/cfi_blocklist.txt" + } + + module_out_path = "dfs_service/dfs_service_daemon/distributedfiledaemon" + + sources = [ + "asset/asset_adapter_sa_client_test.cpp", + ] + + include_dirs = [ + "${distributedfile_path}/frameworks/native/distributed_file_inner/include", + "${distributedfile_path}/test/unittests/distributed_file_daemon/include", + "include", + "${services_path}/distributedfiledaemon/include/", + "${services_path}/distributedfiledaemon/include/ipc", + ] + + deps = [ + "${utils_path}:libdistributedfileutils", + "${services_path}/distributedfiledaemon:distributed_file_daemon_kit_inner", + ] + + external_deps = [ + "app_file_service:remote_file_share_native", + "c_utils:utils", + "device_manager:devicemanagersdk", + "googletest:gmock_main", + "googletest:gtest_main", + "hilog:libhilog", + "ipc:ipc_core", + "samgr:samgr_proxy" + ] + + defines = [ + "private=public", + "LOG_TAG=\"distributedfile_daemon\"", + ] + + use_exceptions = true + part_name = "dfs_service" + subsystem_name = "filemanagement" +} + ohos_unittest("asset_send_callback_stub_test") { branch_protector_ret = "pac_ret" sanitize = { @@ -717,6 +767,7 @@ group("distributed_file_inner") { testonly = true deps = [ + ":asset_adapter_sa_client_test", ":asset_recv_callback_stub_test", ":asset_send_callback_stub_test", ":distributed_file_daemon_proxy_sup_test", diff --git a/test/unittests/distributed_file_inner/asset/asset_adapter_sa_client_test.cpp b/test/unittests/distributed_file_inner/asset/asset_adapter_sa_client_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1d4ca4baede6a8180df2440f96613450223af75e --- /dev/null +++ b/test/unittests/distributed_file_inner/asset/asset_adapter_sa_client_test.cpp @@ -0,0 +1,99 @@ +/* + * 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 "asset/asset_adapter_sa_client.h" + +#include +#include + +#include "dfs_error.h" + +namespace OHOS::Storage::DistributedFile::Test { +using namespace OHOS::FileManagement; +using namespace testing; +using namespace testing::ext; +using namespace std; + +class TestAssetAdapterSaClient : public IRemoteStub { + int32_t OnStart(const std::string &srcNetworkId, + const std::string &dstNetworkId, + const std::string &sessionId, + const std::string &dstBundleName) override + { + return 0; + } + + int32_t OnRecvProgress(const std::string &srcNetworkId, + const sptr &assetObj, + uint64_t totalBytes, + uint64_t processBytes) override + { + return 0; + } + + int32_t OnFinished(const std::string &srcNetworkId, + const sptr &assetObj, + int32_t result) override + { + return 0; + } +}; + +class AssetAdapterSaClientTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void AssetAdapterSaClientTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void AssetAdapterSaClientTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void AssetAdapterSaClientTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void AssetAdapterSaClientTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: AssetAdapterSaClient_RemoveListener_0100 + * @tc.desc: The execution of the RemoveListener failed. + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(AssetAdapterSaClientTest, AssetAdapterSaClient_RemoveListener_0100, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "AssetAdapterSaClient_RemoveListener_0100 Start"; + + auto &client = AssetAdapterSaClient::GetInstance(); + client.listeners_.emplace_back(nullptr); + const sptr listener = sptr(new TestAssetAdapterSaClient()); + client.listeners_.emplace_back(listener); + auto ret = client.RemoveListener(listener); + EXPECT_EQ(ret, E_SA_LOAD_FAILED); + GTEST_LOG_(INFO) << "AssetAdapterSaClient_RemoveListener_0100 End"; +} +} \ No newline at end of file