b9d590ec372a3046a72ff22b745636859621d307
[platform/core/security/cynara.git] / src / client / logic / Logic.cpp
1 /*
2  *  Copyright (c) 2014-2015 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *  Licensed under the Apache License, Version 2.0 (the "License");
5  *  you may not use this file except in compliance with the License.
6  *  You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *  Unless required by applicable law or agreed to in writing, software
11  *  distributed under the License is distributed on an "AS IS" BASIS,
12  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *  See the License for the specific language governing permissions and
14  *  limitations under the License
15  */
16 /**
17  * @file        src/client/logic/Logic.cpp
18  * @author      Lukasz Wojciechowski <l.wojciechow@partner.samsung.com>
19  * @author      Zofia Abramowska <z.abramowska@samsung.com>
20  * @version     1.0
21  * @brief       This file contains implementation of Logic class - main libcynara-client class
22  */
23
24 #include <memory>
25
26 #include <cache/CapacityCache.h>
27 #include <common.h>
28 #include <config/PathConfig.h>
29 #include <cynara-error.h>
30 #include <exceptions/Exception.h>
31 #include <exceptions/UnexpectedErrorException.h>
32 #include <log/log.h>
33 #include <plugins/NaiveInterpreter.h>
34 #include <protocol/Protocol.h>
35 #include <protocol/ProtocolClient.h>
36 #include <request/CheckRequest.h>
37 #include <request/pointers.h>
38 #include <request/SimpleCheckRequest.h>
39 #include <response/CheckResponse.h>
40 #include <response/pointers.h>
41 #include <response/SimpleCheckResponse.h>
42 #include <sockets/SocketClient.h>
43
44 #include <logic/Logic.h>
45
46 namespace Cynara {
47
48 static ProtocolFrameSequenceNumber generateSequenceNumber(void) {
49     static ProtocolFrameSequenceNumber sequenceNumber = 0;
50     return ++sequenceNumber;
51 }
52
53 Logic::Logic(const Configuration &conf) :
54         m_socketClient(PathConfig::SocketPath::client, std::make_shared<ProtocolClient>()),
55         m_cache(conf.getCacheSize()) {
56     auto naiveInterpreter = std::make_shared<NaiveInterpreter>();
57     for (auto &descr : naiveInterpreter->getSupportedPolicyDescr()) {
58         m_cache.registerPlugin(descr, naiveInterpreter);
59     }
60 }
61
62 int Logic::check(const std::string &client, const ClientSession &session, const std::string &user,
63                  const std::string &privilege) {
64     if (!ensureConnection())
65         return CYNARA_API_SERVICE_NOT_AVAILABLE;
66
67     PolicyKey key(client, user, privilege);
68     int ret = m_cache.get(session, key);
69     if (ret != CYNARA_API_CACHE_MISS) {
70         return ret;
71     }
72
73     PolicyResult result;
74     ret = requestResult(key, result);
75     if (ret != CYNARA_API_SUCCESS) {
76         LOGE("Error fetching new entry.");
77         return ret;
78     }
79
80     return m_cache.update(session, key, result);
81 }
82
83 int Logic::simpleCheck(const std::string &client, const ClientSession &session,
84                        const std::string &user, const std::string &privilege) {
85     if (!ensureConnection())
86         return CYNARA_API_SERVICE_NOT_AVAILABLE;
87
88     PolicyKey key(client, user, privilege);
89     int ret = m_cache.get(session, key);
90     if (ret != CYNARA_API_CACHE_MISS) {
91         return ret;
92     }
93
94     PolicyResult result;
95     ret = requestSimpleResult(key, result);
96     if (ret != CYNARA_API_SUCCESS) {
97         if (ret != CYNARA_API_ACCESS_NOT_RESOLVED)
98             LOGE("Error fetching response for simpleCheck.");
99         return ret;
100     }
101
102     return m_cache.update(session, key, result);
103 }
104
105 bool Logic::ensureConnection(void) {
106     if (m_socketClient.isConnected())
107         return true;
108     onDisconnected();
109     if (m_socketClient.connect())
110         return true;
111     LOGW("Cannot connect to cynara. Service not available.");
112     return false;
113 }
114
115 template <typename Req, typename Res>
116 std::shared_ptr<Res> Logic::requestResponse(const PolicyKey &key) {
117     ProtocolFrameSequenceNumber sequenceNumber = generateSequenceNumber();
118
119     //Ask cynara service
120     std::shared_ptr<Res> reqResponse;
121     Req request(key, sequenceNumber);
122     ResponsePtr response;
123     while (!(response = m_socketClient.askCynaraServer(request))) {
124         onDisconnected();
125         if (!m_socketClient.connect())
126             return nullptr;
127     }
128
129     reqResponse = std::dynamic_pointer_cast<Res>(response);
130     return reqResponse;
131 }
132
133 int Logic::requestResult(const PolicyKey &key, PolicyResult &result) {
134     auto checkResponse = requestResponse<CheckRequest, CheckResponse>(key);
135     if (!checkResponse) {
136         LOGC("Critical error. Requesting CheckResponse failed.");
137         return CYNARA_API_SERVICE_NOT_AVAILABLE;
138     }
139     LOGD("checkResponse: policyType = %" PRIu16 ", metadata = %s",
140          checkResponse->m_resultRef.policyType(),
141          checkResponse->m_resultRef.metadata().c_str());
142     result = checkResponse->m_resultRef;
143     return CYNARA_API_SUCCESS;
144 }
145
146 int Logic::requestSimpleResult(const PolicyKey &key, PolicyResult &result) {
147     auto simpleCheckResponse = requestResponse<SimpleCheckRequest, SimpleCheckResponse>(key);
148     if (!simpleCheckResponse) {
149         LOGC("Critical error. Requesting SimpleCheckResponse failed.");
150         return CYNARA_API_SERVICE_NOT_AVAILABLE;
151     }
152
153     if (simpleCheckResponse->getReturnValue() != CYNARA_API_SUCCESS)
154         return simpleCheckResponse->getReturnValue();
155
156     LOGD("SimpleCheckResponse: policyType = %" PRIu16 ", metadata = %s",
157          simpleCheckResponse->getResult().policyType(),
158          simpleCheckResponse->getResult().metadata().c_str());
159
160     result = simpleCheckResponse->getResult();
161     return CYNARA_API_SUCCESS;
162 }
163
164 void Logic::onDisconnected(void) {
165     m_cache.clear();
166 }
167
168 } // namespace Cynara