Fix checking the application status
[platform/core/appfw/app-installers.git] / src / common / step / pkgmgr / step_kill_apps.cc
1 // Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
2 // Use of this source code is governed by an apache-2.0 license that can be
3 // found in the LICENSE file.
4
5 #include "common/step/pkgmgr/step_kill_apps.h"
6
7 #include <sys/time.h>
8 #include <systemd/sd-login.h>
9 #include <aul.h>
10
11 #include <string>
12
13 #include "common/utils/glist_range.h"
14
15 namespace {
16
17 bool CheckAndKill(const std::string& appid, uid_t uid) {
18   int ret = aul_app_get_status_for_uid(appid.c_str(), uid);
19   if (ret < 0)
20     return true;
21
22   int pid = aul_app_get_pid_for_uid(appid.c_str(), uid);
23   if (pid < 0) {
24     LOG(ERROR) << "Failed to get pid for appid[" << appid
25                << "] for uid [" << uid << "]";
26     return true;
27   }
28
29   ret = aul_terminate_pid_sync_without_restart_for_uid(pid, uid);
30   if (ret != AUL_R_OK) {
31     LOG(ERROR) << "Failed to kill app[" << appid << "] for uid [" << uid << "]";
32     return false;
33   }
34
35   return true;
36 }
37
38 bool KillApp(const std::string& appid, const uid_t uid) {
39   uid_t* uids = nullptr;
40   int ret = -1;
41   int i;
42
43   if (uid == 0 || uid == tzplatform_getuid(TZ_SYS_GLOBALAPP_USER)) {
44     ret = sd_get_uids(&uids);
45     if (ret < 0 || (ret == 0 || uids == nullptr)) {
46       LOG(DEBUG) << "Failed to get uids [" << ret << "]";
47       return false;
48     }
49
50     for (i = 0; i < ret; i++) {
51       if (!CheckAndKill(appid, uids[i])) {
52         free(uids);
53         return false;
54       }
55     }
56   } else {
57     if (!CheckAndKill(appid, uid))
58       return false;
59   }
60   free(uids);
61   LOG(DEBUG) << "Application '" << appid << "' has been killed";
62   return true;
63 }
64
65 }  // namespace
66
67 namespace common_installer {
68 namespace pkgmgr {
69
70 Step::Status StepKillApps::process() {
71   manifest_x* old_manifest = context_->old_manifest_data.get() ?
72       context_->old_manifest_data.get() : context_->manifest_data.get();
73   for (application_x* app :
74        GListRange<application_x*>(old_manifest->application)) {
75     (void) KillApp(app->appid, context_->uid.get());
76   }
77   return Status::OK;
78 }
79
80 Step::Status StepKillApps::precheck() {
81   if (!context_->manifest_data.get() && !context_->old_manifest_data.get()) {
82     LOG(ERROR) << "manifest_data is empty";
83     return Status::ERROR;
84   }
85   return Status::OK;
86 }
87
88 }  // namespace pkgmgr
89 }  // namespace common_installer