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 <sys/fsuid.h>
18 #include <unistd.h>
19 
20 #define PARAM_0 0
21 #define ONEVAL 1
22 #define MINUSONE (-1)
23 
Setfsgid(napi_env env, napi_callback_info info)24 static napi_value Setfsgid(napi_env env, napi_callback_info info)
25 {
26     napi_value result;
27     const gid_t fsgid = ONEVAL;
28     int setval = setfsgid(fsgid);
29     if (setval < PARAM_0) {
30         napi_create_int32(env, MINUSONE, &result);
31     } else {
32         napi_create_int32(env, PARAM_0, &result);
33     }
34     return result;
35 }
36 
Setfsuid(napi_env env, napi_callback_info info)37 static napi_value Setfsuid(napi_env env, napi_callback_info info)
38 {
39     const gid_t invalid_fsuid = ONEVAL;
40     int setval = setfsuid(invalid_fsuid);
41     napi_value result;
42     if (setval < PARAM_0) {
43         napi_create_int32(env, MINUSONE, &result);
44     } else {
45         napi_create_int32(env, PARAM_0, &result);
46     }
47     return result;
48 }
49 
50 EXTERN_C_START
Init(napi_env env, napi_value exports)51 static napi_value Init(napi_env env, napi_value exports)
52 {
53     napi_property_descriptor desc[] = {
54         {"setfsgid", nullptr, Setfsgid, nullptr, nullptr, nullptr, napi_default, nullptr},
55         {"setfsuid", nullptr, Setfsuid, nullptr, nullptr, nullptr, napi_default, nullptr},
56     };
57     napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
58     return exports;
59 }
60 
61 EXTERN_C_END
62 
63 static napi_module demoModule = {
64     .nm_version = 1,
65     .nm_flags = 0,
66     .nm_filename = nullptr,
67     .nm_register_func = Init,
68     .nm_modname = "fsuid",
69     .nm_priv = ((void *)0),
70     .reserved = {0},
71 };
72 
RegisterEntryModule(void)73 extern "C" __attribute__((constructor)) void RegisterEntryModule(void) { napi_module_register(&demoModule); }
74