5e50517f098ef984e7a5c26ca93b329ae679d0da
[platform/core/appfw/pkgmgr-info.git] / src / server / worker_thread.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 "worker_thread.hh"
18
19 #include <sqlite3.h>
20 #include <sys/types.h>
21 #include <malloc.h>
22
23 #include <tzplatform_config.h>
24
25 #include "abstract_parcelable.hh"
26 #include "cynara_checker.hh"
27 #include "request_handler_factory.hh"
28 #include "server/database/db_handle_provider.hh"
29 #include "server/database/update_pending_cache_handler.hh"
30 #include "utils/logging.hh"
31
32 #include "pkgmgrinfo_debug.h"
33
34 #ifdef LOG_TAG
35 #undef LOG_TAG
36 #endif
37 #define LOG_TAG "PKGMGR_INFO"
38
39 #ifndef SQLITE_ENABLE_MEMORY_MANAGEMENT
40 #define SQLITE_ENABLE_MEMORY_MANAGEMENT
41 #endif
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 const char PRIVILEGE_PACKAGE_MANAGER_ADMIN[] =
62     "http://tizen.org/privilege/packagemanager.admin";
63
64 std::vector<std::string> GetPrivileges(pkgmgr_common::ReqType type) {
65   std::vector<std::string> ret;
66   if (type == pkgmgr_common::SET_CERT_INFO)
67     ret.emplace_back(PRIVILEGE_PACKAGE_MANAGER_ADMIN);
68   else if (type == pkgmgr_common::SET_PKG_INFO)
69     ret.emplace_back(PRIVILEGE_PACKAGE_MANAGER_ADMIN);
70
71   return ret;
72 }
73
74 }  // namespace
75
76 namespace pkgmgr_server {
77
78 WorkerThread::WorkerThread(unsigned int num) : stop_all_(false) {
79   threads_.reserve(num);
80   for (unsigned int i = 0; i < num; ++i)
81     threads_.emplace_back([this]() -> void { this->Run(); });
82
83   LOG(DEBUG) << num << " Worker threads are created";
84 }
85
86 WorkerThread::~WorkerThread() {
87   stop_all_ = true;
88   cv_.notify_all();
89
90   for (auto& t : threads_)
91     t.join();
92 }
93
94 bool WorkerThread::PushQueue(std::shared_ptr<PkgRequest> req) {
95   {
96     std::unique_lock<std::mutex> u(lock_);
97     queue_.push(req);
98     cv_.notify_one();
99   }
100   return true;
101 }
102
103 std::shared_ptr<PkgRequest> WorkerThread::PopQueue() {
104   SetMemoryTrimTimer();
105   std::unique_lock<std::mutex> u(lock_);
106   cv_.wait(u, [this] { return !this->queue_.empty() || stop_all_; });
107   if (stop_all_ && queue_.empty())
108     return nullptr;
109
110   auto req = queue_.front();
111   queue_.pop();
112   return req;
113 }
114
115 void WorkerThread::Run() {
116   RequestHandlerFactory factory;
117   LOG(DEBUG) << "Initialize request handlers";
118   while (true) {
119     std::shared_ptr<PkgRequest> req = PopQueue();
120     if (req == nullptr)
121       return;
122
123     if (!req->GetPrivilegeChecked()) {
124       if (!req->ReceiveData()) {
125         LOG(ERROR) << "Fail to receive data";
126         continue;
127       }
128
129       pkgmgr_common::ReqType type = req->GetRequestType();
130       std::vector<std::string> privileges = GetPrivileges(type);
131       if (!CynaraChecker::GetInst().CheckPrivilege(this, req, privileges))
132         continue;
133     }
134
135     auto type = req->GetRequestType();
136     LOG(WARNING) << "Request type: " << pkgmgr_common::ReqTypeToString(type)
137         << " pid: " << req->GetSenderPID() << " tid: " << req->GetSenderTID();
138     auto handler = factory.GetRequestHandler(type);
139     if (handler == nullptr)
140       continue;
141
142     try {
143       handler->PreExec();
144       handler->SetUID(ConvertUID(req->GetSenderUID()));
145       handler->SetPID(req->GetSenderPID());
146       if (!handler->HandleRequest(req->DetachData(), req->GetSize(),
147           locale_.GetObject()))
148         LOG(ERROR) << "Failed to handle request";
149
150       if (req->SendData(handler->ExtractResult()) == false)
151         LOG(ERROR) << "Failed to send response pid: " << req->GetSenderPID();
152       else
153         LOG(WARNING) << "Success response pid: " << req->GetSenderPID()
154             << " tid: " << req->GetSenderTID();
155     } catch (const std::exception& err) {
156       LOG(ERROR) << "Exception occurred: " << err.what()
157                  << ", pid: " << req->GetSenderPID();
158       SendError(req);
159     } catch (...) {
160       LOG(ERROR) << "Exception occurred pid: " << req->GetSenderPID();
161       SendError(req);
162     }
163
164     handler->PostExec();
165   }
166 }
167
168 void WorkerThread::SetMemoryTrimTimer() {
169   std::lock_guard<std::recursive_mutex> lock(mutex_);
170   if (timer_ > 0)
171     g_source_remove(timer_);
172
173   timer_ = g_timeout_add_seconds_full(G_PRIORITY_LOW, 10,
174       TrimMemory, this, NULL);
175 }
176
177 gboolean WorkerThread::TrimMemory(void* data) {
178   LOG(DEBUG) << "Trim memory";
179   auto* h = static_cast<WorkerThread*>(data);
180   {
181     std::lock_guard<std::recursive_mutex> lock(h->mutex_);
182     h->timer_ = 0;
183   }
184
185   auto crashed_writer_pids =
186       database::DBHandleProvider::CrashedWriteRequestPIDs();
187   if (!crashed_writer_pids.empty()) {
188     database::UpdatePendingCacheHandler db(getuid(), std::move(crashed_writer_pids), {});
189     db.SetLocale(h->locale_.GetObject());
190     db.Execute();
191   }
192
193   sqlite3_release_memory(-1);
194   malloc_trim(0);
195   return G_SOURCE_REMOVE;
196 }
197
198 void WorkerThread::SetLocale(std::string locale) {
199   LOG(DEBUG) << "Change locale : " << locale_.GetObject()
200       << " -> "  << locale;
201   locale_.SetObject(std::move(locale));
202 }
203
204 void WorkerThread::SendError(const std::shared_ptr<PkgRequest>& req) {
205   pkgmgr_common::parcel::AbstractParcelable parcelable(
206       0, pkgmgr_common::parcel::ParcelableType::Unknown, PMINFO_R_ERROR);
207   tizen_base::Parcel p;
208   p.WriteParcelable(parcelable);
209   req->SendData(p);
210 }
211
212 }  // namespace pkgmgr_server