From aa24106521f476f9bd057ed280a43f6c103912c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AE=81=E7=AB=9E=E8=8E=9C?= Date: Thu, 28 Aug 2025 20:46:55 +0800 Subject: [PATCH 1/5] filemanager-4 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 宁竞莜 --- .../distributed_file_daemon_manager_impl.h | 2 +- .../distributed_file_daemon_manager_impl.cpp | 2 +- .../src/distributed_file_daemon_proxy.cpp | 7 +- .../src/file_dfs_listener_stub.cpp | 12 +- .../include/channel_manager/channel_manager.h | 1 + .../channel_manager/control_cmd_parser.h | 1 + .../include/connect_count/connect_count.h | 14 +- .../include/device/device_manager_agent.h | 20 +- .../include/device/device_profile_adapter.h | 4 +- .../include/ipc/daemon.h | 4 +- .../include/ipc/file_dfs_listener_proxy.h | 3 +- .../include/ipc/i_file_dfs_listener.h | 3 +- .../src/channel_manager/channel_manager.cpp | 30 +- .../channel_manager/control_cmd_parser.cpp | 18 +- .../src/channel_manager/system_notifier.cpp | 13 +- .../src/connect_count/connect_count.cpp | 46 +- .../src/device/device_manager_agent.cpp | 97 ++- .../src/device/device_profile_adapter.cpp | 14 +- .../distributedfiledaemon/src/ipc/daemon.cpp | 258 +++++--- .../src/ipc/daemon_stub.cpp | 22 +- .../src/ipc/file_dfs_listener_proxy.cpp | 17 +- .../src/network/network_agent_template.cpp | 14 +- .../test/mock/channel_manager_mock.cpp | 5 + .../test/mock/device_manager_agent_mock.cpp | 15 +- .../test/mock/include/channel_manager_mock.h | 2 + .../mock/include/device_manager_agent_mock.h | 9 +- .../channel_manager/channel_manager_test.cpp | 116 ++++ .../control_cmd_parser_test.cpp | 1 - .../channel_manager/system_notifier_test.cpp | 7 +- .../connect_count/connect_count_test.cpp | 4 +- .../device/device_manager_agent_sup_test.cpp | 343 ++++++++-- .../device_profile_adapter_test.cpp | 26 +- .../test/unittest/ipc/daemon/BUILD.gn | 2 + .../test/unittest/ipc/daemon/daemon_test.cpp | 586 ++++++++++++++++-- .../daemonstub_fuzzer/daemonstub_fuzzer.cpp | 2 +- .../daemon_stub_sup_test.cpp | 58 +- .../file_dfs_listener_proxy_test.cpp | 51 +- .../include/file_dfs_listener_mock.h | 4 +- .../unittests/distributed_file_inner/BUILD.gn | 54 ++ .../distributed_file_daemon_proxy_test.cpp | 4 +- .../file_dfs_listener_stub_test.cpp | 129 ++++ .../include/i_daemon_mock.h | 2 +- utils/log/include/dfs_error.h | 1 + 43 files changed, 1638 insertions(+), 385 deletions(-) create mode 100644 test/unittests/distributed_file_inner/file_dfs_listener_stub_test.cpp diff --git a/frameworks/native/distributed_file_inner/include/distributed_file_daemon_manager_impl.h b/frameworks/native/distributed_file_inner/include/distributed_file_daemon_manager_impl.h index a073609d5..486ca74e7 100644 --- a/frameworks/native/distributed_file_inner/include/distributed_file_daemon_manager_impl.h +++ b/frameworks/native/distributed_file_inner/include/distributed_file_daemon_manager_impl.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2024 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 diff --git a/frameworks/native/distributed_file_inner/src/distributed_file_daemon_manager_impl.cpp b/frameworks/native/distributed_file_inner/src/distributed_file_daemon_manager_impl.cpp index 68f3762e3..433f02a27 100644 --- a/frameworks/native/distributed_file_inner/src/distributed_file_daemon_manager_impl.cpp +++ b/frameworks/native/distributed_file_inner/src/distributed_file_daemon_manager_impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2024 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 diff --git a/frameworks/native/distributed_file_inner/src/distributed_file_daemon_proxy.cpp b/frameworks/native/distributed_file_inner/src/distributed_file_daemon_proxy.cpp index 69db35085..8e97cb8f2 100644 --- a/frameworks/native/distributed_file_inner/src/distributed_file_daemon_proxy.cpp +++ b/frameworks/native/distributed_file_inner/src/distributed_file_daemon_proxy.cpp @@ -236,11 +236,8 @@ int32_t DistributedFileDaemonProxy::OpenP2PConnectionEx(const std::string &netwo LOGE("Failed to send network id."); return OHOS::FileManagement::E_INVAL_ARG; } - if (remoteReverseObj == nullptr) { - LOGE("remoteReverseObj is nullptr."); - return OHOS::FileManagement::E_BROKEN_IPC; - } - if (!data.WriteRemoteObject(remoteReverseObj->AsObject())) { + + if (remoteReverseObj != nullptr && !data.WriteRemoteObject(remoteReverseObj->AsObject())) { LOGE("fail to WriteRemoteObject remoteReverseObj"); return OHOS::FileManagement::E_BROKEN_IPC; } diff --git a/frameworks/native/distributed_file_inner/src/file_dfs_listener_stub.cpp b/frameworks/native/distributed_file_inner/src/file_dfs_listener_stub.cpp index bcff3fce2..ddf352b71 100644 --- a/frameworks/native/distributed_file_inner/src/file_dfs_listener_stub.cpp +++ b/frameworks/native/distributed_file_inner/src/file_dfs_listener_stub.cpp @@ -66,11 +66,21 @@ int32_t FileDfsListenerStub::HandleOnStatus(MessageParcel &data, MessageParcel & LOGE("read status failed"); return E_INVAL_ARG; } + std::string path; + if (!data.ReadString(path)) { + LOGE("Failed to read path"); + return E_INVAL_ARG; + } + int32_t type = -1; + if (!data.ReadInt32(type)) { + LOGE("Failed to read type"); + return E_INVAL_ARG; + } if (networkId.empty() || status < 0) { LOGE("Invalid arguments"); return E_INVAL_ARG; } - OnStatus(networkId, status); + OnStatus(networkId, status, path, type); return NO_ERROR; } diff --git a/services/distributedfiledaemon/include/channel_manager/channel_manager.h b/services/distributedfiledaemon/include/channel_manager/channel_manager.h index da0da2bbd..5d0cc8343 100644 --- a/services/distributedfiledaemon/include/channel_manager/channel_manager.h +++ b/services/distributedfiledaemon/include/channel_manager/channel_manager.h @@ -50,6 +50,7 @@ public: int32_t SendRequest( const std::string &networkId, ControlCmd &request, ControlCmd &response, bool needResponse = false); int32_t SendBytes(const std::string &networkId, const std::string &data); + int32_t NotifyClient(const std::string &networkId, const ControlCmd &request); void OnSocketError(int32_t socketId, const int32_t errorCode); void OnSocketConnected(int32_t socketId, const PeerSocketInfo &info); diff --git a/services/distributedfiledaemon/include/channel_manager/control_cmd_parser.h b/services/distributedfiledaemon/include/channel_manager/control_cmd_parser.h index 5bf79a1d1..36e3d5c8b 100644 --- a/services/distributedfiledaemon/include/channel_manager/control_cmd_parser.h +++ b/services/distributedfiledaemon/include/channel_manager/control_cmd_parser.h @@ -61,6 +61,7 @@ public: static bool PublishNotification(const ControlCmd &inCmd, ControlCmd &outCmd); static bool CancelNotification(const ControlCmd &inCmd, ControlCmd &outCmd); static bool DisconnectByRemote(const ControlCmd &inCmd, ControlCmd &outCmd); + static bool IsLocalItDevice(); static void RegisterDisconnectCallback(std::function cb); diff --git a/services/distributedfiledaemon/include/connect_count/connect_count.h b/services/distributedfiledaemon/include/connect_count/connect_count.h index c9a9fe819..cd56fb125 100644 --- a/services/distributedfiledaemon/include/connect_count/connect_count.h +++ b/services/distributedfiledaemon/include/connect_count/connect_count.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 @@ -38,6 +38,11 @@ struct Connect { sptr listener; }; +enum class StatusType { + SWITCH_STATUS = 1, + CONNECTION_STATUS +}; + class ConnectCount final { public: ConnectCount() = default; @@ -53,11 +58,16 @@ public: std::vector GetNetworkIds(uint32_t callingTokenId); void NotifyRemoteReverseObj(const std::string &networkId, int32_t status); int32_t FindCallingTokenIdForListerner(const sptr &listener, uint32_t &callingTokenId); - + void AddFileConnect(const std::string &instanceId, const sptr &listener); + bool RmFileConnect(const std::string &instanceId); + void NotifyFileStatusChange(const std::string &networkId, + int32_t status, const std::string &path, StatusType type); private: static std::shared_ptr instance_; std::recursive_mutex connectMutex_; std::unordered_set> connectList_; + std::recursive_mutex fileConnectMutex_; + std::unordered_map> fileConnectMap_; }; } // namespace DistributedFile } // namespace Storage diff --git a/services/distributedfiledaemon/include/device/device_manager_agent.h b/services/distributedfiledaemon/include/device/device_manager_agent.h index ded3f380b..fd8244714 100644 --- a/services/distributedfiledaemon/include/device/device_manager_agent.h +++ b/services/distributedfiledaemon/include/device/device_manager_agent.h @@ -50,6 +50,12 @@ struct GroupInfo { } }; +struct MountCountInfo { + MountCountInfo(std::string networkId, uint32_t callingTokenId); + std::string networkId_; + std::map callingCountMap_; +}; + void from_json(const nlohmann::json &jsonObject, GroupInfo &groupInfo); class DeviceManagerAgent final : public DistributedHardware::DmInitCallback, @@ -87,15 +93,18 @@ public: int32_t FindListenerByObject(const wptr &remote, uint32_t &tokenId, sptr& listener); std::string GetDeviceIdByNetworkId(const std::string &networkId); - int32_t MountDfsDocs(const std::string &networkId, const std::string &deviceId); + int32_t MountDfsDocs(const std::string &networkId, const std::string &deviceId, const uint32_t callingTokenId); int32_t UMountDfsDocs(const std::string &networkId, const std::string &deviceId, bool needClear); void AddNetworkId(uint32_t tokenId, const std::string &networkId); void RemoveNetworkId(uint32_t tokenId); void RemoveNetworkIdByOne(uint32_t tokenId, const std::string &networkId); void RemoveNetworkIdForAllToken(const std::string &networkId); void ClearNetworkId(); - void IncreaseMountDfsCount(const std::string &deviceId); - void RemoveMountDfsCount(const std::string &devcieId); + void IncreaseMountDfsCount(const std::string &networkId, + const std::string &mountPath, + const uint32_t callingTokenId); + void RemoveMountDfsCount(const std::string &mountPath); + void GetConnectedDeviceList(std::vector &deviceList); std::unordered_set GetNetworkIds(uint32_t tokenId); void OfflineAllDevice(); @@ -104,6 +113,7 @@ public: DeviceInfo &GetLocalDeviceInfo(); std::vector GetRemoteDevicesInfo(); + std::unordered_map GetAllMountInfo(); std::mutex appCallConnectMutex_; std::unordered_map> appCallConnect_; @@ -134,8 +144,10 @@ private: int32_t GetCurrentUserId(); void GetStorageManager(); sptr storageMgrProxy_; + + // deviceid(Network 16) -> MountCountInfo std::mutex mountDfsCountMutex_; - std::unordered_map mountDfsCount_; + std::unordered_map mountDfsCount_; std::mutex networkIdMapMutex_; std::unordered_map> networkIdMap_; }; diff --git a/services/distributedfiledaemon/include/device/device_profile_adapter.h b/services/distributedfiledaemon/include/device/device_profile_adapter.h index 7bae78d33..38dfc788b 100644 --- a/services/distributedfiledaemon/include/device/device_profile_adapter.h +++ b/services/distributedfiledaemon/include/device/device_profile_adapter.h @@ -48,9 +48,9 @@ public: static DeviceProfileAdapter instance; return instance; } - bool IsRemoteDfsVersionLower(const std::string &remoteNetworkId, + bool IsRemoteDfsVersionLowerThanLocal(const std::string &remoteNetworkId, VersionPackageName packageName = VersionPackageName::DFS_VERSION); - bool IsRemoteDfsVersionLower(const std::string &remoteNetworkId, + bool IsRemoteDfsVersionLowerThanGiven(const std::string &remoteNetworkId, const DfsVersion& thresholdDfsVersion, VersionPackageName packageName = VersionPackageName::DFS_VERSION); int32_t GetDfsVersionFromNetworkId(const std::string &networkId, DfsVersion &dfsVersion, VersionPackageName packageName = VersionPackageName::DFS_VERSION); diff --git a/services/distributedfiledaemon/include/ipc/daemon.h b/services/distributedfiledaemon/include/ipc/daemon.h index db1acafe3..4d89ae3dc 100644 --- a/services/distributedfiledaemon/include/ipc/daemon.h +++ b/services/distributedfiledaemon/include/ipc/daemon.h @@ -65,8 +65,8 @@ public: int32_t CloseP2PConnectionEx(const std::string &networkId) override; int32_t ConnectionCount(const DistributedHardware::DmDeviceInfo &deviceInfo); int32_t CleanUp(const DistributedHardware::DmDeviceInfo &deviceInfo); - int32_t ConnectionAndMount(const DistributedHardware::DmDeviceInfo &deviceInfo, - const std::string &networkId, uint32_t callingTokenId, sptr remoteReverseObj); + int32_t ConnectionAndMount(const DistributedHardware::DmDeviceInfo &deviceInfo, const std::string &networkId, + sptr remoteReverseObj); int32_t InnerCopy(const std::string &srcUri, const std::string &dstUri, const std::string &srcDeviceId, const sptr &listener, HmdfsInfo &info); int32_t PrepareSession(const std::string &srcUri, diff --git a/services/distributedfiledaemon/include/ipc/file_dfs_listener_proxy.h b/services/distributedfiledaemon/include/ipc/file_dfs_listener_proxy.h index 41ca4fdfb..e06d45954 100644 --- a/services/distributedfiledaemon/include/ipc/file_dfs_listener_proxy.h +++ b/services/distributedfiledaemon/include/ipc/file_dfs_listener_proxy.h @@ -29,7 +29,8 @@ class FileDfsListenerProxy : public IRemoteProxy { public: explicit FileDfsListenerProxy(const sptr &object) : IRemoteProxy(object) {} ~FileDfsListenerProxy() override {} - void OnStatus(const std::string &networkId, int32_t status) override; + void OnStatus(const std::string &networkId, int32_t status, + const std::string &path, int32_t type) override; private: static inline BrokerDelegator delegator_; diff --git a/services/distributedfiledaemon/include/ipc/i_file_dfs_listener.h b/services/distributedfiledaemon/include/ipc/i_file_dfs_listener.h index 2ceaf2f41..e24552334 100644 --- a/services/distributedfiledaemon/include/ipc/i_file_dfs_listener.h +++ b/services/distributedfiledaemon/include/ipc/i_file_dfs_listener.h @@ -26,7 +26,8 @@ class IFileDfsListener : public OHOS::IRemoteBroker { public: DECLARE_INTERFACE_DESCRIPTOR(u"ohos.storage.distributedfile.filedfslistener"); - virtual void OnStatus(const std::string &networkId, int32_t status) = 0; + virtual void OnStatus(const std::string &networkId, int32_t status, + const std::string &path, int32_t type) = 0; enum { FILE_DFS_LISTENER_SUCCESS = 0, diff --git a/services/distributedfiledaemon/src/channel_manager/channel_manager.cpp b/services/distributedfiledaemon/src/channel_manager/channel_manager.cpp index 039b9f6e8..abe471b0e 100644 --- a/services/distributedfiledaemon/src/channel_manager/channel_manager.cpp +++ b/services/distributedfiledaemon/src/channel_manager/channel_manager.cpp @@ -372,7 +372,7 @@ int32_t ChannelManager::DoSendBytes(const std::int32_t socketId, const std::stri void ChannelManager::OnSocketConnected(int32_t socketId, const PeerSocketInfo &info) { - LOGI("socket %{public}d bind now", socketId); + LOGI("socket %{public}d bind now, clientNetworkId is %{public}.6s", socketId, info.networkId); if (socketId <= 0) { LOGE("invalid socket id, %{public}d", socketId); return; @@ -567,6 +567,34 @@ int32_t ChannelManager::SendRequest(const std::string &networkId, return ret; } +int32_t ChannelManager::NotifyClient(const std::string &networkId, const ControlCmd &request) +{ + LOGI("start NotifyClient, networkId: %{public}.6s", networkId.c_str()); + int32_t socketId = -1; + { + std::shared_lock readLock(serverMutex_); + if (serverNetworkSocketMap_.find(networkId) == serverNetworkSocketMap_.end()) { + LOGE("networkId not found"); + return ERR_NO_EXIST_CHANNEL; + } + socketId = serverNetworkSocketMap_[networkId]; + } + + string data; + if (!ControlCmdParser::SerializeToJson(request, data)) { + LOGE("ControlCmdParser::SerializeToJson failed."); + return ERR_DATA_INVALID; + } + + int32_t ret = DoSendBytes(socketId, data); + if (ret != E_OK) { + LOGE("DoSendBytes failed."); + return ERR_SEND_DATA_BY_SOFTBUS_FAILED; + } + + return ret; +} + } // namespace DistributedFile } // namespace Storage } // namespace OHOS \ No newline at end of file diff --git a/services/distributedfiledaemon/src/channel_manager/control_cmd_parser.cpp b/services/distributedfiledaemon/src/channel_manager/control_cmd_parser.cpp index 243ff2f4c..7cbd428b5 100644 --- a/services/distributedfiledaemon/src/channel_manager/control_cmd_parser.cpp +++ b/services/distributedfiledaemon/src/channel_manager/control_cmd_parser.cpp @@ -107,12 +107,8 @@ bool ControlCmdParser::HandleRequest(const ControlCmd &inCmd, ControlCmd &outCmd } } -bool ControlCmdParser::CheckAllowConnect(const ControlCmd &inCmd, ControlCmd &outCmd) +bool ControlCmdParser::IsLocalItDevice() { - outCmd.msgType = ControlCmdType::CMD_MSG_RESPONSE; - outCmd.msgId = inCmd.msgId; - outCmd.msgBody = "false"; - const char *syncType = "1"; const int bufferLen = 10; char paramOutBuf[bufferLen] = {0}; @@ -120,8 +116,16 @@ bool ControlCmdParser::CheckAllowConnect(const ControlCmd &inCmd, ControlCmd &ou LOGI("paramOutBuf: %{public}s, ret: %{public}d", paramOutBuf, ret); if (ret > 0 && strncmp(paramOutBuf, syncType, strlen(syncType)) == 0) { LOGI("Determining the e2e device succeeded."); - outCmd.msgBody = "true"; + return true; } + return false; +} + +bool ControlCmdParser::CheckAllowConnect(const ControlCmd &inCmd, ControlCmd &outCmd) +{ + outCmd.msgType = ControlCmdType::CMD_MSG_RESPONSE; + outCmd.msgId = inCmd.msgId; + outCmd.msgBody = IsLocalItDevice() ? "true" : "false"; return true; } @@ -154,7 +158,7 @@ bool ControlCmdParser::DisconnectByRemote(const ControlCmd &inCmd, ControlCmd &o LOGE("callback is null"); return false; } - disconnectCallback_(inCmd.msgBody); + disconnectCallback_(inCmd.networkId); return true; } diff --git a/services/distributedfiledaemon/src/channel_manager/system_notifier.cpp b/services/distributedfiledaemon/src/channel_manager/system_notifier.cpp index a4a526d88..ab18b8806 100644 --- a/services/distributedfiledaemon/src/channel_manager/system_notifier.cpp +++ b/services/distributedfiledaemon/src/channel_manager/system_notifier.cpp @@ -51,6 +51,7 @@ constexpr const char *DFS_LANGUAGE_FILEPATH_PREFIX = "/system/etc/dfs_service/re constexpr const char *DFS_LANGUAGE_FILEPATH_SUFFIX = ".json"; constexpr const char *DFS_DEFAULT_LANGUAGE = "/system/etc/dfs_service/resources/i18/en-Latn-US.json"; +constexpr const char *DFS_DEFAULT_BUTTON_NAME = "dfs_default_button_name"; constexpr const char *NOTIFICATION_TITLE = "notification_title"; constexpr const char *NOTIFICATION_TEXT = "notification_text"; constexpr const char *CAPSULE_TITLE = "capsule_title"; @@ -154,6 +155,7 @@ static Notification::NotificationLocalLiveViewButton CreateNotificationLocalLive { LOGI("CreateNotificationLocalLiveViewButton start"); Notification::NotificationLocalLiveViewButton button; + button.addSingleButtonName(DFS_DEFAULT_BUTTON_NAME); button.addSingleButtonIcon(pixelMap); return button; } @@ -350,7 +352,6 @@ int32_t SystemNotifier::CreateLocalLiveView(const std::string &networkId) request.SetCreatorUid(DFS_SERVICE_UID); request.SetContent(content); request.SetLittleIcon(notificationIconPixelMap_); - request.SetWantAgent(std::make_shared()); auto ret = Notification::NotificationHelper::PublishNotification(request); if (ret != E_OK) { @@ -381,7 +382,12 @@ int32_t SystemNotifier::DestroyNotifyByNotificationId(int32_t notificationId) } } - auto ret = Notification::NotificationHelper::CancelNotification(notificationId); + if (networkId.empty()) { + LOGE("can not find %{public}.6s in map!", networkId.c_str()); + return ERR_DATA_INVALID; + } + + int32_t ret = Notification::NotificationHelper::CancelNotification(notificationId); LOGI("DestroyNotification (id: %{public}d), result: %{public}d", notificationId, ret); ret = DisconnectByNetworkId(networkId); @@ -419,7 +425,6 @@ int32_t SystemNotifier::DisconnectByNetworkId(const std::string &networkId) { LOGI("DisconnectByNetworkId enter, networkId is %{public}.6s", networkId.c_str()); ControlCmd request; - ControlCmd response; request.msgType = CMD_ACTIVE_DISCONNECT; std::string srcNetworkId; auto result = DistributedHardware::DeviceManager::GetInstance().GetLocalDeviceNetWorkId(SERVICE_NAME, srcNetworkId); @@ -429,7 +434,7 @@ int32_t SystemNotifier::DisconnectByNetworkId(const std::string &networkId) } request.networkId = srcNetworkId; - auto ret = ChannelManager::GetInstance().SendRequest(networkId, request, response); + int32_t ret = ChannelManager::GetInstance().NotifyClient(networkId, request); LOGI("DisconnectByNetworkId end. networkId = %{public}.6s ,ret = %{public}d", networkId.c_str(), ret); return ret; } diff --git a/services/distributedfiledaemon/src/connect_count/connect_count.cpp b/services/distributedfiledaemon/src/connect_count/connect_count.cpp index eaa97a61a..d20695fd6 100644 --- a/services/distributedfiledaemon/src/connect_count/connect_count.cpp +++ b/services/distributedfiledaemon/src/connect_count/connect_count.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 @@ -62,7 +62,7 @@ void ConnectCount::RemoveAllConnect() std::lock_guard lock(connectMutex_); for (const auto &connect : connectList_) { if (connect->listener != nullptr) { - connect->listener->OnStatus(connect->networkId, ON_STATUS_OFFLINE); + connect->listener->OnStatus(connect->networkId, ON_STATUS_OFFLINE, "", 0); } } connectList_.clear(); @@ -123,7 +123,7 @@ void ConnectCount::NotifyRemoteReverseObj(const std::string &networkId, int32_t std::lock_guard lock(connectMutex_); for (const auto &connect : connectList_) { if (connect->networkId == networkId && connect->listener != nullptr) { - connect->listener->OnStatus(networkId, status); + connect->listener->OnStatus(networkId, status, "", 0); LOGI("NotifyRemoteReverseObj, networkId: %{public}s, callingTokenId: %{public}u", Utils::GetAnonyString(networkId).c_str(), connect->callingTokenId); } @@ -141,6 +141,46 @@ int32_t ConnectCount::FindCallingTokenIdForListerner(const sptr & } return FileManagement::ERR_BAD_VALUE; } + +void ConnectCount::AddFileConnect(const std::string &instanceId, const sptr &listener) +{ + LOGI("AddFileConnect instanceId: %{public}s", instanceId.c_str()); + std::lock_guard lock(fileConnectMutex_); + auto iter = fileConnectMap_.find(instanceId); + if (iter != fileConnectMap_.end()) { + LOGW("InstanceId: %{public}s has already exists, replace the listener with a new value", instanceId.c_str()); + iter->second = listener; + } else { + fileConnectMap_.emplace(instanceId, listener); + } +} + +bool ConnectCount::RmFileConnect(const std::string &instanceId) +{ + LOGI("RmFileConnect instanceId: %{public}s", instanceId.c_str()); + std::lock_guard lock(fileConnectMutex_); + auto iter = fileConnectMap_.find(instanceId); + if (iter == fileConnectMap_.end()) { + LOGE("RmFileConnect failed, instanceId: %{public}s not exists", instanceId.c_str()); + return false; + } + fileConnectMap_.erase(iter); + return true; +} + +void ConnectCount::NotifyFileStatusChange(const std::string &networkId, + int32_t status, const std::string &path, StatusType type) +{ + std::lock_guard lock(fileConnectMutex_); + for (const auto &connect : fileConnectMap_) { + if (connect.second != nullptr) { + int32_t tmpType = static_cast(type); + connect.second->OnStatus(networkId, status, path, tmpType); + LOGI("StatusChange, networkId: %{public}s, status: %{public}d, path: %{public}s, type: %{public}d", + Utils::GetAnonyString(networkId).c_str(), status, Utils::GetAnonyString(path).c_str(), tmpType); + } + } +} } // namespace DistributedFile } // namespace Storage } // namespace OHOS diff --git a/services/distributedfiledaemon/src/device/device_manager_agent.cpp b/services/distributedfiledaemon/src/device/device_manager_agent.cpp index 7c0bba179..f74591458 100644 --- a/services/distributedfiledaemon/src/device/device_manager_agent.cpp +++ b/services/distributedfiledaemon/src/device/device_manager_agent.cpp @@ -20,11 +20,13 @@ #include #include +#include "connect_count/connect_count.h" #include "device_auth.h" #include "dfs_daemon_event_dfx.h" #include "dfs_error.h" #include "dfsu_exception.h" #include "ipc/i_daemon.h" +#include "ipc_skeleton.h" #include "iremote_object.h" #include "iservice_registry.h" #include "istorage_manager.h" @@ -49,8 +51,15 @@ const int32_t MOUNT_DFS_COUNT_ONE = 1; const uint32_t MAX_ONLINE_DEVICE_SIZE = 10000; constexpr const char* PARAM_KEY_OS_TYPE = "OS_TYPE"; const std::string SAME_ACCOUNT_MARK = "const.distributed_file_only_for_same_account_test"; +constexpr const char *MOUNT_PATH = "/storage/hmdfs/"; +constexpr int32_t VALID_MOUNT_PATH_LEN = 16; } // namespace using namespace std; +MountCountInfo::MountCountInfo(std::string networkId, uint32_t callingTokenId) +{ + networkId_ = networkId; + callingCountMap_.emplace(callingTokenId, MOUNT_DFS_COUNT_ONE); +} DeviceManagerAgent::DeviceManagerAgent() : DfsuActor(this, std::numeric_limits::max()) {} @@ -224,12 +233,8 @@ void DeviceManagerAgent::OnDeviceOffline(const DistributedHardware::DmDeviceInfo } auto networkId = std::string(deviceInfo.networkId); - auto deviceId = std::string(deviceInfo.deviceId); - if (deviceId.empty()) { - deviceId = GetDeviceIdByNetworkId(networkId); - } if (!networkId.empty()) { - UMountDfsDocs(networkId, deviceId, true); + UMountDfsDocs(networkId, networkId.substr(0, VALID_MOUNT_PATH_LEN), true); } auto cmd2 = make_unique>( @@ -340,20 +345,11 @@ bool DeviceManagerAgent::MountDfsCountOnly(const std::string &deviceId) LOGI("mountDfsCount_ can not find key"); return false; } - if (itCount->second > 0) { - LOGI("[MountDfsCountOnly] deviceId %{public}s has already established a link, count %{public}d, \ - increase count by one now", Utils::GetAnonyString(deviceId).c_str(), itCount->second); - return true; - } - return false; + return true; } bool DeviceManagerAgent::UMountDfsCountOnly(const std::string &deviceId, bool needClear) { - if (deviceId.empty()) { - LOGI("deviceId empty"); - return false; - } std::lock_guard lock(mountDfsCountMutex_); auto itCount = mountDfsCount_.find(deviceId); if (itCount == mountDfsCount_.end()) { @@ -362,14 +358,17 @@ bool DeviceManagerAgent::UMountDfsCountOnly(const std::string &deviceId, bool ne } if (needClear) { LOGI("mountDfsCount_ erase"); - mountDfsCount_.erase(itCount); + itCount->second.callingCountMap_.clear(); return false; } - if (itCount->second > MOUNT_DFS_COUNT_ONE) { + auto &callingCountMap = itCount->second.callingCountMap_; + auto callingTokenId = IPCSkeleton::GetCallingTokenID(); + auto callingIter = callingCountMap.find(callingTokenId); + if (callingIter != callingCountMap.end() && callingIter->second > MOUNT_DFS_COUNT_ONE) { LOGI("[UMountDfsCountOnly] deviceId %{public}s has already established more than one link, \ count %{public}d, decrease count by one now", - Utils::GetAnonyString(deviceId).c_str(), itCount->second); - mountDfsCount_[deviceId]--; + Utils::GetAnonyString(deviceId).c_str(), callingIter->second); + --callingIter->second; return true; } LOGI("[UMountDfsCountOnly] deviceId %{public}s erase count", Utils::GetAnonyString(deviceId).c_str()); @@ -471,9 +470,10 @@ std::unordered_set DeviceManagerAgent::GetNetworkIds(uint32_t token return networkIdMap_[tokenId]; } -int32_t DeviceManagerAgent::MountDfsDocs(const std::string &networkId, const std::string &deviceId) +int32_t DeviceManagerAgent::MountDfsDocs(const std::string &networkId, + const std::string &deviceId, + const uint32_t callingTokenId) { - LOGI("MountDfsDocs start"); if (networkId.empty() || deviceId.empty()) { LOGE("NetworkId or DeviceId is empty"); return INVALID_USER_ID; @@ -481,7 +481,7 @@ int32_t DeviceManagerAgent::MountDfsDocs(const std::string &networkId, const std int32_t ret = NO_ERROR; if (MountDfsCountOnly(deviceId)) { LOGI("only count plus one, do not need mount"); - IncreaseMountDfsCount(deviceId); + IncreaseMountDfsCount(networkId, deviceId, callingTokenId); return ret; } int32_t userId = GetCurrentUserId(); @@ -499,8 +499,8 @@ int32_t DeviceManagerAgent::MountDfsDocs(const std::string &networkId, const std LOGE("MountDfsDocs fail, ret = %{public}d", ret); } else { LOGE("MountDfsDocs success, deviceId %{public}s increase count by one now", - Utils::GetAnonyString(deviceId).c_str()); - IncreaseMountDfsCount(deviceId); + Utils::GetAnonyString(deviceId).c_str()); + IncreaseMountDfsCount(networkId, deviceId, callingTokenId); } LOGI("storageMgr.MountDfsDocs end."); return ret; @@ -533,24 +533,55 @@ int32_t DeviceManagerAgent::UMountDfsDocs(const std::string &networkId, const st 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); + ConnectCount::GetInstance()->NotifyFileStatusChange(networkId, 2, + MOUNT_PATH + networkId.substr(0, VALID_MOUNT_PATH_LEN), StatusType::CONNECTION_STATUS); } LOGI("storageMgr.UMountDfsDocs end."); return ret; } -void DeviceManagerAgent::IncreaseMountDfsCount(const std::string &deviceId) +void DeviceManagerAgent::IncreaseMountDfsCount(const std::string &networkId, + const std::string &mountPath, const uint32_t callingTokenId) +{ + std::lock_guard lock(mountDfsCountMutex_); + auto iter = mountDfsCount_.find(mountPath); + if (iter == mountDfsCount_.end()) { + MountCountInfo tmpInfo(networkId, callingTokenId); + mountDfsCount_.emplace(mountPath, tmpInfo); + } else { + auto &callingCountMap = iter->second.callingCountMap_; + auto callingIter = callingCountMap.find(callingTokenId); + if (callingIter != callingCountMap.end()) { + ++callingIter->second; + LOGI("Mountpath %{public}s has already established more than one link, \ + count %{public}d, Increase count by one now", + Utils::GetAnonyString(mountPath).c_str(), callingIter->second); + } else { + callingCountMap.emplace(callingTokenId, MOUNT_DFS_COUNT_ONE); + } + } +} + +void DeviceManagerAgent::RemoveMountDfsCount(const std::string &mountPath) { std::lock_guard lock(mountDfsCountMutex_); - mountDfsCount_[deviceId]++; + auto iter = mountDfsCount_.find(mountPath); + if (iter == mountDfsCount_.end()) { + LOGE("Can not find mountPath: %{public}s", mountPath.c_str()); + return; + } + mountDfsCount_.erase(mountPath); } -void DeviceManagerAgent::RemoveMountDfsCount(const std::string &deviceId) +void DeviceManagerAgent::GetConnectedDeviceList(std::vector &deviceList) { std::lock_guard lock(mountDfsCountMutex_); - mountDfsCount_.erase(deviceId); + for (const auto &ele : mountDfsCount_) { + deviceList.emplace_back(DfsDeviceInfo(ele.second.networkId_, MOUNT_PATH + ele.first)); + } } void DeviceManagerAgent::NotifyRemoteReverseObj(const std::string &networkId, int32_t status) @@ -562,7 +593,7 @@ void DeviceManagerAgent::NotifyRemoteReverseObj(const std::string &networkId, in LOGI("get onstatusReverseProxy fail"); return; } - onstatusReverseProxy->OnStatus(networkId, status); + onstatusReverseProxy->OnStatus(networkId, status, "", 0); LOGI("NotifyRemoteReverseObj, deviceId: %{public}s", Utils::GetAnonyString(networkId).c_str()); } } @@ -851,6 +882,12 @@ void DeviceManagerAgent::UnregisterFromExternalDm() } LOGI("UnregisterFromExternalDm Succeed"); } + +std::unordered_map DeviceManagerAgent::GetAllMountInfo() +{ + std::lock_guard lock(mountDfsCountMutex_); + return mountDfsCount_; +} } // namespace DistributedFile } // namespace Storage } // namespace OHOS diff --git a/services/distributedfiledaemon/src/device/device_profile_adapter.cpp b/services/distributedfiledaemon/src/device/device_profile_adapter.cpp index 648c4ec28..8937b743b 100644 --- a/services/distributedfiledaemon/src/device/device_profile_adapter.cpp +++ b/services/distributedfiledaemon/src/device/device_profile_adapter.cpp @@ -64,29 +64,29 @@ static inline bool Str2Bool(const std::string &value) } #endif -bool DeviceProfileAdapter::IsRemoteDfsVersionLower(const std::string &remoteNetworkId, +bool DeviceProfileAdapter::IsRemoteDfsVersionLowerThanLocal(const std::string &remoteNetworkId, VersionPackageName packageName) { + LOGI("remoteDevice.networkId: %{public}.6s", remoteNetworkId.c_str()); #ifdef SUPPORT_DEVICE_PROFILE - LOGI("remoteDevice.networkId: %{public}.5s", remoteNetworkId.c_str()); DfsVersion localDfsVersion; int32_t ret = GetLocalDfsVersion(packageName, localDfsVersion); if (ret != FileManagement::ERR_OK) { LOGE("GetLocalDfsVersion failed, ret=%{public}d", ret); return false; } - return IsRemoteDfsVersionLower(remoteNetworkId, localDfsVersion, packageName); + return IsRemoteDfsVersionLowerThanGiven(remoteNetworkId, localDfsVersion, packageName); #else return false; #endif } // Comparison of version numbers later than the current version number is not supported. -bool DeviceProfileAdapter::IsRemoteDfsVersionLower(const std::string &remoteNetworkId, - const DfsVersion &thresholdDfsVersion, VersionPackageName packageName) +bool DeviceProfileAdapter::IsRemoteDfsVersionLowerThanGiven(const std::string &remoteNetworkId, + const DfsVersion &givenDfsVersion, VersionPackageName packageName) { + LOGI("remoteDevice.networkId: %{public}.6s", remoteNetworkId.c_str()); #ifdef SUPPORT_DEVICE_PROFILE - LOGI("remoteDevice.networkId: %{public}.5s", remoteNetworkId.c_str()); if (remoteNetworkId.empty()) { LOGE("remoteNetworkId is empty"); return false; @@ -97,7 +97,7 @@ bool DeviceProfileAdapter::IsRemoteDfsVersionLower(const std::string &remoteNetw LOGE("GetDfsVersionFromNetworkId failed, ret=%{public}d", ret); return false; } - return CompareDfsVersion(remoteDfsVersion, thresholdDfsVersion); + return CompareDfsVersion(remoteDfsVersion, givenDfsVersion); #else return false; #endif diff --git a/services/distributedfiledaemon/src/ipc/daemon.cpp b/services/distributedfiledaemon/src/ipc/daemon.cpp index d1443ae44..75b19880f 100644 --- a/services/distributedfiledaemon/src/ipc/daemon.cpp +++ b/services/distributedfiledaemon/src/ipc/daemon.cpp @@ -44,13 +44,13 @@ #include "iremote_object.h" #include "iservice_registry.h" #include "mountpoint/mount_manager.h" +#include "network/devsl_dispatcher.h" #include "network/softbus/softbus_handler.h" #include "network/softbus/softbus_handler_asset.h" #include "network/softbus/softbus_permission_check.h" #include "network/softbus/softbus_session_dispatcher.h" #include "network/softbus/softbus_session_listener.h" #include "network/softbus/softbus_session_pool.h" -#include "network/devsl_dispatcher.h" #include "remote_file_share.h" #include "sandbox_helper.h" #include "system_ability_definition.h" @@ -74,7 +74,6 @@ using AccessTokenKit = OHOS::Security::AccessToken::AccessTokenKit; namespace { const string FILE_MANAGER_AUTHORITY = "docs"; const string MEDIA_AUTHORITY = "media"; -const int32_t E_PERMISSION_DENIED_NAPI = 201; const int32_t E_INVAL_ARG_NAPI = 401; const int32_t E_CONNECTION_FAILED = 13900045; const int32_t E_UNMOUNT = 13600004; @@ -85,6 +84,11 @@ constexpr int32_t BLOCK_INTERVAL_SEND_FILE = 10 * 1000; constexpr int32_t DEFAULT_USER_ID = 100; constexpr int32_t VALID_MOUNT_NETWORKID_LEN = 16; constexpr uint64_t INNER_COPY_LIMIT = 1024 * 1024 * 1024; +constexpr int32_t ERR_DP_CAN_NOT_FIND = 98566199; +constexpr int32_t DEFAULT_DP_CANNOTFIND_VALUE = -1; +constexpr const char* HMDFS_FATH = "/storage/hmdfs/"; +constexpr DfsVersion FILEMANAGER_VERSION = {6, 0, 1}; +constexpr int32_t MIN_NETWORKID_LENGTH = 16; } // namespace REGISTER_SYSTEM_ABILITY_BY_ID(Daemon, FILEMANAGEMENT_DISTRIBUTED_FILE_DAEMON_SA_ID, true); @@ -175,6 +179,11 @@ void Daemon::OnAddSystemAbility(int32_t systemAbilityId, const std::string &devi } } else if (systemAbilityId == SOFTBUS_SERVER_SA_ID) { SoftBusHandlerAsset::GetInstance().CreateAssetLocalSessionServer(); + ChannelManager::GetInstance().Init(); + ControlCmdParser::RegisterDisconnectCallback([this](std::string networkId) { + LOGE("callback networkid is %{public}.6s", networkId.c_str()); + this->DisconnectByRemote(networkId); + }); } } @@ -189,6 +198,7 @@ void Daemon::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &d LOGI("OnRemoveSystemAbility common event service offline"); } else if (systemAbilityId == SOFTBUS_SERVER_SA_ID) { SoftBusHandlerAsset::GetInstance().DeleteAssetLocalSessionServer(); + ChannelManager::GetInstance().DeInit(); } } @@ -272,10 +282,17 @@ int32_t Daemon::CleanUp(const DistributedHardware::DmDeviceInfo &deviceInfo) } int32_t Daemon::ConnectionAndMount(const DistributedHardware::DmDeviceInfo &deviceInfo, - const std::string &networkId, uint32_t callingTokenId, sptr remoteReverseObj) + const std::string &networkId, + sptr remoteReverseObj) { LOGI("ConnectionAndMount start"); - int32_t ret = NO_ERROR; + int32_t ret = CheckRemoteAllowConnect(networkId); + if (ret != E_OK) { + LOGE("CheckRemoteAllowConnect failed for %{public}.6s, ret is %{public}d", networkId.c_str(), ret); + return ret; + } + + auto callingTokenId = IPCSkeleton::GetCallingTokenID(); ret = ConnectionCount(deviceInfo); if (ret != NO_ERROR) { LOGE("connection failed"); @@ -284,58 +301,64 @@ int32_t Daemon::ConnectionAndMount(const DistributedHardware::DmDeviceInfo &devi } return ret; } + ConnectCount::GetInstance()->AddConnect(callingTokenId, networkId, remoteReverseObj); if (!DfsuAccessTokenHelper::CheckCallerPermission(FILE_ACCESS_MANAGER_PERMISSION)) { LOGW("permission denied: FILE_ACCESS_MANAGER_PERMISSION"); return ret; } + std::string mountPath = networkId.substr(0, VALID_MOUNT_NETWORKID_LEN); auto deviceManager = DeviceManagerAgent::GetInstance(); - std::string deviceId = deviceManager->GetDeviceIdByNetworkId(networkId); - ret = deviceManager->MountDfsDocs(networkId, deviceId); + ret = deviceManager->MountDfsDocs(networkId, mountPath, callingTokenId); if (ret != NO_ERROR) { ConnectCount::GetInstance()->RemoveConnect(callingTokenId, networkId); LOGE("[MountDfsDocs] failed"); + return ret; } + ConnectCount::GetInstance()->NotifyFileStatusChange(networkId, E_OK, HMDFS_FATH + mountPath, + StatusType::CONNECTION_STATUS); + NotifyRemotePublishNotification(networkId); return ret; } int32_t Daemon::OpenP2PConnectionEx(const std::string &networkId, sptr remoteReverseObj) { - std::lock_guard lock(connectMutex_); - LOGI("Daemon::OpenP2PConnectionEx start, networkId %{public}s", Utils::GetAnonyString(networkId).c_str()); + LOGI("Daemon::OpenP2PConnectionEx start, networkId %{public}.6s", networkId.c_str()); if (!DfsuAccessTokenHelper::CheckCallerPermission(PERM_DISTRIBUTED_DATASYNC)) { - LOGE("[OpenP2PConnectionEx] DATASYNC permission denied"); - return E_PERMISSION_DENIED_NAPI; - } - if (dfsListenerDeathRecipient_ == nullptr) { - LOGE("Daemon::OpenP2PConnectionEx, new death recipient"); - dfsListenerDeathRecipient_ = sptr(new (std::nothrow) DfsListenerDeathRecipient()); - } - if (dfsListenerDeathRecipient_ == nullptr) { - LOGE("Daemon::OpenP2PConnectionEx, dfsListenerDeathRecipient is nullptr"); - return E_INVAL_ARG_NAPI; - } - if (remoteReverseObj == nullptr) { - LOGE("Daemon::OpenP2PConnectionEx remoteReverseObj is nullptr"); - return E_INVAL_ARG_NAPI; + LOGE("[CloseP2PConnectionEx] DATASYNC permission denied"); + return E_PERMISSION; } - remoteReverseObj->AsObject()->AddDeathRecipient(dfsListenerDeathRecipient_); - auto deviceManager = DeviceManagerAgent::GetInstance(); - if (networkId.empty() || networkId.length() >= DM_MAX_DEVICE_ID_LEN) { + + if (networkId.length() < MIN_NETWORKID_LENGTH || networkId.length() >= DM_MAX_DEVICE_ID_LEN) { LOGE("Daemon::OpenP2PConnectionEx networkId length is invalid."); return E_INVAL_ARG_NAPI; } + std::lock_guard lock(connectMutex_); + if (remoteReverseObj != nullptr) { + LOGI("Daemon::OpenP2PConnectionEx remoteReverseObj is not nullptr"); + if (dfsListenerDeathRecipient_ == nullptr) { + LOGI("Daemon::OpenP2PConnectionEx, new death recipient"); + dfsListenerDeathRecipient_ = new (std::nothrow) DfsListenerDeathRecipient(); + } + if (dfsListenerDeathRecipient_ == nullptr) { + LOGE("Daemon::OpenP2PConnectionEx failed to allocate memory for dfsListenerDeathRecipient_"); + return E_INVAL_ARG_NAPI; + } + remoteReverseObj->AsObject()->AddDeathRecipient(dfsListenerDeathRecipient_); + } + RemoveDfsDelayTask(networkId); + DistributedHardware::DmDeviceInfo deviceInfo{}; auto res = strcpy_s(deviceInfo.networkId, DM_MAX_DEVICE_ID_LEN, networkId.c_str()); if (res != NO_ERROR) { LOGE("OpenP2PConnectionEx strcpy failed, res = %{public}d", res); return E_INVAL_ARG_NAPI; } - auto callingTokenId = IPCSkeleton::GetCallingTokenID(); - RemoveDfsDelayTask(networkId); - int32_t ret = ConnectionAndMount(deviceInfo, networkId, callingTokenId, remoteReverseObj); + + int32_t ret = ConnectionAndMount(deviceInfo, networkId, remoteReverseObj); if (ret != NO_ERROR) { + LOGE(ConnectionAndMount ret is %{public}d, ret); CleanUp(deviceInfo); return E_CONNECTION_FAILED; } @@ -345,29 +368,26 @@ int32_t Daemon::OpenP2PConnectionEx(const std::string &networkId, sptr lock(connectMutex_); - LOGI("Daemon::CloseP2PConnectionEx start, networkId: %{public}s", Utils::GetAnonyString(networkId).c_str()); + LOGI("Daemon::CloseP2PConnectionEx start, networkId: %{public}.6s", networkId.c_str()); if (!DfsuAccessTokenHelper::CheckCallerPermission(PERM_DISTRIBUTED_DATASYNC)) { LOGE("[CloseP2PConnectionEx] DATASYNC permission denied"); - return E_PERMISSION_DENIED_NAPI; + return E_PERMISSION; } - auto deviceManager = DeviceManagerAgent::GetInstance(); - auto callingTokenId = IPCSkeleton::GetCallingTokenID(); - if (networkId.empty() || networkId.length() >= DM_MAX_DEVICE_ID_LEN) { - LOGE("Daemon::CloseP2PConnectionEx networkId length is invalid. len: %{public}zu", networkId.length()); + + if (networkId.length() < MIN_NETWORKID_LENGTH || networkId.length() >= DM_MAX_DEVICE_ID_LEN) { + LOGE("Daemon::CloseP2PConnectionEx networkId length is invalid. len: %{public}zu", networkId.length()); return E_INVAL_ARG_NAPI; } - std::string deviceId = deviceManager->GetDeviceIdByNetworkId(networkId); - if (deviceId.empty()) { - LOGE("fail to get deviceId"); - return E_CONNECTION_FAILED; - } + std::lock_guard lock(connectMutex_); if (DfsuAccessTokenHelper::CheckCallerPermission(FILE_ACCESS_MANAGER_PERMISSION)) { - LOGE("[UMountDfsDocs] permission ok: FILE_ACCESS_MANAGER_PERMISSION"); - int32_t ret_umount = deviceManager->UMountDfsDocs(networkId, deviceId, false); - if (ret_umount != NO_ERROR) { + LOGI("[UMountDfsDocs] permission ok: FILE_ACCESS_MANAGER_PERMISSION"); + if (DeviceManagerAgent::GetInstance()->UMountDfsDocs(networkId, networkId.substr(0, VALID_MOUNT_NETWORKID_LEN), + false) != NO_ERROR) { LOGE("[UMountDfsDocs] failed"); return E_UNMOUNT; + } else { + auto res = NotifyRemoteCancelNotification(networkId); + LOGI("NotifyRemoteCancelNotification ret is %{public}d", res); } } DistributedHardware::DmDeviceInfo deviceInfo{}; @@ -376,7 +396,7 @@ int32_t Daemon::CloseP2PConnectionEx(const std::string &networkId) LOGE("strcpy failed, res = %{public}d", res); return E_INVAL_ARG_NAPI; } - ConnectCount::GetInstance()->RemoveConnect(callingTokenId, networkId); + ConnectCount::GetInstance()->RemoveConnect(IPCSkeleton::GetCallingTokenID(), networkId); int32_t ret = CleanUp(deviceInfo); if (ret != NO_ERROR) { LOGE("Daemon::CloseP2PConnectionEx disconnection failed"); @@ -442,7 +462,7 @@ int32_t Daemon::RequestSendFile(const std::string &srcUri, } int32_t Daemon::InnerCopy(const std::string &srcUri, const std::string &dstUri, - const std::string &srcDeviceId, const sptr &listener, HmdfsInfo &info) + const std::string &networkId, const sptr &listener, HmdfsInfo &info) { if (!FileSizeUtils::IsFilePathValid(FileSizeUtils::GetRealUri(srcUri)) || !FileSizeUtils::IsFilePathValid(FileSizeUtils::GetRealUri(dstUri))) { @@ -450,7 +470,7 @@ int32_t Daemon::InnerCopy(const std::string &srcUri, const std::string &dstUri, return ERR_BAD_VALUE; } DistributedHardware::DmDeviceInfo deviceInfo; - auto res = strcpy_s(deviceInfo.networkId, DM_MAX_DEVICE_ID_LEN, srcDeviceId.c_str()); + auto res = strcpy_s(deviceInfo.networkId, DM_MAX_DEVICE_ID_LEN, networkId.c_str()); if (res != 0) { LOGE("strcpy failed, res = %{public}d", res); return ERR_BAD_VALUE; @@ -465,10 +485,12 @@ int32_t Daemon::InnerCopy(const std::string &srcUri, const std::string &dstUri, int32_t Daemon::PrepareSession(const std::string &srcUri, const std::string &dstUri, - const std::string &srcDeviceId, + const std::string &networkId, const sptr &listener, HmdfsInfo &info) { + LOGE("PrepareSession networkId: %{public}.6s", networkId.c_str()); + auto listenerCallback = iface_cast(listener); if (listenerCallback == nullptr) { LOGE("ListenerCallback is nullptr"); @@ -490,14 +512,13 @@ int32_t Daemon::PrepareSession(const std::string &srcUri, } DfsVersion remoteDfsVersion; - auto ret = DeviceProfileAdapter::GetInstance().GetDfsVersionFromNetworkId(srcDeviceId, remoteDfsVersion); + auto ret = DeviceProfileAdapter::GetInstance().GetDfsVersionFromNetworkId(networkId, remoteDfsVersion); LOGI("GetRemoteVersion: ret:%{public}d, version:%{public}s", ret, remoteDfsVersion.dump().c_str()); - if ((ret == FileManagement::ERR_OK) && (remoteDfsVersion.majorVersionNum != 0) && fileSize < INNER_COPY_LIMIT) { - return InnerCopy(srcUri, dstUri, srcDeviceId, listenerCallback, info); + return InnerCopy(srcUri, dstUri, networkId, listenerCallback, info); } - return CopyBaseOnRPC(srcUri, dstUri, srcDeviceId, listenerCallback, info); + return CopyBaseOnRPC(srcUri, dstUri, networkId, listenerCallback, info); } int32_t Daemon::CopyBaseOnRPC(const std::string &srcUri, @@ -513,7 +534,7 @@ int32_t Daemon::CopyBaseOnRPC(const std::string &srcUri, } std::string physicalPath; - auto ret = GetRealPath(srcUri, dstUri, physicalPath, info, daemon); + int32_t ret = GetRealPath(srcUri, dstUri, physicalPath, info, daemon); if (ret != E_OK) { LOGE("GetRealPath failed, ret = %{public}d", ret); return ret; @@ -524,8 +545,8 @@ int32_t Daemon::CopyBaseOnRPC(const std::string &srcUri, } auto prepareSessionBlock = std::make_shared>(BLOCK_INTERVAL_SEND_FILE, ERR_BAD_VALUE); - auto prepareSessionData = - std::make_shared(srcUri, physicalPath, info.sessionName, daemon, info, prepareSessionBlock); + auto prepareSessionData = std::make_shared( + srcUri, physicalPath, info.sessionName, daemon, info, prepareSessionBlock); auto msgEvent = AppExecFwk::InnerEvent::Get(DEAMON_EXECUTE_PREPARE_SESSION, prepareSessionData, 0); { std::lock_guard lock(eventHandlerMutex_); @@ -793,23 +814,17 @@ void Daemon::DfsListenerDeathRecipient::OnRemoteDied(const wptr & LOGE("fail to FindCallingTokenIdForListerner"); return; } - auto networkIds = ConnectCount::GetInstance()->RemoveConnect(callingTokenId); + std::vector networkIds = ConnectCount::GetInstance()->RemoveConnect(callingTokenId); if (networkIds.empty()) { LOGE("fail to get networkIdSet"); return; } - auto deviceManager = DeviceManagerAgent::GetInstance(); + for (auto it = networkIds.begin(); it != networkIds.end(); ++it) { if (it->empty()) { LOGE("[DfsListenerDeathRecipient] networkId is null"); continue; } - std::string deviceId = deviceManager->GetDeviceIdByNetworkId(*it); - if (deviceId.empty()) { - LOGE("fail to get deviceId, networkId: %{public}s", Utils::GetAnonyString(*it).c_str()); - continue; - } - deviceManager->UMountDfsDocs(*it, deviceId, false); DistributedHardware::DmDeviceInfo deviceInfo{}; auto res = strcpy_s(deviceInfo.networkId, DM_MAX_DEVICE_ID_LEN, it->c_str()); if (res != 0) { @@ -913,7 +928,11 @@ int32_t Daemon::SendDfsDelayTask(const std::string &networkId) return E_EVENT_HANDLER; } - auto executeFunc = [this, networkId] { DisconnectDevice(networkId); }; + auto executeFunc = [this, networkId] { + DisconnectDevice(networkId); + auto res = CancelControlLink(networkId); + LOGI("cancel control link ret is %{public}d", res); + }; bool isSucc = eventHandler_->PostTask(executeFunc, networkId, DEFAULT_DELAY_INTERVAL, AppExecFwk::EventHandler::Priority::IMMEDIATE); if (!isSucc) { @@ -977,40 +996,118 @@ int32_t Daemon::GetDfsUrisDirFromLocal(const std::vector &uriList, int32_t Daemon::GetDfsSwitchStatus(const std::string &networkId, int32_t &switchStatus) { - LOGI("GetDfsSwitchStatus enter. networkId: %{public}s", Utils::GetAnonyString(networkId).c_str()); - LOGI("GetDfsSwitchStatus end, switchStatus %{public}d", switchStatus); - return E_OK; + LOGI("GetDfsSwitchStatus enter."); + if (networkId.empty() || networkId.length() >= DM_MAX_DEVICE_ID_LEN) { + LOGE("GetDfsSwitchStatus networkId length is invalid."); + return E_INVAL_ARG_NAPI; + } + bool tempStatus = false; + int32_t ret = DeviceProfileAdapter::GetInstance().GetDeviceStatus(networkId, tempStatus); + if (ret == E_OK) { + switchStatus = tempStatus; + return E_OK; + } + if (ret == ERR_DP_CAN_NOT_FIND) { + LOGE("NetworkId: %{public}s not support switch", Utils::GetAnonyString(networkId).c_str()); + switchStatus = DEFAULT_DP_CANNOTFIND_VALUE; + return ret; + } + LOGE("Get switch status failed, networkId: %{pulblic}s", Utils::GetAnonyString(networkId).c_str()); + return ret; } int32_t Daemon::UpdateDfsSwitchStatus(int32_t switchStatus) { LOGI("UpdateDfsSwitchStatus enter, switch status: %{public}d", switchStatus); - return E_OK; + int32_t ret = DeviceProfileAdapter::GetInstance().PutDeviceStatus(switchStatus); + if (ret != E_OK) { + LOGE("UpdateDfsSwitchStatus failed, err: %{public}d", ret); + return ret; + } + if (switchStatus == 0) { + std::unordered_map allMountInfo = + DeviceManagerAgent::GetInstance()->GetAllMountInfo(); + for (const auto &mountInfo : allMountInfo) { + DistributedHardware::DmDeviceInfo deviceInfo{}; + std::string networkId = mountInfo.second.networkId_; + auto res = strcpy_s(deviceInfo.networkId, DM_MAX_DEVICE_ID_LEN, networkId.c_str()); + if (res != NO_ERROR) { + LOGE("strcpy failed, res = %{public}d", res); + return E_INVAL_ARG_NAPI; + } + for (const auto &ele : mountInfo.second.callingCountMap_) { + ConnectCount::GetInstance()->RemoveConnect(ele.first, networkId); + } + ret = CleanUp(deviceInfo); + if (ret != NO_ERROR) { + LOGE("Daemon::CloseP2PConnectionEx disconnection failed"); + return E_CONNECTION_FAILED; + } + } + } + return ret; } int32_t Daemon::GetConnectedDeviceList(std::vector &deviceList) { LOGI("GetConnectedDeviceList enter."); - (void)deviceList; + DeviceManagerAgent::GetInstance()->GetConnectedDeviceList(deviceList); return E_OK; } int32_t Daemon::RegisterFileDfsListener(const std::string &instanceId, const sptr &listener) { LOGI("RegisterFileDfsListener enter, instanceId: %{public}s", instanceId.c_str()); + if (instanceId.empty()) { + LOGE("InstanceId length is invalid."); + return E_INVAL_ARG_NAPI; + } + if (listener == nullptr) { + LOGE("listener is nullptr"); + return E_INVAL_ARG_NAPI; + } + ConnectCount::GetInstance()->AddFileConnect(instanceId, listener); return E_OK; } int32_t Daemon::UnregisterFileDfsListener(const std::string &instanceId) { LOGI("UnregisterFileDfsListener enter, instanceId: %{public}s", instanceId.c_str()); + if (instanceId.empty()) { + LOGE("InstanceId length is invalid."); + return E_INVAL_ARG_NAPI; + } + if (!ConnectCount::GetInstance()->RmFileConnect(instanceId)) { + LOGE("RmFileConnect failed"); + return E_INVAL_ARG_NAPI; + } return E_OK; } int32_t Daemon::IsSameAccountDevice(const std::string &networkId, bool &isSameAccount) { LOGI("IsSameAccountDevice enter, instanceId: %{public}s", Utils::GetAnonyString(networkId).c_str()); +#ifdef SUPPORT_SAME_ACCOUNT + std::vector deviceList; + DistributedHardware::DeviceManager::GetInstance().GetTrustedDeviceList(IDaemon::SERVICE_NAME, "", deviceList); + if (deviceList.size() == 0) { + LOGE("trust device list size is invalid, size=%zu", deviceList.size()); + isSameAccount = false; + return E_INVAL_ARG_NAPI; + } + for (const auto &deviceInfo : deviceList) { + if (std::string(deviceInfo.networkId) == networkId) { + isSameAccount = (deviceInfo.authForm == DistributedHardware::DmAuthForm::IDENTICAL_ACCOUNT); + return E_OK; + } + } + LOGE("The source and sink device is not same account, not support."); + isSameAccount = false; + return E_INVAL_ARG_NAPI; +#else + isSameAccount = true; return E_OK; +#endif } void Daemon::DisconnectByRemote(const string &networkId) @@ -1048,14 +1145,6 @@ int32_t Daemon::CreatControlLink(const std::string &networkId) return ERR_OK; } - DfsVersion remoteDfsVersion; - auto ret = DeviceProfileAdapter::GetInstance().GetDfsVersionFromNetworkId(networkId, remoteDfsVersion); - LOGI("GetRemoteVersion: ret:%{public}d, version:%{public}s", ret, remoteDfsVersion.dump().c_str()); - if ((ret == ERR_OK) && (remoteDfsVersion.majorVersionNum == 0)) { - LOGW("old version, not need CreatControlLink"); - return ERR_OK; - } - if (ChannelManager::GetInstance().CreateClientChannel(networkId) != ERR_OK) { LOGE("create channel failed, networkId: %{public}.6s", networkId.c_str()); return FileManagement::ERR_BAD_VALUE; @@ -1079,15 +1168,20 @@ int32_t Daemon::CancelControlLink(const std::string &networkId) int32_t Daemon::CheckRemoteAllowConnect(const std::string &networkId) { LOGI("start CheckRemoteAllowConnect"); + if (DeviceProfileAdapter::GetInstance().IsRemoteDfsVersionLowerThanGiven(networkId, FILEMANAGER_VERSION)) { + LOGW("remote verison < 6.0.1, pass check!"); + return FileManagement::ERR_OK; + } + int32_t ret = CreatControlLink(networkId); if (ret != ERR_OK) { LOGE("CheckRemoteAllowConnect ret = %{public}d", ret); return ret; } ControlCmd request; + ControlCmd response; request.msgType = ControlCmdType::CMD_CHECK_ALLOW_CONNECT; - ControlCmd response; ret = ChannelManager::GetInstance().SendRequest(networkId, request, response, true); if (ret != ERR_OK) { LOGE("SendRequest ret = %{public}d", ret); @@ -1100,6 +1194,11 @@ int32_t Daemon::CheckRemoteAllowConnect(const std::string &networkId) int32_t Daemon::NotifyRemotePublishNotification(const std::string &networkId) { LOGI("start NotifyRemotePublishNotification"); + if (DeviceProfileAdapter::GetInstance().IsRemoteDfsVersionLowerThanGiven(networkId, FILEMANAGER_VERSION)) { + LOGW("remote verison < 6.0.1, pass check!"); + return FileManagement::ERR_OK; + } + int32_t ret = CreatControlLink(networkId); if (ret != ERR_OK) { LOGE("NotifyRemotePublishNotification ret = %{public}d", ret); @@ -1128,6 +1227,11 @@ int32_t Daemon::NotifyRemotePublishNotification(const std::string &networkId) int32_t Daemon::NotifyRemoteCancelNotification(const std::string &networkId) { LOGI("start NotifyRemoteCancelNotification"); + if (DeviceProfileAdapter::GetInstance().IsRemoteDfsVersionLowerThanGiven(networkId, FILEMANAGER_VERSION)) { + LOGW("remote verison < 6.0.1, pass check!"); + return FileManagement::ERR_OK; + } + int32_t ret = CreatControlLink(networkId); if (ret != ERR_OK) { LOGE("NotifyRemoteCancelNotification ret = %{public}d", ret); diff --git a/services/distributedfiledaemon/src/ipc/daemon_stub.cpp b/services/distributedfiledaemon/src/ipc/daemon_stub.cpp index df6ac89af..2fa662dbf 100644 --- a/services/distributedfiledaemon/src/ipc/daemon_stub.cpp +++ b/services/distributedfiledaemon/src/ipc/daemon_stub.cpp @@ -186,15 +186,9 @@ int32_t DaemonStub::HandleOpenP2PConnectionEx(MessageParcel &data, MessageParcel return E_IPC_READ_FAILED; } auto remote = data.ReadRemoteObject(); - if (remote == nullptr) { - LOGE("read remoteObject failed"); - return E_IPC_READ_FAILED; - } + LOGW("is FileManager ? result is %{public}d", remote == nullptr); + auto remoteReverseObj = iface_cast(remote); - if (remoteReverseObj == nullptr) { - LOGE("remoteReverseObj is null"); - return E_INVAL_ARG; - } int32_t res = OpenP2PConnectionEx(networkId, remoteReverseObj); reply.WriteInt32(res); LOGI("DaemonStub::End OpenP2PConnection, res = %{public}d.", res); @@ -507,10 +501,6 @@ int32_t DaemonStub::HandleGetDfsSwitchStatus(MessageParcel &data, MessageParcel LOGE("HandleGetDfsSwitchStatus write res failed, res is %{public}d", res); return E_IPC_WRITE_FAILED; } - if (res != E_OK) { - LOGE("GetDfsSwitchStatus failed, res is %{public}d", res); - return E_OK; - } if (!reply.WriteInt32(switchStatus)) { LOGE("HandleGetDfsSwitchStatus write switchStatus failed, switchStatus is %{public}d", switchStatus); return E_IPC_WRITE_FAILED; @@ -549,10 +539,6 @@ int32_t DaemonStub::HandleGetConnectedDeviceList(MessageParcel &data, MessagePar LOGE("HandleGetConnectedDeviceList write res failed, res is %{public}d", res); return E_IPC_WRITE_FAILED; } - if (res != E_OK) { - LOGE("GetConnectedDeviceList failed, res is %{public}d", res); - return E_OK; - } size_t len = deviceList.size(); if (!reply.WriteInt32(len)) { LOGE("HandleGetConnectedDeviceList write length failed"); @@ -636,10 +622,6 @@ int32_t DaemonStub::HandleIsSameAccountDevice(MessageParcel &data, MessageParcel LOGE("HandleIsSameAccountDevice write res failed, res is %{public}d", res); return E_IPC_WRITE_FAILED; } - if (res != E_OK) { - LOGE("IsSameAccountDevice failed, res is %{public}d", res); - return E_OK; - } if (!reply.WriteBool(isSameAccount)) { LOGE("HandleIsSameAccountDevice write isSameAccount:%{public}d failed", isSameAccount); return E_IPC_WRITE_FAILED; diff --git a/services/distributedfiledaemon/src/ipc/file_dfs_listener_proxy.cpp b/services/distributedfiledaemon/src/ipc/file_dfs_listener_proxy.cpp index 2ce69efea..a12d272a8 100644 --- a/services/distributedfiledaemon/src/ipc/file_dfs_listener_proxy.cpp +++ b/services/distributedfiledaemon/src/ipc/file_dfs_listener_proxy.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 @@ -28,7 +28,8 @@ using namespace std; using namespace OHOS::Storage; using namespace OHOS::FileManagement; -void FileDfsListenerProxy::OnStatus(const std::string &networkId, int32_t status) +void FileDfsListenerProxy::OnStatus(const std::string &networkId, int32_t status, + const std::string &path, int32_t type) { MessageParcel data; MessageParcel reply; @@ -45,6 +46,14 @@ void FileDfsListenerProxy::OnStatus(const std::string &networkId, int32_t status LOGE("Failed to send status"); return; } + if (!data.WriteString(path)) { + LOGE("Failed to send path"); + return; + } + if (!data.WriteInt32(type)) { + LOGE("Failed to send type"); + return; + } auto remote = Remote(); if (remote == nullptr) { LOGE("remote is nullptr"); @@ -53,12 +62,10 @@ void FileDfsListenerProxy::OnStatus(const std::string &networkId, int32_t status int32_t ret = remote->SendRequest( static_cast(FileDfsListenerInterfaceCode::FILE_DFS_LISTENER_ON_STATUS), data, reply, option); if (ret != E_OK) { - LOGE("Failed to send out the request, errno:%{public}d", errno); + LOGE("Failed to send out the request, ret:%{public}d", ret); return; } - return; } - } // namespace DistributedFile } // namespace Storage } // namespace OHOS \ No newline at end of file diff --git a/services/distributedfiledaemon/src/network/network_agent_template.cpp b/services/distributedfiledaemon/src/network/network_agent_template.cpp index 792b3a0df..1f4d3a551 100644 --- a/services/distributedfiledaemon/src/network/network_agent_template.cpp +++ b/services/distributedfiledaemon/src/network/network_agent_template.cpp @@ -30,6 +30,7 @@ constexpr int32_t DEVICE_OS_TYPE_OH = 10; constexpr int OPEN_SESSSION_DELAY_TIME = 100; constexpr int32_t NOTIFY_GET_SESSION_WAITING_TIME = 2; constexpr const char* PARAM_KEY_OS_TYPE = "OS_TYPE"; +constexpr int32_t VALID_MOUNT_PATH_LEN = 16; } // namespace void NetworkAgentTemplate::Start() @@ -118,12 +119,15 @@ void NetworkAgentTemplate::DisconnectDeviceByP2P(const DeviceInfo info) sessionPool_.ReleaseSession(info.GetCid(), false); } +// dm device offline void NetworkAgentTemplate::DisconnectDeviceByP2PHmdfs(const DeviceInfo info) { 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()); + ConnectCount::GetInstance()->NotifyFileStatusChange( + info.GetCid(), ON_STATUS_OFFLINE, cid.substr(0, VALID_MOUNT_PATH_LEN), StatusType::CONNECTION_STATUS); } void NetworkAgentTemplate::CloseSessionForOneDevice(const string &cid) @@ -134,10 +138,13 @@ void NetworkAgentTemplate::CloseSessionForOneDevice(const string &cid) Recv(move(cmd)); } +// softbus offline, allConnect offline, hmdfs never has socket void NetworkAgentTemplate::CloseSessionForOneDeviceInner(std::string cid) { sessionPool_.ReleaseSession(cid, true); ConnectCount::GetInstance()->NotifyRemoteReverseObj(cid, ON_STATUS_OFFLINE); + ConnectCount::GetInstance()->NotifyFileStatusChange(cid, ON_STATUS_OFFLINE, + cid.substr(0, VALID_MOUNT_PATH_LEN), StatusType::CONNECTION_STATUS); ConnectCount::GetInstance()->RemoveConnect(cid); } @@ -179,6 +186,7 @@ void NetworkAgentTemplate::GetSessionProcessInner(NotifyParam param) } } +// hmdfs offline void NetworkAgentTemplate::GetSession(const string &cid) { std::this_thread::sleep_for(std::chrono::seconds(NOTIFY_GET_SESSION_WAITING_TIME)); @@ -192,11 +200,7 @@ void NetworkAgentTemplate::GetSession(const string &cid) sessionPool_.SinkOffline(cid); ConnectCount::GetInstance()->NotifyRemoteReverseObj(cid, ON_STATUS_OFFLINE); ConnectCount::GetInstance()->RemoveConnect(cid); - auto deviceManager = DeviceManagerAgent::GetInstance(); - auto deviceId = deviceManager->GetDeviceIdByNetworkId(cid); - if (!deviceId.empty()) { - deviceManager->UMountDfsDocs(cid, deviceId, true); - } + DeviceManagerAgent::GetInstance()->UMountDfsDocs(cid, cid.substr(0, VALID_MOUNT_PATH_LEN), true); } catch (const DfsuException &e) { LOGE("reget session failed, code: %{public}d", e.code()); } diff --git a/services/distributedfiledaemon/test/mock/channel_manager_mock.cpp b/services/distributedfiledaemon/test/mock/channel_manager_mock.cpp index 5507289ac..77a0aa6e2 100644 --- a/services/distributedfiledaemon/test/mock/channel_manager_mock.cpp +++ b/services/distributedfiledaemon/test/mock/channel_manager_mock.cpp @@ -53,6 +53,11 @@ int32_t ChannelManager::SendRequest(const std::string &networkId, return IChannelManagerMock::iChannelManagerMock->SendRequest(networkId, request, response, needResponse); } +int32_t ChannelManager::NotifyClient(const std::string &networkId, const ControlCmd &request) +{ + return IChannelManagerMock::iChannelManagerMock->NotifyClient(networkId, request); +} + } // namespace DistributedFile } // namespace Storage } // namespace OHOS \ No newline at end of file diff --git a/services/distributedfiledaemon/test/mock/device_manager_agent_mock.cpp b/services/distributedfiledaemon/test/mock/device_manager_agent_mock.cpp index 82f2fe274..985b1b1c2 100644 --- a/services/distributedfiledaemon/test/mock/device_manager_agent_mock.cpp +++ b/services/distributedfiledaemon/test/mock/device_manager_agent_mock.cpp @@ -167,12 +167,13 @@ std::unordered_set DeviceManagerAgent::GetNetworkIds(uint32_t token return IDeviceManagerAgentMock::iDeviceManagerAgentMock_->GetNetworkIds(tokenId); } -int32_t DeviceManagerAgent::MountDfsDocs(const std::string &networkId, const std::string &deviceId) +int32_t DeviceManagerAgent::MountDfsDocs(const std::string &networkId, + const std::string &deviceId, const uint32_t callingTokenId) { if (IDeviceManagerAgentMock::iDeviceManagerAgentMock_ == nullptr) { return -1; } - return IDeviceManagerAgentMock::iDeviceManagerAgentMock_->MountDfsDocs(networkId, deviceId); + return IDeviceManagerAgentMock::iDeviceManagerAgentMock_->MountDfsDocs(networkId, deviceId, callingTokenId); } int32_t DeviceManagerAgent::UMountDfsDocs(const std::string &networkId, const std::string &deviceId, bool needClear) @@ -183,12 +184,13 @@ int32_t DeviceManagerAgent::UMountDfsDocs(const std::string &networkId, const st return IDeviceManagerAgentMock::iDeviceManagerAgentMock_->UMountDfsDocs(networkId, deviceId, needClear); } -void DeviceManagerAgent::IncreaseMountDfsCount(const std::string &deviceId) +void DeviceManagerAgent::IncreaseMountDfsCount(const std::string &networkId, + const std::string &mountPath, const uint32_t callingTokenId) { return; } -void DeviceManagerAgent::RemoveMountDfsCount(const std::string &deviceId) +void DeviceManagerAgent::RemoveMountDfsCount(const std::string &mountPath) { return; } @@ -321,6 +323,11 @@ void DeviceManagerAgent::UnregisterFromExternalDm() { return; } + +std::unordered_map DeviceManagerAgent::GetAllMountInfo() +{ + return IDeviceManagerAgentMock::iDeviceManagerAgentMock_->GetAllMountInfo(); +} } // namespace DistributedFile } // namespace Storage } // namespace OHOS \ No newline at end of file diff --git a/services/distributedfiledaemon/test/mock/include/channel_manager_mock.h b/services/distributedfiledaemon/test/mock/include/channel_manager_mock.h index 8d2e27e4b..7a3f04dc0 100644 --- a/services/distributedfiledaemon/test/mock/include/channel_manager_mock.h +++ b/services/distributedfiledaemon/test/mock/include/channel_manager_mock.h @@ -35,6 +35,7 @@ public: ControlCmd &response, bool needResponse = false) = 0; virtual int32_t SendBytes(const std::string &networkId, const std::string &data) = 0; + virtual int32_t NotifyClient(const std::string &networkId, const ControlCmd &request) = 0; public: static inline std::shared_ptr iChannelManagerMock = nullptr; @@ -48,6 +49,7 @@ public: MOCK_METHOD4(SendRequest, int32_t(const std::string &networkId, ControlCmd &request, ControlCmd &response, bool needResponse)); MOCK_METHOD2(SendBytes, int32_t(const std::string &networkId, const std::string &data)); + MOCK_METHOD2(NotifyClient, int32_t(const std::string &networkId, const ControlCmd &request)); }; } // namespace DistributedFile } // namespace Storage diff --git a/services/distributedfiledaemon/test/mock/include/device_manager_agent_mock.h b/services/distributedfiledaemon/test/mock/include/device_manager_agent_mock.h index 971c26b49..9f58b421f 100644 --- a/services/distributedfiledaemon/test/mock/include/device_manager_agent_mock.h +++ b/services/distributedfiledaemon/test/mock/include/device_manager_agent_mock.h @@ -17,6 +17,7 @@ #define FILEMANAGEMENT_DFS_SERVICE_DEVICE_MANAGER_AGENT_MOCK_H #include +#include #include "device/device_manager_agent.h" namespace OHOS { @@ -34,12 +35,14 @@ public: virtual int32_t FindListenerByObject(const wptr &remote, uint32_t &tokenId, sptr &listener) = 0; virtual std::string GetDeviceIdByNetworkId(const std::string &networkId) = 0; - virtual int32_t MountDfsDocs(const std::string &networkId, const std::string &deviceId) = 0; + virtual int32_t MountDfsDocs(const std::string &networkId, + const std::string &deviceId, const uint32_t callingTokenId) = 0; virtual int32_t UMountDfsDocs(const std::string &networkId, const std::string &deviceId, bool needClear) = 0; virtual std::unordered_set GetNetworkIds(uint32_t tokenId) = 0; virtual DeviceInfo &GetLocalDeviceInfo() = 0; virtual std::vector GetRemoteDevicesInfo() = 0; virtual sptr GetDfsListener() = 0; + virtual std::unordered_map GetAllMountInfo() = 0; public: static inline std::shared_ptr iDeviceManagerAgentMock_ = nullptr; @@ -55,12 +58,14 @@ public: MOCK_METHOD3(FindListenerByObject, int32_t(const wptr &remote, uint32_t &tokenId, sptr& listener)); MOCK_METHOD1(GetDeviceIdByNetworkId, std::string(const std::string &networkId)); - MOCK_METHOD2(MountDfsDocs, int32_t(const std::string &networkId, const std::string &deviceId)); + MOCK_METHOD3(MountDfsDocs, int32_t(const std::string &networkId, + const std::string &deviceId, const uint32_t callingTokenId)); MOCK_METHOD3(UMountDfsDocs, int32_t(const std::string &networkId, const std::string &deviceId, bool needClear)); MOCK_METHOD1(GetNetworkIds, std::unordered_set(uint32_t tokenId)); MOCK_METHOD0(GetLocalDeviceInfo, DeviceInfo &()); MOCK_METHOD0(GetRemoteDevicesInfo, std::vector()); MOCK_METHOD0(GetDfsListener, sptr()); + MOCK_METHOD0(GetAllMountInfo, std::unordered_map()); }; } // namespace DistributedFile } // namespace Storage diff --git a/services/distributedfiledaemon/test/unittest/channel_manager/channel_manager_test.cpp b/services/distributedfiledaemon/test/unittest/channel_manager/channel_manager_test.cpp index 6b3686848..2b5b458c7 100644 --- a/services/distributedfiledaemon/test/unittest/channel_manager/channel_manager_test.cpp +++ b/services/distributedfiledaemon/test/unittest/channel_manager/channel_manager_test.cpp @@ -794,6 +794,122 @@ HWTEST_F(ChannelManagerTest, ChannelManagerTest_PostCallbackTask_001, TestSize.L GTEST_LOG_(INFO) << "ChannelManagerTest_PostCallbackTask_001 end"; } +/** + * @tc.name: ChannelManagerTest_NotifyClient_001 + * @tc.desc: Verify NotifyClient returns ERR_NO_EXIST_CHANNEL when networkId is not found + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(ChannelManagerTest, ChannelManagerTest_NotifyClient_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ChannelManagerTest_NotifyClient_001 start"; + + // Setup: No networkId in serverNetworkSocketMap_ + ControlCmd request; + request.msgId = 1; + request.msgType = ControlCmdType::CMD_CHECK_ALLOW_CONNECT; + + // Test: Call NotifyClient with non-existent networkId + int32_t ret = ChannelManager::GetInstance().NotifyClient("invalid_network", request); + EXPECT_EQ(ret, ERR_NO_EXIST_CHANNEL); + + GTEST_LOG_(INFO) << "ChannelManagerTest_NotifyClient_001 end"; +} + +/** + * @tc.name: ChannelManagerTest_NotifyClient_002 + * @tc.desc: Verify NotifyClient handles serialization failure + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(ChannelManagerTest, ChannelManagerTest_NotifyClient_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ChannelManagerTest_NotifyClient_002 start"; + + // Initialize ChannelManager + InitChannelManager(); + + // Setup: Add valid networkId to serverNetworkSocketMap_ + ChannelManager::GetInstance().serverNetworkSocketMap_["valid_network"] = 1; + + // Mock serialization failure + g_resSerializeToJson = false; + ControlCmd request; + request.msgId = 2; + request.msgType = ControlCmdType::CMD_CHECK_ALLOW_CONNECT; + + // Test: Call NotifyClient with serialization failure + int32_t ret = ChannelManager::GetInstance().NotifyClient("valid_network", request); + EXPECT_EQ(ret, ERR_DATA_INVALID); + + GTEST_LOG_(INFO) << "ChannelManagerTest_NotifyClient_002 end"; +} + +/** + * @tc.name: ChannelManagerTest_NotifyClient_003 + * @tc.desc: Verify NotifyClient handles DoSendBytes failure + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(ChannelManagerTest, ChannelManagerTest_NotifyClient_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ChannelManagerTest_NotifyClient_003 start"; + + // Initialize ChannelManager + InitChannelManager(); + + // Setup: Add valid networkId to serverNetworkSocketMap_ + ChannelManager::GetInstance().serverNetworkSocketMap_["valid_network"] = 1; + + // Mock successful serialization but failed send + g_resSerializeToJson = true; + EXPECT_CALL(*socketMock_, SendBytes(_, _, _)).WillOnce(Return(ERR_SEND_DATA_BY_SOFTBUS_FAILED)); + + ControlCmd request; + request.msgId = 3; + request.msgType = ControlCmdType::CMD_CHECK_ALLOW_CONNECT; + + // Test: Call NotifyClient with DoSendBytes failure + int32_t ret = ChannelManager::GetInstance().NotifyClient("valid_network", request); + EXPECT_EQ(ret, ERR_SEND_DATA_BY_SOFTBUS_FAILED); + + GTEST_LOG_(INFO) << "ChannelManagerTest_NotifyClient_003 end"; +} + +/** + * @tc.name: ChannelManagerTest_NotifyClient_004 + * @tc.desc: Verify successful NotifyClient execution + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(ChannelManagerTest, ChannelManagerTest_NotifyClient_004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ChannelManagerTest_NotifyClient_004 start"; + + // Initialize ChannelManager + InitChannelManager(); + + // Setup: Add valid networkId to serverNetworkSocketMap_ + ChannelManager::GetInstance().serverNetworkSocketMap_["valid_network"] = 1; + + // Mock successful serialization and send + g_resSerializeToJson = true; + EXPECT_CALL(*socketMock_, SendBytes(_, _, _)).WillOnce(Return(ERR_OK)); + + ControlCmd request; + request.msgId = 4; + request.msgType = ControlCmdType::CMD_CHECK_ALLOW_CONNECT; + + // Test: Call NotifyClient with successful path + int32_t ret = ChannelManager::GetInstance().NotifyClient("valid_network", request); + EXPECT_EQ(ret, ERR_OK); + + // Verify serialization was called + EXPECT_EQ(g_callSerializeToJsonTimes, 1); + + GTEST_LOG_(INFO) << "ChannelManagerTest_NotifyClient_004 end"; +} + } // namespace Test } // namespace DistributedFile } // namespace Storage diff --git a/services/distributedfiledaemon/test/unittest/channel_manager/control_cmd_parser_test.cpp b/services/distributedfiledaemon/test/unittest/channel_manager/control_cmd_parser_test.cpp index 365200ed5..685c90b5e 100644 --- a/services/distributedfiledaemon/test/unittest/channel_manager/control_cmd_parser_test.cpp +++ b/services/distributedfiledaemon/test/unittest/channel_manager/control_cmd_parser_test.cpp @@ -404,7 +404,6 @@ HWTEST_F(ControlCmdParserTest, HandleRequest_DisconnectByRemote_WithCallback, Te bool callbackCalled = false; auto callback = [&callbackCalled](std::string msg) { callbackCalled = true; - EXPECT_EQ(msg, "disconnect-msg"); }; ControlCmdParser::RegisterDisconnectCallback(callback); diff --git a/services/distributedfiledaemon/test/unittest/channel_manager/system_notifier_test.cpp b/services/distributedfiledaemon/test/unittest/channel_manager/system_notifier_test.cpp index 0c10faa50..6518f5186 100644 --- a/services/distributedfiledaemon/test/unittest/channel_manager/system_notifier_test.cpp +++ b/services/distributedfiledaemon/test/unittest/channel_manager/system_notifier_test.cpp @@ -65,6 +65,11 @@ int32_t ChannelManager::SendRequest(const std::string &networkId, return OHOS::FileManagement::ERR_OK; } +int32_t ChannelManager::NotifyClient(const std::string &networkId, const ControlCmd &request) +{ + return OHOS::FileManagement::ERR_OK; +} + namespace Test { using namespace testing; using namespace testing::ext; @@ -226,7 +231,7 @@ HWTEST_F(SystemNotifierTest, CancelNotifyByNotificationId_002, TestSize.Level1) g_cancelNotification = ERR_BAD_VALUE; auto ¬ifier = SystemNotifier::GetInstance(); int32_t ret = notifier.DestroyNotifyByNotificationId(9999); // Non-existent ID - EXPECT_EQ(ret, ERR_OK); + EXPECT_EQ(ret, FileManagement::ERR_DATA_INVALID); GTEST_LOG_(INFO) << "CancelNotifyByNotificationId_002 end"; } diff --git a/services/distributedfiledaemon/test/unittest/connect_count/connect_count_test.cpp b/services/distributedfiledaemon/test/unittest/connect_count/connect_count_test.cpp index b1079c92f..abc673508 100644 --- a/services/distributedfiledaemon/test/unittest/connect_count/connect_count_test.cpp +++ b/services/distributedfiledaemon/test/unittest/connect_count/connect_count_test.cpp @@ -32,7 +32,7 @@ using namespace OHOS::FileManagement; class MockFileDfsListener : public IFileDfsListener { public: - MOCK_METHOD2(OnStatus, void(const std::string &networkId, int32_t status)); + MOCK_METHOD4(OnStatus, void(const std::string &networkId, int32_t status, const std::string &path, int32_t type)); MOCK_METHOD0(AsObject, sptr()); }; @@ -196,7 +196,7 @@ HWTEST_F(ConnectCountTest, NotifyRemoteReverseObj_001, TestSize.Level1) // 设置 EXPECT_CALL EXPECT_CALL(*static_cast(testListener.GetRefPtr()), - OnStatus(testNetworkId, ON_STATUS_OFFLINE)) + OnStatus(testNetworkId, ON_STATUS_OFFLINE, "", 0)) .Times(1); // 仅在当前测试用例中生效 connectCount_->AddConnect(testCallingTokenId, testNetworkId, testListener); diff --git a/services/distributedfiledaemon/test/unittest/device/device_manager_agent_sup_test.cpp b/services/distributedfiledaemon/test/unittest/device/device_manager_agent_sup_test.cpp index ab2c738f6..954267803 100644 --- a/services/distributedfiledaemon/test/unittest/device/device_manager_agent_sup_test.cpp +++ b/services/distributedfiledaemon/test/unittest/device/device_manager_agent_sup_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Copyright (c) 2022-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 @@ -22,10 +22,25 @@ #include "device_manager_impl_mock.h" #include "dfs_error.h" +#include "ipc_skeleton.h" #include "mock_other_method.h" #include "mountpoint/mount_point.h" #include "network/softbus/softbus_agent.h" + +namespace { +uint32_t g_callingId = 0; +} +namespace OHOS { +#ifdef CONFIG_IPC_SINGLE +using namespace IPC_SINGLE; +#endif +uint32_t IPCSkeleton::GetCallingTokenID() +{ + return g_callingId; +} +} + namespace OHOS { namespace Storage { namespace DistributedFile { @@ -33,8 +48,6 @@ namespace Test { using namespace testing; using namespace testing::ext; using namespace std; - -const int32_t MOUNT_DFS_COUNT_ONE = 1; const int32_t INVALID_USER_ID = -1; DistributedHardware::DmDeviceInfo deviceInfo = { @@ -57,6 +70,16 @@ public: void DeviceManagerAgentSupTest::SetUpTestCase(void) { // input testsuit setup step,setup invoked before all testcases +} + +void DeviceManagerAgentSupTest::TearDownTestCase(void) +{ + // input testsuit teardown step,teardown invoked after all testcases +} + +void DeviceManagerAgentSupTest::SetUp(void) +{ + // input testcase setup step,setup invoked before each testcases otherMethodMock_ = make_shared(); DfsDeviceOtherMethodMock::otherMethod = otherMethodMock_; deviceManagerImplMock_ = make_shared(); @@ -70,25 +93,15 @@ void DeviceManagerAgentSupTest::SetUpTestCase(void) EXPECT_CALL(*deviceManagerImplMock_, GetTrustedDeviceList(_, _, _)).WillRepeatedly(Return(0)); } -void DeviceManagerAgentSupTest::TearDownTestCase(void) +void DeviceManagerAgentSupTest::TearDown(void) { - // input testsuit teardown step,teardown invoked after all testcases + // input testcase teardown step,teardown invoked after each testcases DfsDeviceOtherMethodMock::otherMethod = nullptr; otherMethodMock_ = nullptr; DeviceManagerImplMock::dfsDeviceManagerImpl = nullptr; deviceManagerImplMock_ = nullptr; } -void DeviceManagerAgentSupTest::SetUp(void) -{ - // input testcase setup step,setup invoked before each testcases -} - -void DeviceManagerAgentSupTest::TearDown(void) -{ - // input testcase teardown step,teardown invoked after each testcases -} - /** * @tc.name: DeviceManagerAgentTest_MountDfsCountOnly_0100 * @tc.desc: Verify the MountDfsCountOnly function. @@ -103,13 +116,10 @@ HWTEST_F(DeviceManagerAgentSupTest, DeviceManagerAgentTest_MountDfsCountOnly_010 EXPECT_EQ(flag, false); flag = testPtr->MountDfsCountOnly("test"); EXPECT_EQ(flag, false); - testPtr->mountDfsCount_["test"] = 1; + MountCountInfo tmpInfo("test", 0); + testPtr->mountDfsCount_.emplace("test", tmpInfo); flag = testPtr->MountDfsCountOnly("test"); EXPECT_EQ(flag, true); - testPtr->mountDfsCount_["test"] = -3; - flag = testPtr->MountDfsCountOnly("test"); - EXPECT_EQ(flag, false); - testPtr->mountDfsCount_.erase("test"); GTEST_LOG_(INFO) << "DeviceManagerAgentTest_MountDfsCountOnly_0100 end"; } @@ -123,31 +133,25 @@ HWTEST_F(DeviceManagerAgentSupTest, DeviceManagerAgentTest_UMountDfsCountOnly_01 { GTEST_LOG_(INFO) << "DeviceManagerAgentTest_UMountDfsCountOnly_0100 start"; auto testPtr = DeviceManagerAgent::GetInstance(); - bool flag = testPtr->UMountDfsCountOnly("", true); - EXPECT_EQ(flag, false); - flag = testPtr->UMountDfsCountOnly("test", true); - EXPECT_EQ(flag, true); + // map can not find + EXPECT_EQ(testPtr->UMountDfsCountOnly("", true), true); - testPtr->mountDfsCount_["test"] = MOUNT_DFS_COUNT_ONE + 1; - flag = testPtr->UMountDfsCountOnly("test", true); - EXPECT_EQ(flag, false); - EXPECT_EQ(testPtr->mountDfsCount_["test"], 0); + // map find and needclear is true + MountCountInfo info1("networkId", 1); + testPtr->mountDfsCount_.emplace("test", info1); + EXPECT_EQ(testPtr->UMountDfsCountOnly("test", false), false); - testPtr->mountDfsCount_["test"] = MOUNT_DFS_COUNT_ONE + 1; - flag = testPtr->UMountDfsCountOnly("test", false); - EXPECT_EQ(flag, true); - EXPECT_EQ(testPtr->mountDfsCount_["test"], MOUNT_DFS_COUNT_ONE); + // map find & needclear is false & countMap can find + testPtr->mountDfsCount_.emplace("test", info1); + testPtr->mountDfsCount_.find("test")->second.callingCountMap_.emplace(1, 2); + g_callingId = 1; + EXPECT_EQ(testPtr->UMountDfsCountOnly("test", false), true); - flag = testPtr->UMountDfsCountOnly("test", false); - EXPECT_EQ(flag, false); + // map find & needclear is false & countMap can not find + testPtr->mountDfsCount_.emplace("test", info1); + g_callingId = 2; + EXPECT_EQ(testPtr->UMountDfsCountOnly("test", false), false); - auto itCount = testPtr->mountDfsCount_.find("test"); - if (itCount == testPtr->mountDfsCount_.end()) { - EXPECT_TRUE(false); - } else { - EXPECT_TRUE(true); - } - testPtr->mountDfsCount_.erase("test"); GTEST_LOG_(INFO) << "DeviceManagerAgentTest_UMountDfsCountOnly_0100 end"; } @@ -287,17 +291,15 @@ HWTEST_F(DeviceManagerAgentSupTest, DeviceManagerAgentTest_MountDfsDocs_0100, Te { GTEST_LOG_(INFO) << "DeviceManagerAgentTest_MountDfsDocs_0100 start"; auto testPtr = DeviceManagerAgent::GetInstance(); - constexpr int32_t testCount = 1; - testPtr->MountDfsDocs("", ""); - testPtr->MountDfsDocs("test", ""); - testPtr->mountDfsCount_["deviceId"] = testCount; - testPtr->MountDfsDocs("test", "deviceId"); - EXPECT_EQ(testPtr->mountDfsCount_["deviceId"], testCount + 1); - - testPtr->mountDfsCount_["deviceId"] = 0; - EXPECT_CALL(*otherMethodMock_, QueryActiveOsAccountIds(_)).WillOnce(Return(INVALID_USER_ID)); - testPtr->MountDfsDocs("test", "deviceId"); - EXPECT_EQ(testPtr->mountDfsCount_["deviceId"], 0); + uint32_t tokenId = 1; + + // networkId or deviceId is invalid + EXPECT_EQ(testPtr->MountDfsDocs("", "a", tokenId), INVALID_USER_ID); + EXPECT_EQ(testPtr->MountDfsDocs("a", "", tokenId), INVALID_USER_ID); + + // test mountDfsCountOnly false + EXPECT_NE(testPtr->MountDfsDocs("a", "a", tokenId), NO_ERROR); + GTEST_LOG_(INFO) << "DeviceManagerAgentTest_MountDfsDocs_0100 end"; } @@ -311,20 +313,14 @@ HWTEST_F(DeviceManagerAgentSupTest, DeviceManagerAgentTest_UMountDfsDocs_0100, T { GTEST_LOG_(INFO) << "DeviceManagerAgentTest_UMountDfsDocs_0100 start"; auto testPtr = DeviceManagerAgent::GetInstance(); - testPtr->UMountDfsDocs("", "", false); - testPtr->UMountDfsDocs("test", "", false); - testPtr->mountDfsCount_["deviceId"] = MOUNT_DFS_COUNT_ONE + 1; - testPtr->UMountDfsDocs("test", "deviceId", false); - EXPECT_EQ(testPtr->mountDfsCount_["deviceId"], MOUNT_DFS_COUNT_ONE); - - EXPECT_CALL(*otherMethodMock_, QueryActiveOsAccountIds(_)).WillOnce(Return(INVALID_USER_ID)); - testPtr->UMountDfsDocs("test", "deviceId", true); - auto it = testPtr->mountDfsCount_.find("deviceId"); - if (it != testPtr->mountDfsCount_.end()) { - EXPECT_TRUE(false); - } else { - EXPECT_TRUE(true); - } + + // networkId or deviceId is invalid + EXPECT_EQ(testPtr->UMountDfsDocs("", "a", true), INVALID_USER_ID); + EXPECT_EQ(testPtr->UMountDfsDocs("a", "", true), INVALID_USER_ID); + + // networkId or deviceId is valid + EXPECT_EQ(testPtr->UMountDfsDocs("a", "a", true), NO_ERROR); + GTEST_LOG_(INFO) << "DeviceManagerAgentTest_UMountDfsDocs_0100 end"; } @@ -415,6 +411,221 @@ HWTEST_F(DeviceManagerAgentSupTest, DeviceManagerAgentTest_IsSupportedDevice_030 EXPECT_EQ(testPtr->IsSupportedDevice(testInfo), FileManagement::ERR_OK); GTEST_LOG_(INFO) << "DeviceManagerAgentTest_IsSupportedDevice_0300 end"; } + +/** + * @tc.name: DeviceManagerAgentTest_IncreaseMountDfsCount_Basic_0100 + * @tc.desc: Verify the basic functionality of IncreaseMountDfsCount function. + * @tc.type: FUNC + * @tc.require: SR000H0387 + */ +HWTEST_F(DeviceManagerAgentSupTest, DeviceManagerAgentTest_IncreaseMountDfsCount_Basic_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DeviceManagerAgentTest_IncreaseMountDfsCount_Basic_0100 start"; + auto testPtr = DeviceManagerAgent::GetInstance(); + + const std::string networkId = "test_network_id"; + const std::string mountPath = "/test/mount/path"; + const uint32_t callingTokenId = 1001; + + // 测试场景1: 首次为某个mountPath增加计数(map中不存在) + testPtr->IncreaseMountDfsCount(networkId, mountPath, callingTokenId); + + // 验证结果 + auto iter = testPtr->mountDfsCount_.find(mountPath); + ASSERT_NE(iter, testPtr->mountDfsCount_.end()); + EXPECT_EQ(iter->second.networkId_, networkId); + + auto &callingCountMap = iter->second.callingCountMap_; + auto callingIter = callingCountMap.find(callingTokenId); + ASSERT_NE(callingIter, callingCountMap.end()); + EXPECT_EQ(callingIter->second, 1); + + // 清理测试数据 + testPtr->mountDfsCount_.clear(); + GTEST_LOG_(INFO) << "DeviceManagerAgentTest_IncreaseMountDfsCount_Basic_0100 end"; +} + +/** + * @tc.name: DeviceManagerAgentTest_IncreaseMountDfsCount_SameToken_0200 + * @tc.desc: Verify IncreaseMountDfsCount with same callingTokenId multiple times. + * @tc.type: FUNC + * @tc.require: SR000H0387 + */ +HWTEST_F(DeviceManagerAgentSupTest, DeviceManagerAgentTest_IncreaseMountDfsCount_SameToken_0200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DeviceManagerAgentTest_IncreaseMountDfsCount_SameToken_0200 start"; + auto testPtr = DeviceManagerAgent::GetInstance(); + + const std::string networkId = "test_network_id"; + const std::string mountPath = "/test/mount/path"; + const uint32_t callingTokenId = 1001; + + // 第一次增加 + testPtr->IncreaseMountDfsCount(networkId, mountPath, callingTokenId); + + // 第二次增加(同一个callingTokenId) + testPtr->IncreaseMountDfsCount(networkId, mountPath, callingTokenId); + + // 验证计数增加 + auto iter = testPtr->mountDfsCount_.find(mountPath); + ASSERT_NE(iter, testPtr->mountDfsCount_.end()); + + auto &callingCountMap = iter->second.callingCountMap_; + auto callingIter = callingCountMap.find(callingTokenId); + ASSERT_NE(callingIter, callingCountMap.end()); + EXPECT_EQ(callingIter->second, 2); + + // 清理测试数据 + testPtr->mountDfsCount_.clear(); + GTEST_LOG_(INFO) << "DeviceManagerAgentTest_IncreaseMountDfsCount_SameToken_0200 end"; +} + +/** + * @tc.name: DeviceManagerAgentTest_IncreaseMountDfsCount_DifferentToken_0300 + * @tc.desc: Verify IncreaseMountDfsCount with different callingTokenIds. + * @tc.type: FUNC + * @tc.require: SR000H0387 + */ +HWTEST_F(DeviceManagerAgentSupTest, DeviceManagerAgentTest_IncreaseMountDfsCount_DifferentToken_0300, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DeviceManagerAgentTest_IncreaseMountDfsCount_DifferentToken_0300 start"; + auto testPtr = DeviceManagerAgent::GetInstance(); + + const std::string networkId = "test_network_id"; + const std::string mountPath = "/test/mount/path"; + const uint32_t callingTokenId = 1001; + const uint32_t anotherCallingTokenId = 1002; + + // 为第一个token增加两次 + testPtr->IncreaseMountDfsCount(networkId, mountPath, callingTokenId); + testPtr->IncreaseMountDfsCount(networkId, mountPath, callingTokenId); + + // 为第二个token增加一次 + testPtr->IncreaseMountDfsCount(networkId, mountPath, anotherCallingTokenId); + + // 验证新的token被添加 + auto iter = testPtr->mountDfsCount_.find(mountPath); + ASSERT_NE(iter, testPtr->mountDfsCount_.end()); + + auto &callingCountMap = iter->second.callingCountMap_; + + // 验证第二个token + auto callingIter = callingCountMap.find(anotherCallingTokenId); + ASSERT_NE(callingIter, callingCountMap.end()); + EXPECT_EQ(callingIter->second, 1); + + // 验证第一个token计数不变 + callingIter = callingCountMap.find(callingTokenId); + ASSERT_NE(callingIter, callingCountMap.end()); + EXPECT_EQ(callingIter->second, 2); + + // 清理测试数据 + testPtr->mountDfsCount_.clear(); + GTEST_LOG_(INFO) << "DeviceManagerAgentTest_IncreaseMountDfsCount_DifferentToken_0300 end"; +} + +/** + * @tc.name: DeviceManagerAgentTest_RemoveMountDfsCount_0400 + * @tc.desc: Verify the RemoveMountDfsCount function. + * @tc.type: FUNC + * @tc.require: SR000H0387 + */ +HWTEST_F(DeviceManagerAgentSupTest, DeviceManagerAgentTest_RemoveMountDfsCount_0400, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DeviceManagerAgentTest_RemoveMountDfsCount_0400 start"; + auto testPtr = DeviceManagerAgent::GetInstance(); + + const std::string networkId = "test_network_id"; + const std::string mountPath = "/test/mount/path"; + const uint32_t callingTokenId = 1001; + + // 先增加计数 + testPtr->IncreaseMountDfsCount(networkId, mountPath, callingTokenId); + + // 移除存在的mountPath + testPtr->RemoveMountDfsCount(mountPath); + + // 验证mountPath已被移除 + auto iter = testPtr->mountDfsCount_.find(mountPath); + EXPECT_EQ(iter, testPtr->mountDfsCount_.end()); + + GTEST_LOG_(INFO) << "DeviceManagerAgentTest_RemoveMountDfsCount_0400 end"; +} + +/** + * @tc.name: DeviceManagerAgentTest_RemoveMountDfsCount_NonExistent_0500 + * @tc.desc: Verify RemoveMountDfsCount with non-existent mountPath. + * @tc.type: FUNC + * @tc.require: SR000H0387 + */ +HWTEST_F(DeviceManagerAgentSupTest, DeviceManagerAgentTest_RemoveMountDfsCount_NonExistent_0500, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DeviceManagerAgentTest_RemoveMountDfsCount_NonExistent_0500 start"; + auto testPtr = DeviceManagerAgent::GetInstance(); + + const std::string nonExistentPath = "/non/existent/path"; + + // 移除不存在的mountPath(错误路径) + testPtr->RemoveMountDfsCount(nonExistentPath); + + // 验证map状态不变 + auto iter = testPtr->mountDfsCount_.find(nonExistentPath); + EXPECT_EQ(iter, testPtr->mountDfsCount_.end()); + + GTEST_LOG_(INFO) << "DeviceManagerAgentTest_RemoveMountDfsCount_NonExistent_0500 end"; +} + +/** + * @tc.name: DeviceManagerAgentTest_IncreaseMountDfsCount_Concurrent_0600 + * @tc.desc: Verify the IncreaseMountDfsCount function with concurrent access. + * @tc.type: FUNC + * @tc.require: SR000H0387 + */ +HWTEST_F(DeviceManagerAgentSupTest, DeviceManagerAgentTest_IncreaseMountDfsCount_Concurrent_0600, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DeviceManagerAgentTest_IncreaseMountDfsCount_Concurrent_0600 start"; + auto testPtr = DeviceManagerAgent::GetInstance(); + + const std::string mountPath = "/test/mount/path"; + const uint32_t callingTokenId = 1001; + const int threadCount = 5; + const int operationsPerThread = 100; + + std::vector threads; + + // 启动多个线程并发增加计数 + for (int i = 0; i < threadCount; ++i) { + threads.emplace_back([&, i]() { + for (int j = 0; j < operationsPerThread; ++j) { + testPtr->IncreaseMountDfsCount("network_" + std::to_string(i), + mountPath + std::to_string(i), + callingTokenId + i); + } + }); + } + + // 等待所有线程完成 + for (auto &thread : threads) { + thread.join(); + } + + // 验证结果:每个mountPath都应该有正确的计数 + for (int i = 0; i < threadCount; ++i) { + std::string currentPath = mountPath + std::to_string(i); + auto iter = testPtr->mountDfsCount_.find(currentPath); + ASSERT_NE(iter, testPtr->mountDfsCount_.end()); + + auto &callingCountMap = iter->second.callingCountMap_; + auto callingIter = callingCountMap.find(callingTokenId + i); + ASSERT_NE(callingIter, callingCountMap.end()); + EXPECT_EQ(callingIter->second, operationsPerThread); + } + + // 清理测试数据 + testPtr->mountDfsCount_.clear(); + GTEST_LOG_(INFO) << "DeviceManagerAgentTest_IncreaseMountDfsCount_Concurrent_0600 end"; +} + } // namespace Test } // namespace DistributedFile } // namespace Storage diff --git a/services/distributedfiledaemon/test/unittest/device/device_profile_adapter/device_profile_adapter_test.cpp b/services/distributedfiledaemon/test/unittest/device/device_profile_adapter/device_profile_adapter_test.cpp index 114485766..3bebdc702 100644 --- a/services/distributedfiledaemon/test/unittest/device/device_profile_adapter/device_profile_adapter_test.cpp +++ b/services/distributedfiledaemon/test/unittest/device/device_profile_adapter/device_profile_adapter_test.cpp @@ -102,53 +102,53 @@ void DeviceProfileAdapterTest::TearDown(void) } /** - * @tc.name: DeviceProfileAdapterTest_IsRemoteDfsVersionLower_001 + * @tc.name: DeviceProfileAdapterTest_IsRemoteDfsVersionLowerThanLocal_001 * @tc.desc: verify PublishSA. * @tc.type: FUNC * @tc.require: I7TDJK */ -HWTEST_F(DeviceProfileAdapterTest, DeviceProfileAdapterTest_IsRemoteDfsVersionLower_001, TestSize.Level1) +HWTEST_F(DeviceProfileAdapterTest, DeviceProfileAdapterTest_IsRemoteDfsVersionLowerThanLocal_001, TestSize.Level1) { - GTEST_LOG_(INFO) << "DeviceProfileAdapterTest_IsRemoteDfsVersionLower_001 begin"; + GTEST_LOG_(INFO) << "DeviceProfileAdapterTest_IsRemoteDfsVersionLowerThanLocal_001 begin"; g_GetLocalDeviceInfo = ERR_BAD_VALUE; - auto ret = DeviceProfileAdapter::GetInstance().IsRemoteDfsVersionLower(""); + auto ret = DeviceProfileAdapter::GetInstance().IsRemoteDfsVersionLowerThanLocal(""); EXPECT_EQ(ret, false); g_GetLocalDeviceInfo = FileManagement::ERR_OK; g_GetUdidByNetworkId = FileManagement::ERR_OK; g_GetCharacteristicProfile = FileManagement::ERR_OK; - ret = DeviceProfileAdapter::GetInstance().IsRemoteDfsVersionLower(""); + ret = DeviceProfileAdapter::GetInstance().IsRemoteDfsVersionLowerThanLocal(""); EXPECT_EQ(ret, false); - GTEST_LOG_(INFO) << "DeviceProfileAdapterTest_IsRemoteDfsVersionLower_001 end"; + GTEST_LOG_(INFO) << "DeviceProfileAdapterTest_IsRemoteDfsVersionLowerThanLocal_001 end"; } /** - * @tc.name: DeviceProfileAdapterTest_IsRemoteDfsVersionLower_002 + * @tc.name: DeviceProfileAdapterTest_IsRemoteDfsVersionLowerThanGiven_001 * @tc.desc: verify PublishSA. * @tc.type: FUNC * @tc.require: I7TDJK */ -HWTEST_F(DeviceProfileAdapterTest, DeviceProfileAdapterTest_IsRemoteDfsVersionLower_002, TestSize.Level1) +HWTEST_F(DeviceProfileAdapterTest, DeviceProfileAdapterTest_IsRemoteDfsVersionLowerThanGiven_001, TestSize.Level1) { - GTEST_LOG_(INFO) << "DeviceProfileAdapterTest_IsRemoteDfsVersionLower_002 begin"; + GTEST_LOG_(INFO) << "DeviceProfileAdapterTest_IsRemoteDfsVersionLowerThanGiven_001 begin"; - auto ret = DeviceProfileAdapter::GetInstance().IsRemoteDfsVersionLower("", {0, 0, 0}); + auto ret = DeviceProfileAdapter::GetInstance().IsRemoteDfsVersionLowerThanGiven("", {0, 0, 0}); EXPECT_EQ(ret, false); g_GetUdidByNetworkId = -1; std::string remoteNetworkId = "remoteTest"; - ret = DeviceProfileAdapter::GetInstance().IsRemoteDfsVersionLower(remoteNetworkId, {0, 0, 0}); + ret = DeviceProfileAdapter::GetInstance().IsRemoteDfsVersionLowerThanGiven(remoteNetworkId, {0, 0, 0}); EXPECT_EQ(ret, false); g_GetUdidByNetworkId = FileManagement::ERR_OK; g_GetCharacteristicProfile = FileManagement::ERR_OK; DfsVersion thresholdDfsVersion = {99, 99, 99}; - ret = DeviceProfileAdapter::GetInstance().IsRemoteDfsVersionLower(remoteNetworkId, thresholdDfsVersion); + ret = DeviceProfileAdapter::GetInstance().IsRemoteDfsVersionLowerThanGiven(remoteNetworkId, thresholdDfsVersion); EXPECT_EQ(ret, true); - GTEST_LOG_(INFO) << "DeviceProfileAdapterTest_IsRemoteDfsVersionLower_002 end"; + GTEST_LOG_(INFO) << "DeviceProfileAdapterTest_IsRemoteDfsVersionLowerThanGiven_001 end"; } /** diff --git a/services/distributedfiledaemon/test/unittest/ipc/daemon/BUILD.gn b/services/distributedfiledaemon/test/unittest/ipc/daemon/BUILD.gn index b2b582d6b..be61d6118 100644 --- a/services/distributedfiledaemon/test/unittest/ipc/daemon/BUILD.gn +++ b/services/distributedfiledaemon/test/unittest/ipc/daemon/BUILD.gn @@ -24,6 +24,7 @@ config("module_private_config") { "${distributedfile_path}/test", "${services_path}/distributedfiledaemon/include", "${services_path}/distributedfiledaemon/include/ipc", + "${services_path}/distributedfiledaemon/include/channel_manager", ] } @@ -83,6 +84,7 @@ ohos_unittest("daemon_test") { "dataclassification:data_transit_mgr", "device_auth:deviceauth_sdk", "device_manager:devicemanagersdk", + "distributed_notification_service:ans_innerkits", "dsoftbus:softbus_client", "eventhandler:libeventhandler", "googletest:gmock_main", diff --git a/services/distributedfiledaemon/test/unittest/ipc/daemon/daemon_test.cpp b/services/distributedfiledaemon/test/unittest/ipc/daemon/daemon_test.cpp index 85fd35d67..8ea0a091a 100644 --- a/services/distributedfiledaemon/test/unittest/ipc/daemon/daemon_test.cpp +++ b/services/distributedfiledaemon/test/unittest/ipc/daemon/daemon_test.cpp @@ -64,17 +64,20 @@ bool g_subscribeCommonEvent; bool g_unSubscribeCommonEvent; int32_t g_getDfsVersionFromNetworkId = 0; OHOS::Storage::DistributedFile::DfsVersion g_dfsVersion; +bool g_isRemoteDfsVersionLowerThanGiven = false; +int32_t g_getDeviceStatus = 0; +int32_t g_putDeviceStatus = 0; } // namespace namespace { const std::string FILE_MANAGER_AUTHORITY = "docs"; const std::string MEDIA_AUTHORITY = "media"; -const int32_t E_PERMISSION_DENIED_NAPI = 201; const int32_t E_INVAL_ARG_NAPI = 401; const int32_t E_CONNECTION_FAILED = 13900045; -const int32_t E_UNMOUNT = 13600004; const std::string NETWORKID_ONE = "testNetWork1"; const std::string NETWORKID_TWO = "testNetWork2"; +OHOS::DistributedHardware::DmDeviceInfo deviceInfo; +constexpr int32_t ERR_DP_CAN_NOT_FIND = 98566199; } // namespace namespace OHOS::Storage::DistributedFile { @@ -94,6 +97,24 @@ int32_t DeviceProfileAdapter::GetDfsVersionFromNetworkId(const std::string &netw dfsVersion = g_dfsVersion; return g_getDfsVersionFromNetworkId; } + +int32_t DeviceProfileAdapter::GetDeviceStatus(const std::string &networkId, bool &status) +{ + return g_getDeviceStatus; +} + +bool DeviceProfileAdapter::IsRemoteDfsVersionLowerThanGiven( + const std::string &remoteNetworkId, + const DfsVersion &thresholdDfsVersion, + VersionPackageName packageName) +{ + return g_isRemoteDfsVersionLowerThanGiven; +} + +int32_t DeviceProfileAdapter::PutDeviceStatus(bool status) +{ + return g_putDeviceStatus; +} } // namespace OHOS::Storage::DistributedFile namespace OHOS::FileManagement { @@ -152,15 +173,6 @@ DeviceManager &DeviceManager::GetInstance() } // namespace DistributedHardware } // namespace OHOS -OHOS::DistributedHardware::DmDeviceInfo deviceInfo = { - .deviceId = "testdevid", - .deviceName = "testdevname", - .deviceTypeId = 1, - .networkId = "testNetWork1", - .authForm = OHOS::DistributedHardware::DmAuthForm::IDENTICAL_ACCOUNT, - .extraData = "{\"OS_TYPE\":10}", -}; - namespace OHOS { #ifdef CONFIG_IPC_SINGLE using namespace IPC_SINGLE; @@ -234,7 +246,7 @@ public: class FileDfsListenerMock : public IRemoteStub { public: - MOCK_METHOD2(OnStatus, void(const std::string &networkId, int32_t status)); + MOCK_METHOD4(OnStatus, void(const std::string &networkId, int32_t status, const std::string &path, int32_t type)); }; void DaemonTest::SetUpTestCase(void) @@ -268,8 +280,6 @@ void DaemonTest::SetUpTestCase(void) } std::ofstream file(path + "/docs/1.txt"); std::ofstream file1(path + "/docs/1@.txt"); - g_getDfsVersionFromNetworkId = 0; - g_dfsVersion = {0, 0, 0}; } void DaemonTest::TearDownTestCase(void) @@ -307,6 +317,19 @@ void DaemonTest::SetUp(void) bool runOnCreate = true; daemon_ = new (std::nothrow) Daemon(saID, runOnCreate); ASSERT_TRUE(daemon_ != nullptr) << "daemon_ assert failed!"; + g_getDfsVersionFromNetworkId = 0; + g_dfsVersion = {0, 0, 0}; + g_isRemoteDfsVersionLowerThanGiven = false; + g_getDeviceStatus = 0; + g_putDeviceStatus = 0; + deviceInfo = { + .deviceId = "testdevid", + .deviceName = "testdevname", + .deviceTypeId = 1, + .networkId = "testNetWork1", + .authForm = OHOS::DistributedHardware::DmAuthForm::IDENTICAL_ACCOUNT, + .extraData = "{\"OS_TYPE\":10}", + }; } void DaemonTest::TearDown(void) @@ -592,29 +615,28 @@ HWTEST_F(DaemonTest, DaemonTest_CleanUp_001, TestSize.Level1) HWTEST_F(DaemonTest, DaemonTest_ConnectionAndMount_001, TestSize.Level1) { GTEST_LOG_(INFO) << "DaemonTest_ConnectionAndMount_001 begin"; - ASSERT_NE(daemon_, nullptr); DistributedHardware::DmDeviceInfo deviceInfo = {.networkId = "test"}; sptr remoteReverseObj = nullptr; ConnectCount::GetInstance()->RemoveAllConnect(); EXPECT_CALL(*deviceManagerAgentMock_, OnDeviceP2POnline(_)).WillOnce(Return(ERR_BAD_VALUE)); - EXPECT_EQ(daemon_->ConnectionAndMount(deviceInfo, "test", 100, remoteReverseObj), ERR_BAD_VALUE); + EXPECT_EQ(daemon_->ConnectionAndMount(deviceInfo, "test", remoteReverseObj), ERR_BAD_VALUE); EXPECT_CALL(*deviceManagerAgentMock_, OnDeviceP2POnline(_)).WillOnce(Return(E_OK)); EXPECT_CALL(*connectionDetectorMock_, RepeatGetConnectionStatus(_, _)).WillOnce(Return(E_OK)); g_checkCallerPermission = false; - EXPECT_EQ(daemon_->ConnectionAndMount(deviceInfo, "test", 100, remoteReverseObj), E_OK); + EXPECT_EQ(daemon_->ConnectionAndMount(deviceInfo, "test", remoteReverseObj), E_OK); g_checkCallerPermission = true; EXPECT_CALL(*deviceManagerAgentMock_, GetDeviceIdByNetworkId(_)).WillOnce(Return("test")); - EXPECT_CALL(*deviceManagerAgentMock_, MountDfsDocs(_, _)).WillOnce(Return(ERR_BAD_VALUE)); + EXPECT_CALL(*deviceManagerAgentMock_, MountDfsDocs(_, _, _)).WillOnce(Return(ERR_BAD_VALUE)); EXPECT_CALL(*connectionDetectorMock_, RepeatGetConnectionStatus(_, _)).WillOnce(Return(E_OK)); - EXPECT_EQ(daemon_->ConnectionAndMount(deviceInfo, "test", 100, remoteReverseObj), ERR_BAD_VALUE); + EXPECT_EQ(daemon_->ConnectionAndMount(deviceInfo, "test", remoteReverseObj), ERR_BAD_VALUE); EXPECT_CALL(*deviceManagerAgentMock_, OnDeviceP2POnline(_)).WillRepeatedly(Return(E_OK)); EXPECT_CALL(*connectionDetectorMock_, RepeatGetConnectionStatus(_, _)).WillRepeatedly(Return(E_OK)); EXPECT_CALL(*deviceManagerAgentMock_, GetDeviceIdByNetworkId(_)).WillOnce(Return("test")); - EXPECT_CALL(*deviceManagerAgentMock_, MountDfsDocs(_, _)).WillOnce(Return(E_OK)); - EXPECT_EQ(daemon_->ConnectionAndMount(deviceInfo, "test", 100, remoteReverseObj), E_OK); + EXPECT_CALL(*deviceManagerAgentMock_, MountDfsDocs(_, _, _)).WillOnce(Return(E_OK)); + EXPECT_EQ(daemon_->ConnectionAndMount(deviceInfo, "test", remoteReverseObj), E_OK); GTEST_LOG_(INFO) << "DaemonTest_ConnectionAndMount_001 end"; } @@ -627,16 +649,21 @@ HWTEST_F(DaemonTest, DaemonTest_ConnectionAndMount_001, TestSize.Level1) HWTEST_F(DaemonTest, DaemonTest_OpenP2PConnectionEx_001, TestSize.Level1) { GTEST_LOG_(INFO) << "DaemonTest_OpenP2PConnectionEx_001 begin"; - ASSERT_NE(daemon_, nullptr); + + // check permission failed g_checkCallerPermissionDatasync = false; - EXPECT_EQ(daemon_->OpenP2PConnectionEx("", nullptr), E_PERMISSION_DENIED_NAPI); + EXPECT_EQ(daemon_->OpenP2PConnectionEx("", nullptr), E_PERMISSION); + // networkId length is invalid g_checkCallerPermissionDatasync = true; - daemon_->dfsListenerDeathRecipient_ = nullptr; EXPECT_EQ(daemon_->OpenP2PConnectionEx("", nullptr), E_INVAL_ARG_NAPI); + std::string longNetworkId(DM_MAX_DEVICE_ID_LEN, 'a'); + EXPECT_EQ(daemon_->OpenP2PConnectionEx(longNetworkId, nullptr), E_INVAL_ARG_NAPI); + + // networkId is valid + std::string validNetworkId(64, 'a'); + EXPECT_NE(daemon_->OpenP2PConnectionEx("", nullptr), NO_ERROR); - auto listener = sptr(new FileDfsListenerMock()); - EXPECT_EQ(daemon_->OpenP2PConnectionEx("", listener), E_INVAL_ARG_NAPI); GTEST_LOG_(INFO) << "DaemonTest_OpenP2PConnectionEx_001 end"; } @@ -649,21 +676,26 @@ HWTEST_F(DaemonTest, DaemonTest_OpenP2PConnectionEx_001, TestSize.Level1) HWTEST_F(DaemonTest, DaemonTest_CloseP2PConnectionEx_001, TestSize.Level1) { GTEST_LOG_(INFO) << "DaemonTest_CloseP2PConnectionEx_001 begin"; - ASSERT_NE(daemon_, nullptr); + + // check permission failed g_checkCallerPermissionDatasync = false; - EXPECT_EQ(daemon_->CloseP2PConnectionEx(""), E_PERMISSION_DENIED_NAPI); + EXPECT_EQ(daemon_->CloseP2PConnectionEx(""), E_PERMISSION); + // networkId length is invalid g_checkCallerPermissionDatasync = true; EXPECT_EQ(daemon_->CloseP2PConnectionEx(""), E_INVAL_ARG_NAPI); + std::string longNetworkId(DM_MAX_DEVICE_ID_LEN, 'a'); + EXPECT_EQ(daemon_->CloseP2PConnectionEx(longNetworkId), E_INVAL_ARG_NAPI); - std::string networkId = "test"; - EXPECT_CALL(*deviceManagerAgentMock_, GetDeviceIdByNetworkId(_)).WillOnce(Return("")); - EXPECT_EQ(daemon_->CloseP2PConnectionEx(networkId), E_CONNECTION_FAILED); + // networkId is valid but without file access permissions + std::string validNetworkId(64, 'a'); + g_checkCallerPermission = false; + EXPECT_NE(daemon_->CloseP2PConnectionEx(validNetworkId), NO_ERROR); + // networkId is valid with file access permissions g_checkCallerPermission = true; - EXPECT_CALL(*deviceManagerAgentMock_, GetDeviceIdByNetworkId(_)).WillOnce(Return("test")); - EXPECT_CALL(*deviceManagerAgentMock_, UMountDfsDocs(_, _, _)).WillOnce(Return(ERR_BAD_VALUE)); - EXPECT_EQ(daemon_->CloseP2PConnectionEx(networkId), E_UNMOUNT); + EXPECT_NE(daemon_->CloseP2PConnectionEx(validNetworkId), NO_ERROR); + GTEST_LOG_(INFO) << "DaemonTest_CloseP2PConnectionEx_001 end"; } @@ -1403,16 +1435,14 @@ HWTEST_F(DaemonTest, DaemonTest_DestroyControlLink_001, TestSize.Level1) HWTEST_F(DaemonTest, DaemonTest_CheckRemoteAllowConnect_001, TestSize.Level1) { GTEST_LOG_(INFO) << "DaemonTest_CheckRemoteAllowConnect_001"; - ASSERT_NE(daemon_, nullptr); - // Test CreatControlLink failed - g_dfsVersion = {6, 0, 0}; - EXPECT_CALL(*channelManagerMock_, HasExistChannel(_)).WillOnce(Return(false)); - EXPECT_CALL(*channelManagerMock_, CreateClientChannel(_)).WillOnce(Return(FileManagement::ERR_BAD_VALUE)); - EXPECT_EQ(daemon_->CheckRemoteAllowConnect("networkId"), FileManagement::ERR_BAD_VALUE); + // Test remoteDfs version is lower + g_isRemoteDfsVersionLowerThanGiven = true; + EXPECT_EQ(daemon_->CheckRemoteAllowConnect("networkId"), FileManagement::ERR_OK); // Test SendRequest failed - EXPECT_CALL(*channelManagerMock_, HasExistChannel(_)).WillOnce(Return(true)); - EXPECT_CALL(*channelManagerMock_, SendRequest(_, _, _, _)).WillOnce(Return(FileManagement::ERR_BAD_VALUE)); + g_isRemoteDfsVersionLowerThanGiven = false; + EXPECT_CALL(*channelManagerMock_, HasExistChannel(_)).WillOnce(Return(false)); + EXPECT_CALL(*channelManagerMock_, CreateClientChannel(_)).WillOnce(Return(FileManagement::ERR_BAD_VALUE)); EXPECT_EQ(daemon_->CheckRemoteAllowConnect("networkId"), FileManagement::ERR_BAD_VALUE); // Test CheckRemoteAllowConnect success @@ -1432,8 +1462,12 @@ HWTEST_F(DaemonTest, DaemonTest_CheckRemoteAllowConnect_001, TestSize.Level1) HWTEST_F(DaemonTest, DaemonTest_NotifyRemotePublishNotification_001, TestSize.Level1) { GTEST_LOG_(INFO) << "DaemonTest_NotifyRemotePublishNotification_001"; - ASSERT_NE(daemon_, nullptr); + // Test remoteDfs version is lower + g_isRemoteDfsVersionLowerThanGiven = true; + EXPECT_EQ(daemon_->NotifyRemotePublishNotification("networkId"), FileManagement::ERR_OK); + // Test CreatControlLink failed + g_isRemoteDfsVersionLowerThanGiven = false; g_dfsVersion = {6, 0, 0}; EXPECT_CALL(*channelManagerMock_, HasExistChannel(_)).WillOnce(Return(false)); EXPECT_CALL(*channelManagerMock_, CreateClientChannel(_)).WillOnce(Return(FileManagement::ERR_BAD_VALUE)); @@ -1461,8 +1495,12 @@ HWTEST_F(DaemonTest, DaemonTest_NotifyRemotePublishNotification_001, TestSize.Le HWTEST_F(DaemonTest, DaemonTest_NotifyRemoteCancelNotification_001, TestSize.Level1) { GTEST_LOG_(INFO) << "DaemonTest_NotifyRemoteCancelNotification_001"; - ASSERT_NE(daemon_, nullptr); + // Test remoteDfs version is lower + g_isRemoteDfsVersionLowerThanGiven = true; + EXPECT_EQ(daemon_->NotifyRemotePublishNotification("networkId"), FileManagement::ERR_OK); + // Test CreatControlLink failed + g_isRemoteDfsVersionLowerThanGiven = false; g_dfsVersion = {6, 0, 0}; EXPECT_CALL(*channelManagerMock_, HasExistChannel(_)).WillOnce(Return(false)); EXPECT_CALL(*channelManagerMock_, CreateClientChannel(_)).WillOnce(Return(FileManagement::ERR_BAD_VALUE)); @@ -1480,5 +1518,465 @@ HWTEST_F(DaemonTest, DaemonTest_NotifyRemoteCancelNotification_001, TestSize.Lev GTEST_LOG_(INFO) << "DaemonTest_NotifyRemoteCancelNotification_001"; } + +/** + * @tc.name: DaemonTest_IsSameAccountDevice_001 + * @tc.desc: verify IsSameAccountDevice with same account device. + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(DaemonTest, DaemonTest_IsSameAccountDevice_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DaemonTest_IsSameAccountDevice_001 begin"; +#ifdef SUPPORT_SAME_ACCOUNT + bool isSameAccount = false; + std::vector deviceList; + deviceList.push_back(deviceInfo); + + // Test same account device + EXPECT_CALL(*deviceManagerImplMock_, GetTrustedDeviceList(_, _, _)) + .WillOnce(DoAll(SetArgReferee<2>(deviceList), Return(0))); + + int32_t result = daemon_->IsSameAccountDevice(NETWORKID_ONE, isSameAccount); + EXPECT_EQ(result, E_OK); + EXPECT_TRUE(isSameAccount); + GTEST_LOG_(INFO) << "DaemonTest_IsSameAccountDevice_001 end"; +#else + GTEST_LOG_(INFO) << "DaemonTest_IsSameAccountDevice_001 not support!"; +#endif +} + +/** + * @tc.name: DaemonTest_IsSameAccountDevice_002 + * @tc.desc: verify IsSameAccountDevice with different account device. + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(DaemonTest, DaemonTest_IsSameAccountDevice_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DaemonTest_IsSameAccountDevice_002 begin"; +#ifdef SUPPORT_SAME_ACCOUNT + bool isSameAccount = false; + std::vector deviceList; + + // Create device with different account + DistributedHardware::DmDeviceInfo diffAccountDevice = deviceInfo; + diffAccountDevice.authForm = DistributedHardware::DmAuthForm::ACROSS_ACCOUNT; + deviceList.push_back(diffAccountDevice); + + // Test different account device + EXPECT_CALL(*deviceManagerImplMock_, GetTrustedDeviceList(_, _, _)) + .WillOnce(DoAll(SetArgReferee<2>(deviceList), Return(0))); + + int32_t result = daemon_->IsSameAccountDevice(NETWORKID_ONE, isSameAccount); + EXPECT_EQ(result, E_OK); + EXPECT_FALSE(isSameAccount); + + GTEST_LOG_(INFO) << "DaemonTest_IsSameAccountDevice_002 end"; +#else + GTEST_LOG_(INFO) << "DaemonTest_IsSameAccountDevice_002 not support!"; +#endif +} + +/** + * @tc.name: DaemonTest_IsSameAccountDevice_003 + * @tc.desc: verify IsSameAccountDevice with empty device list. + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(DaemonTest, DaemonTest_IsSameAccountDevice_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DaemonTest_IsSameAccountDevice_003 begin"; +#ifdef SUPPORT_SAME_ACCOUNT + bool isSameAccount = true; + std::vector deviceList; + + // Test empty device list + EXPECT_CALL(*deviceManagerImplMock_, GetTrustedDeviceList(_, _, _)) + .WillOnce(DoAll(SetArgReferee<2>(deviceList), Return(0))); + + int32_t result = daemon_->IsSameAccountDevice(NETWORKID_ONE, isSameAccount); + EXPECT_EQ(result, E_INVAL_ARG_NAPI); + EXPECT_FALSE(isSameAccount); + + GTEST_LOG_(INFO) << "DaemonTest_IsSameAccountDevice_003 end"; +#else + GTEST_LOG_(INFO) << "DaemonTest_IsSameAccountDevice_003 not support!"; +#endif +} + +/** + * @tc.name: DaemonTest_IsSameAccountDevice_004 + * @tc.desc: verify IsSameAccountDevice with device not in trusted list. + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(DaemonTest, DaemonTest_IsSameAccountDevice_004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DaemonTest_IsSameAccountDevice_004 begin"; +#ifdef SUPPORT_SAME_ACCOUNT + bool isSameAccount = true; + std::vector deviceList; + + // Create device with different networkId + DistributedHardware::DmDeviceInfo differentDevice = deviceInfo; + (void)memcpy_s(differentDevice.networkId, DM_MAX_DEVICE_NAME_LEN - 1, + "different_network_id", strlen("different_network_id")); + deviceList.push_back(differentDevice); + + // Test device not in trusted list + EXPECT_CALL(*deviceManagerImplMock_, GetTrustedDeviceList(_, _, _)) + .WillOnce(DoAll(SetArgReferee<2>(deviceList), Return(0))); + + int32_t result = daemon_->IsSameAccountDevice(NETWORKID_ONE, isSameAccount); + EXPECT_EQ(result, E_INVAL_ARG_NAPI); + EXPECT_FALSE(isSameAccount); + + GTEST_LOG_(INFO) << "DaemonTest_IsSameAccountDevice_004 end"; +#else + GTEST_LOG_(INFO) << "DaemonTest_IsSameAccountDevice_004 not support!"; +#endif +} + +/** + * @tc.name: DaemonTest_RegisterFileDfsListener_001 + * @tc.desc: verify RegisterFileDfsListener with valid parameters. + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(DaemonTest, DaemonTest_RegisterFileDfsListener_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DaemonTest_RegisterFileDfsListener_001 begin"; + + std::string instanceId = "test_instance"; + sptr listener = new FileDfsListenerMock(); + + // Test valid parameters + int32_t result = daemon_->RegisterFileDfsListener(instanceId, listener); + EXPECT_EQ(result, E_OK); + + // Verify listener was added + EXPECT_TRUE(ConnectCount::GetInstance()->RmFileConnect(instanceId)); + + GTEST_LOG_(INFO) << "DaemonTest_RegisterFileDfsListener_001 end"; +} + +/** + * @tc.name: DaemonTest_RegisterFileDfsListener_002 + * @tc.desc: verify RegisterFileDfsListener with empty instanceId. + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(DaemonTest, DaemonTest_RegisterFileDfsListener_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DaemonTest_RegisterFileDfsListener_002 begin"; + + std::string emptyInstanceId = ""; + sptr listener = new FileDfsListenerMock(); + + // Test empty instanceId + int32_t result = daemon_->RegisterFileDfsListener(emptyInstanceId, listener); + EXPECT_EQ(result, E_INVAL_ARG_NAPI); + + GTEST_LOG_(INFO) << "DaemonTest_RegisterFileDfsListener_002 end"; +} + +/** + * @tc.name: DaemonTest_RegisterFileDfsListener_003 + * @tc.desc: verify RegisterFileDfsListener with null listener. + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(DaemonTest, DaemonTest_RegisterFileDfsListener_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DaemonTest_RegisterFileDfsListener_003 begin"; + + std::string instanceId = "test_instance"; + sptr nullListener = nullptr; + + // Test null listener + int32_t result = daemon_->RegisterFileDfsListener(instanceId, nullListener); + EXPECT_EQ(result, E_INVAL_ARG_NAPI); + + GTEST_LOG_(INFO) << "DaemonTest_RegisterFileDfsListener_003 end"; +} + +/** + * @tc.name: DaemonTest_UnregisterFileDfsListener_001 + * @tc.desc: verify UnregisterFileDfsListener with valid instanceId. + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(DaemonTest, DaemonTest_UnregisterFileDfsListener_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DaemonTest_UnregisterFileDfsListener_001 begin"; + + std::string instanceId = "test_instance"; + sptr listener = new FileDfsListenerMock(); + + // First register a listener + daemon_->RegisterFileDfsListener(instanceId, listener); + + // Test unregister with valid instanceId + int32_t result = daemon_->UnregisterFileDfsListener(instanceId); + EXPECT_EQ(result, E_OK); + + GTEST_LOG_(INFO) << "DaemonTest_UnregisterFileDfsListener_001 end"; +} + +/** + * @tc.name: DaemonTest_UnregisterFileDfsListener_002 + * @tc.desc: verify UnregisterFileDfsListener with empty instanceId. + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(DaemonTest, DaemonTest_UnregisterFileDfsListener_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DaemonTest_UnregisterFileDfsListener_002 begin"; + + std::string emptyInstanceId = ""; + + // Test empty instanceId + int32_t result = daemon_->UnregisterFileDfsListener(emptyInstanceId); + EXPECT_EQ(result, E_INVAL_ARG_NAPI); + + GTEST_LOG_(INFO) << "DaemonTest_UnregisterFileDfsListener_002 end"; +} + +/** + * @tc.name: DaemonTest_UnregisterFileDfsListener_003 + * @tc.desc: verify UnregisterFileDfsListener with non-existent instanceId. + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(DaemonTest, DaemonTest_UnregisterFileDfsListener_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DaemonTest_UnregisterFileDfsListener_003 begin"; + + std::string nonExistentInstanceId = "non_existent_instance"; + + // Test non-existent instanceId + int32_t result = daemon_->UnregisterFileDfsListener(nonExistentInstanceId); + EXPECT_EQ(result, E_INVAL_ARG_NAPI); + + GTEST_LOG_(INFO) << "DaemonTest_UnregisterFileDfsListener_003 end"; +} + +/** + * @tc.name: DaemonTest_GetDfsSwitchStatus_001 + * @tc.desc: verify GetDfsSwitchStatus with valid networkId. + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(DaemonTest, DaemonTest_GetDfsSwitchStatus_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DaemonTest_GetDfsSwitchStatus_001 begin"; + + // Test valid networkId with success + g_getDeviceStatus = E_OK; + int32_t status = 0; + + int32_t result = daemon_->GetDfsSwitchStatus(NETWORKID_ONE, status); + EXPECT_EQ(result, E_OK); + + GTEST_LOG_(INFO) << "DaemonTest_GetDfsSwitchStatus_001 end"; +} + +/** + * @tc.name: DaemonTest_GetDfsSwitchStatus_002 + * @tc.desc: verify GetDfsSwitchStatus with empty networkId. + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(DaemonTest, DaemonTest_GetDfsSwitchStatus_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DaemonTest_GetDfsSwitchStatus_002 begin"; + + std::string emptyNetworkId = ""; + int32_t status = 0; + + // Test empty networkId + int32_t result = daemon_->GetDfsSwitchStatus(emptyNetworkId, status); + EXPECT_EQ(result, E_INVAL_ARG_NAPI); + + GTEST_LOG_(INFO) << "DaemonTest_GetDfsSwitchStatus_002 end"; +} + +/** + * @tc.name: DaemonTest_GetDfsSwitchStatus_003 + * @tc.desc: verify GetDfsSwitchStatus with long networkId. + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(DaemonTest, DaemonTest_GetDfsSwitchStatus_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DaemonTest_GetDfsSwitchStatus_003 begin"; + + std::string longNetworkId(DM_MAX_DEVICE_ID_LEN, 'a'); + int32_t status = 0; + + // Test long networkId + int32_t result = daemon_->GetDfsSwitchStatus(longNetworkId, status); + EXPECT_EQ(result, E_INVAL_ARG_NAPI); + + GTEST_LOG_(INFO) << "DaemonTest_GetDfsSwitchStatus_003 end"; +} + +/** + * @tc.name: DaemonTest_GetDfsSwitchStatus_004 + * @tc.desc: verify GetDfsSwitchStatus with device not found. + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(DaemonTest, DaemonTest_GetDfsSwitchStatus_004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DaemonTest_GetDfsSwitchStatus_004 begin"; + + // Test device not found + g_getDeviceStatus = ERR_DP_CAN_NOT_FIND; + int32_t status = 0; + + int32_t result = daemon_->GetDfsSwitchStatus(NETWORKID_ONE, status); + EXPECT_EQ(result, ERR_DP_CAN_NOT_FIND); + + GTEST_LOG_(INFO) << "DaemonTest_GetDfsSwitchStatus_004 end"; +} + +/** + * @tc.name: DaemonTest_GetDfsSwitchStatus_005 + * @tc.desc: verify GetDfsSwitchStatus with other error. + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(DaemonTest, DaemonTest_GetDfsSwitchStatus_005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DaemonTest_GetDfsSwitchStatus_005 begin"; + + // Test other error + g_getDeviceStatus = ERR_BAD_VALUE; + int32_t status = 0; + + int32_t result = daemon_->GetDfsSwitchStatus(NETWORKID_ONE, status); + EXPECT_EQ(result, ERR_BAD_VALUE); + + GTEST_LOG_(INFO) << "DaemonTest_GetDfsSwitchStatus_005 end"; +} + +/** + * @tc.name: DaemonTest_UpdateDfsSwitchStatus_001 + * @tc.desc: verify UpdateDfsSwitchStatus with valid status. + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(DaemonTest, DaemonTest_UpdateDfsSwitchStatus_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DaemonTest_UpdateDfsSwitchStatus_001 begin"; + + // Test valid status with success + g_putDeviceStatus = E_OK; + + int32_t result = daemon_->UpdateDfsSwitchStatus(1); + EXPECT_EQ(result, E_OK); + + GTEST_LOG_(INFO) << "DaemonTest_UpdateDfsSwitchStatus_001 end"; +} + +/** + * @tc.name: DaemonTest_UpdateDfsSwitchStatus_002 + * @tc.desc: verify UpdateDfsSwitchStatus with PutDeviceStatus failure. + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(DaemonTest, DaemonTest_UpdateDfsSwitchStatus_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DaemonTest_UpdateDfsSwitchStatus_002 begin"; + + // Test PutDeviceStatus failure + g_putDeviceStatus = ERR_BAD_VALUE; + + int32_t result = daemon_->UpdateDfsSwitchStatus(1); + EXPECT_EQ(result, ERR_BAD_VALUE); + + GTEST_LOG_(INFO) << "DaemonTest_UpdateDfsSwitchStatus_002 end"; +} + +/** + * @tc.name: DaemonTest_UpdateDfsSwitchStatus_003 + * @tc.desc: verify UpdateDfsSwitchStatus with status 0 and cleanup. + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(DaemonTest, DaemonTest_UpdateDfsSwitchStatus_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DaemonTest_UpdateDfsSwitchStatus_003 begin"; + + // Prepare mount info + MountCountInfo mountInfo(NETWORKID_ONE, 1); + + std::unordered_map allMountInfo = {{"test", mountInfo}}; + + // Test status 0 with cleanup + g_putDeviceStatus = E_OK; + EXPECT_CALL(*deviceManagerAgentMock_, GetAllMountInfo()).WillOnce(Return(allMountInfo)); + EXPECT_CALL(*deviceManagerAgentMock_, OnDeviceP2POffline(_)).WillOnce(Return(E_OK)); + + int32_t result = daemon_->UpdateDfsSwitchStatus(0); + EXPECT_NE(result, E_OK); + + GTEST_LOG_(INFO) << "DaemonTest_UpdateDfsSwitchStatus_003 end"; +} + +/** + * @tc.name: DaemonTest_UpdateDfsSwitchStatus_004 + * @tc.desc: verify UpdateDfsSwitchStatus with status 0 and cleanup failure. + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(DaemonTest, DaemonTest_UpdateDfsSwitchStatus_004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DaemonTest_UpdateDfsSwitchStatus_004 begin"; + ASSERT_NE(daemon_, nullptr); + + // Prepare mount info + MountCountInfo mountInfo(NETWORKID_ONE, 1); + + std::unordered_map allMountInfo = {{"test", mountInfo}}; + + // Test status 0 with cleanup failure + g_putDeviceStatus = E_OK; + EXPECT_CALL(*deviceManagerAgentMock_, GetAllMountInfo()).WillOnce(Return(allMountInfo)); + EXPECT_CALL(*deviceManagerAgentMock_, OnDeviceP2POffline(_)).WillOnce(Return(ERR_BAD_VALUE)); + + int32_t result = daemon_->UpdateDfsSwitchStatus(0); + EXPECT_EQ(result, E_CONNECTION_FAILED); + + GTEST_LOG_(INFO) << "DaemonTest_UpdateDfsSwitchStatus_004 end"; +} + +/** + * @tc.name: DaemonTest_UpdateDfsSwitchStatus_005 + * @tc.desc: verify UpdateDfsSwitchStatus with status 0 and strcpy failure. + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(DaemonTest, DaemonTest_UpdateDfsSwitchStatus_005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DaemonTest_UpdateDfsSwitchStatus_005 begin"; + + // Prepare mount info with very long networkId to cause strcpy failure + MountCountInfo mountInfo(std::string(DM_MAX_DEVICE_ID_LEN + 1, 'a'), 1); + + std::unordered_map allMountInfo = {{"test", mountInfo}}; + + // Test status 0 with strcpy failure + g_putDeviceStatus = E_OK; + EXPECT_CALL(*deviceManagerAgentMock_, GetAllMountInfo()).WillOnce(Return(allMountInfo)); + + int32_t result = daemon_->UpdateDfsSwitchStatus(0); + EXPECT_EQ(result, E_INVAL_ARG_NAPI); + + GTEST_LOG_(INFO) << "DaemonTest_UpdateDfsSwitchStatus_005 end"; +} + } // namespace Test } // namespace OHOS::Storage::DistributedFile \ No newline at end of file diff --git a/test/fuzztest/daemonstub_fuzzer/daemonstub_fuzzer.cpp b/test/fuzztest/daemonstub_fuzzer/daemonstub_fuzzer.cpp index d1650facd..e32d41f33 100644 --- a/test/fuzztest/daemonstub_fuzzer/daemonstub_fuzzer.cpp +++ b/test/fuzztest/daemonstub_fuzzer/daemonstub_fuzzer.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/test/unittests/distributed_file_daemon/daemon_stub_sup_test.cpp b/test/unittests/distributed_file_daemon/daemon_stub_sup_test.cpp index 2894994fd..b50f81d7b 100644 --- a/test/unittests/distributed_file_daemon/daemon_stub_sup_test.cpp +++ b/test/unittests/distributed_file_daemon/daemon_stub_sup_test.cpp @@ -96,20 +96,12 @@ bool IPCSkeleton::IsLocalCalling() namespace OHOS::FileManagement { bool DfsuAccessTokenHelper::CheckUriPermission(const std::string &uriStr) { - if (g_checkUriPermissionTrue) { - return true; - } - - return false; + return g_checkUriPermissionTrue; } bool DfsuAccessTokenHelper::CheckCallerPermission(const std::string &permissionName) { - if (g_checkCallerPermissionTrue) { - return true; - } - - return false; + return g_checkCallerPermissionTrue; } } @@ -187,6 +179,7 @@ void DaemonStubSupPTest::TearDownTestCase(void) void DaemonStubSupPTest::SetUp(void) { GTEST_LOG_(INFO) << "SetUp"; + g_checkCallerPermissionTrue = true; } void DaemonStubSupPTest::TearDown(void) @@ -253,8 +246,10 @@ HWTEST_F(DaemonStubSupPTest, DaemonStubSupHandleOpenP2PConnectionExTest001, Test EXPECT_CALL(*messageParcelMock_, ReadString(_)).WillOnce(Return(true)); EXPECT_CALL(*messageParcelMock_, ReadRemoteObject()).WillOnce(Return(nullptr)); + EXPECT_CALL(*daemonStub_, OpenP2PConnectionEx(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)); ret = daemonStub_->HandleOpenP2PConnectionEx(data, reply); - EXPECT_EQ(ret, E_IPC_READ_FAILED); + EXPECT_EQ(ret, E_OK); EXPECT_CALL(*messageParcelMock_, ReadString(_)).WillOnce(Return(true)); sptr listenerPtr = sptr(new FileDfsListenerMock()); @@ -666,24 +661,17 @@ HWTEST_F(DaemonStubSupPTest, DaemonStubSupHandleGetDfsSwitchStatus, TestSize.Lev EXPECT_EQ(ret, E_IPC_WRITE_FAILED); EXPECT_CALL(*messageParcelMock_, ReadString(_)).WillOnce(Return(true)); - EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)).WillOnce(Return(false)); EXPECT_CALL(*daemonStub_, GetDfsSwitchStatus(_, _)).WillOnce(Return(E_INVAL_ARG)); ret = daemonStub_->HandleGetDfsSwitchStatus(data, reply); - EXPECT_EQ(ret, E_OK); - - EXPECT_CALL(*messageParcelMock_, ReadString(_)).WillOnce(Return("networkId")); - EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)) - .WillOnce(Return(false)); - EXPECT_CALL(*daemonStub_, GetDfsSwitchStatus(_, _)).WillOnce(Return(E_OK)); - ret = daemonStub_->HandleGetDfsSwitchStatus(data, reply); EXPECT_EQ(ret, E_IPC_WRITE_FAILED); - EXPECT_CALL(*messageParcelMock_, ReadString(_)).WillOnce(Return("networkId")); - EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)) - .WillOnce(Return(true)); - EXPECT_CALL(*daemonStub_, GetDfsSwitchStatus(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*messageParcelMock_, ReadString(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)).WillOnce(Return(true)); + EXPECT_CALL(*daemonStub_, GetDfsSwitchStatus(_, _)).WillOnce(Return(E_INVAL_ARG)); ret = daemonStub_->HandleGetDfsSwitchStatus(data, reply); EXPECT_EQ(ret, E_OK); + GTEST_LOG_(INFO) << "DaemonStubSupHandleGetDfsSwitchStatus End"; } @@ -742,36 +730,28 @@ HWTEST_F(DaemonStubSupPTest, DaemonStubSupHandleGetConnectedDeviceList, TestSize ret = daemonStub_->HandleGetConnectedDeviceList(data, reply); EXPECT_EQ(ret, E_IPC_WRITE_FAILED); - EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)); - EXPECT_CALL(*daemonStub_, GetConnectedDeviceList(_)).WillOnce(Return(E_INVAL_ARG)); - ret = daemonStub_->HandleGetConnectedDeviceList(data, reply); - EXPECT_EQ(ret, E_OK); - - EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)) - .WillOnce(Return(false)); + EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)).WillOnce(Return(false)); EXPECT_CALL(*daemonStub_, GetConnectedDeviceList(_)).WillOnce(Return(E_OK)); ret = daemonStub_->HandleGetConnectedDeviceList(data, reply); EXPECT_EQ(ret, E_IPC_WRITE_FAILED); DfsDeviceInfo testDevice; testDevice.networkId_ = "networkId"; + testDevice.path_ = "test_path"; std::vector deviceList = {testDevice}; - EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)) - .WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)).WillOnce(Return(true)); EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(false)); EXPECT_CALL(*daemonStub_, GetConnectedDeviceList(_)).WillOnce(DoAll(SetArgReferee<0>(deviceList), Return(E_OK))); ret = daemonStub_->HandleGetConnectedDeviceList(data, reply); EXPECT_EQ(ret, E_IPC_WRITE_FAILED); - EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)) - .WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)).WillOnce(Return(true)); EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true)).WillOnce(Return(false)); EXPECT_CALL(*daemonStub_, GetConnectedDeviceList(_)).WillOnce(DoAll(SetArgReferee<0>(deviceList), Return(E_OK))); ret = daemonStub_->HandleGetConnectedDeviceList(data, reply); EXPECT_EQ(ret, E_IPC_WRITE_FAILED); - EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)) - .WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)).WillOnce(Return(true)); EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true)).WillOnce(Return(true)); EXPECT_CALL(*daemonStub_, GetConnectedDeviceList(_)).WillOnce(DoAll(SetArgReferee<0>(deviceList), Return(E_OK))); ret = daemonStub_->HandleGetConnectedDeviceList(data, reply); @@ -881,12 +861,6 @@ HWTEST_F(DaemonStubSupPTest, DaemonStubSupHandleIsSameAccountDevice, TestSize.Le ret = daemonStub_->HandleIsSameAccountDevice(data, reply); EXPECT_EQ(ret, E_IPC_WRITE_FAILED); - EXPECT_CALL(*messageParcelMock_, ReadString(_)).WillOnce(Return(true)); - EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)); - EXPECT_CALL(*daemonStub_, IsSameAccountDevice(_, _)).WillOnce(Return(E_INVAL_ARG)); - ret = daemonStub_->HandleIsSameAccountDevice(data, reply); - EXPECT_EQ(ret, E_OK); - EXPECT_CALL(*messageParcelMock_, ReadString(_)).WillOnce(Return(true)); EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)); EXPECT_CALL(*messageParcelMock_, WriteBool(_)).WillOnce(Return(false)); diff --git a/test/unittests/distributed_file_daemon/file_dfs_listener_proxy_test.cpp b/test/unittests/distributed_file_daemon/file_dfs_listener_proxy_test.cpp index b633f3193..cdd82ef8f 100644 --- a/test/unittests/distributed_file_daemon/file_dfs_listener_proxy_test.cpp +++ b/test/unittests/distributed_file_daemon/file_dfs_listener_proxy_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 @@ -76,17 +76,19 @@ void FileDfsListenerProxyTest::TearDown(void) HWTEST_F(FileDfsListenerProxyTest, FileDfsListener_OnStatus_0100, TestSize.Level0) { GTEST_LOG_(INFO) << "FileDfsListener_OnStatus_0100 Start"; + EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(false)); - proxy_->OnStatus("test", 0); + proxy_->OnStatus("test", 0, "", 0); EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(false)); - proxy_->OnStatus("test", 0); + proxy_->OnStatus("test", 0, "", 0); EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true)); EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(false)); - proxy_->OnStatus("test", 0); + proxy_->OnStatus("test", 0, "", 0); + GTEST_LOG_(INFO) << "FileDfsListener_OnStatus_0100 End"; } @@ -99,11 +101,17 @@ HWTEST_F(FileDfsListenerProxyTest, FileDfsListener_OnStatus_0100, TestSize.Level HWTEST_F(FileDfsListenerProxyTest, FileTransListener_OnStatus_0200, TestSize.Level0) { GTEST_LOG_(INFO) << "FileTransListener_OnStatus_0200 Start"; + EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); - EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true)); - EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(false)); - auto testProxy = make_shared(nullptr); - testProxy->OnStatus("test", 0); + EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true)).WillOnce(Return(false)); + EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)); + proxy_->OnStatus("test", 0, "", 0); + + EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)).WillOnce(Return(false)); + proxy_->OnStatus("test", 0, "", 0); + GTEST_LOG_(INFO) << "FileTransListener_OnStatus_0200 End"; } @@ -116,28 +124,19 @@ HWTEST_F(FileDfsListenerProxyTest, FileTransListener_OnStatus_0200, TestSize.Lev HWTEST_F(FileDfsListenerProxyTest, FileTransListener_OnStatus_0300, TestSize.Level0) { GTEST_LOG_(INFO) << "FileTransListener_OnStatus_0300 Start"; + EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); - EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true)); - EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)).WillOnce(Return((true))); EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(E_INVAL_ARG)); - proxy_->OnStatus("test", 0); - GTEST_LOG_(INFO) << "FileTransListener_OnStatus_0300 End"; -} + proxy_->OnStatus("test", 0, "", 0); -/** - * @tc.name: FileTransListener_OnStatus_0400 - * @tc.desc: The execution of the OnStatus succeeded. - * @tc.type: FUNC - * @tc.require: I7TDJK - */ -HWTEST_F(FileDfsListenerProxyTest, FileTransListener_OnStatus_0400, TestSize.Level0) -{ - GTEST_LOG_(INFO) << "FileTransListener_OnStatus_0400 Start"; EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); - EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true)); - EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)).WillOnce(Return((true))); EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(E_OK)); - proxy_->OnStatus("test", 0); - GTEST_LOG_(INFO) << "FileTransListener_OnStatus_0400 End"; + proxy_->OnStatus("test", 0, "", 0); + + GTEST_LOG_(INFO) << "FileTransListener_OnStatus_0300 End"; } } \ No newline at end of file diff --git a/test/unittests/distributed_file_daemon/include/file_dfs_listener_mock.h b/test/unittests/distributed_file_daemon/include/file_dfs_listener_mock.h index b5c8a0c14..ff53304da 100644 --- a/test/unittests/distributed_file_daemon/include/file_dfs_listener_mock.h +++ b/test/unittests/distributed_file_daemon/include/file_dfs_listener_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 @@ -34,7 +34,7 @@ public: virtual ~FileDfsListenerMock() {} MOCK_METHOD4(SendRequest, int(uint32_t, MessageParcel &, MessageParcel &, MessageOption &)); - MOCK_METHOD2(OnStatus, void(const std::string &networkId, int32_t status)); + MOCK_METHOD4(OnStatus, void(const std::string &networkId, int32_t status, const std::string &path, int32_t type)); }; } // namespace DistributedFile } // namespace Storage diff --git a/test/unittests/distributed_file_inner/BUILD.gn b/test/unittests/distributed_file_inner/BUILD.gn index 9257f8ef5..7b3be49dc 100644 --- a/test/unittests/distributed_file_inner/BUILD.gn +++ b/test/unittests/distributed_file_inner/BUILD.gn @@ -713,6 +713,59 @@ ohos_unittest("ipc_wrapper_test") { subsystem_name = "filemanagement" } +ohos_unittest("file_dfs_listener_stub_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 = [ + "${distributedfile_path}/frameworks/native/distributed_file_inner/src/file_dfs_listener_stub.cpp", + "${distributedfile_path}/test/mock/message_parcel_mock.cpp", + "file_dfs_listener_stub_test.cpp", + ] + + include_dirs = [ + "${distributedfile_path}/frameworks/native/distributed_file_inner/include", + "${distributedfile_path}/frameworks/native/distributed_file_inner/include/copy", + "${distributedfile_path}/test/mock", + "${distributedfile_path}/test/unittests/distributed_file_daemon/include", + "include", + "${services_path}/distributedfiledaemon/include/", + "${services_path}/distributedfiledaemon/include/ipc", + ] + + deps = [ "${utils_path}:libdistributedfileutils" ] + + external_deps = [ + "ability_runtime:abilitykit_native", + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "data_share:datashare_consumer", + "hilog:libhilog", + "googletest:gmock_main", + "googletest:gtest_main", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + defines = [ + "private=public", + "LOG_TAG=\"distributedfile_daemon\"", + ] + + use_exceptions = true + part_name = "dfs_service" + subsystem_name = "filemanagement" +} + group("distributed_file_inner") { testonly = true @@ -730,5 +783,6 @@ group("distributed_file_inner") { ":ipc_wrapper_test", ":remote_file_copy_manager_test", ":trans_listener_test", + ":file_dfs_listener_stub_test", ] } diff --git a/test/unittests/distributed_file_inner/distributed_file_daemon_proxy_test.cpp b/test/unittests/distributed_file_inner/distributed_file_daemon_proxy_test.cpp index 6923e767c..08a4039d0 100644 --- a/test/unittests/distributed_file_inner/distributed_file_daemon_proxy_test.cpp +++ b/test/unittests/distributed_file_inner/distributed_file_daemon_proxy_test.cpp @@ -255,8 +255,10 @@ HWTEST_F(DistributedFileDaemonProxyTest, DistributedFileDaemon_OpenP2PConnection sptr errPtr = nullptr; EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true)); + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*messageParcelMock_, ReadInt32()).WillOnce(Return(E_OK)); ret = proxy_->OpenP2PConnectionEx("test", errPtr); - EXPECT_EQ(ret, E_BROKEN_IPC); + EXPECT_EQ(ret, E_OK); GTEST_LOG_(INFO) << "DistributedFileDaemon_OpenP2PConnectionEx_0200 End"; } diff --git a/test/unittests/distributed_file_inner/file_dfs_listener_stub_test.cpp b/test/unittests/distributed_file_inner/file_dfs_listener_stub_test.cpp new file mode 100644 index 000000000..ae9b15d9a --- /dev/null +++ b/test/unittests/distributed_file_inner/file_dfs_listener_stub_test.cpp @@ -0,0 +1,129 @@ +/* + * 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 +#include + +#include "file_dfs_listener_mock.h" +#include "file_dfs_listener_stub.h" +#include "file_dfs_listener_interface_code.h" +#include "message_parcel_mock.h" +#include "utils_log.h" +#include "dfs_error.h" + +namespace OHOS::Storage::DistributedFile::Test { +using namespace testing; +using namespace testing::ext; +using namespace OHOS::FileManagement; +using namespace FileManagement::ModuleFileIO; + +namespace { + constexpr int NO_ERROR = 0; + constexpr int E_INVAL_ARG = 1; +} + +class MockFileDfsListenerStub final : public FileDfsListenerStub { +public: + MOCK_METHOD4(OnStatus, void(const std::string &networkId, int32_t status, const std::string &path, int32_t type)); +}; + +class FileDfsListenerStubTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +public: + static inline std::shared_ptr mockStub_ = nullptr; + static inline std::shared_ptr messageParcelMock_ = nullptr; +}; + +void FileDfsListenerStubTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + mockStub_ = std::make_shared(); + messageParcelMock_ = std::make_shared(); + MessageParcelMock::messageParcel = messageParcelMock_; +} + +void FileDfsListenerStubTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; + mockStub_ = nullptr; + MessageParcelMock::messageParcel = nullptr; + messageParcelMock_ = nullptr; +} + +void FileDfsListenerStubTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void FileDfsListenerStubTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: FileDfsListenerStub_HandleOnStatus_0100 + * @tc.desc: Verify the HandleOnStatus function with various failure scenarios + * @tc.type: FUNC + * @tc.require: I7M6L1 + */ +HWTEST_F(FileDfsListenerStubTest, FileDfsListenerStub_HandleOnStatus_0100, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FileDfsListenerStub_HandleOnStatus_0100 Start"; + MessageParcel data; + MessageParcel reply; + + // Test case: Read networkId fails + EXPECT_CALL(*messageParcelMock_, ReadString(_)).WillOnce(Return(false)); + auto ret = mockStub_->HandleOnStatus(data, reply); + EXPECT_EQ(ret, E_INVAL_ARG); + + // Test case: Read status fails + EXPECT_CALL(*messageParcelMock_, ReadString(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, ReadInt32(_)).WillOnce(Return(false)); + ret = mockStub_->HandleOnStatus(data, reply); + EXPECT_EQ(ret, E_INVAL_ARG); + + // Test case: Read path fails + EXPECT_CALL(*messageParcelMock_, ReadString(_)).WillOnce(Return(true)).WillOnce(Return(false)); + EXPECT_CALL(*messageParcelMock_, ReadInt32(_)).WillOnce(Return(true)); + ret = mockStub_->HandleOnStatus(data, reply); + EXPECT_EQ(ret, E_INVAL_ARG); + + // Test case: Read type fails + EXPECT_CALL(*messageParcelMock_, ReadString(_)).WillOnce(Return(true)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, ReadInt32(_)).WillOnce(Return(true)).WillOnce(Return(false)); + ret = mockStub_->HandleOnStatus(data, reply); + EXPECT_EQ(ret, E_INVAL_ARG); + + // Test case: Empty networkId + std::string networkId = "aaa"; + std::string path = "testPath"; + int32_t status = 0; + int32_t type = 1; + EXPECT_CALL(*messageParcelMock_, ReadString(_)).WillOnce(DoAll(SetArgReferee<0>(networkId), Return(true))) + .WillOnce(DoAll(SetArgReferee<0>(path), Return(true))); + EXPECT_CALL(*messageParcelMock_, ReadInt32(_)).WillOnce(DoAll(SetArgReferee<0>(status), Return(true))) + .WillOnce(DoAll(SetArgReferee<0>(type), Return(true))); + ret = mockStub_->HandleOnStatus(data, reply); + EXPECT_EQ(ret, NO_ERROR); + + GTEST_LOG_(INFO) << "FileDfsListenerStub_HandleOnStatus_0100 End"; +} + +} // namespace OHOS::Storage::DistributedFile::Test \ No newline at end of file diff --git a/test/unittests/distributed_file_inner/include/i_daemon_mock.h b/test/unittests/distributed_file_inner/include/i_daemon_mock.h index 3a51098c3..cdebb88b4 100644 --- a/test/unittests/distributed_file_inner/include/i_daemon_mock.h +++ b/test/unittests/distributed_file_inner/include/i_daemon_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 diff --git a/utils/log/include/dfs_error.h b/utils/log/include/dfs_error.h index 512b8db99..23814f04f 100644 --- a/utils/log/include/dfs_error.h +++ b/utils/log/include/dfs_error.h @@ -167,6 +167,7 @@ enum DFSErrCode { ERR_NULL_EVENT_HANDLER, ERR_POST_TASK_FAILED, ERR_NO_EXIST_CHANNEL, + ERR_DATA_INVALID, }; static inline std::unordered_map softbusErr2ErrCodeTable { -- Gitee From 2bc665116026d7b0abd38c9201bcdb2ca77e31be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AE=81=E7=AB=9E=E8=8E=9C?= Date: Thu, 28 Aug 2025 21:35:43 +0800 Subject: [PATCH 2/5] fix bug MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 宁竞莜 --- .../include/connect_count/connect_count.h | 6 ++++++ .../src/device/device_manager_agent.cpp | 5 +++-- services/distributedfiledaemon/src/ipc/daemon.cpp | 4 ++-- .../src/network/network_agent_template.cpp | 9 +++++---- .../unittest/device/device_manager_agent_sup_test.cpp | 5 ++--- 5 files changed, 18 insertions(+), 11 deletions(-) diff --git a/services/distributedfiledaemon/include/connect_count/connect_count.h b/services/distributedfiledaemon/include/connect_count/connect_count.h index cd56fb125..1878db397 100644 --- a/services/distributedfiledaemon/include/connect_count/connect_count.h +++ b/services/distributedfiledaemon/include/connect_count/connect_count.h @@ -43,6 +43,12 @@ enum class StatusType { CONNECTION_STATUS }; +enum Status { + CONNECT_OK = 0, + DISCONNECT_OK = 1, + DEVICE_OFFLINE = 2 +}; + class ConnectCount final { public: ConnectCount() = default; diff --git a/services/distributedfiledaemon/src/device/device_manager_agent.cpp b/services/distributedfiledaemon/src/device/device_manager_agent.cpp index f74591458..75a616fcc 100644 --- a/services/distributedfiledaemon/src/device/device_manager_agent.cpp +++ b/services/distributedfiledaemon/src/device/device_manager_agent.cpp @@ -536,8 +536,9 @@ int32_t DeviceManagerAgent::UMountDfsDocs(const std::string &networkId, const st LOGI("UMountDfsDocs success, deviceId %{public}s erase count", Utils::GetAnonyString(deviceId).c_str()); RemoveMountDfsCount(deviceId); - ConnectCount::GetInstance()->NotifyFileStatusChange(networkId, 2, - MOUNT_PATH + networkId.substr(0, VALID_MOUNT_PATH_LEN), StatusType::CONNECTION_STATUS); + ConnectCount::GetInstance()->NotifyFileStatusChange(networkId, Status::DISCONNECT_OK, + MOUNT_PATH + networkId.substr(0, VALID_MOUNT_PATH_LEN), + StatusType::CONNECTION_STATUS); } LOGI("storageMgr.UMountDfsDocs end."); return ret; diff --git a/services/distributedfiledaemon/src/ipc/daemon.cpp b/services/distributedfiledaemon/src/ipc/daemon.cpp index 75b19880f..c2d004395 100644 --- a/services/distributedfiledaemon/src/ipc/daemon.cpp +++ b/services/distributedfiledaemon/src/ipc/daemon.cpp @@ -316,7 +316,7 @@ int32_t Daemon::ConnectionAndMount(const DistributedHardware::DmDeviceInfo &devi LOGE("[MountDfsDocs] failed"); return ret; } - ConnectCount::GetInstance()->NotifyFileStatusChange(networkId, E_OK, HMDFS_FATH + mountPath, + ConnectCount::GetInstance()->NotifyFileStatusChange(networkId, Status::CONNECT_OK, HMDFS_FATH + mountPath, StatusType::CONNECTION_STATUS); NotifyRemotePublishNotification(networkId); return ret; @@ -358,7 +358,7 @@ int32_t Daemon::OpenP2PConnectionEx(const std::string &networkId, sptrNotifyRemoteReverseObj(info.GetCid(), ON_STATUS_OFFLINE); ConnectCount::GetInstance()->RemoveConnect(info.GetCid()); - ConnectCount::GetInstance()->NotifyFileStatusChange( - info.GetCid(), ON_STATUS_OFFLINE, cid.substr(0, VALID_MOUNT_PATH_LEN), StatusType::CONNECTION_STATUS); + ConnectCount::GetInstance()->NotifyFileStatusChange(info.GetCid(), Status::DEVICE_OFFLINE, + info.GetCid().substr(0, VALID_MOUNT_PATH_LEN), + StatusType::CONNECTION_STATUS); } void NetworkAgentTemplate::CloseSessionForOneDevice(const string &cid) @@ -143,8 +144,8 @@ void NetworkAgentTemplate::CloseSessionForOneDeviceInner(std::string cid) { sessionPool_.ReleaseSession(cid, true); ConnectCount::GetInstance()->NotifyRemoteReverseObj(cid, ON_STATUS_OFFLINE); - ConnectCount::GetInstance()->NotifyFileStatusChange(cid, ON_STATUS_OFFLINE, - cid.substr(0, VALID_MOUNT_PATH_LEN), StatusType::CONNECTION_STATUS); + ConnectCount::GetInstance()->NotifyFileStatusChange( + cid, Status::DEVICE_OFFLINE, cid.substr(0, VALID_MOUNT_PATH_LEN), StatusType::CONNECTION_STATUS); ConnectCount::GetInstance()->RemoveConnect(cid); } diff --git a/services/distributedfiledaemon/test/unittest/device/device_manager_agent_sup_test.cpp b/services/distributedfiledaemon/test/unittest/device/device_manager_agent_sup_test.cpp index 954267803..cf25c73c0 100644 --- a/services/distributedfiledaemon/test/unittest/device/device_manager_agent_sup_test.cpp +++ b/services/distributedfiledaemon/test/unittest/device/device_manager_agent_sup_test.cpp @@ -597,9 +597,8 @@ HWTEST_F(DeviceManagerAgentSupTest, DeviceManagerAgentTest_IncreaseMountDfsCount for (int i = 0; i < threadCount; ++i) { threads.emplace_back([&, i]() { for (int j = 0; j < operationsPerThread; ++j) { - testPtr->IncreaseMountDfsCount("network_" + std::to_string(i), - mountPath + std::to_string(i), - callingTokenId + i); + testPtr->IncreaseMountDfsCount("network_" + std::to_string(i), mountPath + std::to_string(i), + callingTokenId + i); } }); } -- Gitee From 7f6a7b5b831cc03172ab9e408df477677c61e0d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AE=81=E7=AB=9E=E8=8E=9C?= Date: Sat, 30 Aug 2025 17:41:46 +0800 Subject: [PATCH 3/5] fix bug MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 宁竞莜 --- .../include/channel_manager/system_notifier.h | 2 + .../channel_manager/control_cmd_parser.cpp | 2 +- .../src/channel_manager/system_notifier.cpp | 20 +++++++ .../src/device/device_manager_agent.cpp | 5 +- .../distributedfiledaemon/src/ipc/daemon.cpp | 36 +++++++----- .../src/network/network_agent_template.cpp | 9 ++- .../test/unittest/ipc/daemon/daemon_test.cpp | 55 ++++++++++++++++--- utils/log/include/dfs_error.h | 1 + 8 files changed, 104 insertions(+), 26 deletions(-) diff --git a/services/distributedfiledaemon/include/channel_manager/system_notifier.h b/services/distributedfiledaemon/include/channel_manager/system_notifier.h index 58cffe553..f704e319f 100644 --- a/services/distributedfiledaemon/include/channel_manager/system_notifier.h +++ b/services/distributedfiledaemon/include/channel_manager/system_notifier.h @@ -42,6 +42,8 @@ public: int32_t CreateNotification(const std::string &networkId); int32_t DestroyNotifyByNetworkId(const std::string &networkId); int32_t DestroyNotifyByNotificationId(int32_t notifyId); + void ClearAllConnect(); + int32_t GetNotificationMapSize(); private: SystemNotifier(); diff --git a/services/distributedfiledaemon/src/channel_manager/control_cmd_parser.cpp b/services/distributedfiledaemon/src/channel_manager/control_cmd_parser.cpp index 7cbd428b5..5ebe7c5c4 100644 --- a/services/distributedfiledaemon/src/channel_manager/control_cmd_parser.cpp +++ b/services/distributedfiledaemon/src/channel_manager/control_cmd_parser.cpp @@ -125,7 +125,7 @@ bool ControlCmdParser::CheckAllowConnect(const ControlCmd &inCmd, ControlCmd &ou { outCmd.msgType = ControlCmdType::CMD_MSG_RESPONSE; outCmd.msgId = inCmd.msgId; - outCmd.msgBody = IsLocalItDevice() ? "true" : "false"; + outCmd.msgBody = IsLocalItDevice() || SystemNotifier::GetInstance().GetNotificationMapSize() > 0 ? "true" : "false"; return true; } diff --git a/services/distributedfiledaemon/src/channel_manager/system_notifier.cpp b/services/distributedfiledaemon/src/channel_manager/system_notifier.cpp index ab18b8806..a62247228 100644 --- a/services/distributedfiledaemon/src/channel_manager/system_notifier.cpp +++ b/services/distributedfiledaemon/src/channel_manager/system_notifier.cpp @@ -513,6 +513,26 @@ std::string SystemNotifier::GetRemoteDeviceName(const std::string &networkId) return deviceName; } +void SystemNotifier::ClearAllConnect() +{ + LOGI("ClearALLConnect start."); + std::shared_lock readLock(mutex); + std::vector needClearItems; + for (const auto &pair : notificationMap_) { + needClearItems.push_back(pair.first); + } + for (const auto &networkId :needClearItems) { + // donot disconncetbyremote + DestroyNotifyByNetworkId(networkId); + } +} + +int32_t SystemNotifier::GetNotificationMapSize() +{ + LOGI("GetNotificationMapSize size is %{public}zu", notificationMap_.size()); + return notificationMap_.size(); +} + } // namespace DistributedFile } // namespace Storage } // namespace OHOS \ No newline at end of file diff --git a/services/distributedfiledaemon/src/device/device_manager_agent.cpp b/services/distributedfiledaemon/src/device/device_manager_agent.cpp index 75a616fcc..15137085a 100644 --- a/services/distributedfiledaemon/src/device/device_manager_agent.cpp +++ b/services/distributedfiledaemon/src/device/device_manager_agent.cpp @@ -37,6 +37,7 @@ #include "parameters.h" #include "softbus_bus_center.h" #include "system_ability_definition.h" +#include "system_notifier.h" #include "utils_log.h" namespace OHOS { @@ -128,6 +129,7 @@ void DeviceManagerAgent::QuitGroup(shared_ptr smp) { LOGI("quit group begin"); OfflineAllDevice(); + SystemNotifier::GetInstance().ClearAllConnect(); if (!smp) { stringstream ss("Failed to quit group: Received empty mountpoint"); @@ -489,6 +491,7 @@ int32_t DeviceManagerAgent::MountDfsDocs(const std::string &networkId, LOGE("GetCurrentUserId Fail"); return INVALID_USER_ID; } + currentUserId_ = userId; GetStorageManager(); if (storageMgrProxy_ == nullptr) { LOGE("storageMgrProxy_ is null"); @@ -519,7 +522,7 @@ int32_t DeviceManagerAgent::UMountDfsDocs(const std::string &networkId, const st LOGE("do not need umount"); return ret; } - int32_t userId = GetCurrentUserId(); + int32_t userId = currentUserId_; if (userId == INVALID_USER_ID) { LOGE("GetCurrentUserId Fail"); return INVALID_USER_ID; diff --git a/services/distributedfiledaemon/src/ipc/daemon.cpp b/services/distributedfiledaemon/src/ipc/daemon.cpp index c2d004395..70f3fb568 100644 --- a/services/distributedfiledaemon/src/ipc/daemon.cpp +++ b/services/distributedfiledaemon/src/ipc/daemon.cpp @@ -286,14 +286,14 @@ int32_t Daemon::ConnectionAndMount(const DistributedHardware::DmDeviceInfo &devi sptr remoteReverseObj) { LOGI("ConnectionAndMount start"); - int32_t ret = CheckRemoteAllowConnect(networkId); - if (ret != E_OK) { - LOGE("CheckRemoteAllowConnect failed for %{public}.6s, ret is %{public}d", networkId.c_str(), ret); - return ret; + bool hasFileAccessManager = DfsuAccessTokenHelper::CheckCallerPermission(FILE_ACCESS_MANAGER_PERMISSION); + if (hasFileAccessManager && CheckRemoteAllowConnect(networkId) != NO_ERROR) { + LOGE("CheckRemoteAllowConnect failed for %{public}.6s", networkId.c_str()); + return E_PERMISSION; } auto callingTokenId = IPCSkeleton::GetCallingTokenID(); - ret = ConnectionCount(deviceInfo); + auto ret = ConnectionCount(deviceInfo); if (ret != NO_ERROR) { LOGE("connection failed"); if (ret == ERR_CHECKOUT_COUNT) { @@ -304,7 +304,7 @@ int32_t Daemon::ConnectionAndMount(const DistributedHardware::DmDeviceInfo &devi ConnectCount::GetInstance()->AddConnect(callingTokenId, networkId, remoteReverseObj); - if (!DfsuAccessTokenHelper::CheckCallerPermission(FILE_ACCESS_MANAGER_PERMISSION)) { + if (!hasFileAccessManager) { LOGW("permission denied: FILE_ACCESS_MANAGER_PERMISSION"); return ret; } @@ -313,7 +313,7 @@ int32_t Daemon::ConnectionAndMount(const DistributedHardware::DmDeviceInfo &devi ret = deviceManager->MountDfsDocs(networkId, mountPath, callingTokenId); if (ret != NO_ERROR) { ConnectCount::GetInstance()->RemoveConnect(callingTokenId, networkId); - LOGE("[MountDfsDocs] failed"); + LOGE("[MountDfsDocs] failed, ret is %{public}d", ret); return ret; } ConnectCount::GetInstance()->NotifyFileStatusChange(networkId, Status::CONNECT_OK, HMDFS_FATH + mountPath, @@ -325,6 +325,11 @@ int32_t Daemon::ConnectionAndMount(const DistributedHardware::DmDeviceInfo &devi int32_t Daemon::OpenP2PConnectionEx(const std::string &networkId, sptr remoteReverseObj) { LOGI("Daemon::OpenP2PConnectionEx start, networkId %{public}.6s", networkId.c_str()); + if (DfsuAccessTokenHelper::CheckCallerPermission(FILE_ACCESS_MANAGER_PERMISSION) && ControlCmdParser::IsLocalItDevice()) { + LOGE("FILE_ACCESS_MANAGER_PERMISSION permission has not support it situation"); + return E_PERMISSION; + } + if (!DfsuAccessTokenHelper::CheckCallerPermission(PERM_DISTRIBUTED_DATASYNC)) { LOGE("[CloseP2PConnectionEx] DATASYNC permission denied"); return E_PERMISSION; @@ -369,6 +374,11 @@ int32_t Daemon::OpenP2PConnectionEx(const std::string &networkId, sptrRemoveAllConnect(); } +// for closeP2P void NetworkAgentTemplate::DisconnectDeviceByP2P(const DeviceInfo info) { LOGI("CloseP2P, cid:%{public}s", Utils::GetAnonyString(info.GetCid()).c_str()); @@ -131,6 +133,7 @@ void NetworkAgentTemplate::DisconnectDeviceByP2PHmdfs(const DeviceInfo info) StatusType::CONNECTION_STATUS); } +// softbus offline, allConnect offline, hmdfs never has socket void NetworkAgentTemplate::CloseSessionForOneDevice(const string &cid) { auto cmd = make_unique>( @@ -139,7 +142,6 @@ void NetworkAgentTemplate::CloseSessionForOneDevice(const string &cid) Recv(move(cmd)); } -// softbus offline, allConnect offline, hmdfs never has socket void NetworkAgentTemplate::CloseSessionForOneDeviceInner(std::string cid) { sessionPool_.ReleaseSession(cid, true); @@ -165,6 +167,7 @@ bool NetworkAgentTemplate::FindSocketId(int32_t socketId) return sessionPool_.FindSocketId(socketId); } +// hmdfs offline void NetworkAgentTemplate::GetSessionProcess(NotifyParam ¶m) { auto cmd = make_unique>( @@ -181,13 +184,15 @@ void NetworkAgentTemplate::GetSessionProcessInner(NotifyParam param) bool ifGetSession = sessionPool_.CheckIfGetSession(fd); sessionPool_.ReleaseSession(fd); if (ifGetSession && ConnectCount::GetInstance()->CheckCount(cidStr)) { + // for client GetSession(cidStr); } else { + // for server sessionPool_.SinkOffline(cidStr); + SystemNotifier::GetInstance().DestroyNotifyByNetworkId(cidStr); } } -// hmdfs offline void NetworkAgentTemplate::GetSession(const string &cid) { std::this_thread::sleep_for(std::chrono::seconds(NOTIFY_GET_SESSION_WAITING_TIME)); diff --git a/services/distributedfiledaemon/test/unittest/ipc/daemon/daemon_test.cpp b/services/distributedfiledaemon/test/unittest/ipc/daemon/daemon_test.cpp index 8ea0a091a..84e3aceaa 100644 --- a/services/distributedfiledaemon/test/unittest/ipc/daemon/daemon_test.cpp +++ b/services/distributedfiledaemon/test/unittest/ipc/daemon/daemon_test.cpp @@ -25,6 +25,7 @@ #include "common_event_manager.h" #include "connect_count/connect_count.h" #include "connection_detector_mock.h" +#include "control_cmd_parser.h" #include "copy/file_size_utils.h" #include "daemon.h" #include "daemon_execute.h" @@ -49,6 +50,7 @@ #include "system_ability_manager_client_mock.h" namespace { +bool g_isLocalItDevice = false; bool g_checkCallerPermission = true; bool g_checkCallerPermissionDatasync = true; int g_getHapTokenInfo = 0; @@ -115,6 +117,11 @@ int32_t DeviceProfileAdapter::PutDeviceStatus(bool status) { return g_putDeviceStatus; } + +bool ControlCmdParser::IsLocalItDevice() +{ + return g_isLocalItDevice; +} } // namespace OHOS::Storage::DistributedFile namespace OHOS::FileManagement { @@ -266,8 +273,6 @@ void DaemonTest::SetUpTestCase(void) ISoftBusHandlerMock::iSoftBusHandlerMock_ = softBusHandlerMock_; deviceManagerImplMock_ = std::make_shared(); DfsDeviceManagerImpl::dfsDeviceManagerImpl = deviceManagerImplMock_; - channelManagerMock_ = std::make_shared(); - IChannelManagerMock::iChannelManagerMock = channelManagerMock_; std::string path = "/mnt/hmdfs/100/account/device_view/local/data/com.example.app"; if (!std::filesystem::exists(path)) { @@ -299,8 +304,6 @@ void DaemonTest::TearDownTestCase(void) softBusHandlerMock_ = nullptr; deviceManagerImplMock_ = nullptr; DfsDeviceManagerImpl::dfsDeviceManagerImpl = nullptr; - channelManagerMock_ = nullptr; - IChannelManagerMock::iChannelManagerMock = nullptr; deviceManagerImplMock_ = nullptr; DfsDeviceManagerImpl::dfsDeviceManagerImpl = nullptr; @@ -330,12 +333,17 @@ void DaemonTest::SetUp(void) .authForm = OHOS::DistributedHardware::DmAuthForm::IDENTICAL_ACCOUNT, .extraData = "{\"OS_TYPE\":10}", }; + g_isLocalItDevice = false; + channelManagerMock_ = std::make_shared(); + IChannelManagerMock::iChannelManagerMock = channelManagerMock_; } void DaemonTest::TearDown(void) { GTEST_LOG_(INFO) << "TearDown"; daemon_ = nullptr; + channelManagerMock_ = nullptr; + IChannelManagerMock::iChannelManagerMock = nullptr; } /** @@ -618,6 +626,17 @@ HWTEST_F(DaemonTest, DaemonTest_ConnectionAndMount_001, TestSize.Level1) DistributedHardware::DmDeviceInfo deviceInfo = {.networkId = "test"}; sptr remoteReverseObj = nullptr; ConnectCount::GetInstance()->RemoveAllConnect(); + + // g_checkCallerPermission is ok but remote reject + g_checkCallerPermission = true; + g_isRemoteDfsVersionLowerThanGiven = true; + EXPECT_CALL(*channelManagerMock_, HasExistChannel(_)).WillRepeatedly(Return(true)); + // EXPECT_CALL(*channelManagerMock_, SendRequest(_, _, _, _)).WillRepeatedly(Return(FileManagement::ERR_OK)); + EXPECT_EQ(daemon_->ConnectionAndMount(deviceInfo, "test", remoteReverseObj), E_PERMISSION); + + // g_checkCallerPermission is false + g_checkCallerPermission = true; + g_isRemoteDfsVersionLowerThanGiven = false; EXPECT_CALL(*deviceManagerAgentMock_, OnDeviceP2POnline(_)).WillOnce(Return(ERR_BAD_VALUE)); EXPECT_EQ(daemon_->ConnectionAndMount(deviceInfo, "test", remoteReverseObj), ERR_BAD_VALUE); @@ -650,19 +669,30 @@ HWTEST_F(DaemonTest, DaemonTest_OpenP2PConnectionEx_001, TestSize.Level1) { GTEST_LOG_(INFO) << "DaemonTest_OpenP2PConnectionEx_001 begin"; + // check fileAccessManager permit failed + g_checkCallerPermission = true; + g_isLocalItDevice = true; + EXPECT_EQ(daemon_->OpenP2PConnectionEx("", nullptr), E_PERMISSION); + // check permission failed + g_isLocalItDevice = false; g_checkCallerPermissionDatasync = false; EXPECT_EQ(daemon_->OpenP2PConnectionEx("", nullptr), E_PERMISSION); // networkId length is invalid + g_checkCallerPermission = false; g_checkCallerPermissionDatasync = true; EXPECT_EQ(daemon_->OpenP2PConnectionEx("", nullptr), E_INVAL_ARG_NAPI); std::string longNetworkId(DM_MAX_DEVICE_ID_LEN, 'a'); EXPECT_EQ(daemon_->OpenP2PConnectionEx(longNetworkId, nullptr), E_INVAL_ARG_NAPI); - // networkId is valid + // networkId is valid and obj is null std::string validNetworkId(64, 'a'); - EXPECT_NE(daemon_->OpenP2PConnectionEx("", nullptr), NO_ERROR); + EXPECT_EQ(daemon_->OpenP2PConnectionEx(validNetworkId, nullptr), NO_ERROR); + + // networkId is valid and obj is not null + auto listener = sptr(new FileDfsListenerMock()); + EXPECT_EQ(daemon_->OpenP2PConnectionEx(validNetworkId, listener), NO_ERROR); GTEST_LOG_(INFO) << "DaemonTest_OpenP2PConnectionEx_001 end"; } @@ -677,11 +707,18 @@ HWTEST_F(DaemonTest, DaemonTest_CloseP2PConnectionEx_001, TestSize.Level1) { GTEST_LOG_(INFO) << "DaemonTest_CloseP2PConnectionEx_001 begin"; + // check fileAccessManager permit failed + g_checkCallerPermission = true; + g_isLocalItDevice = true; + EXPECT_EQ(daemon_->CloseP2PConnectionEx(""), E_PERMISSION); + // check permission failed + g_isLocalItDevice = false; g_checkCallerPermissionDatasync = false; EXPECT_EQ(daemon_->CloseP2PConnectionEx(""), E_PERMISSION); // networkId length is invalid + g_checkCallerPermission = false; g_checkCallerPermissionDatasync = true; EXPECT_EQ(daemon_->CloseP2PConnectionEx(""), E_INVAL_ARG_NAPI); std::string longNetworkId(DM_MAX_DEVICE_ID_LEN, 'a'); @@ -1437,7 +1474,7 @@ HWTEST_F(DaemonTest, DaemonTest_CheckRemoteAllowConnect_001, TestSize.Level1) GTEST_LOG_(INFO) << "DaemonTest_CheckRemoteAllowConnect_001"; // Test remoteDfs version is lower g_isRemoteDfsVersionLowerThanGiven = true; - EXPECT_EQ(daemon_->CheckRemoteAllowConnect("networkId"), FileManagement::ERR_OK); + EXPECT_EQ(daemon_->CheckRemoteAllowConnect("networkId"), FileManagement::ERR_VERSION_NOT_SUPPORT); // Test SendRequest failed g_isRemoteDfsVersionLowerThanGiven = false; @@ -1464,7 +1501,7 @@ HWTEST_F(DaemonTest, DaemonTest_NotifyRemotePublishNotification_001, TestSize.Le GTEST_LOG_(INFO) << "DaemonTest_NotifyRemotePublishNotification_001"; // Test remoteDfs version is lower g_isRemoteDfsVersionLowerThanGiven = true; - EXPECT_EQ(daemon_->NotifyRemotePublishNotification("networkId"), FileManagement::ERR_OK); + EXPECT_EQ(daemon_->NotifyRemotePublishNotification("networkId"), FileManagement::ERR_VERSION_NOT_SUPPORT); // Test CreatControlLink failed g_isRemoteDfsVersionLowerThanGiven = false; @@ -1497,7 +1534,7 @@ HWTEST_F(DaemonTest, DaemonTest_NotifyRemoteCancelNotification_001, TestSize.Lev GTEST_LOG_(INFO) << "DaemonTest_NotifyRemoteCancelNotification_001"; // Test remoteDfs version is lower g_isRemoteDfsVersionLowerThanGiven = true; - EXPECT_EQ(daemon_->NotifyRemotePublishNotification("networkId"), FileManagement::ERR_OK); + EXPECT_EQ(daemon_->NotifyRemoteCancelNotification("networkId"), FileManagement::ERR_VERSION_NOT_SUPPORT); // Test CreatControlLink failed g_isRemoteDfsVersionLowerThanGiven = false; diff --git a/utils/log/include/dfs_error.h b/utils/log/include/dfs_error.h index 23814f04f..4a02ced00 100644 --- a/utils/log/include/dfs_error.h +++ b/utils/log/include/dfs_error.h @@ -168,6 +168,7 @@ enum DFSErrCode { ERR_POST_TASK_FAILED, ERR_NO_EXIST_CHANNEL, ERR_DATA_INVALID, + ERR_VERSION_NOT_SUPPORT }; static inline std::unordered_map softbusErr2ErrCodeTable { -- Gitee From ca1c0e0b15fd8f056bcf4d8f9a1cf33121175326 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AE=81=E7=AB=9E=E8=8E=9C?= Date: Sat, 30 Aug 2025 18:07:10 +0800 Subject: [PATCH 4/5] fix bug MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 宁竞莜 --- .../include/device/device_manager_agent.h | 2 ++ services/distributedfiledaemon/src/ipc/daemon.cpp | 6 ++++-- .../test/unittest/ipc/daemon/daemon_test.cpp | 1 - 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/services/distributedfiledaemon/include/device/device_manager_agent.h b/services/distributedfiledaemon/include/device/device_manager_agent.h index fd8244714..228ae8f1e 100644 --- a/services/distributedfiledaemon/include/device/device_manager_agent.h +++ b/services/distributedfiledaemon/include/device/device_manager_agent.h @@ -150,6 +150,8 @@ private: std::unordered_map mountDfsCount_; std::mutex networkIdMapMutex_; std::unordered_map> networkIdMap_; + + int32_t currentUserId_ = -1; }; } // namespace DistributedFile } // namespace Storage diff --git a/services/distributedfiledaemon/src/ipc/daemon.cpp b/services/distributedfiledaemon/src/ipc/daemon.cpp index 70f3fb568..48cbc604f 100644 --- a/services/distributedfiledaemon/src/ipc/daemon.cpp +++ b/services/distributedfiledaemon/src/ipc/daemon.cpp @@ -325,7 +325,8 @@ int32_t Daemon::ConnectionAndMount(const DistributedHardware::DmDeviceInfo &devi int32_t Daemon::OpenP2PConnectionEx(const std::string &networkId, sptr remoteReverseObj) { LOGI("Daemon::OpenP2PConnectionEx start, networkId %{public}.6s", networkId.c_str()); - if (DfsuAccessTokenHelper::CheckCallerPermission(FILE_ACCESS_MANAGER_PERMISSION) && ControlCmdParser::IsLocalItDevice()) { + if (DfsuAccessTokenHelper::CheckCallerPermission(FILE_ACCESS_MANAGER_PERMISSION) && + ControlCmdParser::IsLocalItDevice()) { LOGE("FILE_ACCESS_MANAGER_PERMISSION permission has not support it situation"); return E_PERMISSION; } @@ -374,7 +375,8 @@ int32_t Daemon::OpenP2PConnectionEx(const std::string &networkId, sptrConnectionAndMount(deviceInfo, "test", remoteReverseObj), E_PERMISSION); // g_checkCallerPermission is false -- Gitee From f52a71e95b3b1c6f2e6dd9f09e883e3cd16b70f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AE=81=E7=AB=9E=E8=8E=9C?= Date: Tue, 2 Sep 2025 11:46:28 +0800 Subject: [PATCH 5/5] =?UTF-8?q?fix=20=E6=A3=80=E8=A7=86=E6=84=8F=E8=A7=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 宁竞莜 --- .../include/connect_count/connect_count.h | 2 +- .../src/channel_manager/channel_manager.cpp | 1 - .../distributedfiledaemon/src/connect_count/connect_count.cpp | 4 +++- .../distributedfiledaemon/src/device/device_manager_agent.cpp | 3 ++- services/distributedfiledaemon/src/ipc/daemon.cpp | 4 ++-- 5 files changed, 8 insertions(+), 6 deletions(-) diff --git a/services/distributedfiledaemon/include/connect_count/connect_count.h b/services/distributedfiledaemon/include/connect_count/connect_count.h index 1878db397..8ac745925 100644 --- a/services/distributedfiledaemon/include/connect_count/connect_count.h +++ b/services/distributedfiledaemon/include/connect_count/connect_count.h @@ -67,7 +67,7 @@ public: void AddFileConnect(const std::string &instanceId, const sptr &listener); bool RmFileConnect(const std::string &instanceId); void NotifyFileStatusChange(const std::string &networkId, - int32_t status, const std::string &path, StatusType type); + const int32_t status, const std::string &path, StatusType type); private: static std::shared_ptr instance_; std::recursive_mutex connectMutex_; diff --git a/services/distributedfiledaemon/src/channel_manager/channel_manager.cpp b/services/distributedfiledaemon/src/channel_manager/channel_manager.cpp index abe471b0e..854ad20fd 100644 --- a/services/distributedfiledaemon/src/channel_manager/channel_manager.cpp +++ b/services/distributedfiledaemon/src/channel_manager/channel_manager.cpp @@ -591,7 +591,6 @@ int32_t ChannelManager::NotifyClient(const std::string &networkId, const Control LOGE("DoSendBytes failed."); return ERR_SEND_DATA_BY_SOFTBUS_FAILED; } - return ret; } diff --git a/services/distributedfiledaemon/src/connect_count/connect_count.cpp b/services/distributedfiledaemon/src/connect_count/connect_count.cpp index d20695fd6..25428d24d 100644 --- a/services/distributedfiledaemon/src/connect_count/connect_count.cpp +++ b/services/distributedfiledaemon/src/connect_count/connect_count.cpp @@ -169,7 +169,9 @@ bool ConnectCount::RmFileConnect(const std::string &instanceId) } void ConnectCount::NotifyFileStatusChange(const std::string &networkId, - int32_t status, const std::string &path, StatusType type) + const int32_t status, + const std::string &path, + StatusType type) { std::lock_guard lock(fileConnectMutex_); for (const auto &connect : fileConnectMap_) { diff --git a/services/distributedfiledaemon/src/device/device_manager_agent.cpp b/services/distributedfiledaemon/src/device/device_manager_agent.cpp index 15137085a..609923cdf 100644 --- a/services/distributedfiledaemon/src/device/device_manager_agent.cpp +++ b/services/distributedfiledaemon/src/device/device_manager_agent.cpp @@ -360,7 +360,8 @@ bool DeviceManagerAgent::UMountDfsCountOnly(const std::string &deviceId, bool ne } if (needClear) { LOGI("mountDfsCount_ erase"); - itCount->second.callingCountMap_.clear(); + std::map emptyMap; + itCount->second.callingCountMap_.swap(emptyMap); return false; } auto &callingCountMap = itCount->second.callingCountMap_; diff --git a/services/distributedfiledaemon/src/ipc/daemon.cpp b/services/distributedfiledaemon/src/ipc/daemon.cpp index 48cbc604f..f60fa3f22 100644 --- a/services/distributedfiledaemon/src/ipc/daemon.cpp +++ b/services/distributedfiledaemon/src/ipc/daemon.cpp @@ -501,7 +501,7 @@ int32_t Daemon::PrepareSession(const std::string &srcUri, const sptr &listener, HmdfsInfo &info) { - LOGE("PrepareSession networkId: %{public}.6s", networkId.c_str()); + LOGI("PrepareSession networkId: %{public}.6s", networkId.c_str()); auto listenerCallback = iface_cast(listener); if (listenerCallback == nullptr) { @@ -1102,7 +1102,7 @@ int32_t Daemon::IsSameAccountDevice(const std::string &networkId, bool &isSameAc #ifdef SUPPORT_SAME_ACCOUNT std::vector deviceList; DistributedHardware::DeviceManager::GetInstance().GetTrustedDeviceList(IDaemon::SERVICE_NAME, "", deviceList); - if (deviceList.size() == 0) { + if (deviceList.empty()) { LOGE("trust device list size is invalid, size=%zu", deviceList.size()); isSameAccount = false; return E_INVAL_ARG_NAPI; -- Gitee