• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-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 #include "open.h"
16 
17 #include <cstdio>
18 #include <cstdlib>
19 #include <cstring>
20 #include <memory>
21 
22 #include "class_file/file_entity.h"
23 #include "class_file/file_n_exporter.h"
24 #include "common_func.h"
25 #include "filemgmt_libhilog.h"
26 #include "file_utils.h"
27 #if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM)
28 #include "ability.h"
29 #include "ability_manager_client.h"
30 #include "bundle_info.h"
31 #include "bundle_mgr_proxy.h"
32 #include "datashare_helper.h"
33 #include "ipc_skeleton.h"
34 #include "iservice_registry.h"
35 #include "remote_uri.h"
36 #include "status_receiver_host.h"
37 #include "system_ability_definition.h"
38 #include "file_uri.h"
39 #endif
40 
41 #ifdef FILE_API_TRACE
42 #include "hitrace_meter.h"
43 #endif
44 
45 namespace OHOS {
46 namespace FileManagement {
47 namespace ModuleFileIO {
48 using namespace std;
49 using namespace OHOS::FileManagement::LibN;
50 #if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM)
51 using namespace OHOS::DistributedFS::ModuleRemoteUri;
52 using namespace OHOS::AppExecFwk;
53 #endif
54 
55 const std::string PROCEDURE_OPEN_NAME = "FileIOOpen";
56 const std::string MEDIALIBRARY_DATA_URI = "datashare:///media";
57 const std::string FILE_DATA_URI = "file://";
58 const std::string PATH_SHARE = "/data/storage/el2/share";
59 const std::string MODE_RW = "/rw/";
60 const std::string MODE_R = "/r/";
61 const std::string MEDIA = "media";
62 const std::string DOCS = "docs";
63 const std::string DATASHARE = "datashare";
64 const std::string SCHEME_BROKER = "content";
65 #if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM)
66 constexpr uint32_t MAX_WANT_FLAG = 4;
67 #endif
68 
GetJsFlags(napi_env env,const NFuncArg & funcArg)69 static tuple<bool, unsigned int> GetJsFlags(napi_env env, const NFuncArg &funcArg)
70 {
71     unsigned int flags = O_RDONLY;
72     if (funcArg.GetArgc() >= NARG_CNT::TWO) {
73         auto [succ, mode] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt32(O_RDONLY);
74         int32_t invalidMode = (O_WRONLY | O_RDWR);
75         if (!succ || mode < 0 || ((mode & invalidMode) == invalidMode)) {
76             HILOGE("Invalid mode");
77             NError(EINVAL).ThrowErr(env);
78             return { false, flags };
79         }
80         flags = static_cast<unsigned int>(mode);
81         (void)CommonFunc::ConvertJsFlags(flags);
82     }
83     return { true, flags };
84 }
85 
InstantiateFile(napi_env env,int fd,string pathOrUri,bool isUri)86 static NVal InstantiateFile(napi_env env, int fd, string pathOrUri, bool isUri)
87 {
88     napi_value objFile = NClass::InstantiateClass(env, FileNExporter::className_, {});
89     if (!objFile) {
90         HILOGE("Failed to instantiate class");
91         NError(EIO).ThrowErr(env);
92         int ret = close(fd);
93         if (ret < 0) {
94             HILOGE("Failed to close fd");
95         }
96         return NVal();
97     }
98 
99     auto fileEntity = NClass::GetEntityOf<FileEntity>(env, objFile);
100     if (!fileEntity) {
101         HILOGE("Failed to get fileEntity");
102         NError(EIO).ThrowErr(env);
103         int ret = close(fd);
104         if (ret < 0) {
105             HILOGE("Failed to close fd");
106         }
107         return NVal();
108     }
109     auto fdg = CreateUniquePtr<DistributedFS::FDGuard>(fd, false);
110     if (fdg == nullptr) {
111         HILOGE("Failed to request heap memory.");
112         close(fd);
113         NError(ENOMEM).ThrowErr(env);
114         return NVal();
115     }
116     fileEntity->fd_.swap(fdg);
117     if (isUri) {
118         fileEntity->path_ = "";
119         fileEntity->uri_ = pathOrUri;
120     } else {
121         fileEntity->path_ = pathOrUri;
122         fileEntity->uri_ = "";
123     }
124     return { env, objFile };
125 }
126 
OpenFileByPath(const string & path,unsigned int mode)127 static int OpenFileByPath(const string &path, unsigned int mode)
128 {
129     unique_ptr<uv_fs_t, decltype(CommonFunc::fs_req_cleanup)*> open_req = {
130         new uv_fs_t, CommonFunc::fs_req_cleanup };
131     if (!open_req) {
132         HILOGE("Failed to request heap memory.");
133         return -ENOMEM;
134     }
135     int ret = uv_fs_open(nullptr, open_req.get(), path.c_str(), mode, S_IRUSR |
136         S_IWUSR | S_IRGRP | S_IWGRP, nullptr);
137     return ret;
138 }
139 
140 #if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM)
141 
OpenFileByDatashare(const string & path,unsigned int flags)142 static int OpenFileByDatashare(const string &path, unsigned int flags)
143 {
144     std::shared_ptr<DataShare::DataShareHelper> dataShareHelper = nullptr;
145     sptr<FileIoToken> remote = new (std::nothrow) IRemoteStub<FileIoToken>();
146     if (!remote) {
147         HILOGE("Failed to get remote object");
148         return -ENOMEM;
149     }
150 
151     dataShareHelper = DataShare::DataShareHelper::Creator(remote->AsObject(), MEDIALIBRARY_DATA_URI);
152     if (!dataShareHelper) {
153         HILOGE("Failed to connect to datashare");
154         return -E_PERMISSION;
155     }
156     Uri uri(path);
157     int fd = dataShareHelper->OpenFile(uri, CommonFunc::GetModeFromFlags(flags));
158     return fd;
159 }
160 
OpenByFileDataUri(Uri & uri,const string & uriStr,unsigned int mode)161 static tuple<int, string> OpenByFileDataUri(Uri &uri, const string &uriStr, unsigned int mode)
162 {
163     string bundleName = uri.GetAuthority();
164     AppFileService::ModuleFileUri::FileUri fileUri(uriStr);
165     string realPath = fileUri.GetRealPath();
166     if (bundleName == MEDIA) {
167         int res = OpenFileByDatashare(uri.ToString(), mode);
168         if (res < 0) {
169             HILOGE("Failed to open file by Datashare error %{public}d", res);
170         }
171         return { res, uri.ToString() };
172     } else if (bundleName == DOCS && access(realPath.c_str(), F_OK) != 0) {
173         int res = OpenFileByDatashare(uri.ToString(), mode);
174         if (res < 0) {
175             HILOGE("Failed to open file by Datashare error %{public}d", res);
176             return { -ENOENT, uri.ToString() };
177         }
178         return { res, uri.ToString() };
179     }
180     int ret = OpenFileByPath(realPath, mode);
181     if (ret < 0) {
182         HILOGE("Failed to open file for libuv error %{public}d", ret);
183     }
184     return { ret, uriStr };
185 }
186 
OpenFileByBroker(const Uri & uri,uint32_t mode)187 static tuple<int, string> OpenFileByBroker(const Uri &uri, uint32_t mode)
188 {
189     uint32_t flag = (mode % MAX_WANT_FLAG) > 0 ?
190         AAFwk::Want::FLAG_AUTH_WRITE_URI_PERMISSION :
191         AAFwk::Want::FLAG_AUTH_READ_URI_PERMISSION;
192     int ret = AAFwk::AbilityManagerClient::GetInstance()->OpenFile(uri, flag);
193     if (ret < 0) {
194         HILOGE("Failed to open file by Broker error %{public}d", ret);
195     }
196     return { ret, uri.ToString() };
197 }
198 
OpenFileByUri(const string & path,unsigned int mode)199 static tuple<int, string> OpenFileByUri(const string &path, unsigned int mode)
200 {
201     Uri uri(path);
202     string uriType = uri.GetScheme();
203     if (uriType == SCHEME_FILE) {
204         return OpenByFileDataUri(uri, path, mode);
205     } else if (uriType == SCHEME_BROKER) {
206         return OpenFileByBroker(uri, mode);
207     } else if (uriType == DATASHARE) {
208         // datashare:////#fdFromBinder=xx
209         int fd = -1;
210         if (RemoteUri::IsRemoteUri(path, fd, mode)) {
211             if (fd >= 0) {
212                 return { fd, path };
213             }
214             HILOGE("Failed to open file by RemoteUri");
215         }
216     }
217     HILOGE("Failed to open file by invalid uri");
218     return { -EINVAL, path };
219 }
220 #endif
221 
Sync(napi_env env,napi_callback_info info)222 napi_value Open::Sync(napi_env env, napi_callback_info info)
223 {
224 #ifdef FILE_API_TRACE
225     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
226 #endif
227     NFuncArg funcArg(env, info);
228     if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) {
229         HILOGE("Number of arguments unmatched");
230         NError(EINVAL).ThrowErr(env);
231         return nullptr;
232     }
233     auto [succPath, path, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8StringPath();
234     if (!succPath) {
235         HILOGE("Invalid path");
236         NError(EINVAL).ThrowErr(env);
237         return nullptr;
238     }
239     auto [succMode, mode] = GetJsFlags(env, funcArg);
240     if (!succMode) {
241         return nullptr;
242     }
243     string pathStr(path.get());
244 #if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM)
245     if (pathStr.find("://") != string::npos) {
246         auto [res, uriStr] = OpenFileByUri(pathStr, mode);
247         if (res < 0) {
248             NError(res).ThrowErr(env);
249             return nullptr;
250         }
251         return InstantiateFile(env, res, uriStr, true).val_;
252     }
253 #endif
254     int ret = OpenFileByPath(pathStr, mode);
255     if (ret < 0) {
256         HILOGD("Failed to open file for libuv error %{public}d", ret);
257         NError(ret).ThrowErr(env);
258         return nullptr;
259     }
260     return InstantiateFile(env, ret, pathStr, false).val_;
261 }
262 
263 struct AsyncOpenFileArg {
264     int fd;
265     string path;
266     string uri;
267 };
268 
AsyncCbExec(shared_ptr<AsyncOpenFileArg> arg,const string & path,unsigned int mode)269 static NError AsyncCbExec(shared_ptr<AsyncOpenFileArg> arg, const string &path, unsigned int mode)
270 {
271     string pathStr(path);
272 #if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM)
273     if (pathStr.find("://") != string::npos) {
274         auto [res, uriStr] = OpenFileByUri(pathStr, mode);
275         if (res < 0) {
276             return NError(res);
277         }
278         arg->fd = res;
279         arg->path = "";
280         arg->uri = uriStr;
281         return NError(ERRNO_NOERR);
282     }
283 #endif
284     int ret = OpenFileByPath(pathStr, mode);
285     if (ret < 0) {
286         HILOGD("Failed to open file for libuv error %{public}d", ret);
287         return NError(ret);
288     }
289     arg->fd = ret;
290     arg->path = pathStr;
291     arg->uri = "";
292     return NError(ERRNO_NOERR);
293 }
294 
Async(napi_env env,napi_callback_info info)295 napi_value Open::Async(napi_env env, napi_callback_info info)
296 {
297 #ifdef FILE_API_TRACE
298     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
299 #endif
300     NFuncArg funcArg(env, info);
301     if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::THREE)) {
302         HILOGE("Number of arguments unmatched");
303         NError(EINVAL).ThrowErr(env);
304         return nullptr;
305     }
306     auto [succPath, path, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8StringPath();
307     if (!succPath) {
308         HILOGE("Invalid path");
309         NError(EINVAL).ThrowErr(env);
310         return nullptr;
311     }
312     auto [succMode, mode] = GetJsFlags(env, funcArg);
313     if (!succMode) {
314         return nullptr;
315     }
316     auto arg = CreateSharedPtr<AsyncOpenFileArg>();
317     if (arg == nullptr) {
318         HILOGE("Failed to request heap memory.");
319         NError(ENOMEM).ThrowErr(env);
320         return nullptr;
321     }
322     auto cbExec = [arg, path = string(path.get()), mode = mode]() -> NError {
323         return AsyncCbExec(arg, path, mode);
324     };
325     auto cbCompl = [arg](napi_env env, NError err) -> NVal {
326         if (err) {
327             return { env, err.GetNapiErr(env) };
328         }
329         if (arg->path.empty() && arg->uri.size()) {
330             return InstantiateFile(env, arg->fd, arg->uri, true);
331         }
332         return InstantiateFile(env, arg->fd, arg->path, false);
333     };
334     NVal thisVar(env, funcArg.GetThisVar());
335     if (funcArg.GetArgc() == NARG_CNT::ONE || (funcArg.GetArgc() == NARG_CNT::TWO &&
336         !NVal(env, funcArg[NARG_POS::SECOND]).TypeIs(napi_function))) {
337         return NAsyncWorkPromise(env, thisVar).Schedule(PROCEDURE_OPEN_NAME, cbExec, cbCompl).val_;
338     } else {
339         int cbIdx = ((funcArg.GetArgc() == NARG_CNT::THREE) ? NARG_POS::THIRD : NARG_POS::SECOND);
340         NVal cb(env, funcArg[cbIdx]);
341         return NAsyncWorkCallback(env, thisVar, cb).Schedule(PROCEDURE_OPEN_NAME, cbExec, cbCompl).val_;
342     }
343 }
344 } // namespace ModuleFileIO
345 } // namespace FileManagement
346 } // namespace OHOS