1 /*
2  * Copyright (c) 2023-2024 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 "recent_n_exporter.h"
16 
17 #include <sys/stat.h>
18 #include <sys/time.h>
19 #include <tuple>
20 #include <unistd.h>
21 
22 #include "access_token.h"
23 #include "accesstoken_kit.h"
24 #include "file_uri.h"
25 #include "file_utils.h"
26 #include "hilog_wrapper.h"
27 #include "ipc_skeleton.h"
28 #include "tokenid_kit.h"
29 #include "user_access_common_utils.h"
30 
31 namespace OHOS {
32 namespace FileManagement {
33 namespace Recent {
34 using namespace std;
35 using namespace LibN;
36 using namespace AppFileService::ModuleFileUri;
37 
38 using namespace FileAccessFwk;
39 static std::mutex g_recentPathMutex;
CheckPermission(const std::string & permission)40 static bool CheckPermission(const std::string &permission)
41 {
42     Security::AccessToken::AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID();
43     return Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, permission) ==
44         Security::AccessToken::PermissionState::PERMISSION_GRANTED;
45 }
46 
IsSystemApp()47 static bool IsSystemApp()
48 {
49     uint64_t accessTokenIDEx = OHOS::IPCSkeleton::GetCallingFullTokenID();
50     return OHOS::Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(accessTokenIDEx);
51 }
52 
CheckSystemAppAndPermission(const std::string & permission,napi_env env)53 static bool CheckSystemAppAndPermission(const std::string &permission, napi_env env)
54 {
55     if (!IsSystemApp()) {
56         HILOG_ERROR("FileTrashNExporter::Recover check IsSystemAppByFullTokenID failed");
57         NError(E_PERMISSION_SYS).ThrowErr(env);
58         return false;
59     }
60     if (!CheckPermission(FILE_ACCESS_PERMISSION)) {
61         HILOG_ERROR("Check permission error");
62         NError(E_PERMISSION).ThrowErr(env);
63         return false;
64     }
65     return true;
66 }
67 
SetFileTime(napi_env env,const string & recentFilePath)68 static napi_value SetFileTime(napi_env env, const string &recentFilePath)
69 {
70     if (lutimes(recentFilePath.c_str(), nullptr) < 0) {
71         HILOG_ERROR("Failed to lutimes recent link, errno=%{public}d", errno);
72         NError(errno).ThrowErr(env);
73         return nullptr;
74     }
75     struct stat statBuf;
76     if (lstat(recentFilePath.c_str(), &statBuf) < 0) {
77         HILOG_ERROR("Failed to stat uri, errno=%{public}d", errno);
78     }
79     return NVal::CreateUndefined(env).val_;
80 }
81 
AddRecentFile(napi_env env,napi_callback_info cbinfo)82 napi_value RecentNExporter::AddRecentFile(napi_env env, napi_callback_info cbinfo)
83 {
84     if (!CheckSystemAppAndPermission(FILE_ACCESS_PERMISSION, env)) {
85         HILOG_ERROR("AddRecentFile CheckSystemAppAndPermission error");
86         return nullptr;
87     }
88 
89     NFuncArg funcArg(env, cbinfo);
90     if (!funcArg.InitArgs(NARG_CNT::ONE)) {
91         HILOG_ERROR("Number of arguments unmatched");
92         NError(EINVAL).ThrowErr(env);
93         return nullptr;
94     }
95     auto [succ, uri, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String();
96     FileUri fileUri(string(uri.get()));
97     auto filePath = fileUri.GetRealPath();
98     struct stat statBuf;
99     if (stat(filePath.c_str(), &statBuf) < 0) {
100         HILOG_ERROR("Failed to stat uri, errno=%{public}d", errno);
101         NError(errno).ThrowErr(env);
102         return nullptr;
103     }
104     string recentFilePath = RecentNExporter::recentPath_ + to_string(statBuf.st_dev) + "_" + to_string(statBuf.st_ino);
105     auto lstatRet = lstat(recentFilePath.c_str(), &statBuf);
106     if (lstatRet == 0) {
107         auto accessRet = access(recentFilePath.c_str(), F_OK);
108         if (accessRet < 0 && errno == ENOENT) {
109             if (unlink(recentFilePath.c_str()) < 0) {
110                 HILOG_ERROR("Failed to unlink invalid recent link, errno=%{public}d", errno);
111                 NError(errno).ThrowErr(env);
112                 return nullptr;
113             }
114         } else if (accessRet == 0) {
115             return SetFileTime(env, recentFilePath);
116         }
117     } else if (lstatRet < 0 && errno != ENOENT) {
118         HILOG_ERROR("Failed to lstat uri, errno=%{public}d", errno);
119         NError(errno).ThrowErr(env);
120         return nullptr;
121     }
122     if (symlink(filePath.c_str(), recentFilePath.c_str()) < 0) {
123         HILOG_ERROR("Failed to symlink uri, errno=%{public}d", errno);
124         NError(errno).ThrowErr(env);
125         return nullptr;
126     }
127     return NVal::CreateUndefined(env).val_;
128 }
129 
RemoveRecentFile(napi_env env,napi_callback_info cbinfo)130 napi_value RecentNExporter::RemoveRecentFile(napi_env env, napi_callback_info cbinfo)
131 {
132     if (!CheckSystemAppAndPermission(FILE_ACCESS_PERMISSION, env)) {
133         HILOG_ERROR("AddRecentFile CheckSystemAppAndPermission error");
134         return nullptr;
135     }
136 
137     NFuncArg funcArg(env, cbinfo);
138     if (!funcArg.InitArgs(NARG_CNT::ONE)) {
139         HILOG_ERROR("Number of arguments unmatched");
140         NError(EINVAL).ThrowErr(env);
141         return nullptr;
142     }
143     auto [succ, uri, ignore] = NVal(env, funcArg[NARG_POS::FIRST]).ToUTF8String();
144     FileUri fileUri(string(uri.get()));
145     auto filePath = fileUri.GetPath();
146     struct stat statBuf;
147     if (stat(filePath.c_str(), &statBuf) < 0) {
148         HILOG_ERROR("Failed to stat uri, errno=%{public}d", errno);
149         NError(errno).ThrowErr(env);
150         return nullptr;
151     }
152     string recentFilePath = RecentNExporter::recentPath_ + to_string(statBuf.st_dev) + "_" + to_string(statBuf.st_ino);
153     if (unlink(recentFilePath.c_str()) < 0) {
154         HILOG_ERROR("Failed to unlink uri, errno=%{public}d", errno);
155         NError(errno).ThrowErr(env);
156     }
157     return nullptr;
158 }
159 
Deleter(struct NameListArg * arg)160 static void Deleter(struct NameListArg *arg)
161 {
162     for (int i = 0; i < arg->direntNum; i++) {
163         free((arg->namelist)[i]);
164         (arg->namelist)[i] = nullptr;
165     }
166     free(arg->namelist);
167 }
168 
GetFileMtime(const string & fileName)169 static int64_t GetFileMtime(const string &fileName)
170 {
171     string filePath = RecentNExporter::recentPath_ + fileName;
172     struct stat statBuf;
173     if (lstat(filePath.c_str(), &statBuf) < 0) {
174         HILOG_ERROR("Failed to lstat uri, errno=%{public}d, fileName=%{public}s", errno, fileName.c_str());
175         return errno;
176     }
177     return static_cast<int64_t>(statBuf.st_mtime);
178 }
179 
GetName(const string & path)180 static string GetName(const string &path)
181 {
182     auto pos = path.find_last_of('/');
183     if (pos == string::npos) {
184         HILOGE("Failed to split filename from path, path: %{public}s", path.c_str());
185     }
186     return path.substr(pos + 1);
187 }
188 
SortReceneFile(const struct dirent ** a,const struct dirent ** b)189 static int SortReceneFile(const struct dirent **a, const struct dirent **b)
190 {
191     return GetFileMtime(string((*b)->d_name)) - GetFileMtime(string((*a)->d_name));
192 }
193 
FilterFunc(const struct dirent * filename)194 static int FilterFunc(const struct dirent *filename)
195 {
196     if (string_view(filename->d_name) == "." || string_view(filename->d_name) == "..") {
197         return false;
198     }
199     return true;
200 }
201 
CheckRealFileExist(const string & recentFilePath)202 static tuple<int, struct stat> CheckRealFileExist(const string &recentFilePath)
203 {
204     struct stat statBuf;
205     int accessRet = access(recentFilePath.c_str(), F_OK);
206     if (accessRet < 0 && errno != ENOENT) {
207         HILOG_ERROR("Failed to access file, errno=%{public}d", errno);
208         return { errno, statBuf };
209     }
210     if (accessRet == 0) {
211         if (stat(recentFilePath.c_str(), &statBuf) < 0) {
212             HILOG_ERROR("Failed to stat file, errno=%{public}d", errno);
213             return { errno, statBuf };
214         }
215         string oldRecentFilePath =
216             RecentNExporter::recentPath_ + to_string(statBuf.st_dev) + "_" + to_string(statBuf.st_ino);
217         if (oldRecentFilePath == recentFilePath) {
218             return { 0, statBuf };
219         }
220     }
221     if (unlink(recentFilePath.c_str()) < 0) {
222         HILOG_ERROR("Failed to unlink non-existent file, errno=%{public}d", errno);
223         return { errno, statBuf };
224     }
225     return { -1, statBuf };
226 }
227 
GetFileInfo(napi_env env,const string & filePath,const struct stat & realFileStatBuf,const struct stat & linkFileStatBuf)228 static napi_value GetFileInfo(napi_env env, const string &filePath, const struct stat &realFileStatBuf,
229     const struct stat &linkFileStatBuf)
230 {
231     FileUri fileUri(filePath);
232     NVal obj = NVal::CreateObject(env);
233     obj.AddProp({
234         NVal::DeclareNapiProperty("uri", NVal::CreateUTF8String(env, fileUri.ToString()).val_),
235         NVal::DeclareNapiProperty("srcPath", NVal::CreateUTF8String(env, filePath).val_),
236         NVal::DeclareNapiProperty("fileName", NVal::CreateUTF8String(env, GetName(filePath)).val_),
237         NVal::DeclareNapiProperty("size", NVal::CreateInt64(env, realFileStatBuf.st_size).val_),
238         NVal::DeclareNapiProperty("mtime", NVal::CreateInt64(env, realFileStatBuf.st_mtim.tv_sec).val_),
239         NVal::DeclareNapiProperty("ctime", NVal::CreateInt64(env, linkFileStatBuf.st_mtim.tv_sec).val_),
240         NVal::DeclareNapiProperty("mode", NVal::CreateInt64(env, realFileStatBuf.st_mode).val_),
241     });
242     return obj.val_;
243 }
244 
GetListFileResult(napi_env env,struct NameListArg * pNameList)245 static napi_value GetListFileResult(napi_env env, struct NameListArg* pNameList)
246 {
247     napi_value res = nullptr;
248     if (napi_create_array(env, &res) != napi_ok) {
249         HILOG_ERROR("Failed to create array");
250         NError(UNKROWN_ERR).ThrowErr(env);
251         return nullptr;
252     }
253     auto buf = CreateUniquePtr<char[]>(BUF_SIZE);
254     int index = 0;
255     for (int i = 0; i < pNameList->direntNum; ++i) {
256         string recentFilePath = RecentNExporter::recentPath_ + string((*(pNameList->namelist[i])).d_name);
257         if (index < MAX_RECENT_SIZE) {
258             auto [checkRealFileRes, realFileStatBuf] = CheckRealFileExist(recentFilePath);
259             if (checkRealFileRes < 0) {
260                 continue;
261             } else if (checkRealFileRes > 0) {
262                 NError(checkRealFileRes).ThrowErr(env);
263                 return nullptr;
264             }
265             auto readLinkRes = readlink(recentFilePath.c_str(), buf.get(), BUF_SIZE);
266             if (readLinkRes < 0) {
267                 HILOG_ERROR("Failed to readlink uri, errno=%{public}d", errno);
268                 NError(errno).ThrowErr(env);
269                 return nullptr;
270             }
271             struct stat linkFileStatBuf;
272             if (lstat(recentFilePath.c_str(), &linkFileStatBuf) < 0) {
273                 HILOG_ERROR("Failed to lstat file, errno=%{public}d", errno);
274                 NError(errno).ThrowErr(env);
275                 return nullptr;
276             }
277             if (napi_set_element(env, res, index, GetFileInfo(env, string(buf.get(), readLinkRes),
278                 realFileStatBuf, linkFileStatBuf)) != napi_ok) {
279                 HILOG_ERROR("Failed to set element");
280                 NError(UNKROWN_ERR).ThrowErr(env);
281                 return nullptr;
282             }
283             ++index;
284         } else {
285             if (unlink(recentFilePath.c_str()) < 0) {
286                 HILOG_ERROR("Failed to unlink file, errno=%{public}d", errno);
287                 NError(errno).ThrowErr(env);
288                 return nullptr;
289             }
290         }
291     }
292     HILOG_INFO("The count of recent file is %{public}d", index);
293     return res;
294 }
295 
ListFileCore(napi_env env)296 static napi_value ListFileCore(napi_env env)
297 {
298     unique_ptr<struct NameListArg, decltype(Deleter)*> pNameList = { new (nothrow) struct NameListArg, Deleter };
299     if (!pNameList) {
300         HILOG_ERROR("Failed to request heap memory.");
301         NError(ENOMEM).ThrowErr(env);
302         return nullptr;
303     }
304     pNameList->direntNum = scandir(RecentNExporter::recentPath_.c_str(),
305         &(pNameList->namelist), FilterFunc, SortReceneFile);
306     if (pNameList->direntNum < 0) {
307         HILOG_ERROR("Failed to scan dir, errno=%{public}d", errno);
308         NError(errno).ThrowErr(env);
309         return nullptr;
310     }
311     return GetListFileResult(env, pNameList.get());
312 }
313 
ListRecentFile(napi_env env,napi_callback_info cbinfo)314 napi_value RecentNExporter::ListRecentFile(napi_env env, napi_callback_info cbinfo)
315 {
316     if (!CheckSystemAppAndPermission(FILE_ACCESS_PERMISSION, env)) {
317         HILOG_ERROR("ListRecentFile CheckSystemAppAndPermission error");
318         return nullptr;
319     }
320 
321     NFuncArg funcArg(env, cbinfo);
322     if (!funcArg.InitArgs(NARG_CNT::ZERO)) {
323         HILOG_ERROR("Number of arguments unmatched");
324         NError(EINVAL).ThrowErr(env);
325         return nullptr;
326     }
327     return ListFileCore(env);
328 }
329 
Export()330 bool RecentNExporter::Export()
331 {
332     return exports_.AddProp({
333         NVal::DeclareNapiFunction("add", AddRecentFile),
334         NVal::DeclareNapiFunction("remove", RemoveRecentFile),
335         NVal::DeclareNapiFunction("listFile", ListRecentFile),
336     });
337 }
338 
GetClassName()339 string RecentNExporter::GetClassName()
340 {
341     return RecentNExporter::className;
342 }
343 
InitRecentPath()344 void RecentNExporter::InitRecentPath()
345 {
346     if (RecentNExporter::recentPath_.empty()) {
347         std::unique_lock<std::mutex> lock(g_recentPathMutex);
348         if (!RecentNExporter::recentPath_.empty()) {
349             return ;
350         }
351         RecentNExporter::recentPath_ = "/storage/Users/currentUser/.Recent/";
352         std::string deviceType;
353         if (IsFullMountEnable()) {
354             std::string userName;
355             if (GetUserName(userName) && userName != "") {
356                 RecentNExporter::recentPath_ = "/storage/Users/" + userName + "/.Recent/";
357             }
358         }
359         HILOG_INFO("GetRecentDir %{public}s", RecentNExporter::recentPath_.c_str());
360     }
361 }
362 
RecentNExporter(napi_env env,napi_value exports)363 RecentNExporter::RecentNExporter(napi_env env, napi_value exports) : NExporter(env, exports)
364 {
365     InitRecentPath();
366 }
367 
~RecentNExporter()368 RecentNExporter::~RecentNExporter() {}
369 } // namespace Recent
370 } // namespace FileManagement
371 } // namespace OHOS