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 #include "dup.h"
16 
17 #include <memory>
18 #include <sys/types.h>
19 #include <tuple>
20 #include <unistd.h>
21 
22 #include "class_file/file_entity.h"
23 #include "common_func.h"
24 #include "filemgmt_libhilog.h"
25 
26 namespace OHOS::FileManagement::ModuleFileIO {
27 using namespace std;
28 using namespace OHOS::FileManagement::LibN;
29 
Sync(napi_env env,napi_callback_info info)30 napi_value Dup::Sync(napi_env env, napi_callback_info info)
31 {
32     NFuncArg funcArg(env, info);
33     if (!funcArg.InitArgs(NARG_CNT::ONE)) {
34         HILOGE("Number of arguments unmatched");
35         NError(EINVAL).ThrowErr(env);
36         return nullptr;
37     }
38     auto [succ, srcFd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32();
39     if (!succ || srcFd < 0) {
40         HILOGE("Invalid fd");
41         NError(EINVAL).ThrowErr(env);
42         return nullptr;
43     }
44     int dstFd = dup(srcFd);
45     if (dstFd < 0) {
46         HILOGE("Failed to dup fd, errno: %{public}d", errno);
47         NError(errno).ThrowErr(env);
48         return nullptr;
49     }
50     unique_ptr<uv_fs_t, decltype(CommonFunc::fs_req_cleanup)*> readlink_req = {
51         new (std::nothrow) uv_fs_t, CommonFunc::fs_req_cleanup };
52     if (!readlink_req) {
53         HILOGE("Failed to request heap memory.");
54         NError(ENOMEM).ThrowErr(env);
55         return nullptr;
56     }
57     string path = "/proc/self/fd/" + to_string(dstFd);
58     int ret = uv_fs_readlink(nullptr, readlink_req.get(), path.c_str(), nullptr);
59     if (ret < 0) {
60         HILOGE("Failed to readlink fd, ret: %{public}d", ret);
61         NError(ret).ThrowErr(env);
62         return nullptr;
63     }
64     return CommonFunc::InstantiateFile(env, dstFd, string(static_cast<const char *>(readlink_req->ptr)), false).val_;
65 }
66 } // namespace OHOS::FileManagement::ModuleFileIO