1 /*
2  * Copyright (c) 2023 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 "napi/native_api.h"
17 #include <js_native_api.h>
18 #include <js_native_api_types.h>
19 #include <linux/capability.h>
20 #include <node_api.h>
21 #include <sys/capability.h>
22 #include <unistd.h>
23 #include <uv.h>
24 
25 #define PARAM_0 0
26 #define PARAM_1 1
27 #define FAIL (-1)
28 #define PARAM_UNNORMAL (-1)
29 #define ERRNO_0 0
30 #define ONEVAL 1
31 
CapGet(napi_env env, napi_callback_info info)32 static napi_value CapGet(napi_env env, napi_callback_info info)
33 {
34     size_t argc = ONEVAL;
35     napi_value args[1] = {nullptr};
36     napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
37     int param;
38     napi_get_value_int32(env, args[0], &param);
39 
40     int ret;
41     struct __user_cap_data_struct cap_data;
42     errno = ERRNO_0;
43     if (param == PARAM_0) {
44         struct __user_cap_header_struct cap_header;
45         cap_header.pid = getpid();
46         cap_header.version = _LINUX_CAPABILITY_VERSION_1;
47         ret = capget(&cap_header, &cap_data);
48     } else {
49         ret = capget(nullptr, &cap_data);
50     }
51 
52     napi_value result = nullptr;
53     napi_create_int32(env, ret, &result);
54     return result;
55 }
56 
57 EXTERN_C_START
Init(napi_env env, napi_value exports)58 static napi_value Init(napi_env env, napi_value exports)
59 {
60     napi_property_descriptor desc[] = {
61         {"capget", nullptr, CapGet, nullptr, nullptr, nullptr, napi_default, nullptr},
62     };
63     napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
64     return exports;
65 }
66 EXTERN_C_END
67 
68 static napi_module demoModule = {
69     .nm_version = 1,
70     .nm_flags = 0,
71     .nm_filename = "capability1ndk",
72     .nm_register_func = Init,
73     .nm_modname = "capability1ndk",
74     .nm_priv = ((void *)0),
75     .reserved = {0},
76 };
77 
RegisterModule(void)78 extern "C" __attribute__((constructor)) void RegisterModule(void) { napi_module_register(&demoModule); }