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