• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
CheckDir(const string & path)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, ret:%{public}d", ret);
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     if (mode == MODE_THROW_ERR) {
156         int ret = uv_fs_access(nullptr, &access_req, dest.c_str(), 0, nullptr);
157         uv_fs_req_cleanup(&access_req);
158         if (ret == 0) {
159             HILOGE("Failed to move file due to existing destPath with MODE_THROW_ERR.");
160             return EEXIST;
161         }
162         if (ret < 0 && (string_view(uv_err_name(ret)) != "ENOENT")) {
163             HILOGE("Failed to access destPath with MODE_THROW_ERR, ret:%{public}d", ret);
164             return ret;
165         }
166     } else {
167         uv_fs_req_cleanup(&access_req);
168     }
169     return RenameFile(src, dest);
170 }
171 
Sync(napi_env env,napi_callback_info info)172 napi_value Move::Sync(napi_env env, napi_callback_info info)
173 {
174     NFuncArg funcArg(env, info);
175     if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::THREE)) {
176         HILOGE("Number of arguments unmatched");
177         NError(EINVAL).ThrowErr(env);
178         return nullptr;
179     }
180     auto [succ, src, dest, mode] = ParseJsOperand(env, funcArg);
181     if (!succ) {
182         NError(EINVAL).ThrowErr(env);
183         return nullptr;
184     }
185     int ret = MoveFile(string(src.get()), string(dest.get()), mode);
186     if (ret) {
187         NError(ret).ThrowErr(env);
188         return nullptr;
189     }
190     return NVal::CreateUndefined(env).val_;
191 }
192 
Async(napi_env env,napi_callback_info info)193 napi_value Move::Async(napi_env env, napi_callback_info info)
194 {
195     NFuncArg funcArg(env, info);
196     if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::FOUR)) {
197         HILOGE("Number of arguments unmatched");
198         NError(EINVAL).ThrowErr(env);
199         return nullptr;
200     }
201     auto [succ, src, dest, mode] = ParseJsOperand(env, funcArg);
202     if (!succ) {
203         NError(EINVAL).ThrowErr(env);
204         return nullptr;
205     }
206 
207     auto cbExec = [srcPath = string(src.get()), destPath = string(dest.get()), mode = mode]() -> NError {
208         int ret = MoveFile(srcPath, destPath, mode);
209         if (ret) {
210             HILOGE("Failed movefile ret %{public}d", ret);
211             return NError(ret);
212         }
213         return NError(ERRNO_NOERR);
214     };
215 
216     auto cbComplCallback = [](napi_env env, NError err) -> NVal {
217         if (err) {
218             return { env, err.GetNapiErr(env) };
219         }
220         return { NVal::CreateUndefined(env) };
221     };
222 
223     NVal thisVar(env, funcArg.GetThisVar());
224     size_t argc = funcArg.GetArgc();
225     if (argc == NARG_CNT::TWO || (argc == NARG_CNT::THREE &&
226         !NVal(env, funcArg[NARG_POS::THIRD]).TypeIs(napi_function))) {
227         return NAsyncWorkPromise(env, thisVar).Schedule(PROCEDURE_MOVE_NAME, cbExec, cbComplCallback).val_;
228     } else {
229         int cbIdx = ((funcArg.GetArgc() == NARG_CNT::THREE) ? NARG_POS::THIRD : NARG_POS::FOURTH);
230         NVal cb(env, funcArg[cbIdx]);
231         return NAsyncWorkCallback(env, thisVar, cb).Schedule(PROCEDURE_MOVE_NAME, cbExec, cbComplCallback).val_;
232     }
233 }
234 } // namespace ModuleFileIO
235 } // namespace FileManagement
236 } // namespace OHOS