1/*
2 * Copyright (c) 2024 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#ifndef OHOS_FILE_FS_FILE_IMPL_H
17#define OHOS_FILE_FS_FILE_IMPL_H
18
19#include <sys/file.h>
20#include <sys/stat.h>
21#include "macro.h"
22#include "fd_guard.h"
23#include "ffi_remote_data.h"
24#include "cj_common_ffi.h"
25#include <cinttypes>
26#include <string>
27#include <memory>
28
29namespace OHOS {
30namespace CJSystemapi {
31namespace FileFs {
32
33class FileEntity : public OHOS::FFI::FFIData {
34public:
35    std::unique_ptr<DistributedFS::FDGuard> fd_ = { nullptr };
36    std::string path_;
37    std::string uri_;
38    ~FileEntity() override
39    {
40        if (!fd_.get()) {
41            return;
42        }
43        int32_t fd = fd_.get()->GetFD();
44        int ret = flock(fd, LOCK_UN);
45        if (ret == 0) {
46            struct stat buf;
47            if (fstat(fd, &buf) == 0) {
48                LOGI("Unlock succeeded inode = %{public}" PRIu64, buf.st_ino);
49            } else {
50                LOGI("Failed to get inode number");
51            }
52        }
53    }
54    FileEntity(std::unique_ptr<DistributedFS::FDGuard> fd, const std::string& path, const std::string& uri)
55        : fd_(std::move(fd)), path_(path), uri_(uri) {}
56    FileEntity() {};
57    static std::tuple<int32_t, sptr<FileEntity>> Open(const char* path, int64_t mode);
58    static std::tuple<int32_t, sptr<FileEntity>> Dup(int32_t fd);
59    static int GetFD(int64_t id);
60    static const char* GetPath(int64_t id);
61    static const char* GetName(int64_t id);
62    int TryLock(int64_t id, bool exclusive);
63    int UnLock(int64_t id);
64    RetDataCString GetParent();
65
66    OHOS::FFI::RuntimeType* GetRuntimeType() override { return GetClassType(); }
67
68private:
69    friend class OHOS::FFI::RuntimeType;
70    friend class OHOS::FFI::TypeBase;
71    static OHOS::FFI::RuntimeType* GetClassType()
72    {
73        static OHOS::FFI::RuntimeType runtimeType = OHOS::FFI::RuntimeType::Create<OHOS::FFI::FFIData>("FileEntity");
74        return &runtimeType;
75    }
76};
77
78}
79}
80}
81#endif // OHOS_FILE_FS_FILE_IMPL_H