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/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>
60 #include <main/Cynara.h>
61 #include <agent/AgentManager.h>
62 #include <sockets/SocketManager.h>
63 #include <storage/Storage.h>
65 #include <cynara-plugin.h>
67 #include <cynara-agent.h>
79 void Logic::execute(RequestContextPtr context UNUSED, SignalRequestPtr request) {
80 LOGD("Processing signal: [%d]", request->signalNumber());
82 switch (request->signalNumber()) {
84 LOGI("SIGTERM received!");
85 m_socketManager->mainLoopStop();
90 void Logic::execute(RequestContextPtr context, AdminCheckRequestPtr request) {
92 bool bucketValid = true;
94 result = m_storage->checkPolicy(request->key(), request->startBucket(),
95 request->recursive());
96 } catch (const BucketNotExistsException &ex) {
100 context->returnResponse(context, std::make_shared<AdminCheckResponse>(result, bucketValid,
101 request->sequenceNumber()));
104 void Logic::execute(RequestContextPtr context, AgentActionRequestPtr request) {
105 AgentTalkerPtr talkerPtr = m_agentManager->getTalker(context->responseQueue(),
106 request->sequenceNumber());
108 LOGD("Received response from agent with invalid request id: [%" PRIu16 "]",
109 request->sequenceNumber());
113 CheckContextPtr checkContextPtr = m_checkRequestManager.getContext(talkerPtr);
114 if (!checkContextPtr) {
115 LOGE("No matching check context for agent talker.");
116 m_agentManager->removeTalker(talkerPtr);
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);
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
134 m_agentManager->removeTalker(talkerPtr);
135 m_checkRequestManager.removeRequest(checkContextPtr);
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()));
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());
153 if (checkContextPtr->cancelled())
156 checkContextPtr->cancel();
157 checkContextPtr->m_agentTalker->cancel();
159 LOGD("Returning response for cancel request id: [%" PRIu16 "].", request->sequenceNumber());
160 context->returnResponse(context, std::make_shared<CancelResponse>(request->sequenceNumber()));
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()));
171 bool Logic::check(const RequestContextPtr &context, const PolicyKey &key,
172 ProtocolFrameSequenceNumber checkId, PolicyResult &result) {
174 if (m_checkRequestManager.getContext(context->responseQueue(), checkId)) {
175 LOGE("Check request for checkId: [%" PRIu16 "] is already processing", checkId);
179 result = m_storage->checkPolicy(key);
181 switch (result.policyType()) {
182 case PredefinedPolicyType::ALLOW :
183 LOGD("check of policy key <%s> returned ALLOW", key.toString().c_str());
185 case PredefinedPolicyType::DENY :
186 LOGD("check of policy key <%s> returned DENY", key.toString().c_str());
190 return pluginCheck(context, key, checkId, result);
193 bool Logic::pluginCheck(const RequestContextPtr &context, const PolicyKey &key,
194 ProtocolFrameSequenceNumber checkId, PolicyResult &result) {
196 LOGD("Trying to check policy: <%s> in plugin.", key.toString().c_str());
198 ExternalPluginPtr plugin = m_pluginManager->getPlugin(result.policyType());
200 LOGE("Plugin not found for policy: [0x%x]", result.policyType());
201 result = PolicyResult(PredefinedPolicyType::DENY);
205 ServicePluginInterfacePtr servicePlugin =
206 std::dynamic_pointer_cast<ServicePluginInterface>(plugin);
208 throw PluginNotFoundException(result);
211 AgentType requiredAgent;
212 PluginData pluginData;
214 auto ret = servicePlugin->check(key.client().toString(), key.user().toString(),
215 key.privilege().toString(), result, requiredAgent, pluginData);
218 case ServicePluginInterface::PluginStatus::ANSWER_READY:
220 case ServicePluginInterface::PluginStatus::ANSWER_NOTREADY: {
221 result = PolicyResult(PredefinedPolicyType::DENY);
222 AgentTalkerPtr agentTalker = m_agentManager->createTalker(requiredAgent);
224 LOGE("Required agent talker for: <%s> could not be created.",
225 requiredAgent.c_str());
229 if (!m_checkRequestManager.createContext(key, context, checkId, servicePlugin,
231 LOGE("Check context for checkId: [%" PRIu16 "] could not be created.",
233 m_agentManager->removeTalker(agentTalker);
236 agentTalker->send(pluginData);
240 throw PluginErrorException(key); // This 'throw' should be removed or handled properly.
244 bool Logic::update(const PolicyKey &key, ProtocolFrameSequenceNumber checkId,
245 const PluginData &agentData, const RequestContextPtr &context,
246 const ServicePluginInterfacePtr &plugin) {
248 LOGD("Check update: <%s>:[%" PRIu16 "]", key.toString().c_str(), checkId);
251 bool answerReady = false;
252 auto ret = plugin->update(key.client().toString(), key.user().toString(),
253 key.privilege().toString(), agentData, result);
255 case ServicePluginInterface::PluginStatus::SUCCESS:
258 case ServicePluginInterface::PluginStatus::ERROR:
259 result = PolicyResult(PredefinedPolicyType::DENY);
263 throw PluginErrorException(key);
266 if (answerReady && context->responseQueue()) {
267 context->returnResponse(context, std::make_shared<CheckResponse>(result, checkId));
274 void Logic::execute(RequestContextPtr context, EraseRequestPtr request) {
275 auto code = CodeResponse::Code::OK;
278 m_storage->erasePolicies(request->startBucket(), request->recursive(), request->filter());
280 } catch (const DatabaseException &ex) {
281 code = CodeResponse::Code::FAILED;
282 } catch (const BucketNotExistsException &ex) {
283 code = CodeResponse::Code::NO_BUCKET;
286 context->returnResponse(context, std::make_shared<CodeResponse>(code,
287 request->sequenceNumber()));
290 void Logic::execute(RequestContextPtr context, InsertOrUpdateBucketRequestPtr request) {
291 auto code = CodeResponse::Code::OK;
294 m_storage->addOrUpdateBucket(request->bucketId(), request->result());
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;
304 context->returnResponse(context, std::make_shared<CodeResponse>(code,
305 request->sequenceNumber()));
308 void Logic::execute(RequestContextPtr context, ListRequestPtr request) {
309 bool bucketValid = true;
311 std::vector<Policy> policies;
313 policies = m_storage->listPolicies(request->bucket(), request->filter());
314 } catch (const BucketNotExistsException &ex) {
318 context->returnResponse(context, std::make_shared<ListResponse>(policies, bucketValid,
319 request->sequenceNumber()));
322 void Logic::execute(RequestContextPtr context, RemoveBucketRequestPtr request) {
323 auto code = CodeResponse::Code::OK;
325 m_storage->deleteBucket(request->bucketId());
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;
334 context->returnResponse(context, std::make_shared<CodeResponse>(code,
335 request->sequenceNumber()));
338 void Logic::execute(RequestContextPtr context, SetPoliciesRequestPtr request) {
339 auto code = CodeResponse::Code::OK;
341 m_storage->insertPolicies(request->policiesToBeInsertedOrUpdated());
342 m_storage->deletePolicies(request->policiesToBeRemoved());
344 } catch (const DatabaseException &ex) {
345 code = CodeResponse::Code::FAILED;
346 } catch (const BucketNotExistsException &ex) {
347 code = CodeResponse::Code::NO_BUCKET;
349 context->returnResponse(context, std::make_shared<CodeResponse>(code,
350 request->sequenceNumber()));
353 void Logic::contextClosed(RequestContextPtr context) {
354 LOGD("context closed");
356 LinkId linkId = context->responseQueue();
358 m_agentManager->cleanupAgent(linkId, [&](const AgentTalkerPtr &talker) -> void {
359 handleAgentTalkerDisconnection(talker); });
361 m_checkRequestManager.cancelRequests(linkId,
362 [&](const CheckContextPtr &checkContextPtr) -> void {
363 handleClientDisconnection(checkContextPtr); });
366 void Logic::onPoliciesChanged(void) {
368 m_socketManager->disconnectAllClients();
369 m_pluginManager->invalidateAll();
370 //todo remove all saved contexts (if there will be any saved contexts)
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.");
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));
386 m_checkRequestManager.removeRequest(checkContextPtr);
389 void Logic::handleClientDisconnection(const CheckContextPtr &checkContextPtr) {
390 LOGD("Handle client disconnection");
392 if (!checkContextPtr->cancelled()) {
393 checkContextPtr->cancel();
394 checkContextPtr->m_agentTalker->cancel();
398 } // namespace Cynara