From 27541d0fdb1e97ba59e4a08b8c710af33fe64af9 Mon Sep 17 00:00:00 2001 From: Marcin Niesluchowski Date: Wed, 24 Sep 2014 14:14:07 +0200 Subject: [PATCH 01/16] Implement cynara_async_cancel_request() Change-Id: I028d6a2941dc68359590263cda9e5bff2b839317 --- src/client-async/callback/ResponseCallback.cpp | 6 ++ src/client-async/callback/ResponseCallback.h | 2 +- src/client-async/check/CheckData.h | 12 +++- src/client-async/logic/Logic.cpp | 80 ++++++++++++++++++++------ src/client-async/logic/Logic.h | 1 + src/common/CMakeLists.txt | 2 + src/common/protocol/ProtocolClient.cpp | 37 ++++++++++++ src/common/protocol/ProtocolClient.h | 6 ++ src/common/protocol/ProtocolOpCode.h | 4 +- src/common/request/CancelRequest.cpp | 34 +++++++++++ src/common/request/CancelRequest.h | 44 ++++++++++++++ src/common/request/RequestTaker.cpp | 4 ++ src/common/request/RequestTaker.h | 1 + src/common/request/pointers.h | 3 + src/common/response/CancelResponse.cpp | 34 +++++++++++ src/common/response/CancelResponse.h | 44 ++++++++++++++ src/common/response/ResponseTaker.cpp | 4 ++ src/common/response/ResponseTaker.h | 1 + src/common/response/pointers.h | 3 + src/service/logic/Logic.cpp | 7 +++ src/service/logic/Logic.h | 1 + 21 files changed, 307 insertions(+), 23 deletions(-) create mode 100644 src/common/request/CancelRequest.cpp create mode 100644 src/common/request/CancelRequest.h create mode 100644 src/common/response/CancelResponse.cpp create mode 100644 src/common/response/CancelResponse.h diff --git a/src/client-async/callback/ResponseCallback.cpp b/src/client-async/callback/ResponseCallback.cpp index e4577b3..9307195 100644 --- a/src/client-async/callback/ResponseCallback.cpp +++ b/src/client-async/callback/ResponseCallback.cpp @@ -34,6 +34,12 @@ void ResponseCallback::onAnswer(cynara_check_id checkId, int response) const { m_callback(checkId, cynara_async_call_cause::CYNARA_CALL_CAUSE_ANSWER, response, m_userData); } +void ResponseCallback::onCancel(cynara_check_id checkId) const { + if (!m_callback) + return; + m_callback(checkId, cynara_async_call_cause::CYNARA_CALL_CAUSE_CANCEL, 0, m_userData); +} + void ResponseCallback::onFinish(cynara_check_id checkId) const { if (!m_callback) return; diff --git a/src/client-async/callback/ResponseCallback.h b/src/client-async/callback/ResponseCallback.h index 47d526a..925d7f4 100644 --- a/src/client-async/callback/ResponseCallback.h +++ b/src/client-async/callback/ResponseCallback.h @@ -34,7 +34,7 @@ public: ~ResponseCallback() {}; void onAnswer(cynara_check_id checkId, int response) const; - // MOCKUP + void onCancel(cynara_check_id checkId) const; void onFinish(cynara_check_id checkId) const; void onDisconnected(cynara_check_id checkId) const; diff --git a/src/client-async/check/CheckData.h b/src/client-async/check/CheckData.h index 1f8fe90..a25abb3 100644 --- a/src/client-async/check/CheckData.h +++ b/src/client-async/check/CheckData.h @@ -37,7 +37,7 @@ class CheckData { public: CheckData(const PolicyKey &key, const std::string &session, const ResponseCallback &callback) - : m_key(key), m_session(session), m_callback(callback) {} + : m_key(key), m_session(session), m_callback(callback), m_cancelled(false) {} ~CheckData() {} const PolicyKey &key(void) const { @@ -52,11 +52,19 @@ public: return m_callback; } + bool cancelled(void) const { + return m_cancelled; + } + + void cancel(void) { + m_cancelled = true; + } + private: PolicyKey m_key; std::string m_session; ResponseCallback m_callback; - // MOCKUP + bool m_cancelled; }; } // namespace Cynara diff --git a/src/client-async/logic/Logic.cpp b/src/client-async/logic/Logic.cpp index 23cd7cc..3a92b2c 100644 --- a/src/client-async/logic/Logic.cpp +++ b/src/client-async/logic/Logic.cpp @@ -31,7 +31,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -52,8 +54,10 @@ Logic::Logic(cynara_status_callback callback, void *userStatusData) } Logic::~Logic() { - for (auto &kv : m_checks) - kv.second.callback().onFinish(kv.first); + for (auto &kv : m_checks) { + if (!kv.second.cancelled()) + kv.second.callback().onFinish(kv.first); + } m_statusCallback.onDisconnected(); } @@ -102,11 +106,21 @@ int Logic::process(void) { } } -int Logic::cancelRequest(cynara_check_id checkId UNUSED) { +int Logic::cancelRequest(cynara_check_id checkId) { if (!ensureConnection()) return CYNARA_API_SERVICE_NOT_AVAILABLE; - // MOCKUP + auto it = m_checks.find(checkId); + if (it == m_checks.end() || it->second.cancelled()) + return CYNARA_API_SUCCESS; + + m_socketClient->appendRequest(std::make_shared(it->first)); + + it->second.cancel(); + it->second.callback().onCancel(it->first); + m_statusCallback.onStatusChange(m_socketClient->getSockFd(), + cynara_async_status::CYNARA_STATUS_FOR_RW); + return CYNARA_API_SUCCESS; } @@ -115,9 +129,14 @@ bool Logic::checkCacheValid(void) { } void Logic::prepareRequestsToSend(void) { - for (auto &kv : m_checks) { - // MOCKUP - m_socketClient->appendRequest(std::make_shared(kv.second.key(), kv.first)); + for (auto it = m_checks.begin(); it != m_checks.end();) { + if (it->second.cancelled()) { + m_sequenceContainer.release(it->first); + it = m_checks.erase(it); + } else { + m_socketClient->appendRequest(std::make_shared(it->second.key(), it->first)); + ++it; + } } } @@ -140,14 +159,32 @@ void Logic::processCheckResponse(CheckResponsePtr checkResponse) { auto it = m_checks.find(checkResponse->sequenceNumber()); if (it == m_checks.end()) { - LOGC("Critical error. Unknown response received: sequenceNumber = [%" PRIu16 "]", + LOGC("Critical error. Unknown checkResponse received: sequenceNumber = [%" PRIu16 "]", checkResponse->sequenceNumber()); throw UnexpectedErrorException("Unexpected response from cynara service"); } int result = m_cache->update(it->second.session(), it->second.key(), checkResponse->m_resultRef); - // MOCKUP - it->second.callback().onAnswer(static_cast(it->first), result); + if (!it->second.cancelled()) + it->second.callback().onAnswer(static_cast(it->first), result); + m_sequenceContainer.release(it->first); + m_checks.erase(it); +} + +void Logic::processCancelResponse(CancelResponsePtr cancelResponse) { + LOGD("cancelResponse"); + + auto it = m_checks.find(cancelResponse->sequenceNumber()); + if (it == m_checks.end()) { + LOGC("Critical error. Unknown cancelResponse received: sequenceNumber = [%" PRIu16 "]", + cancelResponse->sequenceNumber()); + throw UnexpectedErrorException("Unexpected response from cynara service"); + } + if (!it->second.cancelled()) { + LOGC("Critical error. CancelRequest not sent: sequenceNumber = [%" PRIu16 "]", + cancelResponse->sequenceNumber()); + throw UnexpectedErrorException("Unexpected response from cynara service"); + } m_sequenceContainer.release(it->first); m_checks.erase(it); } @@ -155,18 +192,21 @@ void Logic::processCheckResponse(CheckResponsePtr checkResponse) { void Logic::processResponses(void) { ResponsePtr response; CheckResponsePtr checkResponse; - while (true) { - response = m_socketClient->getResponse(); - if (!response) - break; - + CancelResponsePtr cancelResponse; + while (response = m_socketClient->getResponse()) { checkResponse = std::dynamic_pointer_cast(response); if (checkResponse) { processCheckResponse(checkResponse); continue; } - // MOCKUP - LOGC("Critical error. Casting Response to CheckResponse failed."); + + cancelResponse = std::dynamic_pointer_cast(response); + if (cancelResponse) { + processCancelResponse(cancelResponse); + continue; + } + + LOGC("Critical error. Casting Response to known response failed."); throw UnexpectedErrorException("Unexpected response from cynara service"); } } @@ -230,8 +270,10 @@ int Logic::completeConnection(bool &completed) { void Logic::onServiceNotAvailable(void) { - for (auto &kv : m_checks) - kv.second.callback().onDisconnected(kv.first); + for (auto &kv : m_checks) { + if (!kv.second.cancelled()) + kv.second.callback().onDisconnected(kv.first); + } m_checks.clear(); m_sequenceContainer.clear(); } diff --git a/src/client-async/logic/Logic.h b/src/client-async/logic/Logic.h index 53cfba9..0bca98e 100644 --- a/src/client-async/logic/Logic.h +++ b/src/client-async/logic/Logic.h @@ -65,6 +65,7 @@ private: cynara_async_status socketDataStatus(void); bool processOut(void); void processCheckResponse(CheckResponsePtr checkResponse); + void processCancelResponse(CancelResponsePtr cancelResponse); void processResponses(void); bool processIn(void); bool ensureConnection(void); diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt index 490a4f3..d52ddd5 100644 --- a/src/common/CMakeLists.txt +++ b/src/common/CMakeLists.txt @@ -32,12 +32,14 @@ SET(COMMON_SOURCES ${COMMON_PATH}/protocol/ProtocolSerialization.cpp ${COMMON_PATH}/protocol/ProtocolSignal.cpp ${COMMON_PATH}/request/AdminCheckRequest.cpp + ${COMMON_PATH}/request/CancelRequest.cpp ${COMMON_PATH}/request/CheckRequest.cpp ${COMMON_PATH}/request/InsertOrUpdateBucketRequest.cpp ${COMMON_PATH}/request/RemoveBucketRequest.cpp ${COMMON_PATH}/request/RequestTaker.cpp ${COMMON_PATH}/request/SetPoliciesRequest.cpp ${COMMON_PATH}/request/SignalRequest.cpp + ${COMMON_PATH}/response/CancelResponse.cpp ${COMMON_PATH}/response/CheckResponse.cpp ${COMMON_PATH}/response/CodeResponse.cpp ${COMMON_PATH}/response/ResponseTaker.cpp diff --git a/src/common/protocol/ProtocolClient.cpp b/src/common/protocol/ProtocolClient.cpp index 5101900..94811dd 100644 --- a/src/common/protocol/ProtocolClient.cpp +++ b/src/common/protocol/ProtocolClient.cpp @@ -31,8 +31,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -52,6 +54,11 @@ ProtocolPtr ProtocolClient::clone(void) { return std::make_shared(); } +RequestPtr ProtocolClient::deserializeCancelRequest(ProtocolFrameHeader &frame) { + LOGD("Deserialized CancelRequest"); + return std::make_shared(frame.sequenceNumber()); +} + RequestPtr ProtocolClient::deserializeCheckRequest(ProtocolFrameHeader &frame) { std::string clientId, userId, privilegeId; @@ -79,6 +86,8 @@ RequestPtr ProtocolClient::extractRequestFromBuffer(BinaryQueue &bufferQueue) { switch (opCode) { case OpCheckPolicyRequest: return deserializeCheckRequest(m_frameHeader); + case OpCancelRequest: + return deserializeCancelRequest(m_frameHeader); default: throw InvalidProtocolException(InvalidProtocolException::WrongOpCode); break; @@ -88,6 +97,11 @@ RequestPtr ProtocolClient::extractRequestFromBuffer(BinaryQueue &bufferQueue) { return nullptr; } +ResponsePtr ProtocolClient::deserializeCancelResponse(ProtocolFrameHeader &frame) { + LOGD("Deserialized CancelResponse"); + return std::make_shared(frame.sequenceNumber()); +} + ResponsePtr ProtocolClient::deserializeCheckResponse(ProtocolFrameHeader &frame) { PolicyType result; PolicyResult::PolicyMetadata additionalInfo; @@ -115,6 +129,8 @@ ResponsePtr ProtocolClient::extractResponseFromBuffer(BinaryQueue &bufferQueue) switch (opCode) { case OpCheckPolicyResponse: return deserializeCheckResponse(m_frameHeader); + case OpCancelResponse: + return deserializeCancelResponse(m_frameHeader); default: throw InvalidProtocolException(InvalidProtocolException::WrongOpCode); break; @@ -124,6 +140,16 @@ ResponsePtr ProtocolClient::extractResponseFromBuffer(BinaryQueue &bufferQueue) return nullptr; } +void ProtocolClient::execute(RequestContextPtr context, CancelRequestPtr request) { + ProtocolFramePtr frame = ProtocolFrameSerializer::startSerialization(request->sequenceNumber()); + + LOGD("Serializing CancelRequest op [%" PRIu8 "]", OpCancelRequest); + + ProtocolSerialization::serialize(*frame, OpCancelRequest); + + ProtocolFrameSerializer::finishSerialization(frame, context->responseQueue()); +} + void ProtocolClient::execute(RequestContextPtr context, CheckRequestPtr request) { ProtocolFramePtr frame = ProtocolFrameSerializer::startSerialization(request->sequenceNumber()); @@ -139,6 +165,17 @@ void ProtocolClient::execute(RequestContextPtr context, CheckRequestPtr request) ProtocolFrameSerializer::finishSerialization(frame, context->responseQueue()); } +void ProtocolClient::execute(RequestContextPtr context, CancelResponsePtr response) { + ProtocolFramePtr frame = ProtocolFrameSerializer::startSerialization( + response->sequenceNumber()); + + LOGD("Serializing CancelResponse: op [%" PRIu8 "]", OpCancelResponse); + + ProtocolSerialization::serialize(*frame, OpCancelResponse); + + ProtocolFrameSerializer::finishSerialization(frame, context->responseQueue()); +} + void ProtocolClient::execute(RequestContextPtr context, CheckResponsePtr response) { ProtocolFramePtr frame = ProtocolFrameSerializer::startSerialization( response->sequenceNumber()); diff --git a/src/common/protocol/ProtocolClient.h b/src/common/protocol/ProtocolClient.h index 9493a88..1bb1b6a 100644 --- a/src/common/protocol/ProtocolClient.h +++ b/src/common/protocol/ProtocolClient.h @@ -41,11 +41,17 @@ public: virtual RequestPtr extractRequestFromBuffer(BinaryQueue &bufferQueue); virtual ResponsePtr extractResponseFromBuffer(BinaryQueue &bufferQueue); + virtual void execute(RequestContextPtr context, CancelRequestPtr request); virtual void execute(RequestContextPtr context, CheckRequestPtr request); + + virtual void execute(RequestContextPtr context, CancelResponsePtr response); virtual void execute(RequestContextPtr context, CheckResponsePtr response); private: + RequestPtr deserializeCancelRequest(ProtocolFrameHeader &frame); RequestPtr deserializeCheckRequest(ProtocolFrameHeader &frame); + + ResponsePtr deserializeCancelResponse(ProtocolFrameHeader &frame); ResponsePtr deserializeCheckResponse(ProtocolFrameHeader &frame); }; diff --git a/src/common/protocol/ProtocolOpCode.h b/src/common/protocol/ProtocolOpCode.h index 7319ad3..2b4171c 100644 --- a/src/common/protocol/ProtocolOpCode.h +++ b/src/common/protocol/ProtocolOpCode.h @@ -33,8 +33,10 @@ enum ProtocolOpCode : uint8_t { /** Client operations */ OpCheckPolicyRequest = 0, OpCheckPolicyResponse, + OpCancelRequest, + OpCancelResponse, - /** Opcodes 2 - 19 are reserved for future use */ + /** Opcodes 4 - 19 are reserved for future use */ /** Admin operations */ OpInsertOrUpdateBucket = 20, diff --git a/src/common/request/CancelRequest.cpp b/src/common/request/CancelRequest.cpp new file mode 100644 index 0000000..d7a5ffa --- /dev/null +++ b/src/common/request/CancelRequest.cpp @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file src/common/request/CancelRequest.cpp + * @author Marcin Niesluchowski + * @version 1.0 + * @brief This file implements cancel request class + */ + +#include + +#include "CancelRequest.h" + +namespace Cynara { + +void CancelRequest::execute(RequestPtr self, RequestTakerPtr taker, + RequestContextPtr context) const { + taker->execute(context, std::dynamic_pointer_cast(self)); +} + +} // namespace Cynara diff --git a/src/common/request/CancelRequest.h b/src/common/request/CancelRequest.h new file mode 100644 index 0000000..a6192b8 --- /dev/null +++ b/src/common/request/CancelRequest.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file src/common/request/CancelRequest.h + * @author Marcin Niesluchowski + * @version 1.0 + * @brief This file defines cancel request class + */ + +#ifndef SRC_COMMON_REQUEST_CANCELREQUEST_H_ +#define SRC_COMMON_REQUEST_CANCELREQUEST_H_ + +#include +#include +#include + +namespace Cynara { + +class CancelRequest : public Request { +public: + CancelRequest(ProtocolFrameSequenceNumber sequenceNumber) : Request(sequenceNumber) { + } + + virtual ~CancelRequest() {}; + + virtual void execute(RequestPtr self, RequestTakerPtr taker, RequestContextPtr context) const; +}; + +} // namespace Cynara + +#endif /* SRC_COMMON_REQUEST_CANCELREQUEST_H_ */ diff --git a/src/common/request/RequestTaker.cpp b/src/common/request/RequestTaker.cpp index d645aee..c87a9a4 100644 --- a/src/common/request/RequestTaker.cpp +++ b/src/common/request/RequestTaker.cpp @@ -33,6 +33,10 @@ void RequestTaker::execute(RequestContextPtr context UNUSED, AdminCheckRequestPt throw NotImplementedException(); } +void RequestTaker::execute(RequestContextPtr context UNUSED, CancelRequestPtr request UNUSED) { + throw NotImplementedException(); +} + void RequestTaker::execute(RequestContextPtr context UNUSED, CheckRequestPtr request UNUSED) { throw NotImplementedException(); } diff --git a/src/common/request/RequestTaker.h b/src/common/request/RequestTaker.h index 6f1f112..b1d3466 100644 --- a/src/common/request/RequestTaker.h +++ b/src/common/request/RequestTaker.h @@ -33,6 +33,7 @@ public: virtual ~RequestTaker() {}; virtual void execute(RequestContextPtr context, AdminCheckRequestPtr request); + virtual void execute(RequestContextPtr context, CancelRequestPtr request); virtual void execute(RequestContextPtr context, CheckRequestPtr request); virtual void execute(RequestContextPtr context, InsertOrUpdateBucketRequestPtr request); virtual void execute(RequestContextPtr context, RemoveBucketRequestPtr request); diff --git a/src/common/request/pointers.h b/src/common/request/pointers.h index 5800321..5c90004 100644 --- a/src/common/request/pointers.h +++ b/src/common/request/pointers.h @@ -30,6 +30,9 @@ namespace Cynara { class AdminCheckRequest; typedef std::shared_ptr AdminCheckRequestPtr; +class CancelRequest; +typedef std::shared_ptr CancelRequestPtr; + class CheckRequest; typedef std::shared_ptr CheckRequestPtr; diff --git a/src/common/response/CancelResponse.cpp b/src/common/response/CancelResponse.cpp new file mode 100644 index 0000000..69211e7 --- /dev/null +++ b/src/common/response/CancelResponse.cpp @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file src/common/response/CancelResponse.cpp + * @author Marcin Niesluchowski + * @version 1.0 + * @brief This file implements cancel response class + */ + +#include + +#include "CancelResponse.h" + +namespace Cynara { + +void CancelResponse::execute(ResponsePtr self, ResponseTakerPtr taker, + RequestContextPtr context) const { + taker->execute(context, std::dynamic_pointer_cast(self)); +} + +} // namespace Cynara diff --git a/src/common/response/CancelResponse.h b/src/common/response/CancelResponse.h new file mode 100644 index 0000000..657ab2c --- /dev/null +++ b/src/common/response/CancelResponse.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file src/common/response/CancelResponse.h + * @author Marcin Niesluchowski + * @version 1.0 + * @brief This file defines response class for cancel response + */ + +#ifndef SRC_COMMON_RESPONSE_CANCELRESPONSE_H_ +#define SRC_COMMON_RESPONSE_CANCELRESPONSE_H_ + +#include +#include +#include + +namespace Cynara { + +class CancelResponse : public Response { +public: + CancelResponse(ProtocolFrameSequenceNumber sequenceNumber) : Response(sequenceNumber) { + } + + virtual ~CancelResponse() {}; + + virtual void execute(ResponsePtr self, ResponseTakerPtr taker, RequestContextPtr context) const; +}; + +} // namespace Cynara + +#endif /* SRC_COMMON_RESPONSE_CANCELRESPONSE_H_ */ diff --git a/src/common/response/ResponseTaker.cpp b/src/common/response/ResponseTaker.cpp index 7da0dfb..3f558c4 100644 --- a/src/common/response/ResponseTaker.cpp +++ b/src/common/response/ResponseTaker.cpp @@ -28,6 +28,10 @@ namespace Cynara { +void ResponseTaker::execute(RequestContextPtr context UNUSED, CancelResponsePtr response UNUSED) { + throw NotImplementedException(); +} + void ResponseTaker::execute(RequestContextPtr context UNUSED, CheckResponsePtr response UNUSED) { throw NotImplementedException(); } diff --git a/src/common/response/ResponseTaker.h b/src/common/response/ResponseTaker.h index 41425d8..0afdb65 100644 --- a/src/common/response/ResponseTaker.h +++ b/src/common/response/ResponseTaker.h @@ -33,6 +33,7 @@ public: ResponseTaker() = default; virtual ~ResponseTaker() {}; + virtual void execute(RequestContextPtr context, CancelResponsePtr response); virtual void execute(RequestContextPtr context, CheckResponsePtr response); virtual void execute(RequestContextPtr context, CodeResponsePtr response); }; diff --git a/src/common/response/pointers.h b/src/common/response/pointers.h index 088c533..4e9b8fc 100644 --- a/src/common/response/pointers.h +++ b/src/common/response/pointers.h @@ -27,6 +27,9 @@ namespace Cynara { +class CancelResponse; +typedef std::shared_ptr CancelResponsePtr; + class CheckResponse; typedef std::shared_ptr CheckResponsePtr; diff --git a/src/service/logic/Logic.cpp b/src/service/logic/Logic.cpp index c25487e..d05f512 100644 --- a/src/service/logic/Logic.cpp +++ b/src/service/logic/Logic.cpp @@ -30,12 +30,14 @@ #include
#include +#include #include #include #include #include #include #include +#include #include #include #include @@ -70,6 +72,11 @@ void Logic::execute(RequestContextPtr context, AdminCheckRequestPtr request) { request->sequenceNumber())); } +void Logic::execute(RequestContextPtr context, CancelRequestPtr request) { + // MOCKUP + context->returnResponse(context, std::make_shared(request->sequenceNumber())); +} + void Logic::execute(RequestContextPtr context, CheckRequestPtr request) { PolicyResult result(PredefinedPolicyType::DENY); if (check(context, request->key(), result)) { diff --git a/src/service/logic/Logic.h b/src/service/logic/Logic.h index 84af6ff..28fdeea 100644 --- a/src/service/logic/Logic.h +++ b/src/service/logic/Logic.h @@ -51,6 +51,7 @@ public: } virtual void execute(RequestContextPtr context, AdminCheckRequestPtr request); + virtual void execute(RequestContextPtr context, CancelRequestPtr request); virtual void execute(RequestContextPtr context, CheckRequestPtr request); virtual void execute(RequestContextPtr context, InsertOrUpdateBucketRequestPtr request); virtual void execute(RequestContextPtr context, RemoveBucketRequestPtr request); -- 2.7.4 From b13293789e389806a41f15b74ff62a82675d902e Mon Sep 17 00:00:00 2001 From: =?utf8?q?Jos=C3=A9=20Bollo?= Date: Mon, 6 Oct 2014 17:31:59 +0200 Subject: [PATCH 02/16] Improving creation of user 'cynara' MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit To improve the creation of the user cynara, the home directory is now set to /var/lib/empty, the shell is set to /sbin/nologin, the main group is set to cynara. Change-Id: I4582caa9f9a61cd8c52d0a6718f504903cdee479 Signed-off-by: José Bollo --- packaging/cynara.spec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packaging/cynara.spec b/packaging/cynara.spec index 7508fbf..c25347f 100644 --- a/packaging/cynara.spec +++ b/packaging/cynara.spec @@ -273,7 +273,7 @@ fi id -u %{user_name} > /dev/null 2>&1 if [ $? -eq 1 ]; then - useradd %{user_name} -r > /dev/null 2>&1 + useradd -d /var/lib/empty -s /sbin/nologin -r -g %{group_name} %{user_name} > /dev/null 2>&1 fi %post -- 2.7.4 From 4fc95e366db1631e175bf8955fd3e72e610a4d07 Mon Sep 17 00:00:00 2001 From: Zofia Abramowska Date: Fri, 12 Sep 2014 15:45:36 +0200 Subject: [PATCH 03/16] Redo client plugins Let plugin make decision based on last and current client session. Plugin can change PluginResult. Change-Id: Ia985feaf1d60a8c1ebf858ba0d4e0d6f2cc6fa40 --- src/client-common/cache/CapacityCache.cpp | 49 ++++++++++++++-------------- src/client-common/cache/CapacityCache.h | 5 ++- src/client-common/plugins/NaiveInterpreter.h | 8 +++-- src/client-common/plugins/PluginInterface.h | 10 +++--- 4 files changed, 37 insertions(+), 35 deletions(-) diff --git a/src/client-common/cache/CapacityCache.cpp b/src/client-common/cache/CapacityCache.cpp index c4cf680..04f1cb5 100644 --- a/src/client-common/cache/CapacityCache.cpp +++ b/src/client-common/cache/CapacityCache.cpp @@ -30,13 +30,6 @@ namespace Cynara { int CapacityCache::get(const ClientSession &session, const PolicyKey &key) { - //This can be very time heavy. This part is welcomed to be optimized. - if (session != m_session) { - LOGD("Session changed from %s to %s.", m_session.c_str(), session.c_str()); - clear(); - m_session = session; - return CYNARA_API_CACHE_MISS; - } auto resultIt = m_keyValue.find(keyToString(key)); //Do we have entry in cache? if (resultIt == m_keyValue.end()) { @@ -51,23 +44,33 @@ int CapacityCache::get(const ClientSession &session, const PolicyKey &key) { key.user().toString().c_str(), key.privilege().toString().c_str()); - auto pluginIt = m_plugins.find(resultIt->second.first.policyType()); + auto &cachedValue = resultIt->second; + auto &policyResult = std::get<0>(cachedValue); + + auto pluginIt = m_plugins.find(policyResult.policyType()); if (pluginIt == m_plugins.end()) { LOGE("No plugin registered for given PolicyType : %" PRIu16, - resultIt->second.first.policyType()); + policyResult.policyType()); return CYNARA_API_ACCESS_DENIED; } //Is it still usable? InterpreterInterfacePtr plugin = pluginIt->second; - if (plugin->isUsable(resultIt->second.first)) { + auto &prevSession = std::get<1>(cachedValue); + auto usageIt = std::get<2>(cachedValue); + bool updateSession = false; + if (plugin->isUsable(session, prevSession, updateSession, policyResult)) { LOGD("Entry usable."); - m_keyUsage.splice(m_keyUsage.begin(), m_keyUsage, resultIt->second.second); - return plugin->toResult(resultIt->second.first); + m_keyUsage.splice(m_keyUsage.begin(), m_keyUsage, usageIt); + + if (updateSession) { + prevSession = session; + } + + return plugin->toResult(session, policyResult); } //Remove unusable entry LOGD("Entry not usable"); - auto usageIt = resultIt->second.second; m_keyUsage.erase(usageIt); m_keyValue.erase(resultIt); return CYNARA_API_CACHE_MISS; @@ -77,7 +80,6 @@ int CapacityCache::get(const ClientSession &session, const PolicyKey &key) { void CapacityCache::clear(void) { m_keyUsage.clear(); m_keyValue.clear(); - m_session.clear(); } std::string CapacityCache::keyToString(const PolicyKey &key) { @@ -103,12 +105,6 @@ void CapacityCache::evict(void) { int CapacityCache::update(const ClientSession &session, const PolicyKey &key, const PolicyResult &result) { - //This can be very time heavy. This part is welcomed to be optimized. - if (session != m_session) { - LOGD("Session changed from %s to %s.", m_session.c_str(), session.c_str()); - clear(); - m_session = session; - } auto pluginIt = m_plugins.find(result.policyType()); @@ -120,18 +116,21 @@ int CapacityCache::update(const ClientSession &session, } auto plugin = pluginIt->second; - if (m_capacity != 0) { - if (plugin->isCacheable(result)) { + PolicyResult storedResult = result; + + if (m_capacity > 0) { + if (plugin->isCacheable(session, storedResult)) { LOGD("Entry cacheable"); if (m_keyValue.size() == m_capacity) { LOGD("Capacity reached."); evict(); } - m_keyUsage.push_front(keyToString(key)); - m_keyValue[keyToString(key)] = std::make_pair(result, m_keyUsage.begin()); + std::string cacheKey = keyToString(key); + m_keyUsage.push_front(cacheKey); + m_keyValue[cacheKey] = std::make_tuple(storedResult, session, m_keyUsage.begin()); } } - return plugin->toResult(result); + return plugin->toResult(session, storedResult); } } // namespace Cynara diff --git a/src/client-common/cache/CapacityCache.h b/src/client-common/cache/CapacityCache.h index 5bb083e..4218078 100644 --- a/src/client-common/cache/CapacityCache.h +++ b/src/client-common/cache/CapacityCache.h @@ -24,6 +24,7 @@ #define SRC_CLIENT_COMMON_CACHE_CAPACITYCACHE_H_ #include +#include #include #include @@ -46,15 +47,13 @@ public: private: typedef std::list KeyUsageList; typedef std::unordered_map> KeyValueMap; + std::tuple> KeyValueMap; static std::string keyToString(const PolicyKey &key); void evict(void); std::size_t m_capacity; - ClientSession m_session; KeyUsageList m_keyUsage; KeyValueMap m_keyValue; diff --git a/src/client-common/plugins/NaiveInterpreter.h b/src/client-common/plugins/NaiveInterpreter.h index 04d05de..e306ab7 100644 --- a/src/client-common/plugins/NaiveInterpreter.h +++ b/src/client-common/plugins/NaiveInterpreter.h @@ -29,13 +29,15 @@ namespace Cynara { class NaiveInterpreter : public InterpreterInterface { - bool isUsable(const PolicyResult &result UNUSED) { + bool isUsable(const ClientSession &session UNUSED, const ClientSession &prevSession UNUSED, + bool &updateSession UNUSED, PolicyResult &result UNUSED) { return true; } - bool isCacheable(const PolicyResult &result UNUSED) { + bool isCacheable(const ClientSession &session UNUSED, + const PolicyResult &result UNUSED) { return true; } - int toResult(const PolicyResult &result) { + int toResult(const ClientSession &session UNUSED, PolicyResult &result) { if (result.policyType() == PredefinedPolicyType::ALLOW) return CYNARA_API_ACCESS_ALLOWED; else diff --git a/src/client-common/plugins/PluginInterface.h b/src/client-common/plugins/PluginInterface.h index 5f3a947..54bd341 100644 --- a/src/client-common/plugins/PluginInterface.h +++ b/src/client-common/plugins/PluginInterface.h @@ -25,6 +25,7 @@ #include +#include #include namespace Cynara { @@ -34,13 +35,14 @@ typedef std::shared_ptr InterpreterInterfacePtr; class InterpreterInterface { public: - virtual bool isCacheable(const PolicyResult &result) = 0; - virtual bool isUsable(const PolicyResult &result) = 0; - virtual int toResult(const PolicyResult &result) = 0; + virtual bool isCacheable(const ClientSession &session, const PolicyResult &result) = 0; + virtual bool isUsable(const ClientSession &session, const ClientSession &prevSession, + bool &updateSession, PolicyResult &result) = 0; + virtual int toResult(const ClientSession &session, PolicyResult &result) = 0; virtual ~InterpreterInterface() {}; }; -} +} // namespace Cynara #endif // SRC_CLIENT_COMMON_PLUGINS_PLUGININTERFACE_H_ -- 2.7.4 From 9018caa487c2037baf70868a72b0b2cc39ce7217 Mon Sep 17 00:00:00 2001 From: Zofia Abramowska Date: Tue, 16 Sep 2014 12:53:09 +0200 Subject: [PATCH 04/16] Fix cache update method Support update with existing entry. Change-Id: I0a242c9580ae0a521fddb8bf4fc4c2b8be3507c0 --- src/client-common/cache/CapacityCache.cpp | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/client-common/cache/CapacityCache.cpp b/src/client-common/cache/CapacityCache.cpp index 04f1cb5..c6449bc 100644 --- a/src/client-common/cache/CapacityCache.cpp +++ b/src/client-common/cache/CapacityCache.cpp @@ -119,15 +119,31 @@ int CapacityCache::update(const ClientSession &session, PolicyResult storedResult = result; if (m_capacity > 0) { + std::string cacheKey = keyToString(key); + auto resultIt = m_keyValue.find(cacheKey); if (plugin->isCacheable(session, storedResult)) { LOGD("Entry cacheable"); if (m_keyValue.size() == m_capacity) { LOGD("Capacity reached."); evict(); } - std::string cacheKey = keyToString(key); - m_keyUsage.push_front(cacheKey); + + //Move value usage to front + if (resultIt != m_keyValue.end()) { + auto usageIt = std::get<2>(resultIt->second); + m_keyUsage.splice(m_keyUsage.begin(), m_keyUsage, usageIt); + } else { + m_keyUsage.push_front(cacheKey); + } + m_keyValue[cacheKey] = std::make_tuple(storedResult, session, m_keyUsage.begin()); + } else { + //Remove element + if (resultIt != m_keyValue.end()) { + auto usageIt = std::get<2>(resultIt->second); + m_keyUsage.erase(usageIt); + m_keyValue.erase(resultIt); + } } } return plugin->toResult(session, storedResult); -- 2.7.4 From 4c2b3b8d0ce17221e77bcda10be4ef992d82ba72 Mon Sep 17 00:00:00 2001 From: Zofia Abramowska Date: Thu, 18 Sep 2014 17:33:53 +0200 Subject: [PATCH 05/16] Split PolicyResult declaration and definition PolicyResult header will be included in package for external plugin implementations. Change-Id: Ic5224af395b9fd86f57138566295961e80ee8f12 --- src/common/CMakeLists.txt | 1 + src/common/types/PolicyResult.cpp | 64 +++++++++++++++++++++++++++++++++++++++ src/common/types/PolicyResult.h | 53 +++++++++----------------------- test/CMakeLists.txt | 1 + 4 files changed, 81 insertions(+), 38 deletions(-) create mode 100644 src/common/types/PolicyResult.cpp diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt index d52ddd5..461450a 100644 --- a/src/common/CMakeLists.txt +++ b/src/common/CMakeLists.txt @@ -49,6 +49,7 @@ SET(COMMON_SOURCES ${COMMON_PATH}/types/PolicyBucket.cpp ${COMMON_PATH}/types/PolicyKey.cpp ${COMMON_PATH}/types/PolicyKeyHelpers.cpp + ${COMMON_PATH}/types/PolicyResult.cpp ) IF (CMAKE_BUILD_TYPE MATCHES "DEBUG") diff --git a/src/common/types/PolicyResult.cpp b/src/common/types/PolicyResult.cpp new file mode 100644 index 0000000..010139d --- /dev/null +++ b/src/common/types/PolicyResult.cpp @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file src/common/types/PolicyResult.cpp + * @author Aleksander Zdyb + * @author Zofia Abramowska + * @version 1.0 + * @brief PolicyResult implementation + */ + +#include "PolicyResult.h" + +namespace Cynara { + +PolicyResult::PolicyResult() : m_type(PredefinedPolicyType::DENY) {} + +PolicyResult::PolicyResult(const PolicyType &policyType) : m_type(policyType) {} + +PolicyResult::PolicyResult(const PolicyType &policyType, const PolicyMetadata &metadata) + : m_type(policyType) , m_metadata(metadata) {} + +const PolicyType &PolicyResult::policyType(void) const { + return m_type; +} + +const PolicyResult::PolicyMetadata &PolicyResult::metadata(void) const { + return m_metadata; +} + +bool PolicyResult::operator <(const PolicyResult &other) const { + return this->m_type < other.m_type; +} + +bool PolicyResult::operator ==(const PolicyResult &other) const { + return std::tie(m_type, m_metadata) == std::tie(other.m_type, other.m_metadata); +} + +bool PolicyResult::operator !=(const PolicyResult &other) const { + return !(*this == other); +} + +bool PolicyResult::operator ==(const PolicyType &policyType) const { + return (m_type == policyType) && m_metadata.empty(); +} + +bool PolicyResult::operator !=(const PolicyType &policyType) const { + return !(*this == policyType); +} + +} // namespace Cynara + diff --git a/src/common/types/PolicyResult.h b/src/common/types/PolicyResult.h index 28974d7..ae81d15 100644 --- a/src/common/types/PolicyResult.h +++ b/src/common/types/PolicyResult.h @@ -16,12 +16,13 @@ /** * @file src/common/types/PolicyResult.h * @author Aleksander Zdyb + * @author Zofia Abramowska * @version 1.0 * @brief Definitions of PolicyResult and friends */ -#ifndef POLICYRESULT_H_ -#define POLICYRESULT_H_ +#ifndef SRC_COMMON_TYPES_POLICYRESULT_H_ +#define SRC_COMMON_TYPES_POLICYRESULT_H_ #include "types/PolicyType.h" @@ -33,47 +34,23 @@ class PolicyResult { public: typedef std::string PolicyMetadata; -public: - PolicyResult() : m_type(PredefinedPolicyType::DENY) {} - PolicyResult(const PolicyType &policyType) : m_type(policyType) {} - PolicyResult(const PolicyType &policyType, const PolicyMetadata &metadata) - : m_type(policyType), m_metadata(metadata) {} + PolicyResult(); + PolicyResult(const PolicyType &policyType); + PolicyResult(const PolicyType &policyType, const PolicyMetadata &metadata); + + const PolicyType &policyType(void) const; + const PolicyMetadata &metadata(void) const; + bool operator <(const PolicyResult &other) const; + bool operator ==(const PolicyResult &other) const; + bool operator !=(const PolicyResult &other) const; + bool operator ==(const PolicyType &policyType) const; + bool operator !=(const PolicyType &policyType) const; private: PolicyType m_type; PolicyMetadata m_metadata; - -public: - const PolicyType &policyType() const { - return m_type; - } - - const PolicyMetadata& metadata() const { - return m_metadata; - } - - bool operator <(const PolicyResult &other) const { - return this->m_type < other.m_type; - } - - bool operator ==(const PolicyResult &other) const { - return std::tie(m_type, m_metadata) == std::tie(other.m_type, other.m_metadata); - } - - bool operator !=(const PolicyResult &other) const { - return !(*this == other); - } - - bool operator ==(const PolicyType &policyType) const { - return (m_type == policyType) && m_metadata.empty(); - } - - bool operator !=(const PolicyType &policyType) const { - return !(*this == policyType); - } }; } // namespace Cynara - -#endif /* POLICYRESULT_H_ */ +#endif /* SRC_COMMON_TYPES_POLICYRESULT_H_ */ diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 47bcfab..62bdbaa 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -25,6 +25,7 @@ SET(CYNARA_SOURCES_FOR_TESTS ${CYNARA_SRC}/common/types/PolicyBucket.cpp ${CYNARA_SRC}/common/types/PolicyKey.cpp ${CYNARA_SRC}/common/types/PolicyKeyHelpers.cpp + ${CYNARA_SRC}/common/types/PolicyResult.cpp ${CYNARA_SRC}/common/types/PolicyType.cpp ${CYNARA_SRC}/storage/BucketDeserializer.cpp ${CYNARA_SRC}/storage/InMemoryStorageBackend.cpp -- 2.7.4 From abb2d89db389d6636c327343b7e6292a12155bd1 Mon Sep 17 00:00:00 2001 From: Zofia Abramowska Date: Thu, 18 Sep 2014 18:37:40 +0200 Subject: [PATCH 06/16] Add cynara external plugins Add interface for creating external cynara plugin to enable custom policy types support. Change-Id: I43bd31a3e48f9667964107dd243f2286e7ffae8a --- packaging/cynara.spec | 14 ++++ pkgconfig/CMakeLists.txt | 1 + pkgconfig/cynara-plugin/CMakeLists.txt | 25 +++++++ pkgconfig/cynara-plugin/cynara-plugin.pc.in | 11 +++ src/common/CMakeLists.txt | 5 ++ src/include/CMakeLists.txt | 1 + src/include/cynara-plugin.h | 107 ++++++++++++++++++++++++++++ 7 files changed, 164 insertions(+) create mode 100644 pkgconfig/cynara-plugin/CMakeLists.txt create mode 100644 pkgconfig/cynara-plugin/cynara-plugin.pc.in create mode 100644 src/include/cynara-plugin.h diff --git a/packaging/cynara.spec b/packaging/cynara.spec index c25347f..6abd205 100644 --- a/packaging/cynara.spec +++ b/packaging/cynara.spec @@ -141,6 +141,14 @@ Requires: libcynara-commons = %{version}-%{release} cynara common library (devel) with common functionalities ####################################################### +%package -n libcynara-plugin-devel +Summary: Cynara - cynara plugin library (devel) +Requires: libcynara-commons-devel = %{version}-%{release} + +%description -n libcynara-plugin-devel +cynara plugin library (devel) with plugin definitions + +####################################################### %package -n libcynara-creds-commons Summary: Base library for cynara credentials helpers @@ -451,8 +459,14 @@ fi %{_libdir}/libcynara-commons.so.* %files -n libcynara-commons-devel +%{_includedir}/cynara/types/PolicyResult.h +%{_includedir}/cynara/types/PolicyType.h %{_libdir}/libcynara-commons.so +%files -n libcynara-plugin-devel +%{_includedir}/cynara/cynara-plugin.h +%{_libdir}/pkgconfig/cynara-plugin.pc + %files -n cynara-tests %manifest cynara-tests.manifest %attr(755,root,root) /usr/bin/cynara-tests diff --git a/pkgconfig/CMakeLists.txt b/pkgconfig/CMakeLists.txt index 9d4600f..a93ae55 100644 --- a/pkgconfig/CMakeLists.txt +++ b/pkgconfig/CMakeLists.txt @@ -23,4 +23,5 @@ ADD_SUBDIRECTORY(cynara-admin) ADD_SUBDIRECTORY(cynara-creds-commons) ADD_SUBDIRECTORY(cynara-creds-dbus) ADD_SUBDIRECTORY(cynara-creds-socket) +ADD_SUBDIRECTORY(cynara-plugin) ADD_SUBDIRECTORY(cynara-session) diff --git a/pkgconfig/cynara-plugin/CMakeLists.txt b/pkgconfig/cynara-plugin/CMakeLists.txt new file mode 100644 index 0000000..1ea74a5 --- /dev/null +++ b/pkgconfig/cynara-plugin/CMakeLists.txt @@ -0,0 +1,25 @@ +# Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# @file CMakeLists.txt +# @author Zofia Abramowska +# + +CONFIGURE_FILE(cynara-plugin.pc.in cynara-plugin.pc @ONLY) + +INSTALL(FILES + ${CMAKE_BINARY_DIR}/pkgconfig/cynara-plugin/cynara-plugin.pc + DESTINATION + ${LIB_INSTALL_DIR}/pkgconfig + ) diff --git a/pkgconfig/cynara-plugin/cynara-plugin.pc.in b/pkgconfig/cynara-plugin/cynara-plugin.pc.in new file mode 100644 index 0000000..c14de16 --- /dev/null +++ b/pkgconfig/cynara-plugin/cynara-plugin.pc.in @@ -0,0 +1,11 @@ +prefix=@CMAKE_INSTALL_PREFIX@ +exec_prefix=${prefix} +libdir=@LIB_INSTALL_DIR@ +includedir=${prefix}/include + +Name: cynara-plugin +Description: Cynara plugin definition package +Version: @CYNARA_VERSION@ +Requires: +Libs: -L${libdir} -lcynara-commons +Cflags: -I${includedir}/cynara diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt index 461450a..77c7d56 100644 --- a/src/common/CMakeLists.txt +++ b/src/common/CMakeLists.txt @@ -82,3 +82,8 @@ TARGET_LINK_LIBRARIES(${TARGET_CYNARA_COMMON} ) INSTALL(TARGETS ${TARGET_CYNARA_COMMON} DESTINATION ${LIB_INSTALL_DIR}) +INSTALL(FILES + ${COMMON_PATH}/types/PolicyResult.h + ${COMMON_PATH}/types/PolicyType.h + DESTINATION ${INCLUDE_INSTALL_DIR}/cynara/types + ) diff --git a/src/include/CMakeLists.txt b/src/include/CMakeLists.txt index 1be6e10..cb9d00c 100644 --- a/src/include/CMakeLists.txt +++ b/src/include/CMakeLists.txt @@ -26,6 +26,7 @@ INSTALL(FILES ${CYNARA_PATH}/include/cynara-creds-commons.h ${CYNARA_PATH}/include/cynara-creds-dbus.h ${CYNARA_PATH}/include/cynara-creds-socket.h + ${CYNARA_PATH}/include/cynara-plugin.h ${CYNARA_PATH}/include/cynara-session.h DESTINATION ${INCLUDE_INSTALL_DIR}/cynara ) diff --git a/src/include/cynara-plugin.h b/src/include/cynara-plugin.h new file mode 100644 index 0000000..83956fe --- /dev/null +++ b/src/include/cynara-plugin.h @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file src/include/cynara-plugin.h + * @author Zofia Abramowska + * @version 1.0 + * @brief This file defines cynara side external plugin interface + */ + +#ifndef CYNARA_PLUGIN_H_ +#define CYNARA_PLUGIN_H_ + +#include +#include +#include + +#include +#include + +namespace Cynara { + +class ExternalPluginInterface; + +extern "C" { +typedef ExternalPluginInterface *(*createPlugin)(void); +} + +//These typedefs will be defined in external headers +typedef std::string PluginData; +typedef std::string AgentType; +typedef std::vector PolicyTypes; + +/** + * A class defining external plugins interface. + * These plugins work inside of cynara and either can produce + * response through check instantly or require communication + * with given type of agent. Agent must be registered through + * cynara-agent API. + */ + +class ExternalPluginInterface { +public: + /** + * Enum indicating status of calling plugin method. + */ + enum class PluginStatus { + SUCCESS, /** < update() finished successfully*/ + ANSWER_READY, /** < check() returns answer immediately through argument*/ + ANSWER_NOTREADY, /** < check() cannot return answer immediately, + < communication with agent is required */ + ERROR /** < either check() or update() fails */ + }; + + /** + * Policy type supported by plugin. + */ + virtual PolicyTypes getSupportedPolicyTypes(void) = 0; + + /** + * Asks plugin, what kind of permission does client, user and privilege has. + * + * @param[in] client + * @param[in] user + * @param[in] privilege + * @param[out] result Immediate response (if available) + * @param[out] requiredAgent When ANSWER_NOTREADY, required AgentType to communicate with + * @param[out] pluginData Additional data, that will be passed to agent + * @return PluginStatus In case of success - either ANSWER_READY or ANSWER_NOTREADY, + * in case of error - ERROR + */ + virtual PluginStatus check(const std::string &client, const std::string &user, + const std::string &privilege, PolicyResult &result, + AgentType &requiredAgent, PluginData &pluginData) noexcept = 0; + + /** + * Updates response returned by agent + * @param[in] client + * @param[in] user + * @param[in] privilege + * @param[in] agentData Additional data, passed from agent + * @param[out] result Response interpreted from agent + * @return PluginStatus In case of success - SUCCESS, in case of error - ERROR + */ + virtual PluginStatus update(const std::string &client, const std::string &user, + const std::string &privilege, const PluginData &agentData, + PolicyResult &result) noexcept = 0; + + virtual ~ExternalPluginInterface() {}; + +}; + +} // namespace Cynara + +#endif /* CYNARA_PLUGIN_H_ */ -- 2.7.4 From fa70d3d34bf759389e67f52401adb334cf21ec2e Mon Sep 17 00:00:00 2001 From: Zofia Abramowska Date: Fri, 19 Sep 2014 16:42:02 +0200 Subject: [PATCH 07/16] Add PluginManager Add cynara service manager for loading and managing dynamic loaded plugins supporting custom policy types. Change-Id: I94c3bfa4842a6a8d0a078ac910aba5e54db7b468 --- src/service/CMakeLists.txt | 3 + src/service/logic/Logic.cpp | 28 ++++++-- src/service/logic/Logic.h | 7 ++ src/service/main/Cynara.cpp | 17 +++++ src/service/main/Cynara.h | 2 + src/service/main/pointers.h | 3 + src/service/plugin/PluginManager.cpp | 123 +++++++++++++++++++++++++++++++++++ src/service/plugin/PluginManager.h | 55 ++++++++++++++++ 8 files changed, 232 insertions(+), 6 deletions(-) create mode 100644 src/service/plugin/PluginManager.cpp create mode 100644 src/service/plugin/PluginManager.h diff --git a/src/service/CMakeLists.txt b/src/service/CMakeLists.txt index f1c4c8a..f8d2eb8 100644 --- a/src/service/CMakeLists.txt +++ b/src/service/CMakeLists.txt @@ -22,6 +22,7 @@ SET(CYNARA_SOURCES ${CYNARA_SERVICE_PATH}/logic/Logic.cpp ${CYNARA_SERVICE_PATH}/main/Cynara.cpp ${CYNARA_SERVICE_PATH}/main/main.cpp + ${CYNARA_SERVICE_PATH}/plugin/PluginManager.cpp ${CYNARA_SERVICE_PATH}/sockets/Descriptor.cpp ${CYNARA_SERVICE_PATH}/sockets/SocketManager.cpp ) @@ -29,6 +30,7 @@ SET(CYNARA_SOURCES INCLUDE_DIRECTORIES( ${CYNARA_SERVICE_PATH} ${CYNARA_PATH} + ${CYNARA_PATH}/include ) ADD_EXECUTABLE(${TARGET_CYNARA} ${CYNARA_SOURCES}) @@ -37,6 +39,7 @@ TARGET_LINK_LIBRARIES(${TARGET_CYNARA} ${CYNARA_DEP_LIBRARIES} ${TARGET_CYNARA_COMMON} ${TARGET_LIB_CYNARA_STORAGE} + dl ) INSTALL(TARGETS ${TARGET_CYNARA} DESTINATION ${BIN_INSTALL_DIR}) diff --git a/src/service/logic/Logic.cpp b/src/service/logic/Logic.cpp index d05f512..60a0cce 100644 --- a/src/service/logic/Logic.cpp +++ b/src/service/logic/Logic.cpp @@ -97,13 +97,29 @@ bool Logic::check(RequestContextPtr context UNUSED, const PolicyKey &key, LOGD("check of policy key <%s> returned DENY", key.toString().c_str()); return true; } - //todo pass question to proper plugin that: - // 1) returns false when answer has to be waited for (UI) - // 2) returns true if Response is to be generated - // In case 1) context should be saved in plugin in order to return answer when ready. - //in case no proper plugin is found - throw PluginNotFoundException(result); + ExternalPluginPtr plugin = m_pluginManager->getPlugin(result.policyType()); + if (!plugin) { + throw PluginNotFoundException(result); + } + + AgentType requiredAgent; + PluginData pluginData; + + auto ret = plugin->check(key.client().toString(), key.user().toString(), + key.privilege().toString(), result, requiredAgent, pluginData); + + switch (ret) { + case ExternalPluginInterface::PluginStatus::ANSWER_READY: + return true; + case ExternalPluginInterface::PluginStatus::ANSWER_NOTREADY: + //todo send request to agent + //context should be saved in plugin in order to return answer when ready + return false; + default: + //todo make additional class + throw std::runtime_error("Plugin error"); + } } void Logic::execute(RequestContextPtr context, InsertOrUpdateBucketRequestPtr request) { diff --git a/src/service/logic/Logic.h b/src/service/logic/Logic.h index 28fdeea..3c434a5 100644 --- a/src/service/logic/Logic.h +++ b/src/service/logic/Logic.h @@ -27,6 +27,7 @@ #include #include
+#include #include #include @@ -37,6 +38,10 @@ public: Logic(); virtual ~Logic(); + void bindPluginManager(PluginManagerPtr pluginManager) { + m_pluginManager = pluginManager; + } + void bindStorage(StoragePtr storage) { m_storage = storage; } @@ -46,6 +51,7 @@ public: } void unbindAll(void) { + m_pluginManager.reset(); m_storage.reset(); m_socketManager.reset(); } @@ -59,6 +65,7 @@ public: virtual void execute(RequestContextPtr context, SignalRequestPtr request); private: + PluginManagerPtr m_pluginManager; StoragePtr m_storage; SocketManagerPtr m_socketManager; diff --git a/src/service/main/Cynara.cpp b/src/service/main/Cynara.cpp index 4a4deb4..1a0d45e 100644 --- a/src/service/main/Cynara.cpp +++ b/src/service/main/Cynara.cpp @@ -27,6 +27,7 @@ #include #include +#include #include #include #include @@ -58,12 +59,27 @@ const std::string Cynara::storageDir(void) { return dir; } +const std::string Cynara::pluginDir(void) { + std::string dir("/usr/lib/cynara/"); + +#ifdef CYNARA_LIB_PATH + dir = CYNARA_LIB_PATH; +#else + LOGW("Cynara compiled without CYNARA_LIB_PATH flag. Using default plugin directory."); +#endif + dir += "plugin/"; + LOGI("Cynara plugin path <%s>", dir.c_str()); + return dir; +} + void Cynara::init(void) { m_logic = std::make_shared(); + m_pluginManager = std::make_shared(pluginDir()); m_socketManager = std::make_shared(); m_storageBackend = std::make_shared(storageDir()); m_storage = std::make_shared(*m_storageBackend); + m_logic->bindPluginManager(m_pluginManager); m_logic->bindStorage(m_storage); m_logic->bindSocketManager(m_socketManager); @@ -90,6 +106,7 @@ void Cynara::finalize(void) { } m_logic.reset(); + m_pluginManager.reset(); m_socketManager.reset(); m_storageBackend.reset(); m_storage.reset(); diff --git a/src/service/main/Cynara.h b/src/service/main/Cynara.h index ecdde62..e89eda3 100644 --- a/src/service/main/Cynara.h +++ b/src/service/main/Cynara.h @@ -30,10 +30,12 @@ namespace Cynara { class Cynara { private: LogicPtr m_logic; + PluginManagerPtr m_pluginManager; SocketManagerPtr m_socketManager; StoragePtr m_storage; StorageBackendPtr m_storageBackend; + static const std::string pluginDir(void); static const std::string storageDir(void); public: diff --git a/src/service/main/pointers.h b/src/service/main/pointers.h index 652dba3..e31eeb8 100644 --- a/src/service/main/pointers.h +++ b/src/service/main/pointers.h @@ -30,6 +30,9 @@ namespace Cynara { class Logic; typedef std::shared_ptr LogicPtr; +class PluginManager; +typedef std::shared_ptr PluginManagerPtr; + class SocketManager; typedef std::shared_ptr SocketManagerPtr; diff --git a/src/service/plugin/PluginManager.cpp b/src/service/plugin/PluginManager.cpp new file mode 100644 index 0000000..3d21b49 --- /dev/null +++ b/src/service/plugin/PluginManager.cpp @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file src/service/plugin/PluginManager.cpp + * @author Zofia Abramowska + * @version 1.0 + * @brief Definition of PluginManager class + */ + +#define _BSD_SOURCE_ + +#include +#include +#include +#include +#include + +#include + +#include "PluginManager.h" + + +namespace { + int pluginFilter(const struct dirent *ent) { +#ifdef _DIRENT_HAVE_D_TYPE + if (ent->d_type != DT_REG) { + return 0; + } +#endif + if (ent->d_name[0] == '.') { + return 0; + } + return 1; + } +} + +namespace Cynara { + +PluginManager::PluginManager(const std::string &pluginDir) : m_dir(pluginDir) { + loadPlugins(); +} + +ExternalPluginPtr PluginManager::getPlugin(PolicyType pType) { + return m_plugins[pType]; +} + +void PluginManager::loadPlugins(void) { + struct dirent **nameList = NULL; + int fileAmount = scandir(m_dir.c_str(), &nameList, pluginFilter, alphasort); + + if (fileAmount < 0) { + auto error = strerror(errno); + LOGE("Couldn't scan for plugins in <%s> : <%s>", m_dir.c_str(), error); + return; + } + + std::unique_ptr> direntPtr(nameList, + [fileAmount](dirent** dirs) { + for (int i = 0; i < fileAmount; i++) { + free(dirs[i]); + } + free(dirs); + }); + for (int i = 0; i < fileAmount; i++) { + openPlugin(m_dir + nameList[i]->d_name); + } +} + +void PluginManager::openPlugin(const std::string &path) { + void *handle = dlopen(path.c_str(), RTLD_LAZY); + + if (!handle) { + LOGW("File could not be dlopened <%s> : <%s>", path.c_str(), dlerror()); + return; + } + PluginLibPtr handlePtr(handle, std::ptr_fun(dlclose)); + + //Flush any previous errors + dlerror(); + createPlugin func = reinterpret_cast(dlsym(handle, "create")); + + char *error; + if ((error = dlerror()) != NULL) { + LOGE("Couldn't resolve symbol from lib <%s> : <%s>", path.c_str(), error); + return; + } + + ExternalPluginPtr pluginPtr(func()); + + if (!pluginPtr) { + LOGE("Couldn't create plugin for <%s>", path.c_str()); + return; + } + + PolicyTypes policies = pluginPtr->getSupportedPolicyTypes(); + if (policies.empty()) { + LOGE("Plugin <%s> does not support any type!", path.c_str()); + return; + } + for (auto type : policies) { + if (!m_plugins.insert(std::make_pair(type, pluginPtr)).second) { + LOGW("policyType [%" PRIu16 "] was already supported.", type); + } + } + + m_pluginLibs.push_back(std::move(handlePtr)); +} + +} // namespace Cynara + diff --git a/src/service/plugin/PluginManager.h b/src/service/plugin/PluginManager.h new file mode 100644 index 0000000..6338cad --- /dev/null +++ b/src/service/plugin/PluginManager.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file src/service/plugin/PluginManager.h + * @author Zofia Abramowska + * @version 1.0 + * @brief Declaration of PluginManager class + */ + +#ifndef SRC_SERVICE_PLUGIN_PLUGINMANAGER_H_ +#define SRC_SERVICE_PLUGIN_PLUGINMANAGER_H_ + +#include +#include +#include +#include + +#include + +namespace Cynara { +typedef std::shared_ptr ExternalPluginPtr; + +class PluginManager { +public: + PluginManager(const std::string &pluginDir); + ExternalPluginPtr getPlugin(PolicyType pType); + ~PluginManager() {} + +private: + typedef std::unique_ptr> PluginLibPtr; + typedef std::list PluginLibs; + + std::string m_dir; + std::map m_plugins; + PluginLibs m_pluginLibs; + + void loadPlugins(void); + void openPlugin(const std::string &path); +}; + +} // namespace Cynara +#endif /* SRC_SERVICE_PLUGIN_PLUGINMANAGER_H_ */ -- 2.7.4 From 401f59efe466d7bc55174666a598d49941bc3ff8 Mon Sep 17 00:00:00 2001 From: Zofia Abramowska Date: Tue, 7 Oct 2014 14:46:47 +0200 Subject: [PATCH 08/16] Add PluginErrorException Add exception class for plugin processing error. Change-Id: I26090bd3a54bdbc4767fd05735b5b06fae523b2f --- src/common/exceptions/PluginErrorException.h | 48 ++++++++++++++++++++++++++++ src/service/logic/Logic.cpp | 7 ++-- 2 files changed, 52 insertions(+), 3 deletions(-) create mode 100644 src/common/exceptions/PluginErrorException.h diff --git a/src/common/exceptions/PluginErrorException.h b/src/common/exceptions/PluginErrorException.h new file mode 100644 index 0000000..a29eab5 --- /dev/null +++ b/src/common/exceptions/PluginErrorException.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file src/common/exceptions/PluginErrorException.h + * @author Zofia Abramowska + * @version 1.0 + * @brief Implementation of PluginErrorException + */ +#ifndef SRC_COMMON_EXCEPTIONS_PLUGINERROREXCEPTION_H_ +#define SRC_COMMON_EXCEPTIONS_PLUGINERROREXCEPTION_H_ + +#include +#include + +namespace Cynara { + +class PluginErrorException : public Exception { +public: + PluginErrorException(const PolicyKey &key) { + m_message = "Plugin couldn't get result for user <" + key.user().toString() + ">, " + "client <" + key.client().toString() + ">, " + "privilege <" + key.privilege().toString() + ">"; + } + + const std::string message(void) const { + return m_message; + } + +private: + std::string m_message; +}; + +} // namespace Cynara + +#endif // SRC_COMMON_EXCEPTIONS_PLUGINERROREXCEPTION_H_ diff --git a/src/service/logic/Logic.cpp b/src/service/logic/Logic.cpp index 60a0cce..1787575 100644 --- a/src/service/logic/Logic.cpp +++ b/src/service/logic/Logic.cpp @@ -22,10 +22,12 @@ #include #include -#include #include #include #include +#include +#include + #include #include
@@ -117,8 +119,7 @@ bool Logic::check(RequestContextPtr context UNUSED, const PolicyKey &key, //context should be saved in plugin in order to return answer when ready return false; default: - //todo make additional class - throw std::runtime_error("Plugin error"); + throw PluginErrorException(key); } } -- 2.7.4 From adedddc8dbb050342f883b8966b9fe3fad5207f8 Mon Sep 17 00:00:00 2001 From: Lukasz Wojciechowski Date: Tue, 14 Oct 2014 08:47:31 +0200 Subject: [PATCH 09/16] Remove "noexcept" keyword from admin's Logic class We don't want cause application termination. All exceptions should be caught and handled. Change-Id: Ic245fb42a8b8fa7a7d83665ce95c4acb89c5b964 --- src/admin/api/ApiInterface.h | 10 +++++----- src/admin/logic/Logic.cpp | 8 ++++---- src/admin/logic/Logic.h | 10 +++++----- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/admin/api/ApiInterface.h b/src/admin/api/ApiInterface.h index bbfe98d..62c40e5 100644 --- a/src/admin/api/ApiInterface.h +++ b/src/admin/api/ApiInterface.h @@ -42,13 +42,13 @@ public: virtual ~ApiInterface() {}; virtual int setPolicies(const std::map> &insertOrUpdate, - const std::map> &remove) noexcept = 0; - virtual int insertOrUpdateBucket(const PolicyBucketId &bucket, const PolicyResult &policyResult) - noexcept = 0; - virtual int removeBucket(const PolicyBucketId &bucket) noexcept = 0; + const std::map> &remove) = 0; + virtual int insertOrUpdateBucket(const PolicyBucketId &bucket, + const PolicyResult &policyResult) = 0; + virtual int removeBucket(const PolicyBucketId &bucket) = 0; virtual int adminCheck(const PolicyBucketId &startBucket, bool recursive, - const PolicyKey &key, PolicyResult &result) noexcept = 0; + const PolicyKey &key, PolicyResult &result) = 0; }; diff --git a/src/admin/logic/Logic.cpp b/src/admin/logic/Logic.cpp index 6906056..3b004d9 100644 --- a/src/admin/logic/Logic.cpp +++ b/src/admin/logic/Logic.cpp @@ -112,21 +112,21 @@ int Logic::askCynaraAndInterpreteCodeResponse(Args... args) { } int Logic::setPolicies(const std::map> &insertOrUpdate, - const std::map> &remove) noexcept { + const std::map> &remove) { return askCynaraAndInterpreteCodeResponse(insertOrUpdate, remove); } int Logic::insertOrUpdateBucket(const PolicyBucketId &bucket, - const PolicyResult &policyResult) noexcept { + const PolicyResult &policyResult) { return askCynaraAndInterpreteCodeResponse(bucket, policyResult); } -int Logic::removeBucket(const PolicyBucketId &bucket) noexcept { +int Logic::removeBucket(const PolicyBucketId &bucket) { return askCynaraAndInterpreteCodeResponse(bucket); } int Logic::adminCheck(const PolicyBucketId &startBucket, bool recursive, const PolicyKey &key, - PolicyResult &result) noexcept { + PolicyResult &result) { try { if (!ensureConnection()) { LOGE("Cannot connect to cynara. Service not available."); diff --git a/src/admin/logic/Logic.h b/src/admin/logic/Logic.h index 527e992..a8688c2 100644 --- a/src/admin/logic/Logic.h +++ b/src/admin/logic/Logic.h @@ -44,13 +44,13 @@ public: virtual ~Logic() {}; virtual int setPolicies(const std::map> &insertOrUpdate, - const std::map> &remove) noexcept; - virtual int insertOrUpdateBucket(const PolicyBucketId &bucket, const PolicyResult &policyResult) - noexcept; - virtual int removeBucket(const PolicyBucketId &bucket) noexcept; + const std::map> &remove); + virtual int insertOrUpdateBucket(const PolicyBucketId &bucket, + const PolicyResult &policyResult); + virtual int removeBucket(const PolicyBucketId &bucket); virtual int adminCheck(const PolicyBucketId &startBucket, bool recursive, - const PolicyKey &key, PolicyResult &result) noexcept; + const PolicyKey &key, PolicyResult &result); }; } // namespace Cynara -- 2.7.4 From 8c151752c38ea5572e4d2efbdc3ae55292ae8820 Mon Sep 17 00:00:00 2001 From: Lukasz Wojciechowski Date: Tue, 14 Oct 2014 09:21:41 +0200 Subject: [PATCH 10/16] Clean up exception classes Some minor clean-ups in exceptions classes: * remove "noexcept" keyword from exception classes; * catch exceptions in Exception::what(); * correcting comments; * adding missing virtual keyword; * rearranging public and private sections. Change-Id: I99c382838adb22429a7ea8ac35974c988b3d3f33 --- .../exceptions/BucketDeserializationException.h | 2 +- src/common/exceptions/BucketNotExistsException.h | 11 ++++----- .../exceptions/BucketRecordCorruptedException.h | 27 +++++++++++----------- .../exceptions/BucketSerializationException.h | 2 +- src/common/exceptions/CannotCreateFileException.h | 2 +- src/common/exceptions/DatabaseException.h | 3 ++- .../exceptions/DefaultBucketDeletionException.h | 2 +- .../exceptions/DefaultBucketSetNoneException.h | 2 +- .../exceptions/DescriptorNotExistsException.h | 8 +++---- src/common/exceptions/Exception.h | 8 +++++-- src/common/exceptions/FileNotFoundException.h | 2 +- src/common/exceptions/InitException.h | 2 +- src/common/exceptions/InvalidProtocolException.h | 14 +++++------ src/common/exceptions/NoMemoryException.h | 2 +- src/common/exceptions/NotImplementedException.h | 2 +- src/common/exceptions/NullPointerException.h | 10 ++++---- src/common/exceptions/OutOfDataException.h | 8 +++---- src/common/exceptions/PluginNotFoundException.h | 8 +++---- src/common/exceptions/UnexpectedErrorException.h | 8 +++---- 19 files changed, 62 insertions(+), 61 deletions(-) diff --git a/src/common/exceptions/BucketDeserializationException.h b/src/common/exceptions/BucketDeserializationException.h index c6b6f1d..c5670c8 100644 --- a/src/common/exceptions/BucketDeserializationException.h +++ b/src/common/exceptions/BucketDeserializationException.h @@ -30,7 +30,7 @@ namespace Cynara { class BucketDeserializationException : public DatabaseException { public: BucketDeserializationException(const PolicyBucketId &bucketId) : m_bucketId(bucketId) {} - ~BucketDeserializationException() noexcept {}; + virtual ~BucketDeserializationException() {}; const std::string message(void) const { if (m_message.empty()) { diff --git a/src/common/exceptions/BucketNotExistsException.h b/src/common/exceptions/BucketNotExistsException.h index 7802210..9ba9505 100644 --- a/src/common/exceptions/BucketNotExistsException.h +++ b/src/common/exceptions/BucketNotExistsException.h @@ -34,19 +34,18 @@ class BucketNotExistsException : public Exception { public: BucketNotExistsException() = delete; BucketNotExistsException(const PolicyBucketId &bucketId) : m_bucketId(bucketId) {} - virtual ~BucketNotExistsException() noexcept {}; + virtual ~BucketNotExistsException() {}; virtual const std::string message(void) const { return "BucketNotExistsException"; } -private: - PolicyBucketId m_bucketId; - -public: - const PolicyBucketId &bucketId() const { + const PolicyBucketId &bucketId(void) const { return m_bucketId; } + +private: + PolicyBucketId m_bucketId; }; } /* namespace Cynara */ diff --git a/src/common/exceptions/BucketRecordCorruptedException.h b/src/common/exceptions/BucketRecordCorruptedException.h index 4511fb5..92b29f7 100644 --- a/src/common/exceptions/BucketRecordCorruptedException.h +++ b/src/common/exceptions/BucketRecordCorruptedException.h @@ -31,7 +31,7 @@ namespace Cynara { class BucketRecordCorruptedException : public DatabaseException { public: BucketRecordCorruptedException(void) = delete; - virtual ~BucketRecordCorruptedException() noexcept {}; + virtual ~BucketRecordCorruptedException() {}; BucketRecordCorruptedException(const std::string &line) : m_lineNumber(0), m_line(line) {} @@ -60,6 +60,18 @@ public: return m_whatMsg; } + const std::string &filename(void) const { + return m_filename; + } + + const std::string &line(void) const { + return m_line; + } + + size_t lineNumber(void) const { + return m_lineNumber; + } + protected: inline std::string slicedLine(void) const { return m_line.substr(0, 50) + (m_line.size() > 50 ? "..." : ""); @@ -80,19 +92,6 @@ private: std::string m_line; std::string m_filename; mutable std::string m_whatMsg; - -public: - const std::string &filename(void) const { - return m_filename; - } - - const std::string &line(void) const { - return m_line; - } - - size_t lineNumber(void) const { - return m_lineNumber; - } }; } /* namespace Cynara */ diff --git a/src/common/exceptions/BucketSerializationException.h b/src/common/exceptions/BucketSerializationException.h index f6dba4c..1e02823 100644 --- a/src/common/exceptions/BucketSerializationException.h +++ b/src/common/exceptions/BucketSerializationException.h @@ -30,7 +30,7 @@ namespace Cynara { class BucketSerializationException : public DatabaseException { public: BucketSerializationException(const PolicyBucketId &bucketId) : m_bucketId(bucketId) {} - ~BucketSerializationException() noexcept {}; + virtual ~BucketSerializationException() {}; const std::string message(void) const { if (m_message.empty()) { diff --git a/src/common/exceptions/CannotCreateFileException.h b/src/common/exceptions/CannotCreateFileException.h index 4195156..67c1d67 100644 --- a/src/common/exceptions/CannotCreateFileException.h +++ b/src/common/exceptions/CannotCreateFileException.h @@ -32,7 +32,7 @@ namespace Cynara { class CannotCreateFileException : public DatabaseException { public: CannotCreateFileException(const std::string &filename) : m_filename(filename) {}; - virtual ~CannotCreateFileException() noexcept {}; + virtual ~CannotCreateFileException() {}; const std::string message(void) const { if (m_message.empty()) { diff --git a/src/common/exceptions/DatabaseException.h b/src/common/exceptions/DatabaseException.h index 9cbd2b4..834d524 100644 --- a/src/common/exceptions/DatabaseException.h +++ b/src/common/exceptions/DatabaseException.h @@ -27,7 +27,8 @@ namespace Cynara { class DatabaseException : public Exception { - +public: + virtual ~DatabaseException() {}; }; } /* namespace Cynara */ diff --git a/src/common/exceptions/DefaultBucketDeletionException.h b/src/common/exceptions/DefaultBucketDeletionException.h index 9b75a00..a4742be 100644 --- a/src/common/exceptions/DefaultBucketDeletionException.h +++ b/src/common/exceptions/DefaultBucketDeletionException.h @@ -32,7 +32,7 @@ namespace Cynara { class DefaultBucketDeletionException : public Exception { public: DefaultBucketDeletionException() = default; - virtual ~DefaultBucketDeletionException() noexcept {}; + virtual ~DefaultBucketDeletionException() {}; virtual const std::string message(void) const { return "DefaultBucketDeletionException"; diff --git a/src/common/exceptions/DefaultBucketSetNoneException.h b/src/common/exceptions/DefaultBucketSetNoneException.h index b7975cd..243c4d8 100644 --- a/src/common/exceptions/DefaultBucketSetNoneException.h +++ b/src/common/exceptions/DefaultBucketSetNoneException.h @@ -32,7 +32,7 @@ namespace Cynara { class DefaultBucketSetNoneException : public Exception { public: DefaultBucketSetNoneException() = default; - virtual ~DefaultBucketSetNoneException() noexcept {}; + virtual ~DefaultBucketSetNoneException() {}; virtual const std::string message(void) const { return "DefaultBucketSetNoneException"; diff --git a/src/common/exceptions/DescriptorNotExistsException.h b/src/common/exceptions/DescriptorNotExistsException.h index badb64a..3535b91 100644 --- a/src/common/exceptions/DescriptorNotExistsException.h +++ b/src/common/exceptions/DescriptorNotExistsException.h @@ -32,9 +32,6 @@ namespace Cynara { class DescriptorNotExistsException : public Exception { -private: - std::string m_whatMsg; - public: DescriptorNotExistsException() = delete; DescriptorNotExistsException(int desc) { @@ -43,11 +40,14 @@ public: m_whatMsg = stream.str(); } - virtual ~DescriptorNotExistsException() noexcept {}; + virtual ~DescriptorNotExistsException() {}; virtual const std::string message(void) const { return m_whatMsg; } + +private: + std::string m_whatMsg; }; } // namespace Cynara diff --git a/src/common/exceptions/Exception.h b/src/common/exceptions/Exception.h index 4f5f5eb..c5eb709 100644 --- a/src/common/exceptions/Exception.h +++ b/src/common/exceptions/Exception.h @@ -33,11 +33,15 @@ public: m_backtrace = Backtrace::getBacktrace(); } - virtual ~Exception() noexcept {}; + virtual ~Exception() {}; virtual const char *what(void) const noexcept { if(m_whatMessage.empty()) { - m_whatMessage = message() + " From: " + m_backtrace; + try { + m_whatMessage = message() + " From: " + m_backtrace; + } + catch (...) { + } } return m_whatMessage.c_str(); } diff --git a/src/common/exceptions/FileNotFoundException.h b/src/common/exceptions/FileNotFoundException.h index e7aeead..4c446e2 100644 --- a/src/common/exceptions/FileNotFoundException.h +++ b/src/common/exceptions/FileNotFoundException.h @@ -32,7 +32,7 @@ namespace Cynara { class FileNotFoundException : public DatabaseException { public: FileNotFoundException(const std::string &filename) : m_filename(filename) {}; - virtual ~FileNotFoundException() noexcept {}; + virtual ~FileNotFoundException() {}; const std::string message(void) const { if (m_message.empty()) { diff --git a/src/common/exceptions/InitException.h b/src/common/exceptions/InitException.h index c93155c..cdb09a2 100644 --- a/src/common/exceptions/InitException.h +++ b/src/common/exceptions/InitException.h @@ -32,7 +32,7 @@ namespace Cynara { class InitException : public Exception { public: InitException() = default; - virtual ~InitException() noexcept {}; + virtual ~InitException() {}; virtual const std::string message(void) const { return "InitException"; diff --git a/src/common/exceptions/InvalidProtocolException.h b/src/common/exceptions/InvalidProtocolException.h index 89d0e4b..9b6a740 100644 --- a/src/common/exceptions/InvalidProtocolException.h +++ b/src/common/exceptions/InvalidProtocolException.h @@ -38,11 +38,6 @@ public: Other }; -private: - std::string m_whatMessage; - ExceptionType m_exceptionType; - -public: InvalidProtocolException(ExceptionType exceptionType) : m_exceptionType(exceptionType) { switch(m_exceptionType) { @@ -56,18 +51,21 @@ public: m_whatMessage = "Unknown problem"; break; } - } - virtual ~InvalidProtocolException() noexcept {}; + virtual ~InvalidProtocolException() {}; virtual const std::string message(void) const { return m_whatMessage; } - ExceptionType exceptionTyp(void) const { + ExceptionType exceptionType(void) const { return m_exceptionType; } + +private: + std::string m_whatMessage; + ExceptionType m_exceptionType; }; } // namespace Cynara diff --git a/src/common/exceptions/NoMemoryException.h b/src/common/exceptions/NoMemoryException.h index d8a6086..2eca090 100644 --- a/src/common/exceptions/NoMemoryException.h +++ b/src/common/exceptions/NoMemoryException.h @@ -37,7 +37,7 @@ public: m_whatMessage = "NoMemoryException with message <" + errorMsg + ">"; } - virtual ~NoMemoryException() noexcept {}; + virtual ~NoMemoryException() {}; virtual const std::string message(void) const { return m_whatMessage; diff --git a/src/common/exceptions/NotImplementedException.h b/src/common/exceptions/NotImplementedException.h index 1496fd7..8ca3762 100644 --- a/src/common/exceptions/NotImplementedException.h +++ b/src/common/exceptions/NotImplementedException.h @@ -32,7 +32,7 @@ namespace Cynara { class NotImplementedException : public Exception { public: NotImplementedException() = default; - virtual ~NotImplementedException() noexcept {}; + virtual ~NotImplementedException() {}; virtual const std::string message(void) const { return "NotImplementedException"; diff --git a/src/common/exceptions/NullPointerException.h b/src/common/exceptions/NullPointerException.h index 47e4239..e735555 100644 --- a/src/common/exceptions/NullPointerException.h +++ b/src/common/exceptions/NullPointerException.h @@ -17,7 +17,7 @@ * @file src/common/exceptions/NullPointerException.h * @author Lukasz Wojciechowski * @version 1.0 - * @brief Implementation of OutOfDataException + * @brief Implementation of NullPointerException */ #ifndef SRC_COMMON_EXCEPTIONS_NULLPOINTEREXCEPTION_H_ @@ -31,9 +31,6 @@ namespace Cynara { class NullPointerException : public Exception { -private: - std::string m_whatMsg; - public: NullPointerException() = delete; NullPointerException(const char *varName) { @@ -42,11 +39,14 @@ public: + std::string(">"); } - virtual ~NullPointerException() noexcept {}; + virtual ~NullPointerException() {}; virtual const std::string message(void) const { return m_whatMsg; } + +private: + std::string m_whatMsg; }; } // namespace Cynara diff --git a/src/common/exceptions/OutOfDataException.h b/src/common/exceptions/OutOfDataException.h index 716df13..6420819 100644 --- a/src/common/exceptions/OutOfDataException.h +++ b/src/common/exceptions/OutOfDataException.h @@ -32,9 +32,6 @@ namespace Cynara { class OutOfDataException : public Exception { -private: - std::string m_whatMsg; - public: OutOfDataException() = delete; OutOfDataException(size_t dataRange, size_t accessTry) { @@ -44,11 +41,14 @@ public: m_whatMsg = stream.str(); } - virtual ~OutOfDataException() noexcept {}; + virtual ~OutOfDataException() {}; virtual const std::string message(void) const { return m_whatMsg; } + +private: + std::string m_whatMsg; }; } // namespace Cynara diff --git a/src/common/exceptions/PluginNotFoundException.h b/src/common/exceptions/PluginNotFoundException.h index 3604075..4492a53 100644 --- a/src/common/exceptions/PluginNotFoundException.h +++ b/src/common/exceptions/PluginNotFoundException.h @@ -32,9 +32,6 @@ namespace Cynara { class PluginNotFoundException : public Exception { -private: - std::string m_whatMessage; - public: PluginNotFoundException() = delete; PluginNotFoundException(const PolicyResult &result) { @@ -45,11 +42,14 @@ public: m_whatMessage = stream.str(); } - virtual ~PluginNotFoundException() noexcept {}; + virtual ~PluginNotFoundException() {}; virtual const std::string message(void) const { return m_whatMessage; } + +private: + std::string m_whatMessage; }; } // namespace Cynara diff --git a/src/common/exceptions/UnexpectedErrorException.h b/src/common/exceptions/UnexpectedErrorException.h index ed0b72c..3080c0f 100644 --- a/src/common/exceptions/UnexpectedErrorException.h +++ b/src/common/exceptions/UnexpectedErrorException.h @@ -31,9 +31,6 @@ namespace Cynara { class UnexpectedErrorException : public Exception { -private: - std::string m_whatMessage; - public: UnexpectedErrorException() = delete; UnexpectedErrorException(int errorCode, const char *errorMsg) { @@ -49,11 +46,14 @@ public: m_whatMessage = stream.str(); } - virtual ~UnexpectedErrorException() noexcept {}; + virtual ~UnexpectedErrorException() {}; virtual const std::string message(void) const { return m_whatMessage; } + +private: + std::string m_whatMessage; }; } // namespace Cynara -- 2.7.4 From 35c285ba8b553681422b9e996da08e5e721ca38a Mon Sep 17 00:00:00 2001 From: Lukasz Wojciechowski Date: Tue, 14 Oct 2014 11:13:25 +0200 Subject: [PATCH 11/16] Remove "noexcept" keyword from PolicyBucket Change-Id: I0b00841efadb7584e854a04286758caf90e400cc --- src/common/types/PolicyBucket.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/common/types/PolicyBucket.h b/src/common/types/PolicyBucket.h index 92c5f36..122ece0 100644 --- a/src/common/types/PolicyBucket.h +++ b/src/common/types/PolicyBucket.h @@ -86,11 +86,11 @@ public: return const_policy_iterator(m_policyCollection.end()); } - PolicyMap::size_type size(void) const noexcept { + PolicyMap::size_type size(void) const { return m_policyCollection.size(); } - bool empty(void) const noexcept { + bool empty(void) const { return m_policyCollection.empty(); } -- 2.7.4 From 426deba8e8db72050eeef6044b170015b10260e4 Mon Sep 17 00:00:00 2001 From: Lukasz Wojciechowski Date: Tue, 14 Oct 2014 14:09:00 +0200 Subject: [PATCH 12/16] Use client error codes in admin libraries We need to have one unified set of error codes. Client error codes have been adjusted to serve admin errors too. Then client error codes were used in admin libraries keeping following mapping: CYNARA_ADMIN_API_SUCCESS -> CYNARA_API_SUCCESS CYNARA_ADMIN_API_OUT_OF_MEMORY -> CYNARA_API_OUT_OF_MEMORY CYNARA_ADMIN_API_INVALID_PARAM -> CYNARA_API_INVALID_PARAM CYNARA_ADMIN_API_SERVICE_NOT_AVAILABLE -> CYNARA_API_SERVICE_NOT_AVAILABLE CYNARA_ADMIN_API_UNEXPECTED_CLIENT_ERROR -> CYNARA_API_UNKNOWN_ERROR CYNARA_ADMIN_API_OPERATION_NOT_ALLOWED -> CYNARA_API_OPERATION_NOT_ALLOWED CYNARA_ADMIN_API_BUCKET_NOT_FOUND -> CYNARA_API_BUCKET_NOT_FOUND Remove not needed anymore old admin error codes file: src/include/cynara-admin-error.h Change-Id: Ice8990a2b354bd489c67c2a004344a5c60fc15ee --- packaging/cynara.spec | 2 +- src/admin/api/admin-api.cpp | 50 +++++++++++++++++----------------- src/admin/logic/Logic.cpp | 34 +++++++++++------------ src/include/CMakeLists.txt | 1 - src/include/cynara-admin-error.h | 56 -------------------------------------- src/include/cynara-admin.h | 12 ++++---- src/include/cynara-client-error.h | 8 +++++- src/include/cynara-offline-admin.h | 12 ++++---- 8 files changed, 62 insertions(+), 113 deletions(-) delete mode 100644 src/include/cynara-admin-error.h diff --git a/packaging/cynara.spec b/packaging/cynara.spec index 6abd205..17746c8 100644 --- a/packaging/cynara.spec +++ b/packaging/cynara.spec @@ -106,6 +106,7 @@ admin client library for setting, listing and removing policies %package -n libcynara-admin-devel Summary: Cynara - admin client library (devel) Requires: libcynara-admin = %{version}-%{release} +Requires: libcynara-commons-devel = %{version}-%{release} %description -n libcynara-admin-devel admin client library (devel) for setting, listing and removing policies @@ -440,7 +441,6 @@ fi %files -n libcynara-admin-devel %{_includedir}/cynara/cynara-admin.h -%{_includedir}/cynara/cynara-admin-error.h %{_includedir}/cynara/cynara-admin-types.h %{_libdir}/libcynara-admin.so %{_libdir}/pkgconfig/cynara-admin.pc diff --git a/src/admin/api/admin-api.cpp b/src/admin/api/admin-api.cpp index fe426fb..929b075 100644 --- a/src/admin/api/admin-api.cpp +++ b/src/admin/api/admin-api.cpp @@ -37,7 +37,7 @@ #include #include -#include +#include #include #include @@ -55,35 +55,35 @@ struct cynara_admin { CYNARA_API int cynara_admin_initialize(struct cynara_admin **pp_cynara_admin) { if (!pp_cynara_admin) - return CYNARA_ADMIN_API_INVALID_PARAM; + return CYNARA_API_INVALID_PARAM; try { *pp_cynara_admin = new cynara_admin(new Cynara::Logic); } catch (const std::bad_alloc &ex) { - return CYNARA_ADMIN_API_OUT_OF_MEMORY; + return CYNARA_API_OUT_OF_MEMORY; } init_log(); LOGD("Cynara admin initialized"); - return CYNARA_ADMIN_API_SUCCESS; + return CYNARA_API_SUCCESS; } CYNARA_API int cynara_admin_finish(struct cynara_admin *p_cynara_admin) { delete p_cynara_admin; - return CYNARA_ADMIN_API_SUCCESS; + return CYNARA_API_SUCCESS; } CYNARA_API int cynara_admin_set_policies(struct cynara_admin *p_cynara_admin, const struct cynara_admin_policy *const *policies) { if (!p_cynara_admin || !p_cynara_admin->impl) - return CYNARA_ADMIN_API_INVALID_PARAM; + return CYNARA_API_INVALID_PARAM; if (!policies) - return CYNARA_ADMIN_API_INVALID_PARAM; + return CYNARA_API_INVALID_PARAM; std::map> insertOrUpdate; std::map> remove; @@ -106,7 +106,7 @@ int cynara_admin_set_policies(struct cynara_admin *p_cynara_admin, for (auto i = policies; *i; i++) { const cynara_admin_policy *policy = *i; if(!policy->bucket || !policy->client || !policy->user || !policy->privilege) - return CYNARA_ADMIN_API_INVALID_PARAM; + return CYNARA_API_INVALID_PARAM; switch (policy->result) { case CYNARA_ADMIN_DELETE: @@ -122,7 +122,7 @@ int cynara_admin_set_policies(struct cynara_admin *p_cynara_admin, break; case CYNARA_ADMIN_BUCKET: if (!policy->result_extra) - return CYNARA_ADMIN_API_INVALID_PARAM; + return CYNARA_API_INVALID_PARAM; insertOrUpdate[policy->bucket].push_back(Cynara::Policy(key(policy), Cynara::PolicyResult( Cynara::PredefinedPolicyType::BUCKET, @@ -130,11 +130,11 @@ int cynara_admin_set_policies(struct cynara_admin *p_cynara_admin, break; case CYNARA_ADMIN_NONE: default: - return CYNARA_ADMIN_API_INVALID_PARAM; + return CYNARA_API_INVALID_PARAM; } } } catch (const std::bad_alloc &ex) { - return CYNARA_ADMIN_API_OUT_OF_MEMORY; + return CYNARA_API_OUT_OF_MEMORY; } return p_cynara_admin->impl->setPolicies(insertOrUpdate, remove); @@ -144,15 +144,15 @@ CYNARA_API int cynara_admin_set_bucket(struct cynara_admin *p_cynara_admin, const char *bucket, int operation, const char *extra) { if (!p_cynara_admin || !p_cynara_admin->impl) - return CYNARA_ADMIN_API_INVALID_PARAM; + return CYNARA_API_INVALID_PARAM; if (!bucket) - return CYNARA_ADMIN_API_INVALID_PARAM; + return CYNARA_API_INVALID_PARAM; std::string extraStr; try { extraStr = extra ? extra : ""; } catch (const std::bad_alloc &ex) { - return CYNARA_ADMIN_API_OUT_OF_MEMORY; + return CYNARA_API_OUT_OF_MEMORY; } switch (operation) { case CYNARA_ADMIN_DELETE: @@ -168,10 +168,10 @@ int cynara_admin_set_bucket(struct cynara_admin *p_cynara_admin, const char *buc return p_cynara_admin->impl->insertOrUpdateBucket(bucket, Cynara::PolicyResult(Cynara::PredefinedPolicyType::NONE)); } - return CYNARA_ADMIN_API_OPERATION_NOT_ALLOWED; + return CYNARA_API_OPERATION_NOT_ALLOWED; case CYNARA_ADMIN_BUCKET: default: - return CYNARA_ADMIN_API_INVALID_PARAM; + return CYNARA_API_INVALID_PARAM; } } @@ -181,13 +181,13 @@ int cynara_admin_check(struct cynara_admin *p_cynara_admin, const char *client, const char *user, const char *privilege, int *result, char **result_extra) { if (!p_cynara_admin || !p_cynara_admin->impl) - return CYNARA_ADMIN_API_INVALID_PARAM; + return CYNARA_API_INVALID_PARAM; if (!start_bucket) - return CYNARA_ADMIN_API_INVALID_PARAM; + return CYNARA_API_INVALID_PARAM; if (!client || !user || !privilege) - return CYNARA_ADMIN_API_INVALID_PARAM; + return CYNARA_API_INVALID_PARAM; if (!result || !result_extra) - return CYNARA_ADMIN_API_INVALID_PARAM; + return CYNARA_API_INVALID_PARAM; Cynara::PolicyResult policyResult; @@ -195,22 +195,22 @@ int cynara_admin_check(struct cynara_admin *p_cynara_admin, int ret = p_cynara_admin->impl->adminCheck(start_bucket, recursive != 0, Cynara::PolicyKey(client, user, privilege), policyResult); - if (ret != CYNARA_ADMIN_API_SUCCESS) + if (ret != CYNARA_API_SUCCESS) return ret; } catch (const std::bad_alloc &ex) { - return CYNARA_ADMIN_API_OUT_OF_MEMORY; + return CYNARA_API_OUT_OF_MEMORY; } catch (const std::length_error &ex) { - return CYNARA_ADMIN_API_INVALID_PARAM; + return CYNARA_API_INVALID_PARAM; } char *str = nullptr; if (!policyResult.metadata().empty()) { str = strdup(policyResult.metadata().c_str()); if (!str) - return CYNARA_ADMIN_API_OUT_OF_MEMORY; + return CYNARA_API_OUT_OF_MEMORY; } *result = static_cast(policyResult.policyType()); *result_extra = str; - return CYNARA_ADMIN_API_SUCCESS; + return CYNARA_API_SUCCESS; } diff --git a/src/admin/logic/Logic.cpp b/src/admin/logic/Logic.cpp index 3b004d9..d36651e 100644 --- a/src/admin/logic/Logic.cpp +++ b/src/admin/logic/Logic.cpp @@ -23,7 +23,7 @@ #include #include -#include +#include #include #include #include @@ -65,7 +65,7 @@ int Logic::askCynaraAndInterpreteCodeResponse(Args... args) { try { if (!ensureConnection()) { LOGE("Cannot connect to cynara. Service not available."); - return CYNARA_ADMIN_API_SERVICE_NOT_AVAILABLE; + return CYNARA_API_SERVICE_NOT_AVAILABLE; } ProtocolFrameSequenceNumber sequenceNumber = generateSequenceNumber(); @@ -77,37 +77,37 @@ int Logic::askCynaraAndInterpreteCodeResponse(Args... args) { ResponsePtr response; while (!(response = m_socketClient->askCynaraServer(request))) { if (!m_socketClient->connect()) - return CYNARA_ADMIN_API_SERVICE_NOT_AVAILABLE; + return CYNARA_API_SERVICE_NOT_AVAILABLE; } codeResponse = std::dynamic_pointer_cast(response); if (!codeResponse) { LOGC("Critical error. Casting Response to CodeResponse failed."); - return CYNARA_ADMIN_API_UNEXPECTED_CLIENT_ERROR; + return CYNARA_API_UNKNOWN_ERROR; } LOGD("codeResponse: code [%" PRIu16 "]", codeResponse->m_code); switch (codeResponse->m_code) { case CodeResponse::Code::OK: LOGI("Policies set successfully."); - return CYNARA_ADMIN_API_SUCCESS; + return CYNARA_API_SUCCESS; case CodeResponse::Code::NOT_ALLOWED: LOGE("Cynara service answered: Operation not allowed."); - return CYNARA_ADMIN_API_OPERATION_NOT_ALLOWED; + return CYNARA_API_OPERATION_NOT_ALLOWED; case CodeResponse::Code::NO_BUCKET: LOGE("Trying to use unexisting bucket."); - return CYNARA_ADMIN_API_BUCKET_NOT_FOUND; + return CYNARA_API_BUCKET_NOT_FOUND; default: LOGE("Unexpected response code from server: [%d]", static_cast(codeResponse->m_code)); - return CYNARA_ADMIN_API_UNEXPECTED_CLIENT_ERROR; + return CYNARA_API_UNKNOWN_ERROR; } } catch (const std::bad_alloc &ex) { LOGE("Cynara admin client out of memory."); - return CYNARA_ADMIN_API_OUT_OF_MEMORY; + return CYNARA_API_OUT_OF_MEMORY; } catch (const std::exception &ex) { LOGE("Unexpected client error: <%s>", ex.what()); - return CYNARA_ADMIN_API_UNEXPECTED_CLIENT_ERROR; + return CYNARA_API_UNKNOWN_ERROR; } } @@ -130,7 +130,7 @@ int Logic::adminCheck(const PolicyBucketId &startBucket, bool recursive, const P try { if (!ensureConnection()) { LOGE("Cannot connect to cynara. Service not available."); - return CYNARA_ADMIN_API_SERVICE_NOT_AVAILABLE; + return CYNARA_API_SERVICE_NOT_AVAILABLE; } ProtocolFrameSequenceNumber sequenceNumber = generateSequenceNumber(); @@ -143,13 +143,13 @@ int Logic::adminCheck(const PolicyBucketId &startBucket, bool recursive, const P ResponsePtr response; while (!(response = m_socketClient->askCynaraServer(request))) { if (!m_socketClient->connect()) - return CYNARA_ADMIN_API_SERVICE_NOT_AVAILABLE; + return CYNARA_API_SERVICE_NOT_AVAILABLE; } checkResponse = std::dynamic_pointer_cast(response); if (!checkResponse) { LOGC("Casting Response to CheckResponse failed."); - return CYNARA_ADMIN_API_UNEXPECTED_CLIENT_ERROR; + return CYNARA_API_UNKNOWN_ERROR; } LOGD("checkResponse: policyType [%" PRIu16 "], metadata <%s>", @@ -157,16 +157,16 @@ int Logic::adminCheck(const PolicyBucketId &startBucket, bool recursive, const P checkResponse->m_resultRef.metadata().c_str()); result = checkResponse->m_resultRef; - return CYNARA_ADMIN_API_SUCCESS; + return CYNARA_API_SUCCESS; } catch (const UnexpectedErrorException &ex) { LOGE(ex.what()); - return CYNARA_ADMIN_API_UNEXPECTED_CLIENT_ERROR; + return CYNARA_API_UNKNOWN_ERROR; } catch (const std::bad_alloc &ex) { LOGE("Cynara admin client out of memory."); - return CYNARA_ADMIN_API_OUT_OF_MEMORY; + return CYNARA_API_OUT_OF_MEMORY; } catch (const std::exception &ex) { LOGE("Unexpected client error: <%s>", ex.what()); - return CYNARA_ADMIN_API_UNEXPECTED_CLIENT_ERROR; + return CYNARA_API_UNKNOWN_ERROR; } } diff --git a/src/include/CMakeLists.txt b/src/include/CMakeLists.txt index cb9d00c..a6c1945 100644 --- a/src/include/CMakeLists.txt +++ b/src/include/CMakeLists.txt @@ -18,7 +18,6 @@ INSTALL(FILES ${CYNARA_PATH}/include/cynara-admin.h - ${CYNARA_PATH}/include/cynara-admin-error.h ${CYNARA_PATH}/include/cynara-admin-types.h ${CYNARA_PATH}/include/cynara-client.h ${CYNARA_PATH}/include/cynara-client-async.h diff --git a/src/include/cynara-admin-error.h b/src/include/cynara-admin-error.h deleted file mode 100644 index 4b9cad9..0000000 --- a/src/include/cynara-admin-error.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License - */ -/** - * @file src/include/cynara-admin-error.h - * @author Lukasz Wojciechowski - * @author Zofia Abramowska - * @version 1.0 - * @brief This file contains error codes of administration APIs of Cynara. - */ - -#ifndef CYNARA_ADMIN_ERROR_H -#define CYNARA_ADMIN_ERROR_H - -/** - * \name Return Codes - * exported by the foundation API. - * result codes begin with the start error code and extend into negative direction. - * @{ -*/ - -/*! \brief indicating the result of the one specific API is successful or access is allowed */ -#define CYNARA_ADMIN_API_SUCCESS 0 - -/*! \brief indicating client process is running out of memory */ -#define CYNARA_ADMIN_API_OUT_OF_MEMORY -1 - -/*! \brief indicating the API's parameter is malformed */ -#define CYNARA_ADMIN_API_INVALID_PARAM -2 - -/*! \brief service not available (cannot connect to cynara service) */ -#define CYNARA_ADMIN_API_SERVICE_NOT_AVAILABLE -3 - -/*! \brief unexpected error in client library */ -#define CYNARA_ADMIN_API_UNEXPECTED_CLIENT_ERROR -4 - -/*! \brief cynara service does not allow to perform requested operation */ -#define CYNARA_ADMIN_API_OPERATION_NOT_ALLOWED -5 - -/*! \brief cynara service hasn't found requested bucket */ -#define CYNARA_ADMIN_API_BUCKET_NOT_FOUND -6 -/** @}*/ - -#endif // CYNARA_ADMIN_ERROR_H diff --git a/src/include/cynara-admin.h b/src/include/cynara-admin.h index a31b1c5..6f5bc9e 100644 --- a/src/include/cynara-admin.h +++ b/src/include/cynara-admin.h @@ -23,8 +23,8 @@ #ifndef CYNARA_ADMIN_H #define CYNARA_ADMIN_H -#include #include +#include #ifdef __cplusplus extern "C" { @@ -63,7 +63,7 @@ struct cynara_admin; * * \param[out] pp_cynara_admin address of pointer for created cynara_admin structure. * - * \return CYNARA_ADMIN_API_SUCCESS on success, or error code otherwise. + * \return CYNARA_API_SUCCESS on success, or error code otherwise. * * \brief Initialize cynara-admin library. */ @@ -92,7 +92,7 @@ int cynara_admin_initialize(struct cynara_admin **pp_cynara_admin); * * \param[in] p_cynara_admin cynara_admin structure created in cynara_admin_initialize. * - * \return CYNARA_ADMIN_API_SUCCESS on success, or error code otherwise. + * \return CYNARA_API_SUCCESS on success, or error code otherwise. * * \brief Release cynara-admin library. */ @@ -144,7 +144,7 @@ int cynara_admin_finish(struct cynara_admin *p_cynara_admin); * \param[in] p_cynara_admin cynara admin structure. * \param[in] policies NULL terminated array of pointers to policy structures. * - * \return CYNARA_ADMIN_API_SUCCESS on success, or error code otherwise. + * \return CYNARA_API_SUCCESS on success, or error code otherwise. * * \brief Insert, update or delete policies in cynara database. */ @@ -191,7 +191,7 @@ int cynara_admin_set_policies(struct cynara_admin *p_cynara_admin, * \param[in] operation type of operation (default policy or CYNARA_ADMIN_DELETE) * \param[in] extra additional data for default policy (will be available with cynara extensions) * - * \return CYNARA_ADMIN_API_SUCCESS on success, or error code otherwise. + * \return CYNARA_API_SUCCESS on success, or error code otherwise. * * \brief Add, remove or update buckets in cynara database. */ @@ -238,7 +238,7 @@ int cynara_admin_set_bucket(struct cynara_admin *p_cynara_admin, const char *buc * \param[out] result placeholder for matched policy type. * \param[out] result_extra placeholder for matched policy additional data (see Important Notes!). * - * \return CYNARA_ADMIN_API_SUCCESS on success, or error code otherwise. + * \return CYNARA_API_SUCCESS on success, or error code otherwise. * * \brief Raw check client and user access for given privilege without using plugins extensions. */ diff --git a/src/include/cynara-client-error.h b/src/include/cynara-client-error.h index 8dd344f..d4d8bcc 100644 --- a/src/include/cynara-client-error.h +++ b/src/include/cynara-client-error.h @@ -58,8 +58,14 @@ /*! \brief indicating that provided method is not supported by library */ #define CYNARA_API_METHOD_NOT_SUPPORTED -6 +/*! \brief cynara service does not allow to perform requested operation */ +#define CYNARA_API_OPERATION_NOT_ALLOWED -7 + +/*! \brief cynara service hasn't found requested bucket */ +#define CYNARA_API_BUCKET_NOT_FOUND -8 + /*! \brief indicating an unknown error */ -#define CYNARA_API_UNKNOWN_ERROR -7 +#define CYNARA_API_UNKNOWN_ERROR -9 /** @}*/ diff --git a/src/include/cynara-offline-admin.h b/src/include/cynara-offline-admin.h index 1b26901..079ebd3 100644 --- a/src/include/cynara-offline-admin.h +++ b/src/include/cynara-offline-admin.h @@ -25,8 +25,8 @@ #ifndef CYNARA_OFFLINE_ADMIN_H #define CYNARA_OFFLINE_ADMIN_H -#include #include +#include #ifdef __cplusplus extern "C" { @@ -66,7 +66,7 @@ struct cynara_offline_admin; * \param[out] pp_cynara_offline_admin address of pointer for created cynara_offline_admin * structure. * - * \return CYNARA_ADMIN_API_SUCCESS on success, or negative error code otherwise. + * \return CYNARA_API_SUCCESS on success, or negative error code otherwise. * * \brief Initialize cynara-offline-admin library. */ @@ -96,7 +96,7 @@ int cynara_offline_admin_initialize(struct cynara_offline_admin **pp_cynara_offl * \param[in] p_cynara_offline_admin cynara_offline_admin structure created * in cynara_offline_admin_initialize. * - * \return CYNARA_ADMIN_API_SUCCESS on success, or negative error code otherwise. + * \return CYNARA_API_SUCCESS on success, or negative error code otherwise. * * \brief Release cynara-offline-admin library. */ @@ -146,7 +146,7 @@ int cynara_offline_admin_finish(struct cynara_offline_admin *p_cynara_offline_ad * \param[in] p_cynara_offline_admin cynara offline admin structure. * \param[in] policies NULL terminated array of pointers to policy structures. * - * \return CYNARA_ADMIN_API_SUCCESS on success, or negative error code otherwise. + * \return CYNARA_API_SUCCESS on success, or negative error code otherwise. * * \brief Insert, update or delete policies in cynara database. */ @@ -193,7 +193,7 @@ int cynara_offline_admin_set_policies(struct cynara_offline_admin *p_cynara_offl * \param[in] operation type of operation (default policy or CYNARA_ADMIN_DELETE) * \param[in] extra additional data for default policy (will be available with cynara extensions) * - * \return CYNARA_ADMIN_API_SUCCESS on success, or negative error code otherwise. + * \return CYNARA_API_SUCCESS on success, or negative error code otherwise. * * \brief Add, remove or update buckets in cynara database. */ @@ -240,7 +240,7 @@ int cynara_offline_admin_set_bucket(struct cynara_offline_admin *p_cynara_offlin * \param[out] result placeholder for matched policy type * \param[out] result_extra placeholder for matched policy additional data (see Important Notes!) * - * \return CYNARA_ADMIN_API_SUCCESS on success, or error code otherwise. + * \return CYNARA_API_SUCCESS on success, or error code otherwise. * * \brief Raw check client, user access for given privilege without using plugins extensions. */ -- 2.7.4 From cbdeb6113b5e8b8cfbfea846fe7e7ed5d672926f Mon Sep 17 00:00:00 2001 From: Lukasz Wojciechowski Date: Tue, 14 Oct 2014 14:37:07 +0200 Subject: [PATCH 13/16] Rename cynara-client-error.h to cynara-error.h Apply new name to all files. Change-Id: I9e4590a40e11ba5a33442707207635bb0d75a278 --- packaging/cynara.spec | 2 +- src/admin/api/admin-api.cpp | 2 +- src/admin/logic/Logic.cpp | 2 +- src/client-common/cache/CapacityCache.cpp | 2 +- src/client-common/exceptions/TryCatch.h | 2 +- src/client-common/plugins/NaiveInterpreter.h | 2 +- src/client/api/client-api.cpp | 2 +- src/client/logic/Logic.cpp | 2 +- src/helpers/creds-commons/creds-commons.cpp | 2 +- src/helpers/creds-dbus/creds-dbus-inner.cpp | 2 +- src/helpers/creds-dbus/creds-dbus.cpp | 2 +- src/helpers/creds-socket/creds-socket-inner.cpp | 2 +- src/helpers/creds-socket/creds-socket.cpp | 2 +- src/include/CMakeLists.txt | 2 +- src/include/cynara-admin.h | 2 +- src/include/cynara-client-async.h | 2 +- src/include/cynara-client.h | 2 +- src/include/cynara-creds-commons.h | 2 +- src/include/{cynara-client-error.h => cynara-error.h} | 10 +++++----- src/include/cynara-offline-admin.h | 2 +- 20 files changed, 24 insertions(+), 24 deletions(-) rename src/include/{cynara-client-error.h => cynara-error.h} (90%) diff --git a/packaging/cynara.spec b/packaging/cynara.spec index 17746c8..e8d0bc8 100644 --- a/packaging/cynara.spec +++ b/packaging/cynara.spec @@ -431,7 +431,7 @@ fi %{_libdir}/libcynara-client-commons.so.* %files -n libcynara-client-commons-devel -%{_includedir}/cynara/cynara-client-error.h +%{_includedir}/cynara/cynara-error.h %{_libdir}/libcynara-client-commons.so %files -n libcynara-admin diff --git a/src/admin/api/admin-api.cpp b/src/admin/api/admin-api.cpp index 929b075..0df64f3 100644 --- a/src/admin/api/admin-api.cpp +++ b/src/admin/api/admin-api.cpp @@ -37,7 +37,7 @@ #include #include -#include +#include #include #include diff --git a/src/admin/logic/Logic.cpp b/src/admin/logic/Logic.cpp index d36651e..683a2cf 100644 --- a/src/admin/logic/Logic.cpp +++ b/src/admin/logic/Logic.cpp @@ -23,7 +23,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/client-common/cache/CapacityCache.cpp b/src/client-common/cache/CapacityCache.cpp index c6449bc..d07bb2c 100644 --- a/src/client-common/cache/CapacityCache.cpp +++ b/src/client-common/cache/CapacityCache.cpp @@ -22,7 +22,7 @@ #include -#include +#include #include #include diff --git a/src/client-common/exceptions/TryCatch.h b/src/client-common/exceptions/TryCatch.h index 6dc4d0b..08b93d9 100644 --- a/src/client-common/exceptions/TryCatch.h +++ b/src/client-common/exceptions/TryCatch.h @@ -30,7 +30,7 @@ #include #include -#include +#include namespace Cynara { diff --git a/src/client-common/plugins/NaiveInterpreter.h b/src/client-common/plugins/NaiveInterpreter.h index e306ab7..e9e8ba4 100644 --- a/src/client-common/plugins/NaiveInterpreter.h +++ b/src/client-common/plugins/NaiveInterpreter.h @@ -24,7 +24,7 @@ #include #include -#include +#include namespace Cynara { diff --git a/src/client/api/client-api.cpp b/src/client/api/client-api.cpp index 6ca7def..4eb4625 100644 --- a/src/client/api/client-api.cpp +++ b/src/client/api/client-api.cpp @@ -28,7 +28,7 @@ #include #include -#include +#include #include #include diff --git a/src/client/logic/Logic.cpp b/src/client/logic/Logic.cpp index f375e9e..4886b78 100644 --- a/src/client/logic/Logic.cpp +++ b/src/client/logic/Logic.cpp @@ -24,7 +24,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/helpers/creds-commons/creds-commons.cpp b/src/helpers/creds-commons/creds-commons.cpp index 3fa1c9b..35d2ac7 100644 --- a/src/helpers/creds-commons/creds-commons.cpp +++ b/src/helpers/creds-commons/creds-commons.cpp @@ -24,8 +24,8 @@ #include -#include #include +#include CYNARA_API int cynara_creds_get_default_client_method(enum cynara_client_creds *method) { diff --git a/src/helpers/creds-dbus/creds-dbus-inner.cpp b/src/helpers/creds-dbus/creds-dbus-inner.cpp index 34ad453..fc48217 100644 --- a/src/helpers/creds-dbus/creds-dbus-inner.cpp +++ b/src/helpers/creds-dbus/creds-dbus-inner.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include "creds-dbus-inner.h" diff --git a/src/helpers/creds-dbus/creds-dbus.cpp b/src/helpers/creds-dbus/creds-dbus.cpp index e0b235d..4bca2a5 100644 --- a/src/helpers/creds-dbus/creds-dbus.cpp +++ b/src/helpers/creds-dbus/creds-dbus.cpp @@ -27,9 +27,9 @@ #include -#include #include #include +#include CYNARA_API int cynara_creds_dbus_get_client(DBusConnection *connection, const char *uniqueName, diff --git a/src/helpers/creds-socket/creds-socket-inner.cpp b/src/helpers/creds-socket/creds-socket-inner.cpp index 320fca5..bb4ebcc 100644 --- a/src/helpers/creds-socket/creds-socket-inner.cpp +++ b/src/helpers/creds-socket/creds-socket-inner.cpp @@ -30,7 +30,7 @@ #include #include -#include +#include #include "creds-socket-inner.h" diff --git a/src/helpers/creds-socket/creds-socket.cpp b/src/helpers/creds-socket/creds-socket.cpp index d60c241..fb5f963 100644 --- a/src/helpers/creds-socket/creds-socket.cpp +++ b/src/helpers/creds-socket/creds-socket.cpp @@ -29,9 +29,9 @@ #include -#include #include #include +#include CYNARA_API int cynara_creds_socket_get_client(int socket_fd, enum cynara_client_creds method, char **client) { diff --git a/src/include/CMakeLists.txt b/src/include/CMakeLists.txt index a6c1945..245962d 100644 --- a/src/include/CMakeLists.txt +++ b/src/include/CMakeLists.txt @@ -21,10 +21,10 @@ INSTALL(FILES ${CYNARA_PATH}/include/cynara-admin-types.h ${CYNARA_PATH}/include/cynara-client.h ${CYNARA_PATH}/include/cynara-client-async.h - ${CYNARA_PATH}/include/cynara-client-error.h ${CYNARA_PATH}/include/cynara-creds-commons.h ${CYNARA_PATH}/include/cynara-creds-dbus.h ${CYNARA_PATH}/include/cynara-creds-socket.h + ${CYNARA_PATH}/include/cynara-error.h ${CYNARA_PATH}/include/cynara-plugin.h ${CYNARA_PATH}/include/cynara-session.h DESTINATION ${INCLUDE_INSTALL_DIR}/cynara diff --git a/src/include/cynara-admin.h b/src/include/cynara-admin.h index 6f5bc9e..0e92b18 100644 --- a/src/include/cynara-admin.h +++ b/src/include/cynara-admin.h @@ -24,7 +24,7 @@ #define CYNARA_ADMIN_H #include -#include +#include #ifdef __cplusplus extern "C" { diff --git a/src/include/cynara-client-async.h b/src/include/cynara-client-async.h index 1e39d9b..20f5ea4 100644 --- a/src/include/cynara-client-async.h +++ b/src/include/cynara-client-async.h @@ -27,7 +27,7 @@ #include -#include +#include #ifdef __cplusplus extern "C" { diff --git a/src/include/cynara-client.h b/src/include/cynara-client.h index 3f4c938..571bef1 100644 --- a/src/include/cynara-client.h +++ b/src/include/cynara-client.h @@ -23,7 +23,7 @@ #ifndef CYNARA_CLIENT_H #define CYNARA_CLIENT_H -#include +#include #ifdef __cplusplus extern "C" { diff --git a/src/include/cynara-creds-commons.h b/src/include/cynara-creds-commons.h index 0bb3e69..75e4366 100644 --- a/src/include/cynara-creds-commons.h +++ b/src/include/cynara-creds-commons.h @@ -26,7 +26,7 @@ #ifndef CYNARA_CREDS_COMMONS_H #define CYNARA_CREDS_COMMONS_H -#include +#include enum cynara_client_creds { CLIENT_METHOD_SMACK, diff --git a/src/include/cynara-client-error.h b/src/include/cynara-error.h similarity index 90% rename from src/include/cynara-client-error.h rename to src/include/cynara-error.h index d4d8bcc..e8900b8 100644 --- a/src/include/cynara-client-error.h +++ b/src/include/cynara-error.h @@ -14,15 +14,15 @@ * limitations under the License */ /** - * @file src/include/cynara-client-error.h + * @file src/include/cynara-error.h * @author Lukasz Wojciechowski * @author Zofia Abramowska * @version 1.0 - * @brief This file contains error codes returned by client APIs of Cynara. + * @brief This file contains error codes returned by APIs of Cynara. */ -#ifndef CYNARA_CLIENT_ERROR_H -#define CYNARA_CLIENT_ERROR_H +#ifndef CYNARA_ERROR_H +#define CYNARA_ERROR_H /** * \name Return Codes @@ -69,4 +69,4 @@ /** @}*/ -#endif /* CYNARA_CLIENT_ERROR_H */ +#endif /* CYNARA_ERROR_H */ diff --git a/src/include/cynara-offline-admin.h b/src/include/cynara-offline-admin.h index 079ebd3..dbecc78 100644 --- a/src/include/cynara-offline-admin.h +++ b/src/include/cynara-offline-admin.h @@ -26,7 +26,7 @@ #define CYNARA_OFFLINE_ADMIN_H #include -#include +#include #ifdef __cplusplus extern "C" { -- 2.7.4 From 5dca2a965490bd53fa00ac2d8c612b0653eb9fa7 Mon Sep 17 00:00:00 2001 From: Lukasz Wojciechowski Date: Tue, 14 Oct 2014 14:45:27 +0200 Subject: [PATCH 14/16] Move TryCatch from client-common to common library TryCatch can be used also in admin libraries, so it belongs to common library now. Change-Id: Ibdd9c1576b9b34195555c2d9b43e72b57a83a201 --- src/{client-common => common}/exceptions/TryCatch.h | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) rename src/{client-common => common}/exceptions/TryCatch.h (88%) diff --git a/src/client-common/exceptions/TryCatch.h b/src/common/exceptions/TryCatch.h similarity index 88% rename from src/client-common/exceptions/TryCatch.h rename to src/common/exceptions/TryCatch.h index 08b93d9..b1ef172 100644 --- a/src/client-common/exceptions/TryCatch.h +++ b/src/common/exceptions/TryCatch.h @@ -14,14 +14,14 @@ * limitations under the License */ /** - * @file src/client-common/exceptions/TryCatch.h + * @file src/common/exceptions/TryCatch.h * @author Marcin Niesluchowski * @version 1.0 * @brief This file contains functions for catching exceptions */ -#ifndef SRC_CLIENT_COMMON_EXCEPTIONS_TRYCATCH_H_ -#define SRC_CLIENT_COMMON_EXCEPTIONS_TRYCATCH_H_ +#ifndef SRC_COMMON_EXCEPTIONS_TRYCATCH_H_ +#define SRC_COMMON_EXCEPTIONS_TRYCATCH_H_ #include #include @@ -54,5 +54,4 @@ int tryCatch(const std::function &func) { } // namespace Cynara -#endif // SRC_CLIENT_COMMON_EXCEPTIONS_TRYCATCH_H_ - +#endif // SRC_COMMON_EXCEPTIONS_TRYCATCH_H_ -- 2.7.4 From 45c717d1a2f1091ad025fc617dd3af6ab67ef095 Mon Sep 17 00:00:00 2001 From: Lukasz Wojciechowski Date: Thu, 16 Oct 2014 08:25:04 +0200 Subject: [PATCH 15/16] Use TryCatch() for exception catching in admin library Change-Id: I01d0b075c7d9cb5d94cadfe2c1dc5da7bd326027 --- src/admin/api/admin-api.cpp | 141 +++++++++++++++++++++++--------------------- src/admin/logic/Logic.cpp | 133 ++++++++++++++++++----------------------- 2 files changed, 130 insertions(+), 144 deletions(-) diff --git a/src/admin/api/admin-api.cpp b/src/admin/api/admin-api.cpp index 0df64f3..e444b7a 100644 --- a/src/admin/api/admin-api.cpp +++ b/src/admin/api/admin-api.cpp @@ -28,6 +28,7 @@ #include #include +#include #include #include #include @@ -57,17 +58,15 @@ int cynara_admin_initialize(struct cynara_admin **pp_cynara_admin) { if (!pp_cynara_admin) return CYNARA_API_INVALID_PARAM; - try { + return Cynara::tryCatch([&]() { *pp_cynara_admin = new cynara_admin(new Cynara::Logic); - } catch (const std::bad_alloc &ex) { - return CYNARA_API_OUT_OF_MEMORY; - } - init_log(); + init_log(); - LOGD("Cynara admin initialized"); + LOGD("Cynara admin initialized"); - return CYNARA_API_SUCCESS; + return CYNARA_API_SUCCESS; + }); } CYNARA_API @@ -85,24 +84,24 @@ int cynara_admin_set_policies(struct cynara_admin *p_cynara_admin, if (!policies) return CYNARA_API_INVALID_PARAM; - std::map> insertOrUpdate; - std::map> remove; + return Cynara::tryCatch([&]() { + std::map> insertOrUpdate; + std::map> remove; - auto key = ([](const cynara_admin_policy *policy)->Cynara::PolicyKey { - std::string wildcard(CYNARA_ADMIN_WILDCARD); + auto key = ([](const cynara_admin_policy *policy)->Cynara::PolicyKey { + std::string wildcard(CYNARA_ADMIN_WILDCARD); - auto feature = ([&wildcard] (const char *str)->Cynara::PolicyKeyFeature { - if (wildcard.compare(str)) - return Cynara::PolicyKeyFeature::create(str); - else - return Cynara::PolicyKeyFeature::createWildcard(); - }); + auto feature = ([&wildcard] (const char *str)->Cynara::PolicyKeyFeature { + if (wildcard.compare(str)) + return Cynara::PolicyKeyFeature::create(str); + else + return Cynara::PolicyKeyFeature::createWildcard(); + }); - return Cynara::PolicyKey(feature(policy->client), feature(policy->user), - feature(policy->privilege)); - }); + return Cynara::PolicyKey(feature(policy->client), feature(policy->user), + feature(policy->privilege)); + }); - try { for (auto i = policies; *i; i++) { const cynara_admin_policy *policy = *i; if(!policy->bucket || !policy->client || !policy->user || !policy->privilege) @@ -133,11 +132,9 @@ int cynara_admin_set_policies(struct cynara_admin *p_cynara_admin, return CYNARA_API_INVALID_PARAM; } } - } catch (const std::bad_alloc &ex) { - return CYNARA_API_OUT_OF_MEMORY; - } - return p_cynara_admin->impl->setPolicies(insertOrUpdate, remove); + return p_cynara_admin->impl->setPolicies(insertOrUpdate, remove); + }); } CYNARA_API @@ -148,31 +145,29 @@ int cynara_admin_set_bucket(struct cynara_admin *p_cynara_admin, const char *buc if (!bucket) return CYNARA_API_INVALID_PARAM; - std::string extraStr; - try { - extraStr = extra ? extra : ""; - } catch (const std::bad_alloc &ex) { - return CYNARA_API_OUT_OF_MEMORY; - } - switch (operation) { - case CYNARA_ADMIN_DELETE: - return p_cynara_admin->impl->removeBucket(bucket); - case CYNARA_ADMIN_DENY: - return p_cynara_admin->impl->insertOrUpdateBucket(bucket, - Cynara::PolicyResult(Cynara::PredefinedPolicyType::DENY, extraStr)); - case CYNARA_ADMIN_ALLOW: - return p_cynara_admin->impl->insertOrUpdateBucket(bucket, - Cynara::PolicyResult(Cynara::PredefinedPolicyType::ALLOW, extraStr)); - case CYNARA_ADMIN_NONE: - if (bucket != Cynara::defaultPolicyBucketId) { + return Cynara::tryCatch([&]() { + std::string extraStr = extra ? extra : ""; + + switch (operation) { + case CYNARA_ADMIN_DELETE: + return p_cynara_admin->impl->removeBucket(bucket); + case CYNARA_ADMIN_DENY: return p_cynara_admin->impl->insertOrUpdateBucket(bucket, - Cynara::PolicyResult(Cynara::PredefinedPolicyType::NONE)); - } - return CYNARA_API_OPERATION_NOT_ALLOWED; - case CYNARA_ADMIN_BUCKET: - default: - return CYNARA_API_INVALID_PARAM; - } + Cynara::PolicyResult(Cynara::PredefinedPolicyType::DENY, extraStr)); + case CYNARA_ADMIN_ALLOW: + return p_cynara_admin->impl->insertOrUpdateBucket(bucket, + Cynara::PolicyResult(Cynara::PredefinedPolicyType::ALLOW, extraStr)); + case CYNARA_ADMIN_NONE: + if (bucket != Cynara::defaultPolicyBucketId) { + return p_cynara_admin->impl->insertOrUpdateBucket(bucket, + Cynara::PolicyResult(Cynara::PredefinedPolicyType::NONE)); + } + return CYNARA_API_OPERATION_NOT_ALLOWED; + case CYNARA_ADMIN_BUCKET: + default: + return CYNARA_API_INVALID_PARAM; + } + }); } CYNARA_API @@ -189,28 +184,38 @@ int cynara_admin_check(struct cynara_admin *p_cynara_admin, if (!result || !result_extra) return CYNARA_API_INVALID_PARAM; - Cynara::PolicyResult policyResult; + return Cynara::tryCatch([&]() { + Cynara::PolicyResult policyResult; + Cynara::PolicyBucketId startBucket; + std::string clientStr; + std::string userStr; + std::string privilegeStr; + + try { + startBucket = start_bucket; + clientStr = client; + userStr = user; + privilegeStr = privilege; + } catch (const std::length_error &e) { + LOGE(e.what()); + return CYNARA_API_INVALID_PARAM; + } - try { - int ret = p_cynara_admin->impl->adminCheck(start_bucket, recursive != 0, - Cynara::PolicyKey(client, user, privilege), - policyResult); + int ret = p_cynara_admin->impl->adminCheck(startBucket, recursive != 0, + Cynara::PolicyKey(clientStr, userStr, + privilegeStr), policyResult); if (ret != CYNARA_API_SUCCESS) return ret; - } catch (const std::bad_alloc &ex) { - return CYNARA_API_OUT_OF_MEMORY; - } catch (const std::length_error &ex) { - return CYNARA_API_INVALID_PARAM; - } - char *str = nullptr; - if (!policyResult.metadata().empty()) { - str = strdup(policyResult.metadata().c_str()); - if (!str) - return CYNARA_API_OUT_OF_MEMORY; - } - *result = static_cast(policyResult.policyType()); - *result_extra = str; + char *str = nullptr; + if (!policyResult.metadata().empty()) { + str = strdup(policyResult.metadata().c_str()); + if (!str) + return CYNARA_API_OUT_OF_MEMORY; + } + *result = static_cast(policyResult.policyType()); + *result_extra = str; - return CYNARA_API_SUCCESS; + return CYNARA_API_SUCCESS; + }); } diff --git a/src/admin/logic/Logic.cpp b/src/admin/logic/Logic.cpp index 683a2cf..72c40bf 100644 --- a/src/admin/logic/Logic.cpp +++ b/src/admin/logic/Logic.cpp @@ -62,53 +62,45 @@ bool Logic::ensureConnection(void) { template int Logic::askCynaraAndInterpreteCodeResponse(Args... args) { - try { - if (!ensureConnection()) { - LOGE("Cannot connect to cynara. Service not available."); - return CYNARA_API_SERVICE_NOT_AVAILABLE; - } + if (!ensureConnection()) { + LOGE("Cannot connect to cynara. Service not available."); + return CYNARA_API_SERVICE_NOT_AVAILABLE; + } - ProtocolFrameSequenceNumber sequenceNumber = generateSequenceNumber(); + ProtocolFrameSequenceNumber sequenceNumber = generateSequenceNumber(); - //Ask cynara service - CodeResponsePtr codeResponse; + //Ask cynara service + CodeResponsePtr codeResponse; - RequestPtr request = std::make_shared(args..., sequenceNumber); - ResponsePtr response; - while (!(response = m_socketClient->askCynaraServer(request))) { - if (!m_socketClient->connect()) - return CYNARA_API_SERVICE_NOT_AVAILABLE; - } + RequestPtr request = std::make_shared(args..., sequenceNumber); + ResponsePtr response; + while (!(response = m_socketClient->askCynaraServer(request))) { + if (!m_socketClient->connect()) + return CYNARA_API_SERVICE_NOT_AVAILABLE; + } - codeResponse = std::dynamic_pointer_cast(response); - if (!codeResponse) { - LOGC("Critical error. Casting Response to CodeResponse failed."); - return CYNARA_API_UNKNOWN_ERROR; - } - - LOGD("codeResponse: code [%" PRIu16 "]", codeResponse->m_code); - switch (codeResponse->m_code) { - case CodeResponse::Code::OK: - LOGI("Policies set successfully."); - return CYNARA_API_SUCCESS; - case CodeResponse::Code::NOT_ALLOWED: - LOGE("Cynara service answered: Operation not allowed."); - return CYNARA_API_OPERATION_NOT_ALLOWED; - case CodeResponse::Code::NO_BUCKET: - LOGE("Trying to use unexisting bucket."); - return CYNARA_API_BUCKET_NOT_FOUND; - default: - LOGE("Unexpected response code from server: [%d]", - static_cast(codeResponse->m_code)); - return CYNARA_API_UNKNOWN_ERROR; - } - } catch (const std::bad_alloc &ex) { - LOGE("Cynara admin client out of memory."); - return CYNARA_API_OUT_OF_MEMORY; - } catch (const std::exception &ex) { - LOGE("Unexpected client error: <%s>", ex.what()); + codeResponse = std::dynamic_pointer_cast(response); + if (!codeResponse) { + LOGC("Critical error. Casting Response to CodeResponse failed."); return CYNARA_API_UNKNOWN_ERROR; } + + LOGD("codeResponse: code [%" PRIu16 "]", codeResponse->m_code); + switch (codeResponse->m_code) { + case CodeResponse::Code::OK: + LOGI("Policies set successfully."); + return CYNARA_API_SUCCESS; + case CodeResponse::Code::NOT_ALLOWED: + LOGE("Cynara service answered: Operation not allowed."); + return CYNARA_API_OPERATION_NOT_ALLOWED; + case CodeResponse::Code::NO_BUCKET: + LOGE("Trying to use unexisting bucket."); + return CYNARA_API_BUCKET_NOT_FOUND; + default: + LOGE("Unexpected response code from server: [%d]", + static_cast(codeResponse->m_code)); + return CYNARA_API_UNKNOWN_ERROR; + } } int Logic::setPolicies(const std::map> &insertOrUpdate, @@ -127,47 +119,36 @@ int Logic::removeBucket(const PolicyBucketId &bucket) { int Logic::adminCheck(const PolicyBucketId &startBucket, bool recursive, const PolicyKey &key, PolicyResult &result) { - try { - if (!ensureConnection()) { - LOGE("Cannot connect to cynara. Service not available."); - return CYNARA_API_SERVICE_NOT_AVAILABLE; - } - - ProtocolFrameSequenceNumber sequenceNumber = generateSequenceNumber(); + if (!ensureConnection()) { + LOGE("Cannot connect to cynara. Service not available."); + return CYNARA_API_SERVICE_NOT_AVAILABLE; + } - //Ask cynara service - CheckResponsePtr checkResponse; + ProtocolFrameSequenceNumber sequenceNumber = generateSequenceNumber(); - RequestPtr request = std::make_shared(key, startBucket, recursive, - sequenceNumber); - ResponsePtr response; - while (!(response = m_socketClient->askCynaraServer(request))) { - if (!m_socketClient->connect()) - return CYNARA_API_SERVICE_NOT_AVAILABLE; - } + //Ask cynara service + CheckResponsePtr checkResponse; - checkResponse = std::dynamic_pointer_cast(response); - if (!checkResponse) { - LOGC("Casting Response to CheckResponse failed."); - return CYNARA_API_UNKNOWN_ERROR; - } - - LOGD("checkResponse: policyType [%" PRIu16 "], metadata <%s>", - checkResponse->m_resultRef.policyType(), - checkResponse->m_resultRef.metadata().c_str()); + RequestPtr request = std::make_shared(key, startBucket, recursive, + sequenceNumber); + ResponsePtr response; + while (!(response = m_socketClient->askCynaraServer(request))) { + if (!m_socketClient->connect()) + return CYNARA_API_SERVICE_NOT_AVAILABLE; + } - result = checkResponse->m_resultRef; - return CYNARA_API_SUCCESS; - } catch (const UnexpectedErrorException &ex) { - LOGE(ex.what()); - return CYNARA_API_UNKNOWN_ERROR; - } catch (const std::bad_alloc &ex) { - LOGE("Cynara admin client out of memory."); - return CYNARA_API_OUT_OF_MEMORY; - } catch (const std::exception &ex) { - LOGE("Unexpected client error: <%s>", ex.what()); + checkResponse = std::dynamic_pointer_cast(response); + if (!checkResponse) { + LOGC("Casting Response to CheckResponse failed."); return CYNARA_API_UNKNOWN_ERROR; } + + LOGD("checkResponse: policyType [%" PRIu16 "], metadata <%s>", + checkResponse->m_resultRef.policyType(), + checkResponse->m_resultRef.metadata().c_str()); + + result = checkResponse->m_resultRef; + return CYNARA_API_SUCCESS; } } // namespace Cynara -- 2.7.4 From b140c8834b3a514aa6abe0b320bd3e51042a84d5 Mon Sep 17 00:00:00 2001 From: Jacek Bukarewicz Date: Wed, 15 Oct 2014 10:21:00 +0200 Subject: [PATCH 16/16] Set build_type default value in a different way Apparently gbs couldn't parse previous construct properly and installed debug libraries regardless of build_type. Change-Id: I84c6456efc692da9f1bec94b071d8107a540f3d8 Signed-off-by: Jacek Bukarewicz --- packaging/cynara.spec | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packaging/cynara.spec b/packaging/cynara.spec index e8d0bc8..7f02901 100644 --- a/packaging/cynara.spec +++ b/packaging/cynara.spec @@ -33,7 +33,9 @@ BuildRequires: pkgconfig(libsystemd-journal) %global state_path %{_localstatedir}/%{name}/ %global tests_dir %{_datarootdir}/%{name}/tests -%global build_type %{?build_type:%build_type}%{!?build_type:RELEASE} +%if !%{defined build_type} +%define build_type RELEASE +%endif %if %{?build_type} == "DEBUG" -- 2.7.4