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 "move.h"
17 
18 #ifdef __MUSL__
19 #include <filesystem>
20 #else
21 #include <sys/stat.h>
22 #endif
23 
24 #include <tuple>
25 #include <unistd.h>
26 #include "uv.h"
27 
28 #include "common_func.h"
29 #include "filemgmt_libhilog.h"
30 
31 namespace OHOS {
32 namespace FileManagement {
33 namespace ModuleFileIO {
34 using namespace std;
35 using namespace OHOS::FileManagement::LibN;
36 
37 #ifdef __MUSL__
CheckDir(const string & path)38 static bool CheckDir(const string &path)
39 {
40     std::error_code errCode;
41     if (!filesystem::is_directory(path, errCode)) {
42         if (errCode.value() != 0 && errCode.value() != ERRCODE_NOENT) {
43             HILOGE("Failed to check dir, err: %{public}d", errCode.value());
44         }
45         return false;
46     }
47     return true;
48 }
49 #else
CheckDir(const string & path)50 static bool CheckDir(const string &path)
51 {
52     struct stat fileInformation;
53     if (stat(path.c_str(), &fileInformation) == 0) {
54         if (fileInformation.st_mode & S_IFDIR) {
55             return true;
56         }
57     } else {
58         HILOGE("Failed to stat file");
59     }
60     return false;
61 }
62 #endif
63 
ParseJsOperand(napi_env env,const NFuncArg & funcArg)64 static tuple<bool, unique_ptr<char[]>, unique_ptr<char[]>, int> ParseJsOperand(napi_env env, const NFuncArg& funcArg)
65 {
66     auto [resGetFirstArg, src, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8StringPath();
67     if (!resGetFirstArg || CheckDir(string(src.get()))) {
68         HILOGE("Invalid src");
69         return { false, nullptr, nullptr, 0 };
70     }
71     auto [resGetSecondArg, dest, unused] = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8StringPath();
72     if (!resGetSecondArg || CheckDir(string(dest.get()))) {
73         HILOGE("Invalid dest");
74         return { false, nullptr, nullptr, 0 };
75     }
76     int mode = 0;
77     if (funcArg.GetArgc() >= NARG_CNT::THREE) {
78         bool resGetThirdArg = false;
79         tie(resGetThirdArg, mode) = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(mode);
80         if (!resGetThirdArg || (mode != MODE_FORCE_MOVE && mode != MODE_THROW_ERR)) {
81             HILOGE("Invalid mode");
82             return { false, nullptr, nullptr, 0 };
83         }
84     }
85     return { true, move(src), move(dest), mode };
86 }
87 
CopyAndDeleteFile(const string & src,const string & dest)88 static int CopyAndDeleteFile(const string &src, const string &dest)
89 {
90     std::unique_ptr<uv_fs_t, decltype(CommonFunc::fs_req_cleanup)*> stat_req = {
91         new (std::nothrow) uv_fs_t, CommonFunc::fs_req_cleanup };
92     if (!stat_req) {
93         HILOGE("Failed to request heap memory.");
94         return ENOMEM;
95     }
96     int ret = uv_fs_stat(nullptr, stat_req.get(), src.c_str(), nullptr);
97     if (ret < 0) {
98         HILOGE("Failed to stat srcPath");
99         return ret;
100     }
101 #if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM)
102     filesystem::path dstPath(dest);
103     std::error_code errCode;
104     if (filesystem::exists(dstPath, errCode)) {
105         if (!filesystem::remove(dstPath, errCode)) {
106             HILOGE("Failed to remove dest file, error code: %{public}d", errCode.value());
107             return errCode.value();
108         }
109     }
110     filesystem::path srcPath(src);
111     if (!filesystem::copy_file(srcPath, dstPath, filesystem::copy_options::overwrite_existing, errCode)) {
112         HILOGE("Failed to copy file, error code: %{public}d", errCode.value());
113         return errCode.value();
114     }
115 #else
116     uv_fs_t copyfile_req;
117     ret = uv_fs_copyfile(nullptr, &copyfile_req, src.c_str(), dest.c_str(), MODE_FORCE_MOVE, nullptr);
118     uv_fs_req_cleanup(&copyfile_req);
119     if (ret < 0) {
120         HILOGE("Failed to move file using copyfile interface.");
121         return ret;
122     }
123 #endif
124     uv_fs_t unlink_req;
125     ret = uv_fs_unlink(nullptr, &unlink_req, src.c_str(), nullptr);
126     if (ret < 0) {
127         HILOGE("Failed to unlink src file");
128         int result = uv_fs_unlink(nullptr, &unlink_req, dest.c_str(), nullptr);
129         if (result < 0) {
130             HILOGE("Failed to unlink dest file");
131             return result;
132         }
133         uv_fs_req_cleanup(&unlink_req);
134         return ret;
135     }
136     uv_fs_req_cleanup(&unlink_req);
137     return ERRNO_NOERR;
138 }
139 
RenameFile(const string & src,const string & dest)140 static int RenameFile(const string &src, const string &dest)
141 {
142     int ret = 0;
143     uv_fs_t rename_req;
144     ret = uv_fs_rename(nullptr, &rename_req, src.c_str(), dest.c_str(), nullptr);
145     if (ret < 0 && (string_view(uv_err_name(ret)) == "EXDEV")) {
146         return CopyAndDeleteFile(src, dest);
147     }
148     if (ret < 0) {
149         HILOGE("Failed to move file using rename syscall.");
150         return ret;
151     }
152     return ERRNO_NOERR;
153 }
154 
MoveFile(const string & src,const string & dest,int mode)155 static int MoveFile(const string &src, const string &dest, int mode)
156 {
157     uv_fs_t access_req;
158     int ret = uv_fs_access(nullptr, &access_req, src.c_str(), W_OK, nullptr);
159     if (ret < 0) {
160         HILOGE("Failed to move src file due to doesn't exist or hasn't write permission");
161         uv_fs_req_cleanup(&access_req);
162         return ret;
163     }
164     if (mode == MODE_THROW_ERR) {
165         ret = uv_fs_access(nullptr, &access_req, dest.c_str(), 0, nullptr);
166         uv_fs_req_cleanup(&access_req);
167         if (ret == 0) {
168             HILOGE("Failed to move file due to existing destPath with MODE_THROW_ERR.");
169             return EEXIST;
170         }
171         if (ret < 0 && (string_view(uv_err_name(ret)) != "ENOENT")) {
172             HILOGE("Failed to access destPath with MODE_THROW_ERR.");
173             return ret;
174         }
175     } else {
176         uv_fs_req_cleanup(&access_req);
177     }
178     return RenameFile(src, dest);
179 }
180 
Sync(napi_env env,napi_callback_info info)181 napi_value Move::Sync(napi_env env, napi_callback_info info)
182 {
183     NFuncArg funcArg(env, info);
184     if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::THREE)) {
185         HILOGE("Number of arguments unmatched");
186         NError(EINVAL).ThrowErr(env);
187         return nullptr;
188     }
189     auto [succ, src, dest, mode] = ParseJsOperand(env, funcArg);
190     if (!succ) {
191         NError(EINVAL).ThrowErr(env);
192         return nullptr;
193     }
194     int ret = MoveFile(string(src.get()), string(dest.get()), mode);
195     if (ret) {
196         NError(ret).ThrowErr(env);
197         return nullptr;
198     }
199     return NVal::CreateUndefined(env).val_;
200 }
201 
Async(napi_env env,napi_callback_info info)202 napi_value Move::Async(napi_env env, napi_callback_info info)
203 {
204     NFuncArg funcArg(env, info);
205     if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::FOUR)) {
206         HILOGE("Number of arguments unmatched");
207         NError(EINVAL).ThrowErr(env);
208         return nullptr;
209     }
210     auto [succ, src, dest, mode] = ParseJsOperand(env, funcArg);
211     if (!succ) {
212         NError(EINVAL).ThrowErr(env);
213         return nullptr;
214     }
215 
216     auto cbExec = [srcPath = string(src.get()), destPath = string(dest.get()), mode = mode]() -> NError {
217         int ret = MoveFile(srcPath, destPath, mode);
218         if (ret) {
219             return NError(ret);
220         }
221         return NError(ERRNO_NOERR);
222     };
223 
224     auto cbComplCallback = [](napi_env env, NError err) -> NVal {
225         if (err) {
226             return { env, err.GetNapiErr(env) };
227         }
228         return { NVal::CreateUndefined(env) };
229     };
230 
231     NVal thisVar(env, funcArg.GetThisVar());
232     size_t argc = funcArg.GetArgc();
233     if (argc == NARG_CNT::TWO || (argc == NARG_CNT::THREE &&
234         !NVal(env, funcArg[NARG_POS::THIRD]).TypeIs(napi_function))) {
235         return NAsyncWorkPromise(env, thisVar).Schedule(PROCEDURE_MOVE_NAME, cbExec, cbComplCallback).val_;
236     } else {
237         int cbIdx = ((funcArg.GetArgc() == NARG_CNT::THREE) ? NARG_POS::THIRD : NARG_POS::FOURTH);
238         NVal cb(env, funcArg[cbIdx]);
239         return NAsyncWorkCallback(env, thisVar, cb).Schedule(PROCEDURE_MOVE_NAME, cbExec, cbComplCallback).val_;
240     }
241 }
242 } // namespace ModuleFileIO
243 } // namespace FileManagement
244 } // namespace OHOS