Handle client and agent disconnection
[platform/core/security/cynara.git] / src / service / logic / Logic.cpp
1 /*
2  * Copyright (c) 2014 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  * @file        src/service/logic/Logic.cpp
18  * @author      Lukasz Wojciechowski <l.wojciechow@partner.samsung.com>
19  * @version     1.0
20  * @brief       This file implements main class of logic layer in cynara service
21  */
22
23 #include <csignal>
24 #include <cinttypes>
25 #include <functional>
26 #include <memory>
27
28 #include <log/log.h>
29 #include <common.h>
30 #include <log/log.h>
31 #include <exceptions/BucketNotExistsException.h>
32 #include <exceptions/DatabaseException.h>
33 #include <exceptions/DefaultBucketDeletionException.h>
34 #include <exceptions/DefaultBucketSetNoneException.h>
35 #include <exceptions/InvalidBucketIdException.h>
36 #include <exceptions/PluginErrorException.h>
37 #include <exceptions/PluginNotFoundException.h>
38 #include <exceptions/UnexpectedErrorException.h>
39 #include <request/AdminCheckRequest.h>
40 #include <request/AgentActionRequest.h>
41 #include <request/AgentRegisterRequest.h>
42 #include <request/CancelRequest.h>
43 #include <request/CheckRequest.h>
44 #include <request/InsertOrUpdateBucketRequest.h>
45 #include <request/RemoveBucketRequest.h>
46 #include <request/RequestContext.h>
47 #include <request/SetPoliciesRequest.h>
48 #include <request/SignalRequest.h>
49 #include <response/AgentRegisterResponse.h>
50 #include <response/CancelResponse.h>
51 #include <response/CheckResponse.h>
52 #include <response/CodeResponse.h>
53
54 #include <main/Cynara.h>
55 #include <agent/AgentManager.h>
56 #include <sockets/SocketManager.h>
57 #include <storage/Storage.h>
58
59 #include <cynara-plugin.h>
60
61 #include <cynara-agent.h>
62
63 #include "Logic.h"
64
65 namespace Cynara {
66
67 Logic::Logic() {
68 }
69
70 Logic::~Logic() {
71 }
72
73 void Logic::execute(RequestContextPtr context UNUSED, SignalRequestPtr request) {
74     LOGD("Processing signal: [%d]", request->signalNumber());
75
76     switch (request->signalNumber()) {
77     case SIGTERM:
78         LOGI("SIGTERM received!");
79         m_socketManager->mainLoopStop();
80         break;
81     }
82 }
83
84 void Logic::execute(RequestContextPtr context, AdminCheckRequestPtr request) {
85     PolicyResult result = m_storage->checkPolicy(request->key(), request->startBucket(),
86                                                  request->recursive());
87
88     context->returnResponse(context, std::make_shared<CheckResponse>(result,
89                             request->sequenceNumber()));
90 }
91
92 void Logic::execute(RequestContextPtr context, AgentActionRequestPtr request) {
93     AgentTalkerPtr talkerPtr = m_agentManager->getTalker(context->responseQueue(),
94                                                          request->sequenceNumber());
95     if (!talkerPtr) {
96         LOGD("Received response from agent with invalid request id: [%" PRIu16 "]",
97              request->sequenceNumber());
98         return;
99     }
100
101     CheckContextPtr checkContextPtr = m_checkRequestManager.getContext(talkerPtr);
102     if (!checkContextPtr) {
103         LOGE("No matching check context for agent talker.");
104         m_agentManager->removeTalker(talkerPtr);
105         return;
106     }
107
108     if (!checkContextPtr->cancelled()) {
109         PluginData data(request->data().begin(), request->data().end());
110         if (request->type() == CYNARA_MSG_TYPE_CANCEL) {
111             // Nothing to do for now
112         } else if (request->type() == CYNARA_MSG_TYPE_ACTION) {
113             update(checkContextPtr->m_key, checkContextPtr->m_checkId, data,
114                    checkContextPtr->m_requestContext, checkContextPtr->m_plugin);
115         } else {
116             LOGE("Invalid response type [%d] in response from agent <%s>",
117                  static_cast<int>(request->type()), talkerPtr->agentType().c_str());
118             // TODO: disconnect agent
119         }
120     }
121
122     m_agentManager->removeTalker(talkerPtr);
123     m_checkRequestManager.removeRequest(checkContextPtr);
124 }
125
126 void Logic::execute(RequestContextPtr context, AgentRegisterRequestPtr request) {
127     auto result = m_agentManager->registerAgent(request->agentType(), context->responseQueue());
128     context->returnResponse(context, std::make_shared<AgentRegisterResponse>(
129                             result, request->sequenceNumber()));
130 }
131
132 void Logic::execute(RequestContextPtr context, CancelRequestPtr request) {
133     CheckContextPtr checkContextPtr = m_checkRequestManager.getContext(context->responseQueue(),
134                                                                        request->sequenceNumber());
135     if (!checkContextPtr) {
136         LOGD("Cancel request id: [%" PRIu16 "] with no matching request in progress.",
137              request->sequenceNumber());
138         return;
139     }
140
141     if (checkContextPtr->cancelled())
142         return;
143
144     checkContextPtr->cancel();
145     checkContextPtr->m_agentTalker->cancel();
146
147     LOGD("Returning response for cancel request id: [%" PRIu16 "].", request->sequenceNumber());
148     context->returnResponse(context, std::make_shared<CancelResponse>(request->sequenceNumber()));
149 }
150
151 void Logic::execute(RequestContextPtr context, CheckRequestPtr request) {
152     PolicyResult result(PredefinedPolicyType::DENY);
153     if (check(context, request->key(), request->sequenceNumber(), result)) {
154         context->returnResponse(context, std::make_shared<CheckResponse>(result,
155                                 request->sequenceNumber()));
156     }
157 }
158
159 bool Logic::check(const RequestContextPtr &context, const PolicyKey &key,
160                   ProtocolFrameSequenceNumber checkId, PolicyResult &result) {
161
162     if (m_checkRequestManager.getContext(context->responseQueue(), checkId)) {
163         LOGE("Check request for checkId: [%" PRIu16 "] is already processing", checkId);
164         return false;
165     }
166
167     result = m_storage->checkPolicy(key);
168
169     switch (result.policyType()) {
170         case PredefinedPolicyType::ALLOW :
171             LOGD("check of policy key <%s> returned ALLOW", key.toString().c_str());
172             return true;
173         case PredefinedPolicyType::DENY :
174             LOGD("check of policy key <%s> returned DENY", key.toString().c_str());
175             return true;
176     }
177
178     return pluginCheck(context, key, checkId, result);
179 }
180
181 bool Logic::pluginCheck(const RequestContextPtr &context, const PolicyKey &key,
182                         ProtocolFrameSequenceNumber checkId, PolicyResult &result) {
183
184     LOGD("Trying to check policy: <%s> in plugin.", key.toString().c_str());
185
186     ExternalPluginPtr plugin = m_pluginManager->getPlugin(result.policyType());
187     if (!plugin) {
188         LOGE("Plugin not found for policy: [0x%x]", result.policyType());
189         result = PolicyResult(PredefinedPolicyType::DENY);
190         return true;
191     }
192
193     ServicePluginInterfacePtr servicePlugin =
194             std::dynamic_pointer_cast<ServicePluginInterface>(plugin);
195     if (!plugin) {
196         throw PluginNotFoundException(result);
197     }
198
199     AgentType requiredAgent;
200     PluginData pluginData;
201
202     auto ret = servicePlugin->check(key.client().toString(), key.user().toString(),
203                                     key.privilege().toString(), result, requiredAgent, pluginData);
204
205     switch (ret) {
206         case ServicePluginInterface::PluginStatus::ANSWER_READY:
207             return true;
208         case ServicePluginInterface::PluginStatus::ANSWER_NOTREADY: {
209                 result = PolicyResult(PredefinedPolicyType::DENY);
210                 AgentTalkerPtr agentTalker = m_agentManager->createTalker(requiredAgent);
211                 if (!agentTalker) {
212                     LOGE("Required agent talker for: <%s> could not be created.",
213                          requiredAgent.c_str());
214                     return true;
215                 }
216
217                 if (!m_checkRequestManager.createContext(key, context, checkId, servicePlugin,
218                                                          agentTalker)) {
219                     LOGE("Check context for checkId: [%" PRIu16 "] could not be created.",
220                          checkId);
221                     m_agentManager->removeTalker(agentTalker);
222                     return true;
223                 }
224                 agentTalker->send(pluginData);
225             }
226             return false;
227         default:
228             throw PluginErrorException(key); // This 'throw' should be removed or handled properly.
229     }
230 }
231
232 bool Logic::update(const PolicyKey &key, ProtocolFrameSequenceNumber checkId,
233                    const PluginData &agentData, const RequestContextPtr &context,
234                    const ServicePluginInterfacePtr &plugin) {
235
236     LOGD("Check update: <%s>:[%" PRIu16 "]", key.toString().c_str(), checkId);
237
238     PolicyResult result;
239     bool answerReady = false;
240     auto ret = plugin->update(key.client().toString(), key.user().toString(),
241                               key.privilege().toString(), agentData, result);
242     switch (ret) {
243         case ServicePluginInterface::PluginStatus::SUCCESS:
244             answerReady = true;
245             break;
246         case ServicePluginInterface::PluginStatus::ERROR:
247             result = PolicyResult(PredefinedPolicyType::DENY);
248             answerReady = true;
249             break;
250         default:
251             throw PluginErrorException(key);
252     }
253
254     if (answerReady && context->responseQueue()) {
255         context->returnResponse(context, std::make_shared<CheckResponse>(result, checkId));
256         return true;
257     }
258
259     return false;
260 }
261
262 void Logic::execute(RequestContextPtr context, InsertOrUpdateBucketRequestPtr request) {
263     auto code = CodeResponse::Code::OK;
264
265     try {
266         m_storage->addOrUpdateBucket(request->bucketId(), request->result());
267         onPoliciesChanged();
268     } catch (const DatabaseException &ex) {
269         code = CodeResponse::Code::FAILED;
270     } catch (const DefaultBucketSetNoneException &ex) {
271         code = CodeResponse::Code::NOT_ALLOWED;
272     } catch (const InvalidBucketIdException &ex) {
273         code = CodeResponse::Code::NOT_ALLOWED;
274     }
275
276     context->returnResponse(context, std::make_shared<CodeResponse>(code,
277                             request->sequenceNumber()));
278 }
279
280 void Logic::execute(RequestContextPtr context, RemoveBucketRequestPtr request) {
281     auto code = CodeResponse::Code::OK;
282     try {
283         m_storage->deleteBucket(request->bucketId());
284         onPoliciesChanged();
285     } catch (const DatabaseException &ex) {
286         code = CodeResponse::Code::FAILED;
287     } catch (const BucketNotExistsException &ex) {
288         code = CodeResponse::Code::NO_BUCKET;
289     } catch (const DefaultBucketDeletionException &ex) {
290         code = CodeResponse::Code::NOT_ALLOWED;
291     }
292     context->returnResponse(context, std::make_shared<CodeResponse>(code,
293                             request->sequenceNumber()));
294 }
295
296 void Logic::execute(RequestContextPtr context, SetPoliciesRequestPtr request) {
297     auto code = CodeResponse::Code::OK;
298     try {
299         m_storage->insertPolicies(request->policiesToBeInsertedOrUpdated());
300         m_storage->deletePolicies(request->policiesToBeRemoved());
301         onPoliciesChanged();
302     } catch (const DatabaseException &ex) {
303         code = CodeResponse::Code::FAILED;
304     } catch (const BucketNotExistsException &ex) {
305         code = CodeResponse::Code::NO_BUCKET;
306     }
307     context->returnResponse(context, std::make_shared<CodeResponse>(code,
308                             request->sequenceNumber()));
309 }
310
311 void Logic::contextClosed(RequestContextPtr context) {
312     LOGD("context closed");
313
314     LinkId linkId = context->responseQueue();
315
316     m_agentManager->cleanupAgent(linkId, [&](const AgentTalkerPtr &talker) -> void {
317                                  handleAgentTalkerDisconnection(talker); });
318
319     m_checkRequestManager.cancelRequests(linkId,
320                                          [&](const CheckContextPtr &checkContextPtr) -> void {
321                                          handleClientDisconnection(checkContextPtr); });
322 }
323
324 void Logic::onPoliciesChanged(void) {
325     m_storage->save();
326     m_socketManager->disconnectAllClients();
327     //todo remove all saved contexts (if there will be any saved contexts)
328 }
329
330 void Logic::handleAgentTalkerDisconnection(const AgentTalkerPtr &agentTalkerPtr) {
331     CheckContextPtr checkContextPtr = m_checkRequestManager.getContext(agentTalkerPtr);
332     if (checkContextPtr == nullptr) {
333         LOGE("No matching check context for agent talker.");
334         return;
335     }
336
337     if (!checkContextPtr->cancelled() && checkContextPtr->m_requestContext->responseQueue()) {
338         PolicyResult result(PredefinedPolicyType::DENY);
339         checkContextPtr->m_requestContext->returnResponse(checkContextPtr->m_requestContext,
340                 std::make_shared<CheckResponse>(result, checkContextPtr->m_checkId));
341     }
342
343     m_checkRequestManager.removeRequest(checkContextPtr);
344 }
345
346 void Logic::handleClientDisconnection(const CheckContextPtr &checkContextPtr) {
347     LOGD("Handle client disconnection");
348
349     if (!checkContextPtr->cancelled()) {
350         checkContextPtr->cancel();
351         checkContextPtr->m_agentTalker->cancel();
352     }
353 }
354
355 } // namespace Cynara