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/AdminCheckResponse.h>
52 #include <response/AgentRegisterResponse.h>
53 #include <response/CancelResponse.h>
54 #include <response/CheckResponse.h>
55 #include <response/CodeResponse.h>
56 #include <response/ListResponse.h>
57 #include <types/Policy.h>
59 #include <main/Cynara.h>
60 #include <agent/AgentManager.h>
61 #include <sockets/SocketManager.h>
62 #include <storage/Storage.h>
64 #include <cynara-plugin.h>
66 #include <cynara-agent.h>
78 void Logic::execute(RequestContextPtr context UNUSED, SignalRequestPtr request) {
79 LOGD("Processing signal: [%d]", request->signalNumber());
81 switch (request->signalNumber()) {
83 LOGI("SIGTERM received!");
84 m_socketManager->mainLoopStop();
89 void Logic::execute(RequestContextPtr context, AdminCheckRequestPtr request) {
91 bool bucketValid = true;
93 result = m_storage->checkPolicy(request->key(), request->startBucket(),
94 request->recursive());
95 } catch (const BucketNotExistsException &ex) {
99 context->returnResponse(context, std::make_shared<AdminCheckResponse>(result, bucketValid,
100 request->sequenceNumber()));
103 void Logic::execute(RequestContextPtr context, AgentActionRequestPtr request) {
104 AgentTalkerPtr talkerPtr = m_agentManager->getTalker(context->responseQueue(),
105 request->sequenceNumber());
107 LOGD("Received response from agent with invalid request id: [%" PRIu16 "]",
108 request->sequenceNumber());
112 CheckContextPtr checkContextPtr = m_checkRequestManager.getContext(talkerPtr);
113 if (!checkContextPtr) {
114 LOGE("No matching check context for agent talker.");
115 m_agentManager->removeTalker(talkerPtr);
119 if (!checkContextPtr->cancelled()) {
120 PluginData data(request->data().begin(), request->data().end());
121 if (request->type() == CYNARA_MSG_TYPE_CANCEL) {
122 // Nothing to do for now
123 } else if (request->type() == CYNARA_MSG_TYPE_ACTION) {
124 update(checkContextPtr->m_key, checkContextPtr->m_checkId, data,
125 checkContextPtr->m_requestContext, checkContextPtr->m_plugin);
127 LOGE("Invalid response type [%d] in response from agent <%s>",
128 static_cast<int>(request->type()), talkerPtr->agentType().c_str());
129 // TODO: disconnect agent
133 m_agentManager->removeTalker(talkerPtr);
134 m_checkRequestManager.removeRequest(checkContextPtr);
137 void Logic::execute(RequestContextPtr context, AgentRegisterRequestPtr request) {
138 auto result = m_agentManager->registerAgent(request->agentType(), context->responseQueue());
139 context->returnResponse(context, std::make_shared<AgentRegisterResponse>(
140 result, request->sequenceNumber()));
143 void Logic::execute(RequestContextPtr context, CancelRequestPtr request) {
144 CheckContextPtr checkContextPtr = m_checkRequestManager.getContext(context->responseQueue(),
145 request->sequenceNumber());
146 if (!checkContextPtr) {
147 LOGD("Cancel request id: [%" PRIu16 "] with no matching request in progress.",
148 request->sequenceNumber());
152 if (checkContextPtr->cancelled())
155 checkContextPtr->cancel();
156 checkContextPtr->m_agentTalker->cancel();
158 LOGD("Returning response for cancel request id: [%" PRIu16 "].", request->sequenceNumber());
159 context->returnResponse(context, std::make_shared<CancelResponse>(request->sequenceNumber()));
162 void Logic::execute(RequestContextPtr context, CheckRequestPtr request) {
163 PolicyResult result(PredefinedPolicyType::DENY);
164 if (check(context, request->key(), request->sequenceNumber(), result)) {
165 context->returnResponse(context, std::make_shared<CheckResponse>(result,
166 request->sequenceNumber()));
170 bool Logic::check(const RequestContextPtr &context, const PolicyKey &key,
171 ProtocolFrameSequenceNumber checkId, PolicyResult &result) {
173 if (m_checkRequestManager.getContext(context->responseQueue(), checkId)) {
174 LOGE("Check request for checkId: [%" PRIu16 "] is already processing", checkId);
178 result = m_storage->checkPolicy(key);
180 switch (result.policyType()) {
181 case PredefinedPolicyType::ALLOW :
182 LOGD("check of policy key <%s> returned ALLOW", key.toString().c_str());
184 case PredefinedPolicyType::DENY :
185 LOGD("check of policy key <%s> returned DENY", key.toString().c_str());
189 return pluginCheck(context, key, checkId, result);
192 bool Logic::pluginCheck(const RequestContextPtr &context, const PolicyKey &key,
193 ProtocolFrameSequenceNumber checkId, PolicyResult &result) {
195 LOGD("Trying to check policy: <%s> in plugin.", key.toString().c_str());
197 ExternalPluginPtr plugin = m_pluginManager->getPlugin(result.policyType());
199 LOGE("Plugin not found for policy: [0x%x]", result.policyType());
200 result = PolicyResult(PredefinedPolicyType::DENY);
204 ServicePluginInterfacePtr servicePlugin =
205 std::dynamic_pointer_cast<ServicePluginInterface>(plugin);
207 throw PluginNotFoundException(result);
210 AgentType requiredAgent;
211 PluginData pluginData;
213 auto ret = servicePlugin->check(key.client().toString(), key.user().toString(),
214 key.privilege().toString(), result, requiredAgent, pluginData);
217 case ServicePluginInterface::PluginStatus::ANSWER_READY:
219 case ServicePluginInterface::PluginStatus::ANSWER_NOTREADY: {
220 result = PolicyResult(PredefinedPolicyType::DENY);
221 AgentTalkerPtr agentTalker = m_agentManager->createTalker(requiredAgent);
223 LOGE("Required agent talker for: <%s> could not be created.",
224 requiredAgent.c_str());
228 if (!m_checkRequestManager.createContext(key, context, checkId, servicePlugin,
230 LOGE("Check context for checkId: [%" PRIu16 "] could not be created.",
232 m_agentManager->removeTalker(agentTalker);
235 agentTalker->send(pluginData);
239 throw PluginErrorException(key); // This 'throw' should be removed or handled properly.
243 bool Logic::update(const PolicyKey &key, ProtocolFrameSequenceNumber checkId,
244 const PluginData &agentData, const RequestContextPtr &context,
245 const ServicePluginInterfacePtr &plugin) {
247 LOGD("Check update: <%s>:[%" PRIu16 "]", key.toString().c_str(), checkId);
250 bool answerReady = false;
251 auto ret = plugin->update(key.client().toString(), key.user().toString(),
252 key.privilege().toString(), agentData, result);
254 case ServicePluginInterface::PluginStatus::SUCCESS:
257 case ServicePluginInterface::PluginStatus::ERROR:
258 result = PolicyResult(PredefinedPolicyType::DENY);
262 throw PluginErrorException(key);
265 if (answerReady && context->responseQueue()) {
266 context->returnResponse(context, std::make_shared<CheckResponse>(result, checkId));
273 void Logic::execute(RequestContextPtr context, InsertOrUpdateBucketRequestPtr request) {
274 auto code = CodeResponse::Code::OK;
277 m_storage->addOrUpdateBucket(request->bucketId(), request->result());
279 } catch (const DatabaseException &ex) {
280 code = CodeResponse::Code::FAILED;
281 } catch (const DefaultBucketSetNoneException &ex) {
282 code = CodeResponse::Code::NOT_ALLOWED;
283 } catch (const InvalidBucketIdException &ex) {
284 code = CodeResponse::Code::NOT_ALLOWED;
287 context->returnResponse(context, std::make_shared<CodeResponse>(code,
288 request->sequenceNumber()));
291 void Logic::execute(RequestContextPtr context, ListRequestPtr request) {
292 bool bucketValid = true;
294 std::vector<Policy> policies;
296 policies = m_storage->listPolicies(request->bucket(), request->filter());
297 } catch (const BucketNotExistsException &ex) {
301 context->returnResponse(context, std::make_shared<ListResponse>(policies, bucketValid,
302 request->sequenceNumber()));
305 void Logic::execute(RequestContextPtr context, RemoveBucketRequestPtr request) {
306 auto code = CodeResponse::Code::OK;
308 m_storage->deleteBucket(request->bucketId());
310 } catch (const DatabaseException &ex) {
311 code = CodeResponse::Code::FAILED;
312 } catch (const BucketNotExistsException &ex) {
313 code = CodeResponse::Code::NO_BUCKET;
314 } catch (const DefaultBucketDeletionException &ex) {
315 code = CodeResponse::Code::NOT_ALLOWED;
317 context->returnResponse(context, std::make_shared<CodeResponse>(code,
318 request->sequenceNumber()));
321 void Logic::execute(RequestContextPtr context, SetPoliciesRequestPtr request) {
322 auto code = CodeResponse::Code::OK;
324 m_storage->insertPolicies(request->policiesToBeInsertedOrUpdated());
325 m_storage->deletePolicies(request->policiesToBeRemoved());
327 } catch (const DatabaseException &ex) {
328 code = CodeResponse::Code::FAILED;
329 } catch (const BucketNotExistsException &ex) {
330 code = CodeResponse::Code::NO_BUCKET;
332 context->returnResponse(context, std::make_shared<CodeResponse>(code,
333 request->sequenceNumber()));
336 void Logic::contextClosed(RequestContextPtr context) {
337 LOGD("context closed");
339 LinkId linkId = context->responseQueue();
341 m_agentManager->cleanupAgent(linkId, [&](const AgentTalkerPtr &talker) -> void {
342 handleAgentTalkerDisconnection(talker); });
344 m_checkRequestManager.cancelRequests(linkId,
345 [&](const CheckContextPtr &checkContextPtr) -> void {
346 handleClientDisconnection(checkContextPtr); });
349 void Logic::onPoliciesChanged(void) {
351 m_socketManager->disconnectAllClients();
352 m_pluginManager->invalidateAll();
353 //todo remove all saved contexts (if there will be any saved contexts)
356 void Logic::handleAgentTalkerDisconnection(const AgentTalkerPtr &agentTalkerPtr) {
357 CheckContextPtr checkContextPtr = m_checkRequestManager.getContext(agentTalkerPtr);
358 if (checkContextPtr == nullptr) {
359 LOGE("No matching check context for agent talker.");
363 if (!checkContextPtr->cancelled() && checkContextPtr->m_requestContext->responseQueue()) {
364 PolicyResult result(PredefinedPolicyType::DENY);
365 checkContextPtr->m_requestContext->returnResponse(checkContextPtr->m_requestContext,
366 std::make_shared<CheckResponse>(result, checkContextPtr->m_checkId));
369 m_checkRequestManager.removeRequest(checkContextPtr);
372 void Logic::handleClientDisconnection(const CheckContextPtr &checkContextPtr) {
373 LOGD("Handle client disconnection");
375 if (!checkContextPtr->cancelled()) {
376 checkContextPtr->cancel();
377 checkContextPtr->m_agentTalker->cancel();
381 } // namespace Cynara