Handle cancel request
[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/AgentRegisterRequest.h>
41 #include <request/CancelRequest.h>
42 #include <request/CheckRequest.h>
43 #include <request/InsertOrUpdateBucketRequest.h>
44 #include <request/RemoveBucketRequest.h>
45 #include <request/RequestContext.h>
46 #include <request/SetPoliciesRequest.h>
47 #include <request/SignalRequest.h>
48 #include <response/AgentRegisterResponse.h>
49 #include <response/CancelResponse.h>
50 #include <response/CheckResponse.h>
51 #include <response/CodeResponse.h>
52
53 #include <main/Cynara.h>
54 #include <agent/AgentManager.h>
55 #include <sockets/SocketManager.h>
56 #include <storage/Storage.h>
57
58 #include <cynara-plugin.h>
59
60 #include "Logic.h"
61
62 namespace Cynara {
63 Logic::Logic() {
64 }
65
66 Logic::~Logic() {
67 }
68
69 void Logic::execute(RequestContextPtr context UNUSED, SignalRequestPtr request) {
70     LOGD("Processing signal: [%d]", request->signalNumber());
71
72     switch (request->signalNumber()) {
73     case SIGTERM:
74         LOGI("SIGTERM received!");
75         m_socketManager->mainLoopStop();
76         break;
77     }
78 }
79
80 void Logic::execute(RequestContextPtr context, AdminCheckRequestPtr request) {
81     PolicyResult result = m_storage->checkPolicy(request->key(), request->startBucket(),
82                                                  request->recursive());
83
84     context->returnResponse(context, std::make_shared<CheckResponse>(result,
85                             request->sequenceNumber()));
86 }
87
88 void Logic::execute(RequestContextPtr context, AgentRegisterRequestPtr request) {
89     auto result = m_agentManager->registerAgent(request->agentType(), context->responseQueue());
90     context->returnResponse(context, std::make_shared<AgentRegisterResponse>(
91                             result, request->sequenceNumber()));
92 }
93
94 void Logic::execute(RequestContextPtr context, CancelRequestPtr request) {
95     CheckContextPtr checkContextPtr = m_checkRequestManager.getContext(context->responseQueue(),
96                                                                        request->sequenceNumber());
97     if (!checkContextPtr) {
98         LOGD("Cancel request id: [%" PRIu16 "] with no matching request in progress.",
99              request->sequenceNumber());
100         return;
101     }
102
103     if (checkContextPtr->cancelled())
104         return;
105
106     checkContextPtr->cancel();
107     checkContextPtr->m_agentTalker->cancel();
108
109     LOGD("Returning response for cancel request id: [%" PRIu16 "].", request->sequenceNumber());
110     context->returnResponse(context, std::make_shared<CancelResponse>(request->sequenceNumber()));
111 }
112
113 void Logic::execute(RequestContextPtr context, CheckRequestPtr request) {
114     PolicyResult result(PredefinedPolicyType::DENY);
115     if (check(context, request->key(), request->sequenceNumber(), result)) {
116         context->returnResponse(context, std::make_shared<CheckResponse>(result,
117                                 request->sequenceNumber()));
118     }
119 }
120
121 bool Logic::check(const RequestContextPtr &context, const PolicyKey &key,
122                   ProtocolFrameSequenceNumber checkId, PolicyResult &result) {
123
124     if (m_checkRequestManager.getContext(context->responseQueue(), checkId)) {
125         LOGE("Check request for checkId: [%" PRIu16 "] is already processing", checkId);
126         return false;
127     }
128
129     result = m_storage->checkPolicy(key);
130
131     switch (result.policyType()) {
132         case PredefinedPolicyType::ALLOW :
133             LOGD("check of policy key <%s> returned ALLOW", key.toString().c_str());
134             return true;
135         case PredefinedPolicyType::DENY :
136             LOGD("check of policy key <%s> returned DENY", key.toString().c_str());
137             return true;
138     }
139
140     return pluginCheck(context, key, checkId, result);
141 }
142
143 bool Logic::pluginCheck(const RequestContextPtr &context, const PolicyKey &key,
144                         ProtocolFrameSequenceNumber checkId, PolicyResult &result) {
145
146     LOGD("Trying to check policy: <%s> in plugin.", key.toString().c_str());
147
148     ExternalPluginPtr plugin = m_pluginManager->getPlugin(result.policyType());
149     if (!plugin) {
150         LOGE("Plugin not found for policy: [0x%x]", result.policyType());
151         result = PolicyResult(PredefinedPolicyType::DENY);
152         return true;
153     }
154
155     ServicePluginInterfacePtr servicePlugin =
156             std::dynamic_pointer_cast<ServicePluginInterface>(plugin);
157     if (!plugin) {
158         throw PluginNotFoundException(result);
159     }
160
161     AgentType requiredAgent;
162     PluginData pluginData;
163
164     auto ret = servicePlugin->check(key.client().toString(), key.user().toString(),
165                                     key.privilege().toString(), result, requiredAgent, pluginData);
166
167     switch (ret) {
168         case ServicePluginInterface::PluginStatus::ANSWER_READY:
169             return true;
170         case ServicePluginInterface::PluginStatus::ANSWER_NOTREADY: {
171                 result = PolicyResult(PredefinedPolicyType::DENY);
172                 AgentTalkerPtr agentTalker = m_agentManager->createTalker(requiredAgent);
173                 if (!agentTalker) {
174                     LOGE("Required agent talker for: <%s> could not be created.",
175                          requiredAgent.c_str());
176                     return true;
177                 }
178
179                 if (!m_checkRequestManager.createContext(key, context, checkId, servicePlugin,
180                                                          agentTalker)) {
181                     LOGE("Check context for checkId: [%" PRIu16 "] could not be created.",
182                          checkId);
183                     m_agentManager->removeTalker(agentTalker);
184                     return true;
185                 }
186                 agentTalker->send(pluginData);
187             }
188             return false;
189         default:
190             throw PluginErrorException(key); // This 'throw' should be removed or handled properly.
191     }
192 }
193
194 void Logic::execute(RequestContextPtr context, InsertOrUpdateBucketRequestPtr request) {
195     auto code = CodeResponse::Code::OK;
196
197     try {
198         m_storage->addOrUpdateBucket(request->bucketId(), request->result());
199         onPoliciesChanged();
200     } catch (const DatabaseException &ex) {
201         code = CodeResponse::Code::FAILED;
202     } catch (const DefaultBucketSetNoneException &ex) {
203         code = CodeResponse::Code::NOT_ALLOWED;
204     } catch (const InvalidBucketIdException &ex) {
205         code = CodeResponse::Code::NOT_ALLOWED;
206     }
207
208     context->returnResponse(context, std::make_shared<CodeResponse>(code,
209                             request->sequenceNumber()));
210 }
211
212 void Logic::execute(RequestContextPtr context, RemoveBucketRequestPtr request) {
213     auto code = CodeResponse::Code::OK;
214     try {
215         m_storage->deleteBucket(request->bucketId());
216         onPoliciesChanged();
217     } catch (const DatabaseException &ex) {
218         code = CodeResponse::Code::FAILED;
219     } catch (const BucketNotExistsException &ex) {
220         code = CodeResponse::Code::NO_BUCKET;
221     } catch (const DefaultBucketDeletionException &ex) {
222         code = CodeResponse::Code::NOT_ALLOWED;
223     }
224     context->returnResponse(context, std::make_shared<CodeResponse>(code,
225                             request->sequenceNumber()));
226 }
227
228 void Logic::execute(RequestContextPtr context, SetPoliciesRequestPtr request) {
229     auto code = CodeResponse::Code::OK;
230     try {
231         m_storage->insertPolicies(request->policiesToBeInsertedOrUpdated());
232         m_storage->deletePolicies(request->policiesToBeRemoved());
233         onPoliciesChanged();
234     } catch (const DatabaseException &ex) {
235         code = CodeResponse::Code::FAILED;
236     } catch (const BucketNotExistsException &ex) {
237         code = CodeResponse::Code::NO_BUCKET;
238     }
239     context->returnResponse(context, std::make_shared<CodeResponse>(code,
240                             request->sequenceNumber()));
241 }
242
243 void Logic::contextClosed(RequestContextPtr context UNUSED) {
244     //We don't care now, but we will
245 }
246
247 void Logic::onPoliciesChanged(void) {
248     m_storage->save();
249     m_socketManager->disconnectAllClients();
250     //todo remove all saved contexts (if there will be any saved contexts)
251 }
252
253 } // namespace Cynara