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