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