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