Fix build with CYNARA_NO_LOGS
[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 <cinttypes>
25 #include <memory>
26
27 #include <cache/CapacityCache.h>
28 #include <common.h>
29 #include <config/PathConfig.h>
30 #include <cynara-error.h>
31 #include <exceptions/Exception.h>
32 #include <exceptions/UnexpectedErrorException.h>
33 #include <log/log.h>
34 #include <plugins/NaiveInterpreter.h>
35 #include <protocol/Protocol.h>
36 #include <protocol/ProtocolClient.h>
37 #include <request/CheckRequest.h>
38 #include <request/pointers.h>
39 #include <request/SimpleCheckRequest.h>
40 #include <response/CheckResponse.h>
41 #include <response/pointers.h>
42 #include <response/SimpleCheckResponse.h>
43 #include <sockets/SocketClient.h>
44
45 #include <logic/Logic.h>
46
47 namespace Cynara {
48
49 static ProtocolFrameSequenceNumber generateSequenceNumber(void) {
50     static ProtocolFrameSequenceNumber sequenceNumber = 0;
51     return ++sequenceNumber;
52 }
53
54 Logic::Logic(const Configuration &conf) :
55         m_socketClient(PathConfig::SocketPath::client, std::make_shared<ProtocolClient>()),
56         m_cache(conf.getCacheSize()) {
57     auto naiveInterpreter = std::make_shared<NaiveInterpreter>();
58     for (auto &descr : naiveInterpreter->getSupportedPolicyDescr()) {
59         m_cache.registerPlugin(descr, naiveInterpreter);
60     }
61 }
62
63 int Logic::check(const std::string &client, const ClientSession &session, const std::string &user,
64                  const std::string &privilege) {
65     if (!ensureConnection())
66         return CYNARA_API_SERVICE_NOT_AVAILABLE;
67
68     PolicyKey key(client, user, privilege);
69     int ret = m_cache.get(session, key);
70     if (ret != CYNARA_API_CACHE_MISS) {
71         return ret;
72     }
73
74     PolicyResult result;
75     ret = requestResult(key, result);
76     if (ret != CYNARA_API_SUCCESS) {
77         LOGE("Error fetching new entry.");
78         return ret;
79     }
80
81     return m_cache.update(session, key, result);
82 }
83
84 int Logic::simpleCheck(const std::string &client, const ClientSession &session,
85                        const std::string &user, const std::string &privilege) {
86     if (!ensureConnection())
87         return CYNARA_API_SERVICE_NOT_AVAILABLE;
88
89     PolicyKey key(client, user, privilege);
90     int ret = m_cache.get(session, key);
91     if (ret != CYNARA_API_CACHE_MISS) {
92         return ret;
93     }
94
95     PolicyResult result;
96     ret = requestSimpleResult(key, result);
97     if (ret != CYNARA_API_SUCCESS) {
98         if (ret != CYNARA_API_ACCESS_NOT_RESOLVED) {
99             LOGE("Error fetching response for simpleCheck.");
100         }
101         return ret;
102     }
103
104     return m_cache.update(session, key, result);
105 }
106
107 bool Logic::ensureConnection(void) {
108     if (m_socketClient.isConnected())
109         return true;
110     onDisconnected();
111     if (m_socketClient.connect())
112         return true;
113     LOGW("Cannot connect to cynara. Service not available.");
114     return false;
115 }
116
117 template <typename Req, typename Res>
118 std::shared_ptr<Res> Logic::requestResponse(const PolicyKey &key) {
119     ProtocolFrameSequenceNumber sequenceNumber = generateSequenceNumber();
120
121     //Ask cynara service
122     std::shared_ptr<Res> reqResponse;
123     Req request(key, sequenceNumber);
124     ResponsePtr response;
125     while (!(response = m_socketClient.askCynaraServer(request))) {
126         onDisconnected();
127         if (!m_socketClient.connect())
128             return nullptr;
129     }
130
131     reqResponse = std::dynamic_pointer_cast<Res>(response);
132     return reqResponse;
133 }
134
135 int Logic::requestResult(const PolicyKey &key, PolicyResult &result) {
136     auto checkResponse = requestResponse<CheckRequest, CheckResponse>(key);
137     if (!checkResponse) {
138         LOGC("Critical error. Requesting CheckResponse failed.");
139         return CYNARA_API_SERVICE_NOT_AVAILABLE;
140     }
141     LOGD("checkResponse: policyType = %" PRIu16 ", metadata = %s",
142          checkResponse->m_resultRef.policyType(),
143          checkResponse->m_resultRef.metadata().c_str());
144     result = checkResponse->m_resultRef;
145     return CYNARA_API_SUCCESS;
146 }
147
148 int Logic::requestSimpleResult(const PolicyKey &key, PolicyResult &result) {
149     auto simpleCheckResponse = requestResponse<SimpleCheckRequest, SimpleCheckResponse>(key);
150     if (!simpleCheckResponse) {
151         LOGC("Critical error. Requesting SimpleCheckResponse failed.");
152         return CYNARA_API_SERVICE_NOT_AVAILABLE;
153     }
154
155     if (simpleCheckResponse->getReturnValue() != CYNARA_API_SUCCESS)
156         return simpleCheckResponse->getReturnValue();
157
158     LOGD("SimpleCheckResponse: policyType = %" PRIu16 ", metadata = %s",
159          simpleCheckResponse->getResult().policyType(),
160          simpleCheckResponse->getResult().metadata().c_str());
161
162     result = simpleCheckResponse->getResult();
163     return CYNARA_API_SUCCESS;
164 }
165
166 void Logic::onDisconnected(void) {
167     m_cache.clear();
168 }
169
170 } // namespace Cynara