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 <js_native_api.h>
17 #include <js_native_api_types.h>
18 #include <linux/capability.h>
19 #include <node_api.h>
20 #include <sys/capability.h>
21 #include <unistd.h>
22
23 #define PARAM_0 0
24 #define PARAM_1 1
25 #define FAIL (-1)
26
Capset(napi_env env, napi_callback_info info)27 static napi_value Capset(napi_env env, napi_callback_info info)
28 {
29 struct __user_cap_header_struct cap_header;
30 struct __user_cap_data_struct cap_data;
31 cap_header.pid = getpid();
32 cap_header.version = _LINUX_CAPABILITY_VERSION_1;
33 int ret = FAIL;
34 if (capget(&cap_header, &cap_data) >= PARAM_0) {
35 __u32 cap_mask = PARAM_0;
36 cap_mask |= (PARAM_1 << CAP_NET_BIND_SERVICE);
37 cap_data.effective = cap_mask;
38 cap_data.permitted = cap_mask;
39 cap_data.inheritable = PARAM_0;
40 if (capset(&cap_header, &cap_data) >= PARAM_0) {
41 ret = PARAM_1;
42 }
43 }
44 napi_value result;
45 napi_create_int32(env, ret, &result);
46 return result;
47 }
48
49 EXTERN_C_START
Init(napi_env env, napi_value exports)50 static napi_value Init(napi_env env, napi_value exports)
51 {
52 napi_property_descriptor desc[] = {{"capset", nullptr, Capset, nullptr, nullptr, nullptr, napi_default, nullptr}};
53 napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
54 return exports;
55 }
56 EXTERN_C_END
57
58 static napi_module demoModule = {
59 .nm_version = 1,
60 .nm_flags = 0,
61 .nm_filename = "capabilityndk",
62 .nm_register_func = Init,
63 .nm_modname = "capabilityndk",
64 .nm_priv = ((void *)0),
65 .reserved = {0},
66 };
67
RegisterModule(void)68 extern "C" __attribute__((constructor)) void RegisterModule(void) { napi_module_register(&demoModule); }