1 /*
2 * Copyright (c) 2025 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 "dup_core.h"
17
18 #include <memory>
19 #include <tuple>
20 #include <unistd.h>
21 #include <sys/types.h>
22
23 #include "file_entity.h"
24 #include "file_instantiator.h"
25 #include "file_utils.h"
26 #include "filemgmt_libhilog.h"
27 #include "fs_utils.h"
28
29 namespace OHOS::FileManagement::ModuleFileIO {
30 using namespace std;
31
ValidFd(const int32_t & fd)32 static bool ValidFd(const int32_t &fd)
33 {
34 if (fd < 0) {
35 HILOGE("Invalid fd");
36 return false;
37 }
38 return true;
39 }
40
DoDup(const int32_t & fd)41 FsResult<FsFile *> DupCore::DoDup(const int32_t &fd)
42 {
43 if (!ValidFd(fd)) {
44 return FsResult<FsFile *>::Error(EINVAL);
45 }
46 int dstFd = dup(fd);
47 if (dstFd < 0) {
48 HILOGE("Failed to dup fd, errno: %{public}d", errno);
49 return FsResult<FsFile *>::Error(errno);
50 }
51
52 unique_ptr<uv_fs_t, decltype(FsUtils::FsReqCleanup)*> readLinkReq = {
53 new (std::nothrow) uv_fs_t, FsUtils::FsReqCleanup };
54 if (!readLinkReq) {
55 HILOGE("Failed to request heap memory.");
56 close(dstFd);
57 return FsResult<FsFile *>::Error(ENOMEM);
58 }
59 string path = "/proc/self/fd/" + to_string(dstFd);
60 int ret = uv_fs_readlink(nullptr, readLinkReq.get(), path.c_str(), nullptr);
61 if (ret < 0 || readLinkReq->ptr == nullptr) {
62 HILOGE("Failed to readlink fd, ret: %{public}d", ret);
63 close(dstFd);
64 return FsResult<FsFile *>::Error(ret);
65 }
66 return FileInstantiator::InstantiateFile(dstFd, string(static_cast<const char *>(readLinkReq->ptr)), false);
67 }
68 } // namespace OHOS::FileManagement::ModuleFileIO