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
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>
54 #include <main/Cynara.h>
55 #include <agent/AgentManager.h>
56 #include <sockets/SocketManager.h>
57 #include <storage/Storage.h>
59 #include <cynara-plugin.h>
61 #include <cynara-agent.h>
73 void Logic::execute(RequestContextPtr context UNUSED, SignalRequestPtr request) {
74 LOGD("Processing signal: [%d]", request->signalNumber());
76 switch (request->signalNumber()) {
78 LOGI("SIGTERM received!");
79 m_socketManager->mainLoopStop();
84 void Logic::execute(RequestContextPtr context, AdminCheckRequestPtr request) {
85 PolicyResult result = m_storage->checkPolicy(request->key(), request->startBucket(),
86 request->recursive());
88 context->returnResponse(context, std::make_shared<CheckResponse>(result,
89 request->sequenceNumber()));
92 void Logic::execute(RequestContextPtr context, AgentActionRequestPtr request) {
93 AgentTalkerPtr talkerPtr = m_agentManager->getTalker(context->responseQueue(),
94 request->sequenceNumber());
96 LOGD("Received response from agent with invalid request id: [%" PRIu16 "]",
97 request->sequenceNumber());
101 CheckContextPtr checkContextPtr = m_checkRequestManager.getContext(talkerPtr);
102 if (!checkContextPtr) {
103 LOGE("No matching check context for agent talker.");
104 m_agentManager->removeTalker(talkerPtr);
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);
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
122 m_agentManager->removeTalker(talkerPtr);
123 m_checkRequestManager.removeRequest(checkContextPtr);
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()));
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());
141 if (checkContextPtr->cancelled())
144 checkContextPtr->cancel();
145 checkContextPtr->m_agentTalker->cancel();
147 LOGD("Returning response for cancel request id: [%" PRIu16 "].", request->sequenceNumber());
148 context->returnResponse(context, std::make_shared<CancelResponse>(request->sequenceNumber()));
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()));
159 bool Logic::check(const RequestContextPtr &context, const PolicyKey &key,
160 ProtocolFrameSequenceNumber checkId, PolicyResult &result) {
162 if (m_checkRequestManager.getContext(context->responseQueue(), checkId)) {
163 LOGE("Check request for checkId: [%" PRIu16 "] is already processing", checkId);
167 result = m_storage->checkPolicy(key);
169 switch (result.policyType()) {
170 case PredefinedPolicyType::ALLOW :
171 LOGD("check of policy key <%s> returned ALLOW", key.toString().c_str());
173 case PredefinedPolicyType::DENY :
174 LOGD("check of policy key <%s> returned DENY", key.toString().c_str());
178 return pluginCheck(context, key, checkId, result);
181 bool Logic::pluginCheck(const RequestContextPtr &context, const PolicyKey &key,
182 ProtocolFrameSequenceNumber checkId, PolicyResult &result) {
184 LOGD("Trying to check policy: <%s> in plugin.", key.toString().c_str());
186 ExternalPluginPtr plugin = m_pluginManager->getPlugin(result.policyType());
188 LOGE("Plugin not found for policy: [0x%x]", result.policyType());
189 result = PolicyResult(PredefinedPolicyType::DENY);
193 ServicePluginInterfacePtr servicePlugin =
194 std::dynamic_pointer_cast<ServicePluginInterface>(plugin);
196 throw PluginNotFoundException(result);
199 AgentType requiredAgent;
200 PluginData pluginData;
202 auto ret = servicePlugin->check(key.client().toString(), key.user().toString(),
203 key.privilege().toString(), result, requiredAgent, pluginData);
206 case ServicePluginInterface::PluginStatus::ANSWER_READY:
208 case ServicePluginInterface::PluginStatus::ANSWER_NOTREADY: {
209 result = PolicyResult(PredefinedPolicyType::DENY);
210 AgentTalkerPtr agentTalker = m_agentManager->createTalker(requiredAgent);
212 LOGE("Required agent talker for: <%s> could not be created.",
213 requiredAgent.c_str());
217 if (!m_checkRequestManager.createContext(key, context, checkId, servicePlugin,
219 LOGE("Check context for checkId: [%" PRIu16 "] could not be created.",
221 m_agentManager->removeTalker(agentTalker);
224 agentTalker->send(pluginData);
228 throw PluginErrorException(key); // This 'throw' should be removed or handled properly.
232 bool Logic::update(const PolicyKey &key, ProtocolFrameSequenceNumber checkId,
233 const PluginData &agentData, const RequestContextPtr &context,
234 const ServicePluginInterfacePtr &plugin) {
236 LOGD("Check update: <%s>:[%" PRIu16 "]", key.toString().c_str(), checkId);
239 bool answerReady = false;
240 auto ret = plugin->update(key.client().toString(), key.user().toString(),
241 key.privilege().toString(), agentData, result);
243 case ServicePluginInterface::PluginStatus::SUCCESS:
246 case ServicePluginInterface::PluginStatus::ERROR:
247 result = PolicyResult(PredefinedPolicyType::DENY);
251 throw PluginErrorException(key);
254 if (answerReady && context->responseQueue()) {
255 context->returnResponse(context, std::make_shared<CheckResponse>(result, checkId));
262 void Logic::execute(RequestContextPtr context, InsertOrUpdateBucketRequestPtr request) {
263 auto code = CodeResponse::Code::OK;
266 m_storage->addOrUpdateBucket(request->bucketId(), request->result());
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;
276 context->returnResponse(context, std::make_shared<CodeResponse>(code,
277 request->sequenceNumber()));
280 void Logic::execute(RequestContextPtr context, RemoveBucketRequestPtr request) {
281 auto code = CodeResponse::Code::OK;
283 m_storage->deleteBucket(request->bucketId());
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;
292 context->returnResponse(context, std::make_shared<CodeResponse>(code,
293 request->sequenceNumber()));
296 void Logic::execute(RequestContextPtr context, SetPoliciesRequestPtr request) {
297 auto code = CodeResponse::Code::OK;
299 m_storage->insertPolicies(request->policiesToBeInsertedOrUpdated());
300 m_storage->deletePolicies(request->policiesToBeRemoved());
302 } catch (const DatabaseException &ex) {
303 code = CodeResponse::Code::FAILED;
304 } catch (const BucketNotExistsException &ex) {
305 code = CodeResponse::Code::NO_BUCKET;
307 context->returnResponse(context, std::make_shared<CodeResponse>(code,
308 request->sequenceNumber()));
311 void Logic::contextClosed(RequestContextPtr context) {
312 LOGD("context closed");
314 LinkId linkId = context->responseQueue();
316 m_agentManager->cleanupAgent(linkId, [&](const AgentTalkerPtr &talker) -> void {
317 handleAgentTalkerDisconnection(talker); });
319 m_checkRequestManager.cancelRequests(linkId,
320 [&](const CheckContextPtr &checkContextPtr) -> void {
321 handleClientDisconnection(checkContextPtr); });
324 void Logic::onPoliciesChanged(void) {
326 m_socketManager->disconnectAllClients();
327 //todo remove all saved contexts (if there will be any saved contexts)
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.");
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));
343 m_checkRequestManager.removeRequest(checkContextPtr);
346 void Logic::handleClientDisconnection(const CheckContextPtr &checkContextPtr) {
347 LOGD("Handle client disconnection");
349 if (!checkContextPtr->cancelled()) {
350 checkContextPtr->cancel();
351 checkContextPtr->m_agentTalker->cancel();
355 } // namespace Cynara