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