2 * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * @file src/service/logic/Logic.cpp
18 * @author Lukasz Wojciechowski <l.wojciechow@partner.samsung.com>
20 * @brief This file implements main class of logic layer in cynara service
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/InsertOrUpdateBucketRequest.h>
46 #include <request/ListRequest.h>
47 #include <request/RemoveBucketRequest.h>
48 #include <request/RequestContext.h>
49 #include <request/SetPoliciesRequest.h>
50 #include <request/SignalRequest.h>
51 #include <response/AgentRegisterResponse.h>
52 #include <response/CancelResponse.h>
53 #include <response/CheckResponse.h>
54 #include <response/CodeResponse.h>
55 #include <response/ListResponse.h>
56 #include <types/Policy.h>
58 #include <main/Cynara.h>
59 #include <agent/AgentManager.h>
60 #include <sockets/SocketManager.h>
61 #include <storage/Storage.h>
63 #include <cynara-plugin.h>
65 #include <cynara-agent.h>
77 void Logic::execute(RequestContextPtr context UNUSED, SignalRequestPtr request) {
78 LOGD("Processing signal: [%d]", request->signalNumber());
80 switch (request->signalNumber()) {
82 LOGI("SIGTERM received!");
83 m_socketManager->mainLoopStop();
88 void Logic::execute(RequestContextPtr context, AdminCheckRequestPtr request) {
89 PolicyResult result = m_storage->checkPolicy(request->key(), request->startBucket(),
90 request->recursive());
92 context->returnResponse(context, std::make_shared<CheckResponse>(result,
93 request->sequenceNumber()));
96 void Logic::execute(RequestContextPtr context, AgentActionRequestPtr request) {
97 AgentTalkerPtr talkerPtr = m_agentManager->getTalker(context->responseQueue(),
98 request->sequenceNumber());
100 LOGD("Received response from agent with invalid request id: [%" PRIu16 "]",
101 request->sequenceNumber());
105 CheckContextPtr checkContextPtr = m_checkRequestManager.getContext(talkerPtr);
106 if (!checkContextPtr) {
107 LOGE("No matching check context for agent talker.");
108 m_agentManager->removeTalker(talkerPtr);
112 if (!checkContextPtr->cancelled()) {
113 PluginData data(request->data().begin(), request->data().end());
114 if (request->type() == CYNARA_MSG_TYPE_CANCEL) {
115 // Nothing to do for now
116 } else if (request->type() == CYNARA_MSG_TYPE_ACTION) {
117 update(checkContextPtr->m_key, checkContextPtr->m_checkId, data,
118 checkContextPtr->m_requestContext, checkContextPtr->m_plugin);
120 LOGE("Invalid response type [%d] in response from agent <%s>",
121 static_cast<int>(request->type()), talkerPtr->agentType().c_str());
122 // TODO: disconnect agent
126 m_agentManager->removeTalker(talkerPtr);
127 m_checkRequestManager.removeRequest(checkContextPtr);
130 void Logic::execute(RequestContextPtr context, AgentRegisterRequestPtr request) {
131 auto result = m_agentManager->registerAgent(request->agentType(), context->responseQueue());
132 context->returnResponse(context, std::make_shared<AgentRegisterResponse>(
133 result, request->sequenceNumber()));
136 void Logic::execute(RequestContextPtr context, CancelRequestPtr request) {
137 CheckContextPtr checkContextPtr = m_checkRequestManager.getContext(context->responseQueue(),
138 request->sequenceNumber());
139 if (!checkContextPtr) {
140 LOGD("Cancel request id: [%" PRIu16 "] with no matching request in progress.",
141 request->sequenceNumber());
145 if (checkContextPtr->cancelled())
148 checkContextPtr->cancel();
149 checkContextPtr->m_agentTalker->cancel();
151 LOGD("Returning response for cancel request id: [%" PRIu16 "].", request->sequenceNumber());
152 context->returnResponse(context, std::make_shared<CancelResponse>(request->sequenceNumber()));
155 void Logic::execute(RequestContextPtr context, CheckRequestPtr request) {
156 PolicyResult result(PredefinedPolicyType::DENY);
157 if (check(context, request->key(), request->sequenceNumber(), result)) {
158 context->returnResponse(context, std::make_shared<CheckResponse>(result,
159 request->sequenceNumber()));
163 bool Logic::check(const RequestContextPtr &context, const PolicyKey &key,
164 ProtocolFrameSequenceNumber checkId, PolicyResult &result) {
166 if (m_checkRequestManager.getContext(context->responseQueue(), checkId)) {
167 LOGE("Check request for checkId: [%" PRIu16 "] is already processing", checkId);
171 result = m_storage->checkPolicy(key);
173 switch (result.policyType()) {
174 case PredefinedPolicyType::ALLOW :
175 LOGD("check of policy key <%s> returned ALLOW", key.toString().c_str());
177 case PredefinedPolicyType::DENY :
178 LOGD("check of policy key <%s> returned DENY", key.toString().c_str());
182 return pluginCheck(context, key, checkId, result);
185 bool Logic::pluginCheck(const RequestContextPtr &context, const PolicyKey &key,
186 ProtocolFrameSequenceNumber checkId, PolicyResult &result) {
188 LOGD("Trying to check policy: <%s> in plugin.", key.toString().c_str());
190 ExternalPluginPtr plugin = m_pluginManager->getPlugin(result.policyType());
192 LOGE("Plugin not found for policy: [0x%x]", result.policyType());
193 result = PolicyResult(PredefinedPolicyType::DENY);
197 ServicePluginInterfacePtr servicePlugin =
198 std::dynamic_pointer_cast<ServicePluginInterface>(plugin);
200 throw PluginNotFoundException(result);
203 AgentType requiredAgent;
204 PluginData pluginData;
206 auto ret = servicePlugin->check(key.client().toString(), key.user().toString(),
207 key.privilege().toString(), result, requiredAgent, pluginData);
210 case ServicePluginInterface::PluginStatus::ANSWER_READY:
212 case ServicePluginInterface::PluginStatus::ANSWER_NOTREADY: {
213 result = PolicyResult(PredefinedPolicyType::DENY);
214 AgentTalkerPtr agentTalker = m_agentManager->createTalker(requiredAgent);
216 LOGE("Required agent talker for: <%s> could not be created.",
217 requiredAgent.c_str());
221 if (!m_checkRequestManager.createContext(key, context, checkId, servicePlugin,
223 LOGE("Check context for checkId: [%" PRIu16 "] could not be created.",
225 m_agentManager->removeTalker(agentTalker);
228 agentTalker->send(pluginData);
232 throw PluginErrorException(key); // This 'throw' should be removed or handled properly.
236 bool Logic::update(const PolicyKey &key, ProtocolFrameSequenceNumber checkId,
237 const PluginData &agentData, const RequestContextPtr &context,
238 const ServicePluginInterfacePtr &plugin) {
240 LOGD("Check update: <%s>:[%" PRIu16 "]", key.toString().c_str(), checkId);
243 bool answerReady = false;
244 auto ret = plugin->update(key.client().toString(), key.user().toString(),
245 key.privilege().toString(), agentData, result);
247 case ServicePluginInterface::PluginStatus::SUCCESS:
250 case ServicePluginInterface::PluginStatus::ERROR:
251 result = PolicyResult(PredefinedPolicyType::DENY);
255 throw PluginErrorException(key);
258 if (answerReady && context->responseQueue()) {
259 context->returnResponse(context, std::make_shared<CheckResponse>(result, checkId));
266 void Logic::execute(RequestContextPtr context, InsertOrUpdateBucketRequestPtr request) {
267 auto code = CodeResponse::Code::OK;
270 m_storage->addOrUpdateBucket(request->bucketId(), request->result());
272 } catch (const DatabaseException &ex) {
273 code = CodeResponse::Code::FAILED;
274 } catch (const DefaultBucketSetNoneException &ex) {
275 code = CodeResponse::Code::NOT_ALLOWED;
276 } catch (const InvalidBucketIdException &ex) {
277 code = CodeResponse::Code::NOT_ALLOWED;
280 context->returnResponse(context, std::make_shared<CodeResponse>(code,
281 request->sequenceNumber()));
284 void Logic::execute(RequestContextPtr context, ListRequestPtr request) {
285 bool bucketValid = true;
287 std::vector<Policy> policies;
289 policies = m_storage->listPolicies(request->bucket(), request->filter());
290 } catch (const BucketNotExistsException &ex) {
294 context->returnResponse(context, std::make_shared<ListResponse>(policies, bucketValid,
295 request->sequenceNumber()));
298 void Logic::execute(RequestContextPtr context, RemoveBucketRequestPtr request) {
299 auto code = CodeResponse::Code::OK;
301 m_storage->deleteBucket(request->bucketId());
303 } catch (const DatabaseException &ex) {
304 code = CodeResponse::Code::FAILED;
305 } catch (const BucketNotExistsException &ex) {
306 code = CodeResponse::Code::NO_BUCKET;
307 } catch (const DefaultBucketDeletionException &ex) {
308 code = CodeResponse::Code::NOT_ALLOWED;
310 context->returnResponse(context, std::make_shared<CodeResponse>(code,
311 request->sequenceNumber()));
314 void Logic::execute(RequestContextPtr context, SetPoliciesRequestPtr request) {
315 auto code = CodeResponse::Code::OK;
317 m_storage->insertPolicies(request->policiesToBeInsertedOrUpdated());
318 m_storage->deletePolicies(request->policiesToBeRemoved());
320 } catch (const DatabaseException &ex) {
321 code = CodeResponse::Code::FAILED;
322 } catch (const BucketNotExistsException &ex) {
323 code = CodeResponse::Code::NO_BUCKET;
325 context->returnResponse(context, std::make_shared<CodeResponse>(code,
326 request->sequenceNumber()));
329 void Logic::contextClosed(RequestContextPtr context) {
330 LOGD("context closed");
332 LinkId linkId = context->responseQueue();
334 m_agentManager->cleanupAgent(linkId, [&](const AgentTalkerPtr &talker) -> void {
335 handleAgentTalkerDisconnection(talker); });
337 m_checkRequestManager.cancelRequests(linkId,
338 [&](const CheckContextPtr &checkContextPtr) -> void {
339 handleClientDisconnection(checkContextPtr); });
342 void Logic::onPoliciesChanged(void) {
344 m_socketManager->disconnectAllClients();
345 m_pluginManager->invalidateAll();
346 //todo remove all saved contexts (if there will be any saved contexts)
349 void Logic::handleAgentTalkerDisconnection(const AgentTalkerPtr &agentTalkerPtr) {
350 CheckContextPtr checkContextPtr = m_checkRequestManager.getContext(agentTalkerPtr);
351 if (checkContextPtr == nullptr) {
352 LOGE("No matching check context for agent talker.");
356 if (!checkContextPtr->cancelled() && checkContextPtr->m_requestContext->responseQueue()) {
357 PolicyResult result(PredefinedPolicyType::DENY);
358 checkContextPtr->m_requestContext->returnResponse(checkContextPtr->m_requestContext,
359 std::make_shared<CheckResponse>(result, checkContextPtr->m_checkId));
362 m_checkRequestManager.removeRequest(checkContextPtr);
365 void Logic::handleClientDisconnection(const CheckContextPtr &checkContextPtr) {
366 LOGD("Handle client disconnection");
368 if (!checkContextPtr->cancelled()) {
369 checkContextPtr->cancel();
370 checkContextPtr->m_agentTalker->cancel();
374 } // namespace Cynara