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 #include "usb_ddk_permission.h"
16 
17 #include <hdf_log.h>
18 #include <dlfcn.h>
19 
20 #include "ipc_skeleton.h"
21 
22 namespace OHOS {
23 namespace HDI {
24 namespace Usb {
25 namespace Ddk {
26 namespace V1_0 {
27 using VerifyAccessTokenFunc = int(*)(uint32_t callerToken, const std::string &permissionName);
28 
29 static constexpr int PERMISSION_GRANTED = 0;
30 
31 static void *g_libHandle = nullptr;
32 static VerifyAccessTokenFunc g_verifyAccessToken = nullptr;
33 
InitVerifyAccessToken()34 static void InitVerifyAccessToken()
35 {
36     if (g_verifyAccessToken != nullptr) {
37         return;
38     }
39 
40     g_libHandle = dlopen("libusb_ddk_dynamic_library_wrapper.z.so", RTLD_LAZY);
41     if (g_libHandle == nullptr) {
42         HDF_LOGE("%{public}s dlopen failed: %{public}s", __func__, dlerror());
43         return;
44     }
45 
46     void *funcPtr = dlsym(g_libHandle, "VerifyAccessToken");
47     if (funcPtr == nullptr) {
48         HDF_LOGE("%{public}s dlsym failed: %{public}s", __func__, dlerror());
49         dlclose(g_libHandle);
50         g_libHandle = nullptr;
51         return;
52     }
53 
54     g_verifyAccessToken = reinterpret_cast<VerifyAccessTokenFunc>(funcPtr);
55 }
56 
Reset()57 void DdkPermissionManager::Reset()
58 {
59     g_verifyAccessToken = nullptr;
60     if (g_libHandle != nullptr) {
61         dlclose(g_libHandle);
62         g_libHandle = nullptr;
63     }
64 }
65 
VerifyPermission(const std::string & permissionName)66 bool DdkPermissionManager::VerifyPermission(const std::string &permissionName)
67 {
68     InitVerifyAccessToken();
69     if (g_verifyAccessToken == nullptr) {
70         return false;
71     }
72 
73     uint32_t callerToken = IPCSkeleton::GetCallingTokenID();
74     int result = g_verifyAccessToken(callerToken, permissionName);
75     HDF_LOGI("%{public}s VerifyAccessToken: %{public}d", __func__, result);
76     return result == PERMISSION_GRANTED;
77 }
78 } // namespace V1_0
79 } // namespace Ddk
80 } // namespace Usb
81 } // namespace HDI
82 } // namespace OHOS