From 5e5199c24bd0d41cf8694926d0f4fd071bd790b1 Mon Sep 17 00:00:00 2001 From: Aleksander Zdyb Date: Fri, 16 Jan 2015 10:50:55 +0100 Subject: [PATCH 01/16] Implement --list-policies-descriptions option Change-Id: I5be0664a33191863d7a38ab1b5e42004a77b912e --- src/cyad/AdminApiWrapper.cpp | 5 ++ src/cyad/AdminApiWrapper.h | 2 + src/cyad/BaseAdminApiWrapper.h | 2 + src/cyad/CommandlineParser/CmdlineOpts.cpp | 8 +++ src/cyad/CommandlineParser/CmdlineOpts.h | 1 + src/cyad/CommandlineParser/CyadCommand.cpp | 4 ++ src/cyad/CommandlineParser/CyadCommand.h | 8 +++ .../CommandlineParser/CyadCommandlineParser.cpp | 6 ++- src/cyad/CommandsDispatcher.cpp | 28 ++++++++++ src/cyad/CommandsDispatcher.h | 1 + test/cyad/FakeAdminApiWrapper.h | 3 ++ test/cyad/commandline.cpp | 9 ++++ test/cyad/commandline_options.cpp | 3 +- test/cyad/commands_dispatcher.cpp | 60 ++++++++++++++++++++++ 14 files changed, 138 insertions(+), 2 deletions(-) diff --git a/src/cyad/AdminApiWrapper.cpp b/src/cyad/AdminApiWrapper.cpp index 6224a1b..9cca101 100644 --- a/src/cyad/AdminApiWrapper.cpp +++ b/src/cyad/AdminApiWrapper.cpp @@ -69,4 +69,9 @@ int AdminApiWrapper::cynara_admin_list_policies(struct cynara_admin *p_cynara_ad return ::cynara_admin_list_policies(p_cynara_admin, bucket, client, user, privilege, policies); } +int AdminApiWrapper::cynara_admin_list_policies_descriptions(struct cynara_admin *p_cynara_admin, + struct cynara_admin_policy_descr ***descriptions) { + return ::cynara_admin_list_policies_descriptions(p_cynara_admin, descriptions); +} + } /* namespace Cynara */ diff --git a/src/cyad/AdminApiWrapper.h b/src/cyad/AdminApiWrapper.h index 19663dc..62c076a 100644 --- a/src/cyad/AdminApiWrapper.h +++ b/src/cyad/AdminApiWrapper.h @@ -52,6 +52,8 @@ public: virtual int cynara_admin_erase(struct cynara_admin *p_cynara_admin, const char *start_bucket, int recursive, const char *client, const char *user, const char *privilege); + virtual int cynara_admin_list_policies_descriptions(struct cynara_admin *p_cynara_admin, + struct cynara_admin_policy_descr ***descriptions); }; } /* namespace Cynara */ diff --git a/src/cyad/BaseAdminApiWrapper.h b/src/cyad/BaseAdminApiWrapper.h index 41710f9..dff1a7c 100644 --- a/src/cyad/BaseAdminApiWrapper.h +++ b/src/cyad/BaseAdminApiWrapper.h @@ -48,6 +48,8 @@ public: virtual int cynara_admin_erase(struct cynara_admin *p_cynara_admin, const char *start_bucket, int recursive, const char *client, const char *user, const char *privilege) = 0; + virtual int cynara_admin_list_policies_descriptions(struct cynara_admin *p_cynara_admin, + struct cynara_admin_policy_descr ***descriptions) = 0; }; } /* namespace Cynara */ diff --git a/src/cyad/CommandlineParser/CmdlineOpts.cpp b/src/cyad/CommandlineParser/CmdlineOpts.cpp index a356287..5d1246f 100644 --- a/src/cyad/CommandlineParser/CmdlineOpts.cpp +++ b/src/cyad/CommandlineParser/CmdlineOpts.cpp @@ -48,6 +48,9 @@ const OptionsMap commandlineOptions = { { CmdlineOpt::ListPolicies, { "list-policies", CmdlineOpt::ListPolicies, "list-policies=", "name of bucket to erase policies from", OptHasArg::RequiredArgument } }, + { CmdlineOpt::ListPoliciesDesc, + { "list-policies-descriptions", CmdlineOpt::ListPoliciesDesc, "list-policies-descriptions", + "", OptHasArg::NoArgument } }, { CmdlineOpt::Type, { "type", CmdlineOpt::Type, "type=", @@ -172,6 +175,11 @@ std::string makeHelp(void) { helpStr << opt(CmdlineOpt::Privilege) << std::endl; helpStr << std::endl; + helpStr << head("Policies descriptions list options", CmdlineOpt::ListPoliciesDesc) + << std::endl; + helpStr << opt(CmdlineOpt::ListPoliciesDesc) << std::endl; + helpStr << std::endl; + helpStr << head("Help options", CmdlineOpt::Help) << std::endl; helpStr << opt(CmdlineOpt::Help); diff --git a/src/cyad/CommandlineParser/CmdlineOpts.h b/src/cyad/CommandlineParser/CmdlineOpts.h index 8c357f4..6053bf5 100644 --- a/src/cyad/CommandlineParser/CmdlineOpts.h +++ b/src/cyad/CommandlineParser/CmdlineOpts.h @@ -40,6 +40,7 @@ enum CmdlineOpt { Erase = 'e', Check = 'a', ListPolicies = 'l', + ListPoliciesDesc = 'g', Type = 't', Metadata = 'm', diff --git a/src/cyad/CommandlineParser/CyadCommand.cpp b/src/cyad/CommandlineParser/CyadCommand.cpp index 6d5f0ca..cdd63d6 100644 --- a/src/cyad/CommandlineParser/CyadCommand.cpp +++ b/src/cyad/CommandlineParser/CyadCommand.cpp @@ -66,4 +66,8 @@ int ListPoliciesCyadCommand::run(CommandsDispatcher &dispatcher) { return dispatcher.execute(*this); } +int ListPoliciesDescCyadCommand::run(CommandsDispatcher &dispatcher) { + return dispatcher.execute(*this); +} + } /* namespace Cynara */ diff --git a/src/cyad/CommandlineParser/CyadCommand.h b/src/cyad/CommandlineParser/CyadCommand.h index 9973b7c..2133e2b 100644 --- a/src/cyad/CommandlineParser/CyadCommand.h +++ b/src/cyad/CommandlineParser/CyadCommand.h @@ -229,6 +229,14 @@ private: PolicyKey m_policyKey; }; +class ListPoliciesDescCyadCommand : public CyadCommand { +public: + ListPoliciesDescCyadCommand() {} + virtual ~ListPoliciesDescCyadCommand() {} + + virtual int run(CommandsDispatcher &dispatcher); +}; + } /* namespace Cynara */ #endif /* SRC_CYAD_COMMANDLINEPARSER_CYADCOMMAND_H_ */ diff --git a/src/cyad/CommandlineParser/CyadCommandlineParser.cpp b/src/cyad/CommandlineParser/CyadCommandlineParser.cpp index 0ef406e..a775be1 100644 --- a/src/cyad/CommandlineParser/CyadCommandlineParser.cpp +++ b/src/cyad/CommandlineParser/CyadCommandlineParser.cpp @@ -59,7 +59,8 @@ std::shared_ptr CyadCommandlineParser::parseMain(void) { CmdlineOpt::SetPolicy, CmdlineOpt::Erase, CmdlineOpt::Check, - CmdlineOpt::ListPolicies + CmdlineOpt::ListPolicies, + CmdlineOpt::ListPoliciesDesc }; const auto longOpts = Opts::makeLongOptions(opts); @@ -90,6 +91,9 @@ std::shared_ptr CyadCommandlineParser::parseMain(void) { case CmdlineOpt::ListPolicies: return parseListPolicies(optarg); + case CmdlineOpt::ListPoliciesDesc: + return std::make_shared(); + case '?': // Unknown option return sharedError(Err::unknownOption()); diff --git a/src/cyad/CommandsDispatcher.cpp b/src/cyad/CommandsDispatcher.cpp index 2be90c5..0b8f0c0 100644 --- a/src/cyad/CommandsDispatcher.cpp +++ b/src/cyad/CommandsDispatcher.cpp @@ -185,4 +185,32 @@ int CommandsDispatcher::execute(ListPoliciesCyadCommand &command) { return ret; } +int CommandsDispatcher::execute(ListPoliciesDescCyadCommand &) { + // Initialization is needed to make compiler happy (-Werror=maybe-uninitialized, FTW) + cynara_admin_policy_descr **descs = nullptr; + + auto ret = m_adminApiWrapper.cynara_admin_list_policies_descriptions(m_cynaraAdmin, &descs); + + auto printPolicyDesc = [this] (cynara_admin_policy_descr *pd) { + m_io.cout() << pd->result << ";" + << pd->name << std::endl; + }; + + auto freePolicyDesc = [] (cynara_admin_policy_descr *pd) { + free(pd->name); + free(pd); + }; + + if (ret == CYNARA_API_SUCCESS) { + for (int i = 0; descs[i]; ++i) { + auto p = descs[i]; + printPolicyDesc(p); + freePolicyDesc(p); + } + free(descs); + } + + return ret; +} + } /* namespace Cynara */ diff --git a/src/cyad/CommandsDispatcher.h b/src/cyad/CommandsDispatcher.h index 396bbe6..b8b7f29 100644 --- a/src/cyad/CommandsDispatcher.h +++ b/src/cyad/CommandsDispatcher.h @@ -47,6 +47,7 @@ public: virtual int execute(EraseCyadCommand &); virtual int execute(CheckCyadCommand &); virtual int execute(ListPoliciesCyadCommand &); + virtual int execute(ListPoliciesDescCyadCommand &); private: BaseDispatcherIO &m_io; diff --git a/test/cyad/FakeAdminApiWrapper.h b/test/cyad/FakeAdminApiWrapper.h index 3dc3d4b..528b57d 100644 --- a/test/cyad/FakeAdminApiWrapper.h +++ b/test/cyad/FakeAdminApiWrapper.h @@ -53,6 +53,9 @@ public: MOCK_METHOD6(cynara_admin_erase, int(struct cynara_admin *p_cynara_admin, const char *start_bucket, int recursive, const char *client, const char *user, const char *privilege)); + MOCK_METHOD2(cynara_admin_list_policies_descriptions, + int(struct cynara_admin *p_cynara_admin, + struct cynara_admin_policy_descr ***descriptions)); }; #endif /* TEST_CYAD_FAKEADMINAPIWRAPPER_H_ */ diff --git a/test/cyad/commandline.cpp b/test/cyad/commandline.cpp index af503eb..b935685 100644 --- a/test/cyad/commandline.cpp +++ b/test/cyad/commandline.cpp @@ -242,3 +242,12 @@ TEST_F(CyadCommandlineTest, listPoliciesOtherBucket) { ASSERT_EQ("some-bucket", result->bucketId()); ASSERT_EQ(Cynara::PolicyKey("c", "u", "p"), result->policyKey()); } + +TEST_F(CyadCommandlineTest, listPoliciesDesc) { + prepare_argv({ "./cyad", "--list-policies-descriptions" }); + Cynara::CyadCommandlineParser parser(this->argc(), this->argv()); + + auto result = std::dynamic_pointer_cast( + parser.parseMain()); + ASSERT_NE(nullptr, result); +} diff --git a/test/cyad/commandline_options.cpp b/test/cyad/commandline_options.cpp index 0dca2f5..59dd0b8 100644 --- a/test/cyad/commandline_options.cpp +++ b/test/cyad/commandline_options.cpp @@ -30,7 +30,7 @@ TEST(CommandlineOptions, allOptionsPresent) { using Cynara::CmdlineOpts::commandlineOptions; // A cheap trick to make sure this test is updated, when new options are added - ASSERT_EQ(15, commandlineOptions.size()); + ASSERT_EQ(16, commandlineOptions.size()); ASSERT_NO_THROW(commandlineOptions.at(CmdlineOpt::SetBucket)); ASSERT_NO_THROW(commandlineOptions.at(CmdlineOpt::DeleteBucket)); @@ -38,6 +38,7 @@ TEST(CommandlineOptions, allOptionsPresent) { ASSERT_NO_THROW(commandlineOptions.at(CmdlineOpt::Erase)); ASSERT_NO_THROW(commandlineOptions.at(CmdlineOpt::Check)); ASSERT_NO_THROW(commandlineOptions.at(CmdlineOpt::ListPolicies)); + ASSERT_NO_THROW(commandlineOptions.at(CmdlineOpt::ListPoliciesDesc)); ASSERT_NO_THROW(commandlineOptions.at(CmdlineOpt::Type)); ASSERT_NO_THROW(commandlineOptions.at(CmdlineOpt::Metadata)); diff --git a/test/cyad/commands_dispatcher.cpp b/test/cyad/commands_dispatcher.cpp index e962312..471997e 100644 --- a/test/cyad/commands_dispatcher.cpp +++ b/test/cyad/commands_dispatcher.cpp @@ -395,3 +395,63 @@ TEST_F(CyadCommandlineDispatcherTest, listPoliciesTwo) { ASSERT_EQ("bucket;cli;usr;privilege;0;metadata\nbucket-2;cli;usr;privilege;65535;\n", m_io.coutRaw().str()); } + +TEST_F(CyadCommandlineDispatcherTest, listPoliciesDescNone) { + using ::testing::_; + using ::testing::DoAll; + using ::testing::NotNull; + using ::testing::Return; + using ::testing::SetArgPointee; + + FakeAdminApiWrapper adminApi; + + EXPECT_CALL(adminApi, cynara_admin_initialize(_)).WillOnce(Return(CYNARA_API_SUCCESS)); + EXPECT_CALL(adminApi, cynara_admin_finish(_)).WillOnce(Return(CYNARA_API_SUCCESS)); + + Cynara::CommandsDispatcher dispatcher(m_io, adminApi); + + Cynara::ListPoliciesDescCyadCommand command; + + auto descs = static_cast( + calloc(1, sizeof(cynara_admin_policy_descr *))); + descs[0] = nullptr; + + EXPECT_CALL(adminApi, cynara_admin_list_policies_descriptions(_, NotNull())) + .WillOnce(DoAll(SetArgPointee<1>(descs), Return(CYNARA_API_SUCCESS))); + + dispatcher.execute(command); + + ASSERT_EQ("", m_io.coutRaw().str()); +} + +TEST_F(CyadCommandlineDispatcherTest, listPoliciesDescOne) { + using ::testing::_; + using ::testing::DoAll; + using ::testing::NotNull; + using ::testing::Return; + using ::testing::SetArgPointee; + + FakeAdminApiWrapper adminApi; + + EXPECT_CALL(adminApi, cynara_admin_initialize(_)).WillOnce(Return(CYNARA_API_SUCCESS)); + EXPECT_CALL(adminApi, cynara_admin_finish(_)).WillOnce(Return(CYNARA_API_SUCCESS)); + + Cynara::CommandsDispatcher dispatcher(m_io, adminApi); + + Cynara::ListPoliciesDescCyadCommand command; + + auto descs = static_cast( + calloc(2, sizeof(cynara_admin_policy_descr *))); + + descs[0] = static_cast(malloc(sizeof(cynara_admin_policy_descr))); + descs[0]->result = 42; + descs[0]->name = strdup("adams"); + descs[1] = nullptr; + + EXPECT_CALL(adminApi, cynara_admin_list_policies_descriptions(_, NotNull())) + .WillOnce(DoAll(SetArgPointee<1>(descs), Return(CYNARA_API_SUCCESS))); + + dispatcher.execute(command); + + ASSERT_EQ("42;adams\n", m_io.coutRaw().str()); +} -- 2.7.4 From 79b72aab9abb2ed15eafbacda5028f58a5740de5 Mon Sep 17 00:00:00 2001 From: Lukasz Wojciechowski Date: Fri, 16 Jan 2015 13:21:46 +0100 Subject: [PATCH 02/16] Fix missing predefined policies description in offline Predefined policies description were returned only in online admin mode. Offline admin mode returned just policy types provided by plugins. Now both offline and online mode return predefined and plugin provided policy types. Change-Id: I890062638a8d2d54dc67edd4a883cfccea5f3905 --- src/admin/logic/OfflineLogic.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/admin/logic/OfflineLogic.cpp b/src/admin/logic/OfflineLogic.cpp index f421f2a..2a7bc89 100644 --- a/src/admin/logic/OfflineLogic.cpp +++ b/src/admin/logic/OfflineLogic.cpp @@ -31,6 +31,7 @@ #include #include #include +#include #include #include @@ -148,6 +149,8 @@ int OfflineLogic::adminCheck(const PolicyBucketId &startBucket, bool recursive, int OfflineLogic::listDescriptions(std::vector &descriptions) { acquirePlugins(); descriptions = m_pluginManager->getPolicyDescriptions(); + descriptions.insert(descriptions.begin(), predefinedPolicyDescr.begin(), + predefinedPolicyDescr.end()); return CYNARA_API_SUCCESS; } -- 2.7.4 From 6c079ffeed2e4dc0c8cec00e5a7da67f3c5e2564 Mon Sep 17 00:00:00 2001 From: Lukasz Wojciechowski Date: Fri, 16 Jan 2015 11:32:46 +0100 Subject: [PATCH 03/16] Release 0.5.0 Change-Id: Iaf6d9ba8649a23477ba08dc50ccac2044ffa48b6 --- CMakeLists.txt | 4 ++-- changelog | 32 +++++++++++++++++++++++++++++++- packaging/cynara.spec | 2 +- src/admin/CMakeLists.txt | 4 ++-- src/client-common/CMakeLists.txt | 4 ++-- src/client/CMakeLists.txt | 4 ++-- src/common/CMakeLists.txt | 4 ++-- src/helpers/creds-commons/CMakeLists.txt | 4 ++-- src/helpers/creds-dbus/CMakeLists.txt | 4 ++-- src/helpers/creds-socket/CMakeLists.txt | 4 ++-- src/helpers/session/CMakeLists.txt | 4 ++-- 11 files changed, 50 insertions(+), 20 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 048d098..b6db3e7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved +# Copyright (c) 2014-2015 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. @@ -21,7 +21,7 @@ CMAKE_MINIMUM_REQUIRED(VERSION 2.8.3) PROJECT("cynara") -set(CYNARA_VERSION 0.4.2) +set(CYNARA_VERSION 0.5.0) ############################# cmake packages ################################## diff --git a/changelog b/changelog index 25fb0f5..10a0dc7 100644 --- a/changelog +++ b/changelog @@ -1,4 +1,34 @@ -############################## +############################### + +Release: 0.5.0 +Date: 2015.01.16 +Name: Cyad, offline-admin, erase, listPolicies, listDescriptions + +Libraries: +libcynara-admin.0.5.0 +libcynara-agent.0.5.0 +libcynara-client-async.0.5.0 +libcynara-client-commmons.0.5.0 +libcynara-client.0.5.0 +libcynara-commons.0.5.0 +libcynara-creds-commons.0.5.0 +libcynara-creds-dbus.0.5.0 +libcynara-creds-socket.0.5.0 +libcynara-session.0.5.0 +libcynara-storage.0.5.0 + +Executables: +cyad +cynara + +Description: +Shell command admin tool - cyad +Admin operational in both offline (no cynara service running) and online modes +New admin API functions: erase, listPolicies, listPolicyDescriptions +Change in API for plugins (policy descriptions) +Some bug fixes + +############################# Release: 0.4.2 Date: 2014.11.18 diff --git a/packaging/cynara.spec b/packaging/cynara.spec index 2d5a620..7076933 100644 --- a/packaging/cynara.spec +++ b/packaging/cynara.spec @@ -1,6 +1,6 @@ Name: cynara Summary: Cynara service with client libraries -Version: 0.4.2 +Version: 0.5.0 Release: 1 Group: Security/Application Privilege License: Apache-2.0 diff --git a/src/admin/CMakeLists.txt b/src/admin/CMakeLists.txt index 3cbff78..dcb2419 100644 --- a/src/admin/CMakeLists.txt +++ b/src/admin/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved +# Copyright (c) 2014-2015 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. @@ -17,7 +17,7 @@ # SET(LIB_CYNARA_ADMIN_VERSION_MAJOR 0) -SET(LIB_CYNARA_ADMIN_VERSION ${LIB_CYNARA_ADMIN_VERSION_MAJOR}.4.2) +SET(LIB_CYNARA_ADMIN_VERSION ${LIB_CYNARA_ADMIN_VERSION_MAJOR}.5.0) SET(CYNARA_LIB_CYNARA_ADMIN_PATH ${CYNARA_PATH}/admin) diff --git a/src/client-common/CMakeLists.txt b/src/client-common/CMakeLists.txt index 2c60ca9..6629aec 100644 --- a/src/client-common/CMakeLists.txt +++ b/src/client-common/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved +# Copyright (c) 2014-2015 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. @@ -17,7 +17,7 @@ # SET(LIB_CYNARA_CLIENT_COMMON_VERSION_MAJOR 0) -SET(LIB_CYNARA_CLIENT_COMMON_VERSION ${LIB_CYNARA_CLIENT_COMMON_VERSION_MAJOR}.4.2) +SET(LIB_CYNARA_CLIENT_COMMON_VERSION ${LIB_CYNARA_CLIENT_COMMON_VERSION_MAJOR}.5.0) SET(LIB_CYNARA_COMMON_PATH ${CYNARA_PATH}/client-common) diff --git a/src/client/CMakeLists.txt b/src/client/CMakeLists.txt index 2d5c0a2..059fac2 100644 --- a/src/client/CMakeLists.txt +++ b/src/client/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved +# Copyright (c) 2014-2015 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. @@ -18,7 +18,7 @@ # SET(LIB_CYNARA_VERSION_MAJOR 0) -SET(LIB_CYNARA_VERSION ${LIB_CYNARA_VERSION_MAJOR}.4.2) +SET(LIB_CYNARA_VERSION ${LIB_CYNARA_VERSION_MAJOR}.5.0) SET(LIB_CYNARA_PATH ${CYNARA_PATH}/client) diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt index f3670ad..96b747c 100644 --- a/src/common/CMakeLists.txt +++ b/src/common/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved +# Copyright (c) 2014-2015 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. @@ -17,7 +17,7 @@ # SET(CYNARA_COMMON_VERSION_MAJOR 0) -SET(CYNARA_COMMON_VERSION ${CYNARA_COMMON_VERSION_MAJOR}.4.2) +SET(CYNARA_COMMON_VERSION ${CYNARA_COMMON_VERSION_MAJOR}.5.0) SET(COMMON_PATH ${CYNARA_PATH}/common) diff --git a/src/helpers/creds-commons/CMakeLists.txt b/src/helpers/creds-commons/CMakeLists.txt index 9ff7aa7..961219b 100644 --- a/src/helpers/creds-commons/CMakeLists.txt +++ b/src/helpers/creds-commons/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved +# Copyright (c) 2014-2015 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. @@ -19,7 +19,7 @@ # SET(LIB_CREDS_COMMONS_VERSION_MAJOR 0) -SET(LIB_CREDS_COMMONS_VERSION ${LIB_CREDS_COMMONS_VERSION_MAJOR}.4.2) +SET(LIB_CREDS_COMMONS_VERSION ${LIB_CREDS_COMMONS_VERSION_MAJOR}.5.0) SET(LIB_CREDS_COMMONS_PATH ${CYNARA_PATH}/helpers/creds-commons) diff --git a/src/helpers/creds-dbus/CMakeLists.txt b/src/helpers/creds-dbus/CMakeLists.txt index 90f6cbe..4001207 100644 --- a/src/helpers/creds-dbus/CMakeLists.txt +++ b/src/helpers/creds-dbus/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved +# Copyright (c) 2014-2015 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. @@ -19,7 +19,7 @@ # SET(LIB_CREDS_DBUS_VERSION_MAJOR 0) -SET(LIB_CREDS_DBUS_VERSION ${LIB_CREDS_DBUS_VERSION_MAJOR}.4.2) +SET(LIB_CREDS_DBUS_VERSION ${LIB_CREDS_DBUS_VERSION_MAJOR}.5.0) SET(LIB_CREDS_DBUS_PATH ${CYNARA_PATH}/helpers/creds-dbus) diff --git a/src/helpers/creds-socket/CMakeLists.txt b/src/helpers/creds-socket/CMakeLists.txt index 27f9b0c..950561c 100644 --- a/src/helpers/creds-socket/CMakeLists.txt +++ b/src/helpers/creds-socket/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved +# Copyright (c) 2014-2015 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. @@ -19,7 +19,7 @@ # SET(LIB_CREDS_SOCKET_VERSION_MAJOR 0) -SET(LIB_CREDS_SOCKET_VERSION ${LIB_CREDS_SOCKET_VERSION_MAJOR}.4.2) +SET(LIB_CREDS_SOCKET_VERSION ${LIB_CREDS_SOCKET_VERSION_MAJOR}.5.0) SET(LIB_CREDS_SOCKET_PATH ${CYNARA_PATH}/helpers/creds-socket) diff --git a/src/helpers/session/CMakeLists.txt b/src/helpers/session/CMakeLists.txt index b783ebc..7897828 100644 --- a/src/helpers/session/CMakeLists.txt +++ b/src/helpers/session/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved +# Copyright (c) 2014-2015 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. @@ -19,7 +19,7 @@ # SET(LIB_SESSION_VERSION_MAJOR 0) -SET(LIB_SESSION_VERSION ${LIB_SESSION_VERSION_MAJOR}.4.2) +SET(LIB_SESSION_VERSION ${LIB_SESSION_VERSION_MAJOR}.5.0) SET(LIB_SESSION_PATH ${CYNARA_PATH}/helpers/session) -- 2.7.4 From 81ca220b027c93d55f9c7c573e1145c0a03e6f92 Mon Sep 17 00:00:00 2001 From: Radoslaw Bartosiak Date: Wed, 21 Jan 2015 16:12:57 +0100 Subject: [PATCH 04/16] Fix catching exceptions in socket helper functions Cynara socket helpers functions could throw exceptions (GET_CRED macro in cders-socket-inner.cpp used std::to_string()). Fixed it with Cynara::tryCatch(). Change-Id: Ic0db847bc04e9817d1afa86310452147f9678431 Signed-off-by: Radoslaw Bartosiak --- src/helpers/creds-socket/creds-socket-inner.cpp | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/src/helpers/creds-socket/creds-socket-inner.cpp b/src/helpers/creds-socket/creds-socket-inner.cpp index bb4ebcc..8b5143e 100644 --- a/src/helpers/creds-socket/creds-socket-inner.cpp +++ b/src/helpers/creds-socket/creds-socket-inner.cpp @@ -22,14 +22,14 @@ * @brief Implementation of internal libcynara-creds-socket functions */ - -#include +#include +#include #include -#include - #include #include +#include + #include #include "creds-socket-inner.h" @@ -59,16 +59,18 @@ int getClientSmackLabel(int socketFd, char **client) { } #define GET_CRED(SOCK, RESULT, CRED) \ - struct ucred credentials; \ - int ret = getCredentials(SOCK, &credentials); \ - if (ret < 0) \ - return ret; \ + return Cynara::tryCatch([&]() { \ + struct ucred credentials; \ + int ret = getCredentials(SOCK, &credentials); \ + if (ret < 0) \ + return ret; \ \ - *RESULT = strdup(std::to_string(credentials.CRED).c_str()); \ - if (*RESULT == nullptr) \ + *RESULT = strdup(std::to_string(credentials.CRED).c_str()); \ + if (*RESULT == nullptr) \ return CYNARA_API_OUT_OF_MEMORY; \ \ - return CYNARA_API_SUCCESS; \ + return CYNARA_API_SUCCESS; \ + }); int getClientPid(int socketFd, char **client) { GET_CRED(socketFd, client, pid) -- 2.7.4 From 7be683efd4f8ac326228128d871cc7d50796697b Mon Sep 17 00:00:00 2001 From: Zofia Abramowska Date: Tue, 13 Jan 2015 15:24:17 +0100 Subject: [PATCH 05/16] Add API descriptions of cynara-async-configuration calls Introduce three new API calls specific for cynara_async_configuration creation, destruction and cache size setting. Change-Id: I51665a2885c6de3a49ebd30dcfc10a733707673b --- src/include/cynara-client-async.h | 100 +++++++++++++++++++++++++++++++++++++- 1 file changed, 99 insertions(+), 1 deletion(-) diff --git a/src/include/cynara-client-async.h b/src/include/cynara-client-async.h index d9b4d2f..1a165c2 100644 --- a/src/include/cynara-client-async.h +++ b/src/include/cynara-client-async.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014-2015 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. @@ -25,6 +25,7 @@ #ifndef CYNARA_CLIENT_ASYNC_H #define CYNARA_CLIENT_ASYNC_H +#include #include #include @@ -137,6 +138,103 @@ typedef void (*cynara_status_callback) (int old_fd, int new_fd, cynara_async_sta /** * \par Description: + * Initialize cynara_async_configuration. Create structure used in following configuration + * API calls. + * + * \par Purpose: + * For configuration parameter to be used in cynara async initialization function, this API must be + * called before any other cynara async configuration API function. + * It will create cynara_async_configuration structure, an optional parameter of cynara async + * initialization. + * + * \par Typical use case: + * Once before setting parameters of cynara async configuration and passing to + * cynara_async_initialize(). + * + * \par Method of function operation: + * This API initializes inner library structures and in case of success returns pointer + * to created cynara_async_configuration structure. + * + * \par Sync (or) Async: + * This as a synchronous API. + * + * \par Thread-safety: + * This function is NOT thread-safe. If functions from described API are called by multithreaded + * application from different threads, they must be put into protected critical section. + * + * \par Important notes: + * Structure cynara_async_configuration created by cynara_async_configuration_create() call + * should be released with cynara_async_configuration_destroy(). + * Structure cynara_async_configuration should be destroyed after passing it to + * cynara_async_initialize(). + * + * \param[out] pp_conf Placeholder for created cynara_async_configuration structure. + * + * \return CYNARA_API_SUCCESS on success + * or negative error code on error. + */ +int cynara_async_configuration_create(cynara_async_configuration **pp_conf); + + +/** + * \par Description: + * Release cynara_async_configuration structure created with cynara_async_configuration_create(). + * + * \par Purpose: + * This API should be used to clean up after usage of cynara_async_configuration. + * + * \par Typical use case: + * Once cynara_async_configuration is not needed. + * + * \par Method of function operation: + * This API releases inner library structure and destroys cynara_async_configuration structure. + * + * \par Sync (or) Async: + * This is a synchronous API. + * + * \par Thread-safety: + * This function is NOT thread-safe. If functions from described API are called by multithreaded + * application from different threads, they must be put into protected critical section. + * + * \param[in] p_conf cynara_async_configuration structure. If NULL, the call has no effect. + */ +void cynara_async_configuration_destroy(cynara_async_configuration *p_conf); + +/** + * \par Description: + * Set client cache size. + * + * \par Purpose: + * This API is used to change default number of cached responses returned from cynara. + * + * \par Typical use case: + * Once before setting parameters of cynara async configuration and passing to + * cynara_async_initialize(). + * + * \par Method of function operation: + * This API initializes cache with given capacity. + * + * \par Sync (or) Async: + * This as a synchronous API. + * + * \par Thread-safety: + * This function is NOT thread-safe. If functions from described API are called by multithreaded + * application from different threads, they must be put into protected critical section. + * + * \par Important notes: + * After passing cynara_async_configuration to cynara_async_initialize() calling this API will have + * no effect. + * + * \param[in] p_conf cynara_async_configuration structure pointer. + * \param[in] cache_size Cache size to be set. + * + * \return CYNARA_API_SUCCESS on success + * or negative error code on error. + */ +int cynara_async_configuration_set_cache_size(cynara_async_configuration *p_conf, + size_t cache_size); +/** + * \par Description: * Initialize cynara-async-client library with given configuration. Create structure used in * following API calls and register callback and user_status_data for * further cynara async API calls. -- 2.7.4 From 14c6df7e6a6af076a73304186bec686fac2a7ff1 Mon Sep 17 00:00:00 2001 From: Zofia Abramowska Date: Tue, 13 Jan 2015 15:28:46 +0100 Subject: [PATCH 06/16] Add API descriptions of cynara-configuration calls Introduce three new API calls specific for cynara_configuration creation, destruction and cache size setting. Change-Id: Id24175765ebff71b18bfdd4fd94c9a671c0035dc --- src/include/cynara-client.h | 99 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 98 insertions(+), 1 deletion(-) diff --git a/src/include/cynara-client.h b/src/include/cynara-client.h index 571bef1..61a8fcf 100644 --- a/src/include/cynara-client.h +++ b/src/include/cynara-client.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014-2015 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. @@ -23,6 +23,8 @@ #ifndef CYNARA_CLIENT_H #define CYNARA_CLIENT_H +#include + #include #ifdef __cplusplus @@ -32,6 +34,101 @@ extern "C" { typedef struct cynara cynara; typedef struct cynara_configuration cynara_configuration; +/** + * \par Description: + * Initialize cynara_configuration. Create structure used in following configuration + * API calls. + * + * \par Purpose: + * For configuration parameter to be used in cynara initialization function, this API must be + * called before any other cynara configuration API function. + * It will create cynara_configuration structure, an optional parameter of cynara initialization. + * + * \par Typical use case: + * Once before setting parameters of cynara async configuration and passing to + * cynara_initialize(). + * + * \par Method of function operation: + * This API initializes inner library structures and in case of success returns pointer + * to created cynara_configuration structure. + * + * \par Sync (or) Async: + * This as a synchronous API. + * + * \par Thread-safety: + * This function is NOT thread-safe. If functions from described API are called by multithreaded + * application from different threads, they must be put into protected critical section. + * + * \par Important notes: + * Structure cynara_configuration created by cynara_configuration_create() call + * should be released with cynara_configuration_destroy(). + * Structure cynara_configuration should be destroyed after passing it to + * cynara_initialize(). + * + * \param[out] pp_conf Placeholder for created cynara_configuration structure. + * + * \return CYNARA_API_SUCCESS on success + * or negative error code on error. + */ +int cynara_configuration_create(cynara_configuration **pp_conf); + + +/** + * \par Description: + * Release cynara_configuration structure created with cynara_configuration_create(). + * + * \par Purpose: + * This API should be used to clean up after usage of cynara_configuration. + * + * \par Typical use case: + * Once cynara_configuration is not needed. + * + * \par Method of function operation: + * This API releases inner library structure and destroys cynara_configuration structure. + * + * \par Sync (or) Async: + * This is a synchronous API. + * + * \par Thread-safety: + * This function is NOT thread-safe. If functions from described API are called by multithreaded + * application from different threads, they must be put into protected critical section. + * + * \param[in] p_conf cynara_configuration structure. If NULL, the call has no effect. + */ +void cynara_configuration_destroy(cynara_configuration *p_conf); + +/** + * \par Description: + * Set client cache size. + * + * \par Purpose: + * This API is used to change default number of cached responses returned from cynara. + * + * \par Typical use case: + * Once before setting parameters of cynara async configuration and passing to + * cynara_initialize(). + * + * \par Method of function operation: + * This API initializes cache with given capacity. + * + * \par Sync (or) Async: + * This as a synchronous API. + * + * \par Thread-safety: + * This function is NOT thread-safe. If functions from described API are called by multithreaded + * application from different threads, they must be put into protected critical section. + * + * \par Important notes: + * After passing cynara_configuration to cynara_initialize() calling this API will have + * no effect. + * + * \param[in] p_conf cynara_configuration structure pointer. + * \param[in] cache_size Cache size to be set. + * + * \return CYNARA_API_SUCCESS on success + * or negative error code on error. + */ +int cynara_configuration_set_cache_size(cynara_configuration *p_conf, size_t cache_size); /** * \par Description: -- 2.7.4 From a03fdba1b663b62e28ae74108c3d5882d5cd6587 Mon Sep 17 00:00:00 2001 From: Zofia Abramowska Date: Wed, 14 Jan 2015 13:49:46 +0100 Subject: [PATCH 07/16] Add api side implementation of configuration Add implementation of cynara client (both async and sync) configuration initialization, destruction and cache size option setting. Change-Id: I34a81cb7c1578fc9a51944b73478ace3b623b9cc --- src/client-async/api/client-async-api.cpp | 45 ++++++++++++++++++++- src/client-common/configuration/Configuration.h | 53 +++++++++++++++++++++++++ src/client/api/client-api.cpp | 46 ++++++++++++++++++++- 3 files changed, 141 insertions(+), 3 deletions(-) create mode 100644 src/client-common/configuration/Configuration.h diff --git a/src/client-async/api/client-async-api.cpp b/src/client-async/api/client-async-api.cpp index e3e4ef1..82433da 100644 --- a/src/client-async/api/client-async-api.cpp +++ b/src/client-async/api/client-async-api.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014-2015 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. @@ -16,6 +16,7 @@ /** * @file src/client-async/api/client-async-api.cpp * @author Marcin Niesluchowski + * @author Zofia Abramowska * @version 1.0 * @brief Implementation of external libcynara-client-async API */ @@ -27,6 +28,7 @@ #include #include +#include #include #include @@ -41,6 +43,47 @@ struct cynara_async { } }; +struct cynara_async_configuration { + Cynara::Configuration* impl; + + cynara_async_configuration(Cynara::Configuration *_impl) : impl(_impl) {} + + ~cynara_async_configuration() { + delete impl; + } +}; + +CYNARA_API +int cynara_async_configuration_create(cynara_async_configuration **pp_conf) { + if (!pp_conf) + return CYNARA_API_INVALID_PARAM; + + return Cynara::tryCatch([&]() { + Cynara::ConfigurationUniquePtr ptr(new Cynara::Configuration()); + *pp_conf = new cynara_async_configuration(ptr.get()); + ptr.release(); + LOGD("Cynara configuration initialized"); + return CYNARA_API_SUCCESS; + }); +} + +CYNARA_API +void cynara_async_configuration_destroy(cynara_async_configuration *p_conf) { + delete p_conf; +} + +CYNARA_API +int cynara_async_configuration_set_cache_size(cynara_async_configuration *p_conf, + size_t cache_size) { + if (!p_conf || !p_conf->impl) + return CYNARA_API_INVALID_PARAM; + + return Cynara::tryCatch([&]() { + p_conf->impl->setCacheSize(cache_size); + return CYNARA_API_SUCCESS; + }); +} + CYNARA_API int cynara_async_initialize(cynara_async **pp_cynara, const cynara_async_configuration *p_conf UNUSED, diff --git a/src/client-common/configuration/Configuration.h b/src/client-common/configuration/Configuration.h new file mode 100644 index 0000000..1d2e031 --- /dev/null +++ b/src/client-common/configuration/Configuration.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2015 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/client-common/configuration/Configuration.h + * @author Zofia Abramowska + * @version 1.0 + * @brief This file contains client configuration class. + */ + +#ifndef SRC_CLIENT_COMMON_CONFIGURATION_CONFIGURATION_H_ +#define SRC_CLIENT_COMMON_CONFIGURATION_CONFIGURATION_H_ + +#include +#include + +#include + +namespace Cynara { + +class Configuration; +typedef std::unique_ptr ConfigurationUniquePtr; + +class Configuration { +public: + Configuration() : m_cacheSize(CapacityCache::CACHE_DEFAULT_CAPACITY) {}; + + void setCacheSize(std::size_t size) { + m_cacheSize = size; + } + std::size_t getCacheSize(void) const { + return m_cacheSize; + } + ~Configuration() {} +private: + std::size_t m_cacheSize; +}; + +} /* namespace Cynara */ + +#endif /* SRC_CLIENT_COMMON_CONFIGURATION_CONFIGURATION_H_ */ diff --git a/src/client/api/client-api.cpp b/src/client/api/client-api.cpp index 0bd7c91..2b96c74 100644 --- a/src/client/api/client-api.cpp +++ b/src/client/api/client-api.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014-2015 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. @@ -16,6 +16,7 @@ /** * @file src/client/api/client-api.cpp * @author Lukasz Wojciechowski + * @author Zofia Abramowska * @version 1.0 * @brief Implementation of external libcynara-client API */ @@ -27,6 +28,7 @@ #include #include +#include #include #include #include @@ -42,6 +44,46 @@ struct cynara { } }; +struct cynara_configuration { + Cynara::Configuration* impl; + + cynara_configuration(Cynara::Configuration *_impl) : impl(_impl) {} + + ~cynara_configuration() { + delete impl; + } +}; + +CYNARA_API +int cynara_configuration_create(cynara_configuration **pp_conf) { + if (!pp_conf) + return CYNARA_API_INVALID_PARAM; + + return Cynara::tryCatch([&]() { + Cynara::ConfigurationUniquePtr ptr(new Cynara::Configuration()); + *pp_conf = new cynara_configuration(ptr.get()); + ptr.release(); + LOGD("Cynara configuration initialized"); + return CYNARA_API_SUCCESS; + }); +} + +CYNARA_API +void cynara_configuration_destroy(cynara_configuration *p_conf) { + delete p_conf; +} + +CYNARA_API +int cynara_configuration_set_cache_size(cynara_configuration *p_conf, size_t cache_size) { + if (!p_conf || !p_conf->impl) + return CYNARA_API_INVALID_PARAM; + + return Cynara::tryCatch([&]() { + p_conf->impl->setCacheSize(cache_size); + return CYNARA_API_SUCCESS; + }); +} + CYNARA_API int cynara_initialize(cynara **pp_cynara, const cynara_configuration *p_conf UNUSED) { @@ -51,7 +93,7 @@ int cynara_initialize(cynara **pp_cynara, const cynara_configuration *p_conf UNU init_log(); return Cynara::tryCatch([&]() { - *pp_cynara = new cynara(new Cynara::Logic); + *pp_cynara = new cynara(new Cynara::Logic()); LOGD("Cynara client initialized"); -- 2.7.4 From 5eb8725c244da3b859d57dd4c2a92b10e62811ff Mon Sep 17 00:00:00 2001 From: Zofia Abramowska Date: Wed, 14 Jan 2015 14:06:07 +0100 Subject: [PATCH 08/16] Add logic implementation of configuration Add optional configuration parameter to client logic creation. Change-Id: I66091d539b66803e069bcf7c6223017cc5e65e39 --- src/client-async/api/client-async-api.cpp | 8 ++++++-- src/client-async/logic/Logic.cpp | 12 +++++++----- src/client-async/logic/Logic.h | 7 +++++-- src/client/api/client-api.cpp | 7 +++++-- src/client/logic/Logic.cpp | 7 ++++--- src/client/logic/Logic.h | 17 ++++++++++------- 6 files changed, 37 insertions(+), 21 deletions(-) diff --git a/src/client-async/api/client-async-api.cpp b/src/client-async/api/client-async-api.cpp index 82433da..273d5a2 100644 --- a/src/client-async/api/client-async-api.cpp +++ b/src/client-async/api/client-async-api.cpp @@ -86,7 +86,7 @@ int cynara_async_configuration_set_cache_size(cynara_async_configuration *p_conf CYNARA_API int cynara_async_initialize(cynara_async **pp_cynara, - const cynara_async_configuration *p_conf UNUSED, + const cynara_async_configuration *p_conf, cynara_status_callback callback, void *user_status_data) { if (!pp_cynara) return CYNARA_API_INVALID_PARAM; @@ -94,7 +94,11 @@ int cynara_async_initialize(cynara_async **pp_cynara, init_log(); return Cynara::tryCatch([&]() { - *pp_cynara = new cynara_async(new Cynara::Logic(callback, user_status_data)); + if (p_conf && p_conf->impl) + *pp_cynara = new cynara_async(new Cynara::Logic(callback, user_status_data, + *(p_conf->impl))); + else + *pp_cynara = new cynara_async(new Cynara::Logic(callback, user_status_data)); LOGD("Cynara client async initialized"); diff --git a/src/client-async/logic/Logic.cpp b/src/client-async/logic/Logic.cpp index 7504c7e..d5edf79 100644 --- a/src/client-async/logic/Logic.cpp +++ b/src/client-async/logic/Logic.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014-2015 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. @@ -16,6 +16,7 @@ /** * @file src/client-async/logic/Logic.cpp * @author Marcin Niesluchowski + * @author Zofia Abramowska * @version 1.0 * @brief This file contains implementation of Logic class - main * libcynara-client-async class @@ -42,13 +43,14 @@ namespace Cynara { -Logic::Logic(cynara_status_callback callback, void *userStatusData) - : m_statusCallback(callback, userStatusData), m_operationPermitted(true), - m_inAnswerCancelResponseCallback(false) { +Logic::Logic(cynara_status_callback callback, void *userStatusData, const Configuration &conf) + : m_statusCallback(callback, userStatusData), + m_operationPermitted(true), m_inAnswerCancelResponseCallback(false) { + m_socketClient = std::make_shared( PathConfig::SocketPath::client, std::make_shared()); - m_cache = std::make_shared(); + m_cache = std::make_shared(conf.getCacheSize()); auto naiveInterpreter = std::make_shared(); for (auto &descr : naiveInterpreter->getSupportedPolicyDescr()) { m_cache->registerPlugin(descr, naiveInterpreter); diff --git a/src/client-async/logic/Logic.h b/src/client-async/logic/Logic.h index 6d41412..6598375 100644 --- a/src/client-async/logic/Logic.h +++ b/src/client-async/logic/Logic.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014-2015 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. @@ -16,6 +16,7 @@ /** * @file src/client-async/logic/Logic.h * @author Marcin Niesluchowski + * @author Zofia Abramowska * @version 1.0 * @brief This file contains declaration of Logic class - main * libcynara-client-async class @@ -25,6 +26,7 @@ #define SRC_CLIENT_ASYNC_LOGIC_LOGIC_H_ #include +#include #include #include @@ -38,7 +40,8 @@ namespace Cynara { class Logic : public ApiInterface { public: - Logic(cynara_status_callback callback, void *userStatusData); + Logic(cynara_status_callback callback, void *userStatusData, + const Configuration &conf = Configuration()); virtual ~Logic(); virtual int checkCache(const std::string &client, const std::string &session, diff --git a/src/client/api/client-api.cpp b/src/client/api/client-api.cpp index 2b96c74..0aadd85 100644 --- a/src/client/api/client-api.cpp +++ b/src/client/api/client-api.cpp @@ -85,7 +85,7 @@ int cynara_configuration_set_cache_size(cynara_configuration *p_conf, size_t cac } CYNARA_API -int cynara_initialize(cynara **pp_cynara, const cynara_configuration *p_conf UNUSED) +int cynara_initialize(cynara **pp_cynara, const cynara_configuration *p_conf) { if (!pp_cynara) return CYNARA_API_INVALID_PARAM; @@ -93,7 +93,10 @@ int cynara_initialize(cynara **pp_cynara, const cynara_configuration *p_conf UNU init_log(); return Cynara::tryCatch([&]() { - *pp_cynara = new cynara(new Cynara::Logic()); + if (p_conf && p_conf->impl) + *pp_cynara = new cynara(new Cynara::Logic(*(p_conf->impl))); + else + *pp_cynara = new cynara(new Cynara::Logic()); LOGD("Cynara client initialized"); diff --git a/src/client/logic/Logic.cpp b/src/client/logic/Logic.cpp index f8fc543..d34caa6 100644 --- a/src/client/logic/Logic.cpp +++ b/src/client/logic/Logic.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014-2015 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. @@ -16,6 +16,7 @@ /** * @file src/client/logic/Logic.cpp * @author Lukasz Wojciechowski + * @author Zofia Abramowska * @version 1.0 * @brief This file contains implementation of Logic class - main libcynara-client class */ @@ -47,10 +48,10 @@ static ProtocolFrameSequenceNumber generateSequenceNumber(void) { return ++sequenceNumber; } -Logic::Logic() { +Logic::Logic(const Configuration &conf) { m_socket = std::make_shared(PathConfig::SocketPath::client, std::make_shared()); - m_cache = std::make_shared(); + m_cache = std::make_shared(conf.getCacheSize()); auto naiveInterpreter = std::make_shared(); for (auto &descr : naiveInterpreter->getSupportedPolicyDescr()) { m_cache->registerPlugin(descr, naiveInterpreter); diff --git a/src/client/logic/Logic.h b/src/client/logic/Logic.h index c72309c..0199250 100644 --- a/src/client/logic/Logic.h +++ b/src/client/logic/Logic.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014-2015 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. @@ -16,6 +16,7 @@ /** * @file src/client/logic/Logic.h * @author Lukasz Wojciechowski + * @author Zofia Abramowska * @version 1.0 * @brief This file contains definition of Logic class - main libcynara-client class */ @@ -29,12 +30,20 @@ #include #include +#include + #include #include namespace Cynara { class Logic : public ApiInterface { +public: + explicit Logic(const Configuration &conf = Configuration()); + virtual ~Logic() {}; + + virtual int check(const std::string &client, const ClientSession &session, + const std::string &user, const std::string &privilege); private: SocketClientPtr m_socket; PluginCachePtr m_cache; @@ -42,12 +51,6 @@ private: void onDisconnected(void); bool ensureConnection(void); int requestResult(const PolicyKey &key, PolicyResult &result); -public: - Logic(); - virtual ~Logic() {}; - - virtual int check(const std::string &client, const ClientSession &session, - const std::string &user, const std::string &privilege); }; } // namespace Cynara -- 2.7.4 From 02979784159eb45d8d0e5bb81c785f5e8ed544b6 Mon Sep 17 00:00:00 2001 From: Zofia Abramowska Date: Tue, 3 Feb 2015 13:02:26 +0100 Subject: [PATCH 09/16] Fix possible memory leaks in Logic initialization Change for: * client logic * client-async logic * admin logic * agent logic Change-Id: Ie2f4db0324652a24d1e4755a888fff4e713eac8c --- src/admin/api/admin-api.cpp | 4 +++- src/admin/logic/Logic.h | 6 +++++- src/agent/api/agent-api.cpp | 6 ++++-- src/agent/logic/Logic.h | 7 ++++++- src/client-async/api/client-async-api.cpp | 13 ++++++++----- src/client-async/logic/Logic.h | 4 ++++ src/client/api/client-api.cpp | 12 ++++++++---- src/client/logic/Logic.h | 4 ++++ 8 files changed, 42 insertions(+), 14 deletions(-) diff --git a/src/admin/api/admin-api.cpp b/src/admin/api/admin-api.cpp index d15a736..aa33e9e 100644 --- a/src/admin/api/admin-api.cpp +++ b/src/admin/api/admin-api.cpp @@ -67,7 +67,9 @@ int cynara_admin_initialize(struct cynara_admin **pp_cynara_admin) { return Cynara::tryCatch([&]() { try { - *pp_cynara_admin = new cynara_admin(new Cynara::Logic); + Cynara::LogicUniquePtr ptr(new Cynara::Logic()); + *pp_cynara_admin = new cynara_admin(ptr.get()); + ptr.release(); } catch (const Cynara::FileLockAcquiringException &ex) { LOGE("%s", ex.what()); return CYNARA_API_OPERATION_FAILED; diff --git a/src/admin/logic/Logic.h b/src/admin/logic/Logic.h index e9c7774..8c19df9 100644 --- a/src/admin/logic/Logic.h +++ b/src/admin/logic/Logic.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014-2015 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. @@ -25,6 +25,7 @@ #define SRC_ADMIN_LOGIC_LOGIC_H_ #include +#include #include @@ -32,6 +33,9 @@ namespace Cynara { +class Logic; +typedef std::unique_ptr LogicUniquePtr; + class OnlineLogic; class OfflineLogic; diff --git a/src/agent/api/agent-api.cpp b/src/agent/api/agent-api.cpp index fe5eb40..972d9d1 100644 --- a/src/agent/api/agent-api.cpp +++ b/src/agent/api/agent-api.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014-2015 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. @@ -54,7 +54,9 @@ int cynara_agent_initialize(cynara_agent **pp_cynara_agent, const char *p_agent_ init_log(); return Cynara::tryCatch([&]() { - *pp_cynara_agent = new cynara_agent(new Cynara::Logic(p_agent_type)); + Cynara::LogicUniquePtr ptr(new Cynara::Logic(p_agent_type)); + *pp_cynara_agent = new cynara_agent(ptr.get()); + ptr.release(); LOGD("Cynara agent initialized"); diff --git a/src/agent/logic/Logic.h b/src/agent/logic/Logic.h index e8ff3e7..f6c9d42 100644 --- a/src/agent/logic/Logic.h +++ b/src/agent/logic/Logic.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014-2015 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. @@ -23,6 +23,8 @@ #ifndef SRC_AGENT_LOGIC_LOGIC_H_ #define SRC_AGENT_LOGIC_LOGIC_H_ +#include + #include #include @@ -30,6 +32,9 @@ namespace Cynara { +class Logic; +typedef std::unique_ptr LogicUniquePtr; + class Logic : public ApiInterface { public: Logic(const AgentType &agentType); diff --git a/src/client-async/api/client-async-api.cpp b/src/client-async/api/client-async-api.cpp index 273d5a2..38c6fb6 100644 --- a/src/client-async/api/client-async-api.cpp +++ b/src/client-async/api/client-async-api.cpp @@ -94,11 +94,14 @@ int cynara_async_initialize(cynara_async **pp_cynara, init_log(); return Cynara::tryCatch([&]() { - if (p_conf && p_conf->impl) - *pp_cynara = new cynara_async(new Cynara::Logic(callback, user_status_data, - *(p_conf->impl))); - else - *pp_cynara = new cynara_async(new Cynara::Logic(callback, user_status_data)); + Cynara::LogicUniquePtr ptr; + if (p_conf && p_conf->impl) { + ptr.reset(new Cynara::Logic(callback, user_status_data, *(p_conf->impl))); + } else { + ptr.reset(new Cynara::Logic(callback, user_status_data)); + } + *pp_cynara = new cynara_async(ptr.get()); + ptr.release(); LOGD("Cynara client async initialized"); diff --git a/src/client-async/logic/Logic.h b/src/client-async/logic/Logic.h index 6598375..a38d51d 100644 --- a/src/client-async/logic/Logic.h +++ b/src/client-async/logic/Logic.h @@ -25,6 +25,8 @@ #ifndef SRC_CLIENT_ASYNC_LOGIC_LOGIC_H_ #define SRC_CLIENT_ASYNC_LOGIC_LOGIC_H_ +#include + #include #include #include @@ -37,6 +39,8 @@ #include namespace Cynara { +class Logic; +typedef std::unique_ptr LogicUniquePtr; class Logic : public ApiInterface { public: diff --git a/src/client/api/client-api.cpp b/src/client/api/client-api.cpp index 0aadd85..3d3189a 100644 --- a/src/client/api/client-api.cpp +++ b/src/client/api/client-api.cpp @@ -93,10 +93,14 @@ int cynara_initialize(cynara **pp_cynara, const cynara_configuration *p_conf) init_log(); return Cynara::tryCatch([&]() { - if (p_conf && p_conf->impl) - *pp_cynara = new cynara(new Cynara::Logic(*(p_conf->impl))); - else - *pp_cynara = new cynara(new Cynara::Logic()); + Cynara::LogicUniquePtr ptr; + if (p_conf && p_conf->impl) { + ptr.reset(new Cynara::Logic(*(p_conf->impl))); + } else { + ptr.reset(new Cynara::Logic()); + } + *pp_cynara = new cynara(ptr.get()); + ptr.release(); LOGD("Cynara client initialized"); diff --git a/src/client/logic/Logic.h b/src/client/logic/Logic.h index 0199250..5641ca4 100644 --- a/src/client/logic/Logic.h +++ b/src/client/logic/Logic.h @@ -24,6 +24,7 @@ #ifndef SRC_CLIENT_LOGIC_LOGIC_H_ #define SRC_CLIENT_LOGIC_LOGIC_H_ +#include #include #include @@ -37,6 +38,9 @@ namespace Cynara { +class Logic; +typedef std::unique_ptr LogicUniquePtr; + class Logic : public ApiInterface { public: explicit Logic(const Configuration &conf = Configuration()); -- 2.7.4 From f868f4447f698148efb83b566dc5244d4e455f29 Mon Sep 17 00:00:00 2001 From: Zofia Abramowska Date: Tue, 3 Feb 2015 14:13:40 +0100 Subject: [PATCH 10/16] Add new cynara_simple_check synchronous client API New API description put in synchronous client header. New return code added - CYNARA_API_ACCESS_NOT_RESOLVED. Mockup function to Logic added. Change-Id: I57968b3e17cf70c3b294af1faf8158e265ffe2b6 --- src/client/api/ApiInterface.h | 5 ++++- src/client/api/client-api.cpp | 27 ++++++++++++++++++++++ src/client/logic/Logic.cpp | 9 ++++++++ src/client/logic/Logic.h | 2 ++ src/include/cynara-client.h | 52 ++++++++++++++++++++++++++++++++++++++++++- src/include/cynara-error.h | 4 +++- 6 files changed, 96 insertions(+), 3 deletions(-) diff --git a/src/client/api/ApiInterface.h b/src/client/api/ApiInterface.h index 3a724c5..f979a1d 100644 --- a/src/client/api/ApiInterface.h +++ b/src/client/api/ApiInterface.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014-2015 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. @@ -16,6 +16,7 @@ /** * @file src/client/api/ApiInterface.h * @author Lukasz Wojciechowski + * @author Zofia Abramowska * @version 1.0 * @brief This file contains libcynara-client API interface definition. */ @@ -37,6 +38,8 @@ public: virtual int check(const std::string &client, const ClientSession &session, const std::string &user, const std::string &privilege) = 0; + virtual int simpleCheck(const std::string &client, const ClientSession &session, + const std::string &user, const std::string &privilege) = 0; }; } // namespace Cynara diff --git a/src/client/api/client-api.cpp b/src/client/api/client-api.cpp index 3d3189a..3e4134c 100644 --- a/src/client/api/client-api.cpp +++ b/src/client/api/client-api.cpp @@ -143,3 +143,30 @@ int cynara_check(cynara *p_cynara, const char *client, const char *client_sessio return p_cynara->impl->check(clientStr, clientSessionStr, userStr, privilegeStr); }); } + +CYNARA_API +int cynara_simple_check(cynara *p_cynara, const char *client, const char *client_session, + const char *user, const char *privilege) { + if (!p_cynara || !p_cynara->impl) + return CYNARA_API_INVALID_PARAM; + if (!client || !client_session || !user || !privilege) + return CYNARA_API_INVALID_PARAM; + + return Cynara::tryCatch([&]() { + std::string clientStr; + std::string clientSessionStr; + std::string userStr; + std::string privilegeStr; + + try { + clientStr = client; + clientSessionStr = client_session; + userStr = user; + privilegeStr = privilege; + } catch (const std::length_error &e) { + LOGE("%s", e.what()); + return CYNARA_API_INVALID_PARAM; + } + return p_cynara->impl->simpleCheck(clientStr, clientSessionStr, userStr, privilegeStr); + }); +} diff --git a/src/client/logic/Logic.cpp b/src/client/logic/Logic.cpp index d34caa6..c171cce 100644 --- a/src/client/logic/Logic.cpp +++ b/src/client/logic/Logic.cpp @@ -81,6 +81,15 @@ int Logic::check(const std::string &client, const ClientSession &session, const return m_cache->update(session, key, result); } +int Logic::simpleCheck(const std::string &client, const ClientSession &session, + const std::string &user, const std::string &privilege) { + (void)client; + (void)session; + (void)user; + (void)privilege; + return CYNARA_API_ACCESS_NOT_RESOLVED; +} + bool Logic::ensureConnection(void) { if (m_socket->isConnected()) return true; diff --git a/src/client/logic/Logic.h b/src/client/logic/Logic.h index 5641ca4..695f7cd 100644 --- a/src/client/logic/Logic.h +++ b/src/client/logic/Logic.h @@ -48,6 +48,8 @@ public: virtual int check(const std::string &client, const ClientSession &session, const std::string &user, const std::string &privilege); + virtual int simpleCheck(const std::string &client, const ClientSession &session, + const std::string &user, const std::string &privilege); private: SocketClientPtr m_socket; PluginCachePtr m_cache; diff --git a/src/include/cynara-client.h b/src/include/cynara-client.h index 61a8fcf..a617246 100644 --- a/src/include/cynara-client.h +++ b/src/include/cynara-client.h @@ -16,6 +16,7 @@ /** * @file src/include/cynara-client.h * @author Lukasz Wojciechowski + * @author Zofia Abramowska * @version 1.0 * @brief This file contains client APIs of Cynara available with libcynara-client. */ @@ -234,7 +235,56 @@ int cynara_finish(cynara *p_cynara); * or other error code on error. */ int cynara_check(cynara *p_cynara, const char *client, const char *client_session, const char *user, - const char *privilege); + const char *privilege); + +/** + * \par Description: + * Check for (potential) permission to take some action or access a resource. + * + * \par Purpose: + * This API should be used for a quick check if a user running application identified as client + * has access to a given privilege. + * + * \par Typical use case: + * An application may use this API to check, if it has (potential) permission to take some action + * or access resource in future (permissions may rarely change). The typical use would be to disable + * or hide some of functionalities, if they probably could not be used anyways. + * + * \par Method of function operation: + * This function is very similar to cynara_check() with the difference, that in case of answer not + * being one of CYNARA_API_PERMISSION_DENIED or CYNARA_API_PERMISSION_ALLOWED, no external + * application will be consulted. Instead, CYNARA_API_ACCESS_NOT_RESOLVED is returned, meaning, + * that only running full cynara_check() API would yield eventual answer. + * Similarly, like in cynara_check(), argument client_session can be used to distinguish client + * sessions and grant possibility to yield answer from cache. + * + * \par Sync (or) Async: + * This is a synchronous API. + * + * \par Thread-safety: + * This function is NOT thread-safe. If functions from described API are called by multithreaded + * application from different threads, they must be put into mutex protected critical section. + * + * \par Important notes: + * The answer will be taken from Cynara's database without consulting any external applications. + * If the answer cannot be resolved in one of CYNARA_API_PERMISSION_DENIED or + * CYNARA_API_PERMISSION_ALLOWED without communicating with external application the API will return + * CYNARA_API_ACCESS_NOT_RESOLVED. + * Call to cynara_simple_check needs cynara structure to be created first with call to + * cynara_initialize. + * + * \param[in] p_cynara Cynara structure. + * \param[in] client Application or process identifier. + * \param[in] client_session Session of client (connection, launch). + * \param[in] user User running client. + * \param[in] privilege Privilege that is a subject of a check. + * + * \return CYNARA_API_ACCESS_ALLOWED on access allowed, CYNARA_API_ACCESS_DENIED on access denial, + * CYNARA_API_ACCESS_NOT_RESOLVED when decision is not known without usage of external plugins or + * agents or negative error code on error. + */ +int cynara_simple_check(cynara *p_cynara, const char *client, const char *client_session, + const char *user, const char *privilege); #ifdef __cplusplus } diff --git a/src/include/cynara-error.h b/src/include/cynara-error.h index 66d75f0..ac69412 100644 --- a/src/include/cynara-error.h +++ b/src/include/cynara-error.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014-2015 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. @@ -32,6 +32,8 @@ * result codes beginning with negative codes indicate an error. * @{ */ +/*! \brief indicating access that cannot be resolved without further actions*/ +#define CYNARA_API_ACCESS_NOT_RESOLVED 3 /*! \brief indicating access that was checked is allowed */ #define CYNARA_API_ACCESS_ALLOWED 2 -- 2.7.4 From cc65a1523566af45fb9e44c620e38b2fd480a99b Mon Sep 17 00:00:00 2001 From: Zofia Abramowska Date: Tue, 10 Feb 2015 16:21:42 +0100 Subject: [PATCH 11/16] Create request and response types for simple check client API call Create SimpleCheckResponse and SimpleCheckRequest. Change-Id: I75796fb035ac9dfd5ecbe1e8bfc68d37a55ba6f4 --- src/common/CMakeLists.txt | 2 + src/common/protocol/ProtocolOpCode.h | 7 +++- src/common/request/RequestTaker.cpp | 7 +++- src/common/request/RequestTaker.h | 4 +- src/common/request/SimpleCheckRequest.cpp | 34 ++++++++++++++++ src/common/request/SimpleCheckRequest.h | 54 +++++++++++++++++++++++++ src/common/request/pointers.h | 6 ++- src/common/response/ResponseTaker.cpp | 8 +++- src/common/response/ResponseTaker.h | 4 +- src/common/response/SimpleCheckResponse.cpp | 34 ++++++++++++++++ src/common/response/SimpleCheckResponse.h | 63 +++++++++++++++++++++++++++++ src/common/response/pointers.h | 6 ++- 12 files changed, 221 insertions(+), 8 deletions(-) create mode 100644 src/common/request/SimpleCheckRequest.cpp create mode 100644 src/common/request/SimpleCheckRequest.h create mode 100644 src/common/response/SimpleCheckResponse.cpp create mode 100644 src/common/response/SimpleCheckResponse.h diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt index 96b747c..885e325 100644 --- a/src/common/CMakeLists.txt +++ b/src/common/CMakeLists.txt @@ -52,6 +52,7 @@ SET(COMMON_SOURCES ${COMMON_PATH}/request/RequestTaker.cpp ${COMMON_PATH}/request/SetPoliciesRequest.cpp ${COMMON_PATH}/request/SignalRequest.cpp + ${COMMON_PATH}/request/SimpleCheckRequest.cpp ${COMMON_PATH}/response/AdminCheckResponse.cpp ${COMMON_PATH}/response/AgentActionResponse.cpp ${COMMON_PATH}/response/AgentRegisterResponse.cpp @@ -61,6 +62,7 @@ SET(COMMON_SOURCES ${COMMON_PATH}/response/DescriptionListResponse.cpp ${COMMON_PATH}/response/ListResponse.cpp ${COMMON_PATH}/response/ResponseTaker.cpp + ${COMMON_PATH}/response/SimpleCheckResponse.cpp ${COMMON_PATH}/sockets/Socket.cpp ${COMMON_PATH}/sockets/SocketClient.cpp ${COMMON_PATH}/types/PolicyBucket.cpp diff --git a/src/common/protocol/ProtocolOpCode.h b/src/common/protocol/ProtocolOpCode.h index 6aefb10..efd6a63 100644 --- a/src/common/protocol/ProtocolOpCode.h +++ b/src/common/protocol/ProtocolOpCode.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014-2015 Samsung Electronics Co., Ltd All Rights Reserved * * Contact: Lukasz Wojciechowski * @@ -19,6 +19,7 @@ * @file src/common/protocol/ProtocolOpCode.h * @author Adam Malinowski * @author Lukasz Wojciechowski + * @author Zofia Abramowska * @version 1.0 * @brief Declaration of protocol frame operation codes. */ @@ -36,8 +37,10 @@ enum ProtocolOpCode : uint8_t { OpCheckPolicyResponse, OpCancelRequest, OpCancelResponse, + OpSimpleCheckPolicyRequest, + OpSimpleCheckPolicyResponse, - /** Opcodes 4 - 19 are reserved for future use */ + /** Opcodes 6 - 19 are reserved for future use */ /** Admin operations */ OpInsertOrUpdateBucket = 20, diff --git a/src/common/request/RequestTaker.cpp b/src/common/request/RequestTaker.cpp index ea25f16..1f238fd 100644 --- a/src/common/request/RequestTaker.cpp +++ b/src/common/request/RequestTaker.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014-2015 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. @@ -17,6 +17,7 @@ * @file src/common/request/RequestTaker.cpp * @author Lukasz Wojciechowski * @author Adam Malinowski + * @author Zofia Abramowska * @version 1.0 * @brief This file implements RequestTaker class */ @@ -81,6 +82,10 @@ void RequestTaker::execute(RequestContextPtr context UNUSED, SignalRequestPtr re throw NotImplementedException(); } +void RequestTaker::execute(RequestContextPtr context UNUSED, SimpleCheckRequestPtr request UNUSED) { + throw NotImplementedException(); +} + void RequestTaker::contextClosed(RequestContextPtr context UNUSED) { throw NotImplementedException(); } diff --git a/src/common/request/RequestTaker.h b/src/common/request/RequestTaker.h index e6e3f08..a38ab28 100644 --- a/src/common/request/RequestTaker.h +++ b/src/common/request/RequestTaker.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014-2015 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. @@ -16,6 +16,7 @@ /** * @file src/common/request/RequestTaker.h * @author Lukasz Wojciechowski + * @author Zofia Abramowska * @version 1.0 * @brief This file defines RequestTaker class */ @@ -44,6 +45,7 @@ public: virtual void execute(RequestContextPtr context, RemoveBucketRequestPtr request); virtual void execute(RequestContextPtr context, SetPoliciesRequestPtr request); virtual void execute(RequestContextPtr context, SignalRequestPtr request); + virtual void execute(RequestContextPtr context, SimpleCheckRequestPtr request); virtual void contextClosed(RequestContextPtr context); }; diff --git a/src/common/request/SimpleCheckRequest.cpp b/src/common/request/SimpleCheckRequest.cpp new file mode 100644 index 0000000..ecf8e06 --- /dev/null +++ b/src/common/request/SimpleCheckRequest.cpp @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2015 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/SimpleCheckRequest.cpp + * @author Zofia Abramowska + * @version 1.0 + * @brief This file implements simple check request class + */ + +#include + +#include "SimpleCheckRequest.h" + +namespace Cynara { + +void SimpleCheckRequest::execute(RequestPtr self, RequestTakerPtr taker, + RequestContextPtr context) const { + taker->execute(context, std::dynamic_pointer_cast(self)); +} + +} // namespace Cynara diff --git a/src/common/request/SimpleCheckRequest.h b/src/common/request/SimpleCheckRequest.h new file mode 100644 index 0000000..2748b0e --- /dev/null +++ b/src/common/request/SimpleCheckRequest.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2015 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/SimpleCheckRequest.h + * @author Zofia Abramowska + * @version 1.0 + * @brief This file defines simple check request class + */ + +#ifndef SRC_COMMON_REQUEST_SIMPLECHECKREQUEST_H_ +#define SRC_COMMON_REQUEST_SIMPLECHECKREQUEST_H_ + +#include + +#include +#include +#include + +namespace Cynara { + +class SimpleCheckRequest : public Request { +private: + PolicyKey m_key; + +public: + SimpleCheckRequest(const PolicyKey &key, ProtocolFrameSequenceNumber sequenceNumber) : + Request(sequenceNumber), m_key(key) { + } + + virtual ~SimpleCheckRequest() {}; + + const PolicyKey &key(void) const { + return m_key; + } + + virtual void execute(RequestPtr self, RequestTakerPtr taker, RequestContextPtr context) const; +}; + +} // namespace Cynara + +#endif /* SRC_COMMON_REQUEST_SIMPLECHECKREQUEST_H_ */ diff --git a/src/common/request/pointers.h b/src/common/request/pointers.h index be1fdeb..227e8fc 100644 --- a/src/common/request/pointers.h +++ b/src/common/request/pointers.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014-2015 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. @@ -16,6 +16,7 @@ /** * @file src/common/request/pointers.h * @author Lukasz Wojciechowski + * @author Zofia Abramowska * @version 1.0 * @brief This file defines request classes pointers */ @@ -72,6 +73,9 @@ typedef std::shared_ptr SetPoliciesRequestPtr; class SignalRequest; typedef std::shared_ptr SignalRequestPtr; +class SimpleCheckRequest; +typedef std::shared_ptr SimpleCheckRequestPtr; + } // namespace Cynara #endif /* SRC_COMMON_REQUEST_POINTERS_H_ */ diff --git a/src/common/response/ResponseTaker.cpp b/src/common/response/ResponseTaker.cpp index 492af6e..410f8c9 100644 --- a/src/common/response/ResponseTaker.cpp +++ b/src/common/response/ResponseTaker.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014-2015 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. @@ -16,6 +16,7 @@ /** * @file src/common/response/ResponseTaker.cpp * @author Lukasz Wojciechowski + * @author Zofia Abramowska * @version 1.0 * @brief This file implements ResponseTaker class */ @@ -64,4 +65,9 @@ void ResponseTaker::execute(RequestContextPtr context UNUSED, ListResponsePtr re throw NotImplementedException(); } +void ResponseTaker::execute(RequestContextPtr context UNUSED, + SimpleCheckResponsePtr response UNUSED) { + throw NotImplementedException(); +} + } // namespace Cynara diff --git a/src/common/response/ResponseTaker.h b/src/common/response/ResponseTaker.h index c642b4f..31b7714 100644 --- a/src/common/response/ResponseTaker.h +++ b/src/common/response/ResponseTaker.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014-2015 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. @@ -16,6 +16,7 @@ /** * @file src/common/response/ResponseTaker.h * @author Lukasz Wojciechowski + * @author Zofia Abramowska * @version 1.0 * @brief This file defines ResponseTaker class */ @@ -41,6 +42,7 @@ public: virtual void execute(RequestContextPtr context, CodeResponsePtr response); virtual void execute(RequestContextPtr context, DescriptionListResponsePtr response); virtual void execute(RequestContextPtr context, ListResponsePtr response); + virtual void execute(RequestContextPtr context, SimpleCheckResponsePtr response); }; } // namespace Cynara diff --git a/src/common/response/SimpleCheckResponse.cpp b/src/common/response/SimpleCheckResponse.cpp new file mode 100644 index 0000000..52976fa --- /dev/null +++ b/src/common/response/SimpleCheckResponse.cpp @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2015 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/SimpleCheckResponse.cpp + * @author Zofia Abramowska + * @version 1.0 + * @brief This file implements simple check response class + */ + +#include + +#include "SimpleCheckResponse.h" + +namespace Cynara { + +void SimpleCheckResponse::execute(ResponsePtr self, ResponseTakerPtr taker, + RequestContextPtr context) const { + taker->execute(context, std::dynamic_pointer_cast(self)); +} + +} // namespace Cynara diff --git a/src/common/response/SimpleCheckResponse.h b/src/common/response/SimpleCheckResponse.h new file mode 100644 index 0000000..8fe28e6 --- /dev/null +++ b/src/common/response/SimpleCheckResponse.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2015 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/SimpleCheckResponse.h + * @author Zofia Abramowska + * @version 1.0 + * @brief This file defines response class for simple check request + */ + +#ifndef SRC_COMMON_RESPONSE_SIMPLECHECKRESPONSE_H_ +#define SRC_COMMON_RESPONSE_SIMPLECHECKRESPONSE_H_ + +#include + +#include + +#include +#include +#include + +namespace Cynara { + +class SimpleCheckResponse : public Response { +public: + SimpleCheckResponse(int32_t retValue, const PolicyResult &result, + ProtocolFrameSequenceNumber sequenceNumber) : + Response(sequenceNumber), m_resultRef(result), m_retValue(retValue) { + } + + SimpleCheckResponse(int retValue, ProtocolFrameSequenceNumber sequenceNumber); + + PolicyResult getResult(void) const { + return m_resultRef; + } + + int32_t getReturnValue(void) const { + return m_retValue; + } + virtual ~SimpleCheckResponse() {} + + virtual void execute(ResponsePtr self, ResponseTakerPtr taker, + RequestContextPtr context) const; +private: + const PolicyResult m_resultRef; + const int32_t m_retValue; +}; + +} // namespace Cynara + +#endif /* SRC_COMMON_RESPONSE_SIMPLECHECKRESPONSE_H_ */ diff --git a/src/common/response/pointers.h b/src/common/response/pointers.h index 5e90289..f30415f 100644 --- a/src/common/response/pointers.h +++ b/src/common/response/pointers.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014-2015 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. @@ -16,6 +16,7 @@ /** * @file src/common/response/pointers.h * @author Lukasz Wojciechowski + * @author Zofia Abramowska * @version 1.0 * @brief This file defines response classes pointers */ @@ -54,6 +55,9 @@ typedef std::shared_ptr ListResponsePtr; class Response; typedef std::shared_ptr ResponsePtr; +class SimpleCheckResponse; +typedef std::shared_ptr SimpleCheckResponsePtr; + class ResponseTaker; typedef std::shared_ptr ResponseTakerPtr; typedef std::weak_ptr ResponseTakerWeakPtr; -- 2.7.4 From 7acf06e3c1429405bbfdebd92b12a0fa06376862 Mon Sep 17 00:00:00 2001 From: Zofia Abramowska Date: Mon, 9 Feb 2015 16:14:34 +0100 Subject: [PATCH 12/16] Add logic side implementation of simple check Add implementation of client and service logic side implementation of simple check API and request and response handling. Change-Id: Ie59fb86e20fae383196025580b164c15e855bc62 --- src/client/logic/Logic.cpp | 67 ++++++++++++++++++++++++++++++++++----------- src/client/logic/Logic.h | 3 ++ src/service/logic/Logic.cpp | 57 ++++++++++++++++++++++++++++++++++++++ src/service/logic/Logic.h | 2 ++ 4 files changed, 113 insertions(+), 16 deletions(-) diff --git a/src/client/logic/Logic.cpp b/src/client/logic/Logic.cpp index c171cce..9f738fb 100644 --- a/src/client/logic/Logic.cpp +++ b/src/client/logic/Logic.cpp @@ -35,8 +35,10 @@ #include #include #include +#include #include #include +#include #include #include @@ -65,12 +67,10 @@ int Logic::check(const std::string &client, const ClientSession &session, const PolicyKey key(client, user, privilege); int ret = m_cache->get(session, key); - //Any other situation than cache miss if (ret != CYNARA_API_CACHE_MISS) { return ret; } - //No value in Cache PolicyResult result; ret = requestResult(key, result); if (ret != CYNARA_API_SUCCESS) { @@ -83,11 +83,24 @@ int Logic::check(const std::string &client, const ClientSession &session, const int Logic::simpleCheck(const std::string &client, const ClientSession &session, const std::string &user, const std::string &privilege) { - (void)client; - (void)session; - (void)user; - (void)privilege; - return CYNARA_API_ACCESS_NOT_RESOLVED; + if (!ensureConnection()) + return CYNARA_API_SERVICE_NOT_AVAILABLE; + + PolicyKey key(client, user, privilege); + int ret = m_cache->get(session, key); + if (ret != CYNARA_API_CACHE_MISS) { + return ret; + } + + PolicyResult result; + ret = requestSimpleResult(key, result); + if (ret != CYNARA_API_SUCCESS) { + if (ret != CYNARA_API_ACCESS_NOT_RESOLVED) + LOGE("Error fetching response for simpleCheck."); + return ret; + } + + return m_cache->update(session, key, result); } bool Logic::ensureConnection(void) { @@ -100,33 +113,55 @@ bool Logic::ensureConnection(void) { return false; } -int Logic::requestResult(const PolicyKey &key, PolicyResult &result) { +template +std::shared_ptr Logic::requestResponse(const PolicyKey &key) { ProtocolFrameSequenceNumber sequenceNumber = generateSequenceNumber(); //Ask cynara service - CheckResponsePtr checkResponse; - RequestPtr request = std::make_shared(key, sequenceNumber); + std::shared_ptr reqResponse; + RequestPtr request = std::make_shared(key, sequenceNumber); ResponsePtr response; while (!(response = m_socket->askCynaraServer(request))) { onDisconnected(); if (!m_socket->connect()) - return CYNARA_API_SERVICE_NOT_AVAILABLE; + return nullptr; } - checkResponse = std::dynamic_pointer_cast(response); + reqResponse = std::dynamic_pointer_cast(response); + return reqResponse; +} + +int Logic::requestResult(const PolicyKey &key, PolicyResult &result) { + auto checkResponse = requestResponse(key); if (!checkResponse) { - LOGC("Critical error. Casting Response to CheckResponse failed."); - return CYNARA_API_ACCESS_DENIED; + LOGC("Critical error. Requesting CheckResponse failed."); + return CYNARA_API_SERVICE_NOT_AVAILABLE; } - LOGD("checkResponse: policyType = %" PRIu16 ", metadata = %s", checkResponse->m_resultRef.policyType(), checkResponse->m_resultRef.metadata().c_str()); - result = checkResponse->m_resultRef; return CYNARA_API_SUCCESS; } +int Logic::requestSimpleResult(const PolicyKey &key, PolicyResult &result) { + auto simpleCheckResponse = requestResponse(key); + if (!simpleCheckResponse) { + LOGC("Critical error. Requesting SimpleCheckResponse failed."); + return CYNARA_API_SERVICE_NOT_AVAILABLE; + } + + if (simpleCheckResponse->getReturnValue() != CYNARA_API_SUCCESS) + return simpleCheckResponse->getReturnValue(); + + LOGD("SimpleCheckResponse: policyType = %" PRIu16 ", metadata = %s", + simpleCheckResponse->getResult().policyType(), + simpleCheckResponse->getResult().metadata().c_str()); + + result = simpleCheckResponse->getResult(); + return CYNARA_API_SUCCESS; +} + void Logic::onDisconnected(void) { m_cache->clear(); } diff --git a/src/client/logic/Logic.h b/src/client/logic/Logic.h index 695f7cd..e98f950 100644 --- a/src/client/logic/Logic.h +++ b/src/client/logic/Logic.h @@ -56,7 +56,10 @@ private: void onDisconnected(void); bool ensureConnection(void); + template + std::shared_ptr requestResponse(const PolicyKey &key); int requestResult(const PolicyKey &key, PolicyResult &result); + int requestSimpleResult(const PolicyKey &key, PolicyResult &result); }; } // namespace Cynara diff --git a/src/service/logic/Logic.cpp b/src/service/logic/Logic.cpp index 5e3f82a..95656e5 100644 --- a/src/service/logic/Logic.cpp +++ b/src/service/logic/Logic.cpp @@ -16,6 +16,7 @@ /** * @file src/service/logic/Logic.cpp * @author Lukasz Wojciechowski + * @author Zofia Abramowska * @version 1.0 * @brief This file implements main class of logic layer in cynara service */ @@ -51,6 +52,7 @@ #include #include #include +#include #include #include #include @@ -58,6 +60,7 @@ #include #include #include +#include #include #include
@@ -367,6 +370,60 @@ void Logic::execute(RequestContextPtr context, SetPoliciesRequestPtr request) { request->sequenceNumber())); } +void Logic::execute(RequestContextPtr context, SimpleCheckRequestPtr request) { + int retValue = CYNARA_API_SUCCESS; + PolicyResult result; + PolicyKey key = request->key(); + result = m_storage->checkPolicy(key); + + switch (result.policyType()) { + case PredefinedPolicyType::ALLOW: + LOGD("simple check of policy key <%s> returned ALLOW", key.toString().c_str()); + break; + case PredefinedPolicyType::DENY: + LOGD("simple check of policy key <%s> returned DENY", key.toString().c_str()); + break; + default: { + ExternalPluginPtr plugin = m_pluginManager->getPlugin(result.policyType()); + if (!plugin) { + LOGE("Plugin not found for policy: [0x%x]", result.policyType()); + result = PolicyResult(PredefinedPolicyType::DENY); + retValue = CYNARA_API_SUCCESS; + break; + } + + ServicePluginInterfacePtr servicePlugin = + std::dynamic_pointer_cast(plugin); + if (!servicePlugin) { + LOGE("Couldn't cast plugin pointer to ServicePluginInterface"); + result = PolicyResult(PredefinedPolicyType::DENY); + retValue = CYNARA_API_SUCCESS; + break; + } + + AgentType requiredAgent; + PluginData pluginData; + auto ret = servicePlugin->check(key.client().toString(), key.user().toString(), + key.privilege().toString(), result, requiredAgent, + pluginData); + switch (ret) { + case ServicePluginInterface::PluginStatus::ANSWER_READY: + LOGD("simple check of policy key <%s> in plugin returned [" PRIu16 "]", + key.toString().c_str(), result.policyType()); + break; + case ServicePluginInterface::PluginStatus::ANSWER_NOTREADY: + retValue = CYNARA_API_ACCESS_NOT_RESOLVED; + break; + default: + result = PolicyResult(PredefinedPolicyType::DENY); + retValue = CYNARA_API_SUCCESS; + } + } + } + context->returnResponse(context, std::make_shared(retValue, result, + request->sequenceNumber())); +} + void Logic::checkPoliciesTypes(const std::map> &policies, bool allowBucket, bool allowNone) { for (const auto &group : policies) { diff --git a/src/service/logic/Logic.h b/src/service/logic/Logic.h index fc577bd..444f734 100644 --- a/src/service/logic/Logic.h +++ b/src/service/logic/Logic.h @@ -16,6 +16,7 @@ /** * @file src/service/logic/Logic.h * @author Lukasz Wojciechowski + * @author Zofia Abramowska * @version 1.0 * @brief This file defines main class of logic layer in cynara service */ @@ -82,6 +83,7 @@ public: virtual void execute(RequestContextPtr context, RemoveBucketRequestPtr request); virtual void execute(RequestContextPtr context, SetPoliciesRequestPtr request); virtual void execute(RequestContextPtr context, SignalRequestPtr request); + virtual void execute(RequestContextPtr context, SimpleCheckRequestPtr request); virtual void contextClosed(RequestContextPtr context); -- 2.7.4 From be6cd08e0ba56f50c792a27961c9df2b55f3a0b3 Mon Sep 17 00:00:00 2001 From: Zofia Abramowska Date: Tue, 10 Feb 2015 16:53:39 +0100 Subject: [PATCH 13/16] Add client protocol side implementation of simple check Change-Id: I379bf96ac664827d89379b1df36d903864749a4b --- src/common/protocol/ProtocolClient.cpp | 73 +++++++++++++++++++++++++++++++++- src/common/protocol/ProtocolClient.h | 6 ++- 2 files changed, 77 insertions(+), 2 deletions(-) diff --git a/src/common/protocol/ProtocolClient.cpp b/src/common/protocol/ProtocolClient.cpp index 3f13653..05aac89 100644 --- a/src/common/protocol/ProtocolClient.cpp +++ b/src/common/protocol/ProtocolClient.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014-2015 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. @@ -17,6 +17,7 @@ * @file src/common/protocol/ProtocolClient.cpp * @author Lukasz Wojciechowski * @author Adam Malinowski + * @author Zofia Abramowska * @version 1.0 * @brief This file implements protocol class for communication with client */ @@ -34,8 +35,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -73,6 +76,20 @@ RequestPtr ProtocolClient::deserializeCheckRequest(void) { m_frameHeader.sequenceNumber()); } +RequestPtr ProtocolClient::deserializeSimpleCheckRequest(void) { + std::string clientId, userId, privilegeId; + + ProtocolDeserialization::deserialize(m_frameHeader, clientId); + ProtocolDeserialization::deserialize(m_frameHeader, userId); + ProtocolDeserialization::deserialize(m_frameHeader, privilegeId); + + LOGD("Deserialized SimpleCheckRequest: client <%s>, user <%s>, privilege <%s>", + clientId.c_str(), userId.c_str(), privilegeId.c_str()); + + return std::make_shared(PolicyKey(clientId, userId, privilegeId), + m_frameHeader.sequenceNumber()); +} + RequestPtr ProtocolClient::extractRequestFromBuffer(BinaryQueuePtr bufferQueue) { ProtocolFrameSerializer::deserializeHeader(m_frameHeader, bufferQueue); @@ -88,6 +105,8 @@ RequestPtr ProtocolClient::extractRequestFromBuffer(BinaryQueuePtr bufferQueue) return deserializeCheckRequest(); case OpCancelRequest: return deserializeCancelRequest(); + case OpSimpleCheckPolicyRequest: + return deserializeSimpleCheckRequest(); default: throw InvalidProtocolException(InvalidProtocolException::WrongOpCode); break; @@ -117,6 +136,24 @@ ResponsePtr ProtocolClient::deserializeCheckResponse(void) { return std::make_shared(policyResult, m_frameHeader.sequenceNumber()); } +ResponsePtr ProtocolClient::deserializeSimpleCheckResponse() { + int32_t retValue; + PolicyType result; + PolicyResult::PolicyMetadata additionalInfo; + + ProtocolDeserialization::deserialize(m_frameHeader, retValue); + ProtocolDeserialization::deserialize(m_frameHeader, result); + ProtocolDeserialization::deserialize(m_frameHeader, additionalInfo); + + const PolicyResult policyResult(result, additionalInfo); + + LOGD("Deserialized SimpleCheckResponse: retVal [%" PRIi32 "%] result [%" PRIu16 "]," + " metadata <%s>", retValue, policyResult.policyType(), policyResult.metadata().c_str()); + + return std::make_shared(retValue, policyResult, + m_frameHeader.sequenceNumber()); +} + ResponsePtr ProtocolClient::extractResponseFromBuffer(BinaryQueuePtr bufferQueue) { ProtocolFrameSerializer::deserializeHeader(m_frameHeader, bufferQueue); @@ -131,6 +168,8 @@ ResponsePtr ProtocolClient::extractResponseFromBuffer(BinaryQueuePtr bufferQueue return deserializeCheckResponse(); case OpCancelResponse: return deserializeCancelResponse(); + case OpSimpleCheckPolicyResponse: + return deserializeSimpleCheckResponse(); default: throw InvalidProtocolException(InvalidProtocolException::WrongOpCode); break; @@ -165,6 +204,21 @@ void ProtocolClient::execute(RequestContextPtr context, CheckRequestPtr request) ProtocolFrameSerializer::finishSerialization(frame, *(context->responseQueue())); } +void ProtocolClient::execute(RequestContextPtr context, SimpleCheckRequestPtr request) { + ProtocolFrame frame = ProtocolFrameSerializer::startSerialization(request->sequenceNumber()); + + LOGD("Serializing SimpleCheckRequest: client <%s>, user <%s>, privilege <%s>", + request->key().client().value().c_str(), request->key().user().value().c_str(), + request->key().privilege().value().c_str()); + + ProtocolSerialization::serialize(frame, OpSimpleCheckPolicyRequest); + ProtocolSerialization::serialize(frame, request->key().client().value()); + ProtocolSerialization::serialize(frame, request->key().user().value()); + ProtocolSerialization::serialize(frame, request->key().privilege().value()); + + ProtocolFrameSerializer::finishSerialization(frame, *(context->responseQueue())); +} + void ProtocolClient::execute(RequestContextPtr context, CancelResponsePtr response) { ProtocolFrame frame = ProtocolFrameSerializer::startSerialization( response->sequenceNumber()); @@ -191,4 +245,21 @@ void ProtocolClient::execute(RequestContextPtr context, CheckResponsePtr respons ProtocolFrameSerializer::finishSerialization(frame, *(context->responseQueue())); } +void ProtocolClient::execute(RequestContextPtr context, SimpleCheckResponsePtr response) { + ProtocolFrame frame = ProtocolFrameSerializer::startSerialization( + response->sequenceNumber()); + + LOGD("Serializing SimpleCheckResponse: op [%" PRIu8 "], retVal [%" PRIi32 "]," + " policyType [%" PRIu16 "], metadata <%s>", OpCheckPolicyResponse, + response->getReturnValue(), response->getResult().policyType(), + response->getResult().metadata().c_str()); + + ProtocolSerialization::serialize(frame, OpSimpleCheckPolicyResponse); + ProtocolSerialization::serialize(frame, response->getReturnValue()); + ProtocolSerialization::serialize(frame, response->getResult().policyType()); + ProtocolSerialization::serialize(frame, response->getResult().metadata()); + + ProtocolFrameSerializer::finishSerialization(frame, *(context->responseQueue())); +} + } // namespace Cynara diff --git a/src/common/protocol/ProtocolClient.h b/src/common/protocol/ProtocolClient.h index a1c5110..7ed41b1 100644 --- a/src/common/protocol/ProtocolClient.h +++ b/src/common/protocol/ProtocolClient.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014-2015 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. @@ -43,16 +43,20 @@ public: virtual void execute(RequestContextPtr context, CancelRequestPtr request); virtual void execute(RequestContextPtr context, CheckRequestPtr request); + virtual void execute(RequestContextPtr context, SimpleCheckRequestPtr request); virtual void execute(RequestContextPtr context, CancelResponsePtr response); virtual void execute(RequestContextPtr context, CheckResponsePtr response); + virtual void execute(RequestContextPtr context, SimpleCheckResponsePtr request); private: RequestPtr deserializeCancelRequest(void); RequestPtr deserializeCheckRequest(void); + RequestPtr deserializeSimpleCheckRequest(void); ResponsePtr deserializeCancelResponse(void); ResponsePtr deserializeCheckResponse(void); + ResponsePtr deserializeSimpleCheckResponse(void); }; } // namespace Cynara -- 2.7.4 From 66b5ad8e0b0906e7b3919d45d8f3f403cb1052f1 Mon Sep 17 00:00:00 2001 From: Zofia Abramowska Date: Thu, 12 Feb 2015 17:39:21 +0100 Subject: [PATCH 14/16] Fix pluginCheck in service logic Change-Id: I835c471b38756a9d3cee1ddfe4c4b90591744aa4 --- src/service/logic/Logic.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/service/logic/Logic.cpp b/src/service/logic/Logic.cpp index 95656e5..e92808e 100644 --- a/src/service/logic/Logic.cpp +++ b/src/service/logic/Logic.cpp @@ -210,8 +210,9 @@ bool Logic::pluginCheck(const RequestContextPtr &context, const PolicyKey &key, ServicePluginInterfacePtr servicePlugin = std::dynamic_pointer_cast(plugin); - if (!plugin) { - throw PluginNotFoundException(result); + if (!servicePlugin) { + result = PolicyResult(PredefinedPolicyType::DENY); + return true; } AgentType requiredAgent; @@ -243,7 +244,8 @@ bool Logic::pluginCheck(const RequestContextPtr &context, const PolicyKey &key, } return false; default: - throw PluginErrorException(key); // This 'throw' should be removed or handled properly. + result = PolicyResult(PredefinedPolicyType::DENY); + return true; } } -- 2.7.4 From 56ffb7914c4f8410a8bc71a7f9d8a06c5117510d Mon Sep 17 00:00:00 2001 From: Aleksander Zdyb Date: Thu, 22 Jan 2015 11:25:00 +0100 Subject: [PATCH 15/16] Add API description of cynara_strerror() Introduce new API call of cynara_strerror() used to obtain error message from error number. Change-Id: Ibd5b5a2af700a04fe8b3bfea8fde715b17db3a61 --- src/common/CMakeLists.txt | 1 + src/common/error/api.cpp | 96 ++++++++++++++++++++++++++++++++++++++++++++++ src/include/cynara-error.h | 55 ++++++++++++++++++++++++++ 3 files changed, 152 insertions(+) create mode 100644 src/common/error/api.cpp diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt index 885e325..07167bc 100644 --- a/src/common/CMakeLists.txt +++ b/src/common/CMakeLists.txt @@ -28,6 +28,7 @@ INCLUDE_DIRECTORIES( SET(COMMON_SOURCES ${COMMON_PATH}/config/PathConfig.cpp ${COMMON_PATH}/containers/BinaryQueue.cpp + ${COMMON_PATH}/error/api.cpp ${COMMON_PATH}/lock/FileLock.cpp ${COMMON_PATH}/log/log.cpp ${COMMON_PATH}/plugin/PluginManager.cpp diff --git a/src/common/error/api.cpp b/src/common/error/api.cpp new file mode 100644 index 0000000..d8243b4 --- /dev/null +++ b/src/common/error/api.cpp @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2015 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/error/api.cpp + * @author Aleksander Zdyb + * @version 1.0 + * @brief Implementation of cynara_strerror + */ + +#include + +#include + +int cynara_strerror(int errnum, char *buf, size_t buflen) { + if (buf == nullptr) + return CYNARA_API_INVALID_PARAM; + + const char *message = nullptr; + + switch (errnum) { + case CYNARA_API_ACCESS_NOT_RESOLVED: + message = "Access not resolved"; + break; + case CYNARA_API_ACCESS_ALLOWED: + message = "Access granted"; + break; + case CYNARA_API_ACCESS_DENIED: + message = "Access denied"; + break; + case CYNARA_API_SUCCESS: + message = "Operation successful"; + break; + case CYNARA_API_CACHE_MISS: + message = "Value not in cache"; + break; + case CYNARA_API_MAX_PENDING_REQUESTS: + message = "Pending requests exceeded maximum"; + break; + case CYNARA_API_OUT_OF_MEMORY: + message = "Out of memory"; + break; + case CYNARA_API_INVALID_PARAM: + message = "Invalid param"; + break; + case CYNARA_API_SERVICE_NOT_AVAILABLE: + message = "Service not available"; + break; + case CYNARA_API_METHOD_NOT_SUPPORTED: + message = "Method not supported"; + break; + case CYNARA_API_OPERATION_NOT_ALLOWED: + message = "Operation not allowed"; + break; + case CYNARA_API_OPERATION_FAILED: + message = "Operation failed"; + break; + case CYNARA_API_BUCKET_NOT_FOUND: + message = "Bucket not found"; + break; + case CYNARA_API_UNKNOWN_ERROR: + message = "Unknown error"; + break; + case CYNARA_API_CONFIGURATION_ERROR: + message = "Configuration error"; + break; + case CYNARA_API_INVALID_COMMANDLINE_PARAM: + message = "Invalid parameter in command-line"; + break; + case CYNARA_API_BUFFER_TOO_SHORT: + message = "Buffer too short"; + break; + } + + if (message == nullptr) + return CYNARA_API_INVALID_PARAM; + + if (buflen < strlen(message) + 1) + return CYNARA_API_BUFFER_TOO_SHORT; + + strcpy(buf, message); + + return CYNARA_API_SUCCESS; +} diff --git a/src/include/cynara-error.h b/src/include/cynara-error.h index ac69412..875d877 100644 --- a/src/include/cynara-error.h +++ b/src/include/cynara-error.h @@ -26,6 +26,8 @@ #ifndef CYNARA_ERROR_H #define CYNARA_ERROR_H +#include + /** * \name Return Codes * exported by the foundation API. @@ -79,6 +81,59 @@ /*! \brief indicating invalid parameter in command-line */ #define CYNARA_API_INVALID_COMMANDLINE_PARAM -12 + +/*! \brief indicating that provided buffer is too short */ +#define CYNARA_API_BUFFER_TOO_SHORT -13 /** @}*/ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \par Description: + * Returns the error string in the user-supplied buffer buf of length buflen. + * + * \par Purpose: + * This function populates passed argument buf with a string that describes the error code + * passed in the argument errnum, possibly using the LC_MESSAGES part of the current locale + * to select the appropriate language. + * + * \par Typical use case: + * Once after any of API functions returns negative value (if the error message is to be presented + * to the user). + * + * \par Method of function operation: + * This function copies error string to memory pointed by argument buf along with termination + * character ('\0'). + * + * \par Sync (or) async: + * This is a synchronous API. + * + * \par Thread-safety: + * This function is thread-safe as long as setlocale() is not invoked concurrently. + * + * \par Important notes: + * This function copies error string to memory pointed by argument buf only if the buffer is + * of sufficient size (indicated by argument buflen). User is responsible for allocating sufficient + * memory for both error string and termination character ('\0'). + * Moreover, the user must not invoke setlocale() concurrently with this function, because results + * are unspecified. + * + * \param[in] errnum error number + * \param[out] buf buffer for error message + * \param[in] buflen buffer size + * + * \return CYNARA_API_SUCCESS on success, CYNARA_API_BUFFER_TOO_SHORT, if error message couldn't fit + * into allocated buffer, or CYNARA_API_INVALID_PARAM if errnum is not a valid error number + * or argument buf is NULL. + * + * \brief Obtain error message from error number. + */ +int cynara_strerror(int errnum, char *buf, size_t buflen); + +#ifdef __cplusplus +} +#endif + #endif /* CYNARA_ERROR_H */ -- 2.7.4 From ba91952220726c7e51f98e3c1e95b6c9dc040f0c Mon Sep 17 00:00:00 2001 From: Aleksander Zdyb Date: Mon, 2 Feb 2015 14:11:47 +0100 Subject: [PATCH 16/16] Print error messages to stderr in Cyad Every dispatched command checks return value from Cynara API and prints possible error message using cynara_strerror() function. Call to cynara_strerror() is not of course subject to above check & print routine. Change-Id: I008d1fbd592061646478b47be8ae53bbc408cb1b --- src/cyad/BaseErrorApiWrapper.h | 38 +++++++++++++++++ src/cyad/CMakeLists.txt | 1 + src/cyad/CommandsDispatcher.cpp | 86 +++++++++++++++++++++++++++++++-------- src/cyad/CommandsDispatcher.h | 8 +++- src/cyad/Cyad.cpp | 4 +- src/cyad/Cyad.h | 4 +- src/cyad/ErrorApiWrapper.cpp | 37 +++++++++++++++++ src/cyad/ErrorApiWrapper.h | 39 ++++++++++++++++++ test/cyad/FakeErrorApiWrapper.h | 39 ++++++++++++++++++ test/cyad/commands_dispatcher.cpp | 60 +++++++++++++++++++-------- 10 files changed, 279 insertions(+), 37 deletions(-) create mode 100644 src/cyad/BaseErrorApiWrapper.h create mode 100644 src/cyad/ErrorApiWrapper.cpp create mode 100644 src/cyad/ErrorApiWrapper.h create mode 100644 test/cyad/FakeErrorApiWrapper.h diff --git a/src/cyad/BaseErrorApiWrapper.h b/src/cyad/BaseErrorApiWrapper.h new file mode 100644 index 0000000..721edef --- /dev/null +++ b/src/cyad/BaseErrorApiWrapper.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2015 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/cyad/BaseErrorApiWrapper.h + * @author Aleksander Zdyb + * @version 1.0 + * @brief Wrapper around cynara-error API (base) + */ + +#ifndef SRC_CYAD_BASEERRORAPIWRAPPER_H_ +#define SRC_CYAD_BASEERRORAPIWRAPPER_H_ + +#include + +namespace Cynara { + +class BaseErrorApiWrapper { +public: + virtual ~BaseErrorApiWrapper() {}; + virtual int cynara_strerror(int errnum, char *buf, size_t buflen) = 0; +}; + +} /* namespace Cynara */ + +#endif /* SRC_CYAD_BASEERRORAPIWRAPPER_H_ */ diff --git a/src/cyad/CMakeLists.txt b/src/cyad/CMakeLists.txt index 1415f6d..1873046 100644 --- a/src/cyad/CMakeLists.txt +++ b/src/cyad/CMakeLists.txt @@ -30,6 +30,7 @@ SET(CYAD_SOURCES ${CYAD_PATH}/CommandlineParser/HumanReadableParser.cpp ${CYAD_PATH}/CommandsDispatcher.cpp ${CYAD_PATH}/DispatcherIO.cpp + ${CYAD_PATH}/ErrorApiWrapper.cpp ${CYAD_PATH}/main.cpp ) diff --git a/src/cyad/CommandsDispatcher.cpp b/src/cyad/CommandsDispatcher.cpp index 0b8f0c0..6862a42 100644 --- a/src/cyad/CommandsDispatcher.cpp +++ b/src/cyad/CommandsDispatcher.cpp @@ -35,20 +35,26 @@ namespace Cynara { -CommandsDispatcher::CommandsDispatcher(BaseDispatcherIO &io, BaseAdminApiWrapper &adminApiWrapper) - : m_io(io), m_adminApiWrapper(adminApiWrapper), m_cynaraAdmin(nullptr) +CommandsDispatcher::CommandsDispatcher(BaseDispatcherIO &io, BaseAdminApiWrapper &adminApiWrapper, + BaseErrorApiWrapper &errorApiWrapper) + : m_io(io), m_adminApiWrapper(adminApiWrapper), m_errorApiWrapper(errorApiWrapper), + m_cynaraAdmin(nullptr) { auto ret = m_adminApiWrapper.cynara_admin_initialize(&m_cynaraAdmin); - if (ret != CYNARA_API_SUCCESS) + if (ret != CYNARA_API_SUCCESS) { + printAdminApiError(ret); throw AdminLibraryInitializationFailedException(ret); + } } CommandsDispatcher::~CommandsDispatcher() { - m_adminApiWrapper.cynara_admin_finish(m_cynaraAdmin); + auto ret = m_adminApiWrapper.cynara_admin_finish(m_cynaraAdmin); + if (ret != CYNARA_API_SUCCESS) + printAdminApiError(ret); } int CommandsDispatcher::execute(CyadCommand &) { - m_io.cout() << "Whatever you wanted, it's not implemented" << std::endl; + m_io.cerr() << "Whatever you wanted, it's not implemented" << std::endl; return CYNARA_API_UNKNOWN_ERROR; } @@ -58,25 +64,35 @@ int CommandsDispatcher::execute(HelpCyadCommand &) { } int CommandsDispatcher::execute(ErrorCyadCommand &result) { - m_io.cout() << "There was an error in command-line options:" << std::endl; - m_io.cout() << result.message() << std::endl; + m_io.cerr() << "There was an error in command-line options:" << std::endl; + m_io.cerr() << result.message() << std::endl; - m_io.cout() << std::endl << CmdlineOpts::makeHelp() << std::endl; + m_io.cerr() << std::endl << CmdlineOpts::makeHelp() << std::endl; return CYNARA_API_INVALID_COMMANDLINE_PARAM; } int CommandsDispatcher::execute(DeleteBucketCyadCommand &result) { - return m_adminApiWrapper.cynara_admin_set_bucket(m_cynaraAdmin, result.bucketId().c_str(), - CYNARA_ADMIN_DELETE, nullptr); + auto ret = m_adminApiWrapper.cynara_admin_set_bucket(m_cynaraAdmin, result.bucketId().c_str(), + CYNARA_ADMIN_DELETE, nullptr); + + if (ret != CYNARA_API_SUCCESS) + printAdminApiError(ret); + + return ret; } int CommandsDispatcher::execute(SetBucketCyadCommand &result) { const auto &policyResult = result.policyResult(); const char *metadata = policyResult.metadata().empty() ? nullptr : policyResult.metadata().c_str(); - return m_adminApiWrapper.cynara_admin_set_bucket(m_cynaraAdmin, - result.bucketId().c_str(), - policyResult.policyType(), metadata); + auto ret = m_adminApiWrapper.cynara_admin_set_bucket(m_cynaraAdmin, + result.bucketId().c_str(), + policyResult.policyType(), metadata); + + if (ret != CYNARA_API_SUCCESS) + printAdminApiError(ret); + + return ret; } int CommandsDispatcher::execute(SetPolicyCyadCommand &result) { @@ -85,7 +101,12 @@ int CommandsDispatcher::execute(SetPolicyCyadCommand &result) { policies.add(result.bucketId(), result.policyResult(), result.policyKey()); policies.seal(); - return m_adminApiWrapper.cynara_admin_set_policies(m_cynaraAdmin, policies.data()); + auto ret = m_adminApiWrapper.cynara_admin_set_policies(m_cynaraAdmin, policies.data()); + + if (ret != CYNARA_API_SUCCESS) + printAdminApiError(ret); + + return ret; } int CommandsDispatcher::execute(SetPolicyBulkCyadCommand &result) { @@ -93,7 +114,10 @@ int CommandsDispatcher::execute(SetPolicyBulkCyadCommand &result) { try { auto policies = Cynara::AdminPolicyParser::parse(input); - return m_adminApiWrapper.cynara_admin_set_policies(m_cynaraAdmin, policies.data()); + auto ret = m_adminApiWrapper.cynara_admin_set_policies(m_cynaraAdmin, policies.data()); + if (ret != CYNARA_API_SUCCESS) + printAdminApiError(ret); + return ret; } catch (const BucketRecordCorruptedException &ex) { m_io.cerr() << ex.message(); return CYNARA_API_INVALID_COMMANDLINE_PARAM; @@ -106,8 +130,13 @@ int CommandsDispatcher::execute(EraseCyadCommand &result) { auto user = key.user().toString().c_str(); auto privilege = key.privilege().toString().c_str(); - return m_adminApiWrapper.cynara_admin_erase(m_cynaraAdmin, result.bucketId().c_str(), - result.recursive(), client, user, privilege); + auto ret = m_adminApiWrapper.cynara_admin_erase(m_cynaraAdmin, result.bucketId().c_str(), + result.recursive(), client, user, privilege); + + if (ret != CYNARA_API_SUCCESS) + printAdminApiError(ret); + + return ret; } int CommandsDispatcher::execute(CheckCyadCommand &command) { @@ -133,6 +162,8 @@ int CommandsDispatcher::execute(CheckCyadCommand &command) { } m_io.cout() << std::endl; + } else { + printAdminApiError(ret); } return ret; @@ -180,6 +211,8 @@ int CommandsDispatcher::execute(ListPoliciesCyadCommand &command) { freePolicy(p); } free(policies); + } else { + printAdminApiError(ret); } return ret; @@ -208,9 +241,28 @@ int CommandsDispatcher::execute(ListPoliciesDescCyadCommand &) { freePolicyDesc(p); } free(descs); + } else { + printAdminApiError(ret); } return ret; } +void CommandsDispatcher::printAdminApiError(int errnum) { + const std::size_t buffSize = 256; + char buf[buffSize]; + auto ret = m_errorApiWrapper.cynara_strerror(errnum, buf, buffSize); + + m_io.cerr() << "Cynara: [" << errnum << "] "; + + if (ret == CYNARA_API_SUCCESS) + m_io.cerr() << buf << std::endl; + else if (ret == CYNARA_API_INVALID_PARAM) + m_io.cerr() << "Unknown error (sic!)" << std::endl; + else if (ret == CYNARA_API_BUFFER_TOO_SHORT) + m_io.cerr() << "Error message too long" << std::endl; + else + m_io.cerr() << "Unknown error (sic! sic!)" << std::endl; +} + } /* namespace Cynara */ diff --git a/src/cyad/CommandsDispatcher.h b/src/cyad/CommandsDispatcher.h index b8b7f29..a025303 100644 --- a/src/cyad/CommandsDispatcher.h +++ b/src/cyad/CommandsDispatcher.h @@ -24,6 +24,7 @@ #define SRC_CYAD_COMMANDSDISPATCHER_H_ #include +#include #include #include @@ -34,7 +35,8 @@ namespace Cynara { class CommandsDispatcher { public: - CommandsDispatcher(BaseDispatcherIO &io, BaseAdminApiWrapper &adminApiWrapper); + CommandsDispatcher(BaseDispatcherIO &io, BaseAdminApiWrapper &adminApiWrapper, + BaseErrorApiWrapper &errorApiWrapper); virtual ~CommandsDispatcher(); virtual int execute(CyadCommand &); @@ -49,9 +51,13 @@ public: virtual int execute(ListPoliciesCyadCommand &); virtual int execute(ListPoliciesDescCyadCommand &); +protected: + void printAdminApiError(int errnum); + private: BaseDispatcherIO &m_io; BaseAdminApiWrapper &m_adminApiWrapper; + BaseErrorApiWrapper &m_errorApiWrapper; struct cynara_admin *m_cynaraAdmin; }; diff --git a/src/cyad/Cyad.cpp b/src/cyad/Cyad.cpp index 092d9a7..1589d14 100644 --- a/src/cyad/Cyad.cpp +++ b/src/cyad/Cyad.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014-2015 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. @@ -33,7 +33,7 @@ namespace Cynara { Cyad::Cyad(int argc, char **argv) : m_parser(argc, argv), m_cynaraInitError(CYNARA_API_SUCCESS) { try { - m_dispatcher.reset(new CommandsDispatcher(m_io, m_adminApiWrapper)); + m_dispatcher.reset(new CommandsDispatcher(m_io, m_adminApiWrapper, m_errorApiWrapper)); } catch (const Cynara::AdminLibraryInitializationFailedException &ex) { m_cynaraInitError = ex.errorCode(); } diff --git a/src/cyad/Cyad.h b/src/cyad/Cyad.h index ba98fd8..dbb54b8 100644 --- a/src/cyad/Cyad.h +++ b/src/cyad/Cyad.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014-2015 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. @@ -29,6 +29,7 @@ #include #include #include +#include namespace Cynara { @@ -42,6 +43,7 @@ public: private: AdminApiWrapper m_adminApiWrapper; + ErrorApiWrapper m_errorApiWrapper; DispatcherIO m_io; std::unique_ptr m_dispatcher; CyadCommandlineParser m_parser; diff --git a/src/cyad/ErrorApiWrapper.cpp b/src/cyad/ErrorApiWrapper.cpp new file mode 100644 index 0000000..510e43a --- /dev/null +++ b/src/cyad/ErrorApiWrapper.cpp @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2015 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/cyad/ErrorApiWrapper.cpp + * @author Aleksander Zdyb + * @version 1.0 + * @brief Wrapper around cynara-error API + */ + +#include + +#include "ErrorApiWrapper.h" + +namespace Cynara { + +ErrorApiWrapper::ErrorApiWrapper() {} + +ErrorApiWrapper::~ErrorApiWrapper() {} + +int ErrorApiWrapper::cynara_strerror(int errnum, char *buf, size_t buflen) { + return ::cynara_strerror(errnum, buf, buflen); +} + +} /* namespace Cynara */ diff --git a/src/cyad/ErrorApiWrapper.h b/src/cyad/ErrorApiWrapper.h new file mode 100644 index 0000000..472630f --- /dev/null +++ b/src/cyad/ErrorApiWrapper.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2015 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/cyad/ErrorApiWrapper.h + * @author Aleksander Zdyb + * @version 1.0 + * @brief Wrapper around cynara-error API + */ + +#ifndef SRC_CYAD_ERRORAPIWRAPPER_H_ +#define SRC_CYAD_ERRORAPIWRAPPER_H_ + +#include "BaseErrorApiWrapper.h" + +namespace Cynara { + +class ErrorApiWrapper : public BaseErrorApiWrapper { +public: + ErrorApiWrapper(); + virtual ~ErrorApiWrapper(); + virtual int cynara_strerror(int errnum, char *buf, size_t buflen); +}; + +} /* namespace Cynara */ + +#endif /* SRC_CYAD_ERRORAPIWRAPPER_H_ */ diff --git a/test/cyad/FakeErrorApiWrapper.h b/test/cyad/FakeErrorApiWrapper.h new file mode 100644 index 0000000..f1cc51a --- /dev/null +++ b/test/cyad/FakeErrorApiWrapper.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2014-2015 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 test/cyad/FakeErrorApiWrapper.h + * @author Aleksander Zdyb + * @version 1.0 + * @brief Wrapper around cynara-error API (mock) + */ + +#ifndef TEST_CYAD_FAKEERRORAPIWRAPPER_H_ +#define TEST_CYAD_FAKEERRORAPIWRAPPER_H_ + +#include +#include + +#include + +class FakeErrorApiWrapper : public Cynara::BaseErrorApiWrapper { +public: + using BaseErrorApiWrapper::BaseErrorApiWrapper; + + MOCK_METHOD3(cynara_strerror, + int((int errnum, char *buf, size_t buflen))); +}; + +#endif /* TEST_CYAD_FAKEERRORAPIWRAPPER_H_ */ diff --git a/test/cyad/commands_dispatcher.cpp b/test/cyad/commands_dispatcher.cpp index 471997e..35a0ab8 100644 --- a/test/cyad/commands_dispatcher.cpp +++ b/test/cyad/commands_dispatcher.cpp @@ -20,6 +20,7 @@ * @brief Tests for CommandsDispatcher */ +#include #include #include #include @@ -39,6 +40,7 @@ #include "CyadCommandlineDispatcherTest.h" #include "FakeAdminApiWrapper.h" +#include "FakeErrorApiWrapper.h" #include "helpers.h" /** @@ -52,11 +54,12 @@ TEST_F(CyadCommandlineDispatcherTest, noApi) { using ::testing::Return; FakeAdminApiWrapper adminApi; + FakeErrorApiWrapper errorApi; EXPECT_CALL(adminApi, cynara_admin_initialize(_)).WillOnce(Return(CYNARA_API_SUCCESS)); EXPECT_CALL(adminApi, cynara_admin_finish(_)).WillOnce(Return(CYNARA_API_SUCCESS)); - Cynara::CommandsDispatcher dispatcher(m_io, adminApi); + Cynara::CommandsDispatcher dispatcher(m_io, adminApi, errorApi); Cynara::CyadCommand result; Cynara::HelpCyadCommand helpResult; @@ -74,11 +77,12 @@ TEST_F(CyadCommandlineDispatcherTest, deleteBucket) { using ::testing::IsNull; FakeAdminApiWrapper adminApi; + FakeErrorApiWrapper errorApi; EXPECT_CALL(adminApi, cynara_admin_initialize(_)).WillOnce(Return(CYNARA_API_SUCCESS)); EXPECT_CALL(adminApi, cynara_admin_finish(_)).WillOnce(Return(CYNARA_API_SUCCESS)); - Cynara::CommandsDispatcher dispatcher(m_io, adminApi); + Cynara::CommandsDispatcher dispatcher(m_io, adminApi, errorApi); Cynara::DeleteBucketCyadCommand result("test-bucket"); EXPECT_CALL(adminApi, @@ -98,11 +102,12 @@ TEST_F(CyadCommandlineDispatcherTest, setBucket) { using Cynara::PolicyResult; FakeAdminApiWrapper adminApi; + FakeErrorApiWrapper errorApi; EXPECT_CALL(adminApi, cynara_admin_initialize(_)).WillOnce(Return(CYNARA_API_SUCCESS)); EXPECT_CALL(adminApi, cynara_admin_finish(_)).WillOnce(Return(CYNARA_API_SUCCESS)); - Cynara::CommandsDispatcher dispatcher(m_io, adminApi); + Cynara::CommandsDispatcher dispatcher(m_io, adminApi, errorApi); typedef std::tuple BucketData; typedef std::vector Buckets; @@ -141,11 +146,12 @@ TEST_F(CyadCommandlineDispatcherTest, setPolicy) { using ::testing::Return; FakeAdminApiWrapper adminApi; + FakeErrorApiWrapper errorApi; EXPECT_CALL(adminApi, cynara_admin_initialize(_)).WillOnce(Return(CYNARA_API_SUCCESS)); EXPECT_CALL(adminApi, cynara_admin_finish(_)).WillOnce(Return(CYNARA_API_SUCCESS)); - Cynara::CommandsDispatcher dispatcher(m_io, adminApi); + Cynara::CommandsDispatcher dispatcher(m_io, adminApi, errorApi); Cynara::SetPolicyCyadCommand result("test-bucket", { CYNARA_ADMIN_ALLOW, "" }, { "client", "user", "privilege" }); @@ -165,11 +171,12 @@ TEST_F(CyadCommandlineDispatcherTest, setPolicyWithMetadata) { using ::testing::Return; FakeAdminApiWrapper adminApi; + FakeErrorApiWrapper errorApi; EXPECT_CALL(adminApi, cynara_admin_initialize(_)).WillOnce(Return(CYNARA_API_SUCCESS)); EXPECT_CALL(adminApi, cynara_admin_finish(_)).WillOnce(Return(CYNARA_API_SUCCESS)); - Cynara::CommandsDispatcher dispatcher(m_io, adminApi); + Cynara::CommandsDispatcher dispatcher(m_io, adminApi, errorApi); Cynara::SetPolicyCyadCommand result("test-bucket", { CYNARA_ADMIN_ALLOW, "metadata" }, Cynara::PolicyKey("client", "user", "privilege")); @@ -189,11 +196,12 @@ TEST_F(CyadCommandlineDispatcherTest, setPoliciesBulk) { using ::testing::Return; FakeAdminApiWrapper adminApi; + FakeErrorApiWrapper errorApi; EXPECT_CALL(adminApi, cynara_admin_initialize(_)).WillOnce(Return(CYNARA_API_SUCCESS)); EXPECT_CALL(adminApi, cynara_admin_finish(_)).WillOnce(Return(CYNARA_API_SUCCESS)); - Cynara::CommandsDispatcher dispatcher(m_io, adminApi); + Cynara::CommandsDispatcher dispatcher(m_io, adminApi, errorApi); Cynara::SetPolicyBulkCyadCommand result("-"); // fake stdin ;) @@ -216,11 +224,12 @@ TEST_F(CyadCommandlineDispatcherTest, setPoliciesBulkInputError) { using ::testing::Return; FakeAdminApiWrapper adminApi; + FakeErrorApiWrapper errorApi; EXPECT_CALL(adminApi, cynara_admin_initialize(_)).WillOnce(Return(CYNARA_API_SUCCESS)); EXPECT_CALL(adminApi, cynara_admin_finish(_)).WillOnce(Return(CYNARA_API_SUCCESS)); - Cynara::CommandsDispatcher dispatcher(m_io, adminApi); + Cynara::CommandsDispatcher dispatcher(m_io, adminApi, errorApi); Cynara::SetPolicyBulkCyadCommand result("-"); // fake stdin ;) @@ -237,11 +246,12 @@ TEST_F(CyadCommandlineDispatcherTest, erase) { using ::testing::StrEq; FakeAdminApiWrapper adminApi; + FakeErrorApiWrapper errorApi; EXPECT_CALL(adminApi, cynara_admin_initialize(_)).WillOnce(Return(CYNARA_API_SUCCESS)); EXPECT_CALL(adminApi, cynara_admin_finish(_)).WillOnce(Return(CYNARA_API_SUCCESS)); - Cynara::CommandsDispatcher dispatcher(m_io, adminApi); + Cynara::CommandsDispatcher dispatcher(m_io, adminApi, errorApi); Cynara::EraseCyadCommand command("", true, { "client", "user", "privilege" }); @@ -261,11 +271,12 @@ TEST_F(CyadCommandlineDispatcherTest, check) { using ::testing::StrEq; FakeAdminApiWrapper adminApi; + FakeErrorApiWrapper errorApi; EXPECT_CALL(adminApi, cynara_admin_initialize(_)).WillOnce(Return(CYNARA_API_SUCCESS)); EXPECT_CALL(adminApi, cynara_admin_finish(_)).WillOnce(Return(CYNARA_API_SUCCESS)); - Cynara::CommandsDispatcher dispatcher(m_io, adminApi); + Cynara::CommandsDispatcher dispatcher(m_io, adminApi, errorApi); Cynara::CheckCyadCommand command("", true, { "client", "user", "privilege" }); int result = 42; @@ -289,11 +300,12 @@ TEST_F(CyadCommandlineDispatcherTest, checkWithMetadata) { using ::testing::StrEq; FakeAdminApiWrapper adminApi; + FakeErrorApiWrapper errorApi; EXPECT_CALL(adminApi, cynara_admin_initialize(_)).WillOnce(Return(CYNARA_API_SUCCESS)); EXPECT_CALL(adminApi, cynara_admin_finish(_)).WillOnce(Return(CYNARA_API_SUCCESS)); - Cynara::CommandsDispatcher dispatcher(m_io, adminApi); + Cynara::CommandsDispatcher dispatcher(m_io, adminApi, errorApi); Cynara::CheckCyadCommand command("", true, { "client", "user", "privilege" }); int result = 42; @@ -311,26 +323,38 @@ TEST_F(CyadCommandlineDispatcherTest, checkWithMetadata) { TEST_F(CyadCommandlineDispatcherTest, checkWithError) { using ::testing::_; + using ::testing::HasSubstr; + using ::testing::Invoke; using ::testing::NotNull; using ::testing::Return; using ::testing::StrEq; + using ::testing::Unused; FakeAdminApiWrapper adminApi; + FakeErrorApiWrapper errorApi; EXPECT_CALL(adminApi, cynara_admin_initialize(_)).WillOnce(Return(CYNARA_API_SUCCESS)); EXPECT_CALL(adminApi, cynara_admin_finish(_)).WillOnce(Return(CYNARA_API_SUCCESS)); - Cynara::CommandsDispatcher dispatcher(m_io, adminApi); + Cynara::CommandsDispatcher dispatcher(m_io, adminApi, errorApi); Cynara::CheckCyadCommand command("", true, { "client", "user", "privilege" }); + auto setErrorMessage = [] (Unused, char *buf, std::size_t buflen) { + strncpy(buf, "Test error message", buflen); + }; + EXPECT_CALL(adminApi, cynara_admin_check(_, StrEq(""), true, StrEq("client"), StrEq("user"), StrEq("privilege"), NotNull(), NotNull())) .WillOnce(Return(CYNARA_API_UNKNOWN_ERROR)); + // Should we expect some minimal buflen here? + EXPECT_CALL(errorApi, cynara_strerror(CYNARA_API_UNKNOWN_ERROR, NotNull(), _)) + .WillOnce(DoAll(Invoke(setErrorMessage), Return(CYNARA_API_SUCCESS))); + dispatcher.execute(command); - ASSERT_TRUE(m_io.coutRaw().str().empty()); + ASSERT_THAT(m_io.cerrRaw().str(), HasSubstr("Test error message")); } TEST_F(CyadCommandlineDispatcherTest, listPoliciesNone) { @@ -342,11 +366,12 @@ TEST_F(CyadCommandlineDispatcherTest, listPoliciesNone) { using ::testing::StrEq; FakeAdminApiWrapper adminApi; + FakeErrorApiWrapper errorApi; EXPECT_CALL(adminApi, cynara_admin_initialize(_)).WillOnce(Return(CYNARA_API_SUCCESS)); EXPECT_CALL(adminApi, cynara_admin_finish(_)).WillOnce(Return(CYNARA_API_SUCCESS)); - Cynara::CommandsDispatcher dispatcher(m_io, adminApi); + Cynara::CommandsDispatcher dispatcher(m_io, adminApi, errorApi); Cynara::ListPoliciesCyadCommand command("", { "client", "user", "privilege" }); @@ -372,11 +397,12 @@ TEST_F(CyadCommandlineDispatcherTest, listPoliciesTwo) { using ::testing::StrEq; FakeAdminApiWrapper adminApi; + FakeErrorApiWrapper errorApi; EXPECT_CALL(adminApi, cynara_admin_initialize(_)).WillOnce(Return(CYNARA_API_SUCCESS)); EXPECT_CALL(adminApi, cynara_admin_finish(_)).WillOnce(Return(CYNARA_API_SUCCESS)); - Cynara::CommandsDispatcher dispatcher(m_io, adminApi); + Cynara::CommandsDispatcher dispatcher(m_io, adminApi, errorApi); Cynara::ListPoliciesCyadCommand command("", { "client", "user", "privilege" }); @@ -404,11 +430,12 @@ TEST_F(CyadCommandlineDispatcherTest, listPoliciesDescNone) { using ::testing::SetArgPointee; FakeAdminApiWrapper adminApi; + FakeErrorApiWrapper errorApi; EXPECT_CALL(adminApi, cynara_admin_initialize(_)).WillOnce(Return(CYNARA_API_SUCCESS)); EXPECT_CALL(adminApi, cynara_admin_finish(_)).WillOnce(Return(CYNARA_API_SUCCESS)); - Cynara::CommandsDispatcher dispatcher(m_io, adminApi); + Cynara::CommandsDispatcher dispatcher(m_io, adminApi, errorApi); Cynara::ListPoliciesDescCyadCommand command; @@ -432,11 +459,12 @@ TEST_F(CyadCommandlineDispatcherTest, listPoliciesDescOne) { using ::testing::SetArgPointee; FakeAdminApiWrapper adminApi; + FakeErrorApiWrapper errorApi; EXPECT_CALL(adminApi, cynara_admin_initialize(_)).WillOnce(Return(CYNARA_API_SUCCESS)); EXPECT_CALL(adminApi, cynara_admin_finish(_)).WillOnce(Return(CYNARA_API_SUCCESS)); - Cynara::CommandsDispatcher dispatcher(m_io, adminApi); + Cynara::CommandsDispatcher dispatcher(m_io, adminApi, errorApi); Cynara::ListPoliciesDescCyadCommand command; -- 2.7.4