1/*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#include "plugin_loader.h"
17
18#include <dlfcn.h>
19#include <unistd.h>
20#include <vector>
21
22#include "utils_log.h"
23
24namespace OHOS::FileManagement::CloudFile {
25using namespace std;
26
27PluginLoader &PluginLoader::GetInstance()
28{
29    static PluginLoader instance;
30    return instance;
31}
32
33PluginLoader::~PluginLoader()
34{
35    if (cloudKitPulginHandle_ == nullptr) {
36        return;
37    }
38    dlclose(cloudKitPulginHandle_);
39    LOGI("succ to unload plugin");
40    cloudKitPulginHandle_ = nullptr;
41}
42
43string GetPluginPath(const string &pluginFileName)
44{
45    const string searchDirs[] = {"/system/lib64/", "system/lib/"};
46    string pluginFilePath = "";
47    for (auto &searchDir : searchDirs) {
48        std::string tmpPath = searchDir + pluginFileName;
49        if (access(tmpPath.c_str(), F_OK) == 0) {
50            pluginFilePath = tmpPath;
51            break;
52        }
53    }
54    return pluginFilePath;
55}
56
57void PluginLoader::LoadCloudKitPlugin(bool isSupportCloudSync)
58{
59    std::vector<std::string> pluginFileNames;
60    pluginFileNames.emplace_back(isSupportCloudSync ? "libcloudfile_ext.z.so" : "libcloudfile_ext_core.z.so");
61    pluginFileNames.emplace_back("libcloud_adapter.z.so");
62    for (auto &pluginFileName : pluginFileNames) {
63        auto pluginFilePath = GetPluginPath(pluginFileName);
64        if (!pluginFilePath.empty()) {
65            char resolvedPath[PATH_MAX] = {'\0'};
66            if (realpath(pluginFilePath.c_str(), resolvedPath) == nullptr) {
67                LOGE("realpath failed in line path: %s", pluginFilePath.c_str());
68                return;
69            }
70            cloudKitPulginHandle_ = dlopen(pluginFilePath.c_str(), RTLD_LAZY);
71            if (cloudKitPulginHandle_ == nullptr) {
72                LOGE("dlopen failed, path:%{public}s", pluginFilePath.c_str());
73            } else {
74                LOGI("succ to load plugin, path:%{public}s", pluginFilePath.c_str());
75            }
76            return;
77        }
78    }
79    LOGE("Load CloudKit Plugin failed");
80}
81} // namespace OHOS::FileManagement::CloudFile