Handle agent response
[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 Logic::Logic() {
67 }
68
69 Logic::~Logic() {
70 }
71
72 void Logic::execute(RequestContextPtr context UNUSED, SignalRequestPtr request) {
73     LOGD("Processing signal: [%d]", request->signalNumber());
74
75     switch (request->signalNumber()) {
76     case SIGTERM:
77         LOGI("SIGTERM received!");
78         m_socketManager->mainLoopStop();
79         break;
80     }
81 }
82
83 void Logic::execute(RequestContextPtr context, AdminCheckRequestPtr request) {
84     PolicyResult result = m_storage->checkPolicy(request->key(), request->startBucket(),
85                                                  request->recursive());
86
87     context->returnResponse(context, std::make_shared<CheckResponse>(result,
88                             request->sequenceNumber()));
89 }
90
91 void Logic::execute(RequestContextPtr context, AgentActionRequestPtr request) {
92     AgentTalkerPtr talkerPtr = m_agentManager->getTalker(context->responseQueue(),
93                                                          request->sequenceNumber());
94     if (!talkerPtr) {
95         LOGD("Received response from agent with invalid request id: [%" PRIu16 "]",
96              request->sequenceNumber());
97         return;
98     }
99
100     CheckContextPtr checkContextPtr = m_checkRequestManager.getContext(talkerPtr);
101     if (!checkContextPtr) {
102         LOGE("No matching check context for agent talker.");
103         m_agentManager->removeTalker(talkerPtr);
104         return;
105     }
106
107     if (!checkContextPtr->cancelled()) {
108         PluginData data(request->data().begin(), request->data().end());
109         if (request->type() == CYNARA_MSG_TYPE_CANCEL) {
110             // Nothing to do for now
111         } else if (request->type() == CYNARA_MSG_TYPE_ACTION) {
112             update(checkContextPtr->m_key, checkContextPtr->m_checkId, data,
113                    checkContextPtr->m_requestContext, checkContextPtr->m_plugin);
114         } else {
115             LOGE("Invalid response type [%d] in response from agent <%s>",
116                  static_cast<int>(request->type()), talkerPtr->agentType().c_str());
117             // TODO: disconnect agent
118         }
119     }
120
121     m_agentManager->removeTalker(talkerPtr);
122     m_checkRequestManager.removeRequest(checkContextPtr);
123 }
124
125 void Logic::execute(RequestContextPtr context, AgentRegisterRequestPtr request) {
126     auto result = m_agentManager->registerAgent(request->agentType(), context->responseQueue());
127     context->returnResponse(context, std::make_shared<AgentRegisterResponse>(
128                             result, request->sequenceNumber()));
129 }
130
131 void Logic::execute(RequestContextPtr context, CancelRequestPtr request) {
132     CheckContextPtr checkContextPtr = m_checkRequestManager.getContext(context->responseQueue(),
133                                                                        request->sequenceNumber());
134     if (!checkContextPtr) {
135         LOGD("Cancel request id: [%" PRIu16 "] with no matching request in progress.",
136              request->sequenceNumber());
137         return;
138     }
139
140     if (checkContextPtr->cancelled())
141         return;
142
143     checkContextPtr->cancel();
144     checkContextPtr->m_agentTalker->cancel();
145
146     LOGD("Returning response for cancel request id: [%" PRIu16 "].", request->sequenceNumber());
147     context->returnResponse(context, std::make_shared<CancelResponse>(request->sequenceNumber()));
148 }
149
150 void Logic::execute(RequestContextPtr context, CheckRequestPtr request) {
151     PolicyResult result(PredefinedPolicyType::DENY);
152     if (check(context, request->key(), request->sequenceNumber(), result)) {
153         context->returnResponse(context, std::make_shared<CheckResponse>(result,
154                                 request->sequenceNumber()));
155     }
156 }
157
158 bool Logic::check(const RequestContextPtr &context, const PolicyKey &key,
159                   ProtocolFrameSequenceNumber checkId, PolicyResult &result) {
160
161     if (m_checkRequestManager.getContext(context->responseQueue(), checkId)) {
162         LOGE("Check request for checkId: [%" PRIu16 "] is already processing", checkId);
163         return false;
164     }
165
166     result = m_storage->checkPolicy(key);
167
168     switch (result.policyType()) {
169         case PredefinedPolicyType::ALLOW :
170             LOGD("check of policy key <%s> returned ALLOW", key.toString().c_str());
171             return true;
172         case PredefinedPolicyType::DENY :
173             LOGD("check of policy key <%s> returned DENY", key.toString().c_str());
174             return true;
175     }
176
177     return pluginCheck(context, key, checkId, result);
178 }
179
180 bool Logic::pluginCheck(const RequestContextPtr &context, const PolicyKey &key,
181                         ProtocolFrameSequenceNumber checkId, PolicyResult &result) {
182
183     LOGD("Trying to check policy: <%s> in plugin.", key.toString().c_str());
184
185     ExternalPluginPtr plugin = m_pluginManager->getPlugin(result.policyType());
186     if (!plugin) {
187         LOGE("Plugin not found for policy: [0x%x]", result.policyType());
188         result = PolicyResult(PredefinedPolicyType::DENY);
189         return true;
190     }
191
192     ServicePluginInterfacePtr servicePlugin =
193             std::dynamic_pointer_cast<ServicePluginInterface>(plugin);
194     if (!plugin) {
195         throw PluginNotFoundException(result);
196     }
197
198     AgentType requiredAgent;
199     PluginData pluginData;
200
201     auto ret = servicePlugin->check(key.client().toString(), key.user().toString(),
202                                     key.privilege().toString(), result, requiredAgent, pluginData);
203
204     switch (ret) {
205         case ServicePluginInterface::PluginStatus::ANSWER_READY:
206             return true;
207         case ServicePluginInterface::PluginStatus::ANSWER_NOTREADY: {
208                 result = PolicyResult(PredefinedPolicyType::DENY);
209                 AgentTalkerPtr agentTalker = m_agentManager->createTalker(requiredAgent);
210                 if (!agentTalker) {
211                     LOGE("Required agent talker for: <%s> could not be created.",
212                          requiredAgent.c_str());
213                     return true;
214                 }
215
216                 if (!m_checkRequestManager.createContext(key, context, checkId, servicePlugin,
217                                                          agentTalker)) {
218                     LOGE("Check context for checkId: [%" PRIu16 "] could not be created.",
219                          checkId);
220                     m_agentManager->removeTalker(agentTalker);
221                     return true;
222                 }
223                 agentTalker->send(pluginData);
224             }
225             return false;
226         default:
227             throw PluginErrorException(key); // This 'throw' should be removed or handled properly.
228     }
229 }
230
231 bool Logic::update(const PolicyKey &key, ProtocolFrameSequenceNumber checkId,
232                    const PluginData &agentData, const RequestContextPtr &context,
233                    const ServicePluginInterfacePtr &plugin) {
234
235     LOGD("Check update: <%s>:[%" PRIu16 "]", key.toString().c_str(), checkId);
236
237     PolicyResult result;
238     bool answerReady = false;
239     auto ret = plugin->update(key.client().toString(), key.user().toString(),
240                               key.privilege().toString(), agentData, result);
241     switch (ret) {
242         case ServicePluginInterface::PluginStatus::SUCCESS:
243             answerReady = true;
244             break;
245         case ServicePluginInterface::PluginStatus::ERROR:
246             result = PolicyResult(PredefinedPolicyType::DENY);
247             answerReady = true;
248             break;
249         default:
250             throw PluginErrorException(key);
251     }
252
253     if (answerReady && context->responseQueue()) {
254         context->returnResponse(context, std::make_shared<CheckResponse>(result, checkId));
255         return true;
256     }
257
258     return false;
259 }
260
261 void Logic::execute(RequestContextPtr context, InsertOrUpdateBucketRequestPtr request) {
262     auto code = CodeResponse::Code::OK;
263
264     try {
265         m_storage->addOrUpdateBucket(request->bucketId(), request->result());
266         onPoliciesChanged();
267     } catch (const DatabaseException &ex) {
268         code = CodeResponse::Code::FAILED;
269     } catch (const DefaultBucketSetNoneException &ex) {
270         code = CodeResponse::Code::NOT_ALLOWED;
271     } catch (const InvalidBucketIdException &ex) {
272         code = CodeResponse::Code::NOT_ALLOWED;
273     }
274
275     context->returnResponse(context, std::make_shared<CodeResponse>(code,
276                             request->sequenceNumber()));
277 }
278
279 void Logic::execute(RequestContextPtr context, RemoveBucketRequestPtr request) {
280     auto code = CodeResponse::Code::OK;
281     try {
282         m_storage->deleteBucket(request->bucketId());
283         onPoliciesChanged();
284     } catch (const DatabaseException &ex) {
285         code = CodeResponse::Code::FAILED;
286     } catch (const BucketNotExistsException &ex) {
287         code = CodeResponse::Code::NO_BUCKET;
288     } catch (const DefaultBucketDeletionException &ex) {
289         code = CodeResponse::Code::NOT_ALLOWED;
290     }
291     context->returnResponse(context, std::make_shared<CodeResponse>(code,
292                             request->sequenceNumber()));
293 }
294
295 void Logic::execute(RequestContextPtr context, SetPoliciesRequestPtr request) {
296     auto code = CodeResponse::Code::OK;
297     try {
298         m_storage->insertPolicies(request->policiesToBeInsertedOrUpdated());
299         m_storage->deletePolicies(request->policiesToBeRemoved());
300         onPoliciesChanged();
301     } catch (const DatabaseException &ex) {
302         code = CodeResponse::Code::FAILED;
303     } catch (const BucketNotExistsException &ex) {
304         code = CodeResponse::Code::NO_BUCKET;
305     }
306     context->returnResponse(context, std::make_shared<CodeResponse>(code,
307                             request->sequenceNumber()));
308 }
309
310 void Logic::contextClosed(RequestContextPtr context UNUSED) {
311     //We don't care now, but we will
312 }
313
314 void Logic::onPoliciesChanged(void) {
315     m_storage->save();
316     m_socketManager->disconnectAllClients();
317     //todo remove all saved contexts (if there will be any saved contexts)
318 }
319
320 } // namespace Cynara