Handle abnormally terminated installer process
[platform/core/appfw/pkgmgr-info.git] / src / server / database / db_handle_provider.cc
1 /*
2  * Copyright (c) 2021 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "db_handle_provider.hh"
18
19 #include <fcntl.h>
20 #include <glib.h>
21 #include <sys/stat.h>
22 #include <sys/types.h>
23
24 #include <tzplatform_config.h>
25
26 #include <algorithm>
27 #include <string>
28 #include <vector>
29
30 #include "cache_flag.hh"
31 #include "utils/logging.hh"
32
33 #include "pkgmgr-info.h"
34 #include "pkgmgrinfo_debug.h"
35 #include "pkgmgrinfo_internal.h"
36 #include "pkgmgrinfo_private.h"
37
38 #ifdef LOG_TAG
39 #undef LOG_TAG
40 #endif
41 #define LOG_TAG "PKGMGR_INFO"
42
43 namespace {
44
45 uid_t globaluser_uid = -1;
46
47 uid_t GetGlobalUID() {
48   if (globaluser_uid == (uid_t)-1)
49     globaluser_uid = tzplatform_getuid(TZ_SYS_GLOBALAPP_USER);
50
51   return globaluser_uid;
52 }
53
54 uid_t ConvertUID(uid_t uid) {
55   if (uid < REGULAR_USER)
56     return GetGlobalUID();
57   else
58     return uid;
59 }
60
61 bool GetModifiedTime(const char* dbpath, timespec* t) {
62   if (dbpath == nullptr || t == nullptr) {
63     LOG(ERROR) << "Invalid argument";
64     return false;
65   }
66
67   struct stat attr;
68   if (stat(dbpath, &attr)) {
69     LOG(ERROR) << "Fail to get status from file "
70         << dbpath << " errno : " << errno;
71     return false;
72   }
73
74   *t = attr.st_mtim;
75
76   return true;
77 }
78
79 }  // namespace
80
81 namespace pkgmgr_server {
82 namespace database {
83
84 std::unordered_map<uid_t, std::unique_ptr<DBHandleProvider>>
85     DBHandleProvider::provider_map_;
86 std::string DBHandleProvider::global_parser_filedb_path_;
87 std::string DBHandleProvider::cert_filedb_path_;
88 std::unordered_set<pid_t> DBHandleProvider::writer_pid_list_;
89 std::shared_mutex DBHandleProvider::pid_list_lock_;
90
91 DBHandleProvider::DBHandleProvider(uid_t uid) : uid_(uid) {
92   char* tmp_path;
93
94   if (global_parser_filedb_path_.empty()) {
95     tmp_path = getUserPkgParserDBPathUID(GetGlobalUID());
96     global_parser_filedb_path_ = tmp_path;
97     free(tmp_path);
98   }
99
100   if (cert_filedb_path_.empty()) {
101     tmp_path = getUserPkgCertDBPath();
102     cert_filedb_path_ = tmp_path;
103     free(tmp_path);
104   }
105
106   tmp_path = getUserPkgParserDBPathUID(uid_);
107   user_parser_filedb_path_ = tmp_path;
108   free(tmp_path);
109 }
110
111 DBHandleProvider& DBHandleProvider::GetInst(uid_t uid) {
112   static std::shared_mutex singleton_lock_;
113   std::shared_lock<std::shared_mutex> s(singleton_lock_);
114
115   uid = ConvertUID(uid);
116   auto it = provider_map_.find(uid);
117   if (it != provider_map_.end())
118     return *(it->second);
119
120   s.unlock();
121   std::unique_lock<std::shared_mutex> u(singleton_lock_);
122   auto& prov = provider_map_[uid];
123   if (prov == nullptr)
124     prov.reset(new DBHandleProvider(uid));
125
126   return *prov;
127 }
128
129 std::vector<pid_t> DBHandleProvider::CrashedWriteRequestPIDs() {
130   std::unique_lock<std::shared_mutex> u(pid_list_lock_);
131
132   if (writer_pid_list_.empty())
133     return {};
134
135   LOG(DEBUG) << "Check process count : " << writer_pid_list_.size();
136   std::vector<pid_t> remove_pids;
137   for (pid_t pid : writer_pid_list_) {
138     std::string status_path = "/proc/" + std::to_string(pid) + "/status";
139
140     int fd = open(status_path.c_str(), O_RDONLY);
141     if (fd < 0) {
142       LOG(ERROR) << "Process is crashed : " << pid;
143       remove_pids.push_back(pid);
144     } else {
145       close(fd);
146     }
147   }
148
149   for (pid_t pid : remove_pids)
150     writer_pid_list_.erase(pid);
151
152   return remove_pids;
153 }
154
155 std::vector<std::pair<std::string, uid_t>> DBHandleProvider::GetParserDBPath() {
156   std::vector<std::pair<std::string, uid_t>> db_path_list;
157
158   if (uid_ > REGULAR_USER)
159     db_path_list.emplace_back(std::make_pair(user_parser_filedb_path_, uid_));
160
161   db_path_list.emplace_back(
162       std::make_pair(global_parser_filedb_path_, GetGlobalUID()));
163
164   if (db_path_list.size() == 1) {
165     LOG(DEBUG) << "global db path : " << db_path_list[0].first;
166   } else {
167     LOG(DEBUG) << "local db path : " << db_path_list[0].first;
168     LOG(DEBUG) << "global db path : " << db_path_list[1].first;
169   }
170
171   return db_path_list;
172 }
173
174 std::string DBHandleProvider::GetCertDBPath() {
175   return cert_filedb_path_;
176 }
177
178 void DBHandleProvider::TrimCache() {
179   if (!released_)
180     ReleaseCache();
181 }
182
183 void DBHandleProvider::ReleaseCache() {
184   auto lock = CacheFlag::GetWriterLock();
185   CacheFlag::SetStatus(CacheFlag::Status::PREPARING);
186
187   app_map_.clear();
188   pkg_map_.clear();
189   pending_pkg_.clear();
190   pkg_app_map_.clear();
191   CacheFlag::SetStatus(CacheFlag::Status::UNPREPARED);
192
193   released_ = true;
194 }
195
196 bool DBHandleProvider::IsWriter(pid_t pid) {
197   std::unique_lock<std::shared_mutex> s(pid_list_lock_);
198   return writer_pid_list_.find(pid) != writer_pid_list_.end();
199 }
200
201 int DBHandleProvider::UpdateCache(const tizen_base::Database& db, pid_t pid,
202     uid_t uid, bool write, const std::string& locale) {
203   pkg_map_.clear();
204   app_map_.clear();
205   pending_pkg_.clear();
206   pkg_app_map_.clear();
207
208   const char* dbpath = sqlite3_db_filename(db.GetRaw(), "main");
209
210   timespec start_time = { 0, };
211   timespec end_time = { 0, };
212   if (!GetModifiedTime(dbpath, &start_time))
213     return PMINFO_R_ERROR;
214
215   pkgmgrinfo_filter_x tmp_filter = { 0, };
216   tmp_filter.cache_flag = true;
217   std::map<std::string, std::shared_ptr<package_x>> pkgs;
218   int ret = internal::GetPkgInfo(db, &tmp_filter, uid_, locale, pkgs);
219   if (ret == PMINFO_R_OK) {
220     for (auto& [key, val] : pkgs)
221       AddPackage(std::move(key), std::move(val));
222   }
223
224   if (!GetModifiedTime(dbpath, &end_time))
225     return PMINFO_R_ERROR;
226
227   if (start_time.tv_sec != end_time.tv_sec ||
228       start_time.tv_nsec != end_time.tv_nsec) {
229     LOG(ERROR) << "Database(" << dbpath << ") modification was detected";
230     return PMINFO_R_ERROR;
231   }
232
233   std::vector<std::shared_ptr<application_x>> app_list;
234   ret = internal::GetAppInfo(db, &tmp_filter, uid_, uid, locale, app_list);
235
236   if (!GetModifiedTime(dbpath, &end_time))
237     return PMINFO_R_ERROR;
238
239   if (start_time.tv_sec != end_time.tv_sec ||
240       start_time.tv_nsec != end_time.tv_nsec) {
241     LOG(ERROR) << "Database(" << dbpath << ") modification was detected";
242     return PMINFO_R_ERROR;
243   }
244
245   if (ret == PMINFO_R_OK) {
246     for (auto& app : app_list) {
247       auto it = pkg_map_.find(app->package);
248       if (it == pkg_map_.end()) {
249         LOG(ERROR) << "Can not find package from pkg_map";
250         return PMINFO_R_ERROR;
251       }
252
253       app->privileges = it->second->privileges;
254       std::string appid = app->appid;
255       AddApplication(std::move(appid), std::move(app));
256     }
257   }
258
259   released_ = false;
260
261   return ret;
262 }
263
264 inline bool CheckMetadataFilter(GList* metadata_list,
265     const std::unordered_map<std::string, std::string>& metadata_map) {
266   for (auto* it = metadata_list; it != nullptr; it = g_list_next(it)) {
267     auto* node = reinterpret_cast<metadata_x*>(it->data);
268     if (node->key != nullptr) {
269       auto metadata = metadata_map.find(node->key);
270       if (metadata == metadata_map.end())
271         continue;
272
273       if (metadata->second.empty() ||
274           strcmp(node->value ? node->value : "", metadata->second.c_str()) == 0)
275         return true;
276     }
277   }
278   return false;
279 }
280
281 inline bool CheckPkgFilters(pkgmgrinfo_filter_x* filter,
282     const std::shared_ptr<package_x>& info,
283     const std::unordered_map<std::string, std::string>& metadata_map) {
284   for (auto* it = filter->list; it != nullptr; it = g_slist_next(it)) {
285     auto node = reinterpret_cast<pkgmgrinfo_node_x*>(it->data);
286     auto* checker = FilterCheckerProvider::GetInst().
287         GetPkgFilterChecker(node->prop);
288     if (!checker->CheckFilter(node, info.get()))
289       return false;
290   }
291
292   bool pass = true;
293   if (!metadata_map.empty())
294     pass = CheckMetadataFilter(info->metadata, metadata_map);
295
296   return pass;
297 }
298
299 std::vector<std::shared_ptr<package_x>> DBHandleProvider::GetPackages(
300     pid_t pid, pkgmgrinfo_filter_x* filter,
301     const std::string& package) {
302   std::vector<std::shared_ptr<package_x>> ret;
303
304   /* make metadata filter map */
305   std::unordered_map<std::string, std::string> metadata_map;
306   for (auto* it = filter->list_pkg_metadata; it != nullptr;
307       it = g_slist_next(it)) {
308     auto node = reinterpret_cast<pkgmgrinfo_metadata_node_x*>(it->data);
309     if (node->key == nullptr)
310       continue;
311     LOG(ERROR) << "add metadata filter";
312     metadata_map[node->key] = (node->value ? node->value : "");
313   }
314
315   if (internal::CheckPackageStorageStatus(filter)) {
316     if (pkgmgrinfo_pkginfo_filter_add_bool(filter,
317         PMINFO_PKGINFO_PROP_PACKAGE_CHECK_STORAGE, true) != PMINFO_R_OK) {
318       LOG(ERROR) << "Fail to add check storage value to filter";
319       return {};
320     }
321   }
322   if (package.empty()) {
323     for (auto& info : pkg_map_) {
324       if (CheckPkgFilters(filter, info.second, metadata_map))
325         ret.push_back(info.second);
326     }
327   } else {
328     auto map_it = pkg_map_.find(package);
329     if (map_it != pkg_map_.end() && CheckPkgFilters(filter, map_it->second,
330         metadata_map))
331       ret.push_back(map_it->second);
332   }
333
334   return ret;
335 }
336
337 void DBHandleProvider::AddPackage(std::string package,
338     std::shared_ptr<package_x> info) {
339   pkg_map_[package] = std::move(info);
340 }
341
342 inline bool CheckAppFilters(pkgmgrinfo_filter_x* filter,
343   const std::shared_ptr<application_x>& app_info,
344   const std::shared_ptr<package_x>& pkg_info,
345   const std::unordered_map<std::string, std::string>& metadata_map) {
346   for (auto* it = filter->list; it != nullptr; it = g_slist_next(it)) {
347     auto node = reinterpret_cast<pkgmgrinfo_node_x*>(it->data);
348     auto* checker = FilterCheckerProvider::GetInst().
349         GetAppFilterChecker(node->prop);
350     if (!checker->CheckFilter(node, app_info.get(), pkg_info.get()))
351       return false;
352   }
353
354   bool pass = true;
355   if (!metadata_map.empty())
356     pass = CheckMetadataFilter(app_info->metadata, metadata_map);
357   return pass;
358 }
359
360 std::shared_ptr<package_x> DBHandleProvider::GetPackageByApp(
361     const char* appid) {
362   auto it = pkg_map_.find(appid);
363   if (it == pkg_map_.end())
364     return nullptr;
365
366   return it->second;
367 }
368
369 std::vector<std::shared_ptr<application_x>> DBHandleProvider::GetApplications(
370     pid_t pid, pkgmgrinfo_filter_x* filter,
371     const std::string& app) {
372   /* make metadata filter map */
373   std::unordered_map<std::string, std::string> metadata_map;
374   for (auto* it = filter->list_metadata; it != nullptr; it = g_slist_next(it)) {
375     auto node = reinterpret_cast<pkgmgrinfo_metadata_node_x*>(it->data);
376     if (node->key == nullptr)
377       continue;
378
379     metadata_map[node->key] = (node->value ? node->value : "");
380   }
381
382   std::vector<std::shared_ptr<application_x>> ret;
383   if (internal::CheckAppStorageStatus(filter)) {
384     if (pkgmgrinfo_appinfo_filter_add_bool(filter,
385         PMINFO_APPINFO_PROP_APP_CHECK_STORAGE, true) != PMINFO_R_OK) {
386       LOG(ERROR) << "Fail to add check storage value to filter";
387       return {};
388     }
389   }
390
391   if (app.empty()) {
392     for (auto& info : app_map_) {
393       if (CheckAppFilters(filter, info.second,
394           GetPackageByApp(info.second->package), metadata_map))
395         ret.push_back(info.second);
396     }
397   } else {
398     auto map_it = app_map_.find(app);
399     if (map_it != app_map_.end() &&
400         CheckAppFilters(filter, map_it->second,
401             GetPackageByApp(map_it->second->package), metadata_map))
402       ret.push_back(map_it->second);
403   }
404
405   return ret;
406 }
407
408 void DBHandleProvider::AddApplication(std::string app,
409     std::shared_ptr<application_x> info) {
410   pkg_app_map_[info->package].emplace(app);
411   app_map_[app] = std::move(info);
412 }
413
414 void DBHandleProvider::InsertPID(pid_t pid) {
415   std::unique_lock<std::shared_mutex> u(pid_list_lock_);
416
417   writer_pid_list_.insert(pid);
418 }
419
420 bool DBHandleProvider::ErasePID(pid_t pid) {
421   std::unique_lock<std::shared_mutex> u(pid_list_lock_);
422
423   return writer_pid_list_.erase(pid) == 1;
424 }
425
426 void DBHandleProvider::RegisterPendingPackageInfo(package_x* info, pid_t pid) {
427   if (!info || !info->package)
428     return;
429
430   InsertPID(pid);
431
432   pending_pkg_[pid].emplace(info->package);
433 }
434
435 void DBHandleProvider::UpdatePendingPackageInfo(const tizen_base::Database& db,
436     const std::vector<pid_t>& pids, uid_t uid, const std::string& locale) {
437   pkgmgrinfo_filter_x tmp_filter = { 0, };
438   pkgmgrinfo_node_x node = {
439     .prop = E_PMINFO_PKGINFO_PROP_PACKAGE_ID
440   };
441   tmp_filter.cache_flag = true;
442   tmp_filter.list = g_slist_append(tmp_filter.list, (gpointer)&node);
443   std::map<std::string, std::shared_ptr<package_x>> pkgs;
444   for (const pid_t& pid : pids) {
445     for (const auto& pkg : pending_pkg_[pid]) {
446       pkg_map_.erase(pkg);
447       for (auto& appid : pkg_app_map_[pkg]) {
448         app_map_.erase(appid);
449       }
450
451       pkg_app_map_.erase(pkg);
452       node.value = const_cast<char*>(pkg.c_str());
453       internal::GetPkgInfo(db, &tmp_filter, uid_, locale, pkgs);
454     }
455
456     pending_pkg_.erase(pid);
457   }
458
459   for (auto& [key, val] : pkgs)
460     AddPackage(key, val);
461
462   node.prop = E_PMINFO_APPINFO_PROP_APP_PACKAGE;
463   for (auto& [key, val] : pkgs) {
464     node.value = val->package;
465     std::vector<std::shared_ptr<application_x>> app_list;
466     internal::GetAppInfo(db, &tmp_filter, uid_, uid, locale, app_list);
467
468     for (auto& app : app_list) {
469       app->privileges = val->privileges;
470       std::string appid = app->appid;
471       AddApplication(std::move(appid), std::move(app));
472     }
473   }
474
475   g_slist_free(tmp_filter.list);
476 }
477
478 bool DBHandleProvider::UpdateCachePkg(const tizen_base::Database& db, uid_t uid,
479     const std::string& pkgid, const std::string& locale) {
480   pkgmgrinfo_filter_x tmp_filter = { 0, };
481   pkgmgrinfo_node_x node = {
482     .prop = E_PMINFO_PKGINFO_PROP_PACKAGE_ID,
483     .value = const_cast<char*>(pkgid.c_str())
484   };
485   tmp_filter.cache_flag = true;
486   tmp_filter.list = g_slist_append(tmp_filter.list, (gpointer)&node);
487   std::map<std::string, std::shared_ptr<package_x>> pkgs;
488   internal::GetPkgInfo(db, &tmp_filter, uid_, locale, pkgs);
489   for (auto& [key, val] : pkgs) {
490     AddPackage(key, val);
491     for (auto& appid : pkg_app_map_[key]) {
492       app_map_.erase(appid);
493     }
494
495     pkg_app_map_.erase(key);
496     std::vector<std::shared_ptr<application_x>> app_list;
497     node.prop = E_PMINFO_APPINFO_PROP_APP_PACKAGE;
498     node.value = const_cast<char*>(key.c_str());
499     internal::GetAppInfo(db, &tmp_filter, uid_, uid, locale, app_list);
500     for (auto& app : app_list) {
501       app->privileges = val->privileges;
502       std::string appid = app->appid;
503       AddApplication(std::move(appid), std::move(app));
504     }
505   }
506
507   return true;
508 }
509
510 bool DBHandleProvider::UpdateCacheApp(const tizen_base::Database& db, uid_t uid,
511     const std::string& appid, const std::string& locale) {
512   pkgmgrinfo_filter_x tmp_filter = { 0, };
513   pkgmgrinfo_node_x node = {
514     .prop = E_PMINFO_APPINFO_PROP_APP_ID,
515     .value = const_cast<char*>(appid.c_str())
516   };
517   tmp_filter.cache_flag = true;
518   tmp_filter.list = g_slist_append(tmp_filter.list, (gpointer)&node);
519
520   std::vector<std::shared_ptr<application_x>> app_list;
521   app_map_.erase(appid);
522   internal::GetAppInfo(db, &tmp_filter, uid_, uid, locale, app_list);
523   g_slist_free(tmp_filter.list);
524
525   for (auto& app : app_list) {
526     auto it = pkg_map_.find(app->package);
527     if (it == pkg_map_.end()) {
528       LOG(ERROR) << "Can not find package from pkg_map";
529       return false;
530     }
531
532     pkg_app_map_[app->package].erase(app->appid);
533     app->privileges = it->second->privileges;
534     std::string appid = app->appid;
535     AddApplication(std::move(appid), std::move(app));
536   }
537
538   return true;
539 }
540
541 bool DBHandleProvider::UpdateCacheAppByPkgid(const tizen_base::Database& db,
542     uid_t uid, const std::string& pkgid, const std::string& locale) {
543   auto it = pkg_map_.find(pkgid);
544   if (it == pkg_map_.end()) {
545     LOG(ERROR) << "Can not find package from pkg_map";
546     return false;
547   }
548
549   auto& pkg = it->second;
550   pkgmgrinfo_filter_x tmp_filter = { 0, };
551   pkgmgrinfo_node_x node = {
552     .prop = E_PMINFO_APPINFO_PROP_APP_PACKAGE,
553     .value = pkg->package
554   };
555
556   tmp_filter.cache_flag = true;
557   tmp_filter.list = g_slist_append(tmp_filter.list, (gpointer)&node);
558
559   std::vector<std::shared_ptr<application_x>> app_list;
560   internal::GetAppInfo(db, &tmp_filter, uid_, uid, locale, app_list);
561
562   for (auto& appid : pkg_app_map_[pkgid]) {
563     app_map_.erase(appid);
564   }
565   pkg_app_map_.erase(pkgid);
566
567   for (auto& app : app_list) {
568     app->privileges = pkg->privileges;
569     std::string appid = app->appid;
570     AddApplication(std::move(appid), std::move(app));
571   }
572
573   g_slist_free(tmp_filter.list);
574   return true;
575 }
576
577 }  // namespace database
578 }  // namespace pkgmgr_server