2 * Copyright (c) 2019 Samsung Electronics Co., Ltd All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 #include "include/fb_generated.h"
17 #include "print_content.hpp"
18 #include "serialized_convert.hpp"
19 #include "serializer.hpp"
20 #include "storage_backend_serialized.hpp"
21 #include "transaction_guard.hpp"
23 #include <boost/tokenizer.hpp>
29 #include <sys/types.h>
33 using ldp_xml_parser::MatchItemSend;
35 namespace ldp_serialized {
37 // Set max size of serialized file to prevent mmap with unexpected memory size.
39 #define MAX_SFILE_SIZE (1024 * 1024)
41 typedef boost::tokenizer<boost::char_separator<char>> tokenizer;
48 inline boost::string_ref s(const flatbuffers::String *str) {
49 return boost::string_ref(str->c_str(), str->size());
52 template <typename T, typename I>
53 bool match(const T &match, const I *i) {
54 return match.match(makeMessageType(i->type()),
60 makeDecision(i->decision()->decision()));
63 template <> bool match(const ldp_xml_parser::MatchItemAccess &match, const FB::ItemAccess *item) {
64 return match.match(makeBusAccessType(item->type()), item->uid(), item->gid());
67 template <typename T, typename P = typename type_helper<T>::policy_type>
68 ldp_xml_parser::DecisionItem getDecisionItem(const T &item, const P *policy) {
69 const auto *v = policy->items();
70 for (auto it = v->rbegin(); it != v->rend(); ++it) {
72 return makeDecisionItem((*it)->decision());
74 return ldp_xml_parser::Decision::ANY;
77 const DecisionItem *getDecisionItemFromTree(const FB::PolicyOwnNode *node,
79 tokenizer::iterator &iterator) {
80 if (iterator == tokens.end()) {
81 if (node->decision_item()->decision() != Decision_ANY)
82 return node->decision_item();
84 return node->prefix_decision_item();
87 auto child = node->children()->LookupByKey(iterator->c_str());
89 return node->prefix_decision_item();
92 const DecisionItem *child_decision = getDecisionItemFromTree(child, tokens, iterator);
93 if (child_decision->decision() == Decision_ANY)
94 return node->prefix_decision_item();
96 return child_decision;
99 template <> ldp_xml_parser::DecisionItem getDecisionItem(const ldp_xml_parser::MatchItemOwn &item,
100 const PolicyOwn *policy) {
101 if (item.getName().length() == 0)
102 return ldp_xml_parser::Decision::DENY;
104 boost::char_separator<char> separator(".");
105 tokenizer tokens(item.getName(), separator);
107 auto node = policy->tree();
109 return ldp_xml_parser::Decision::ANY;
111 auto iterator = tokens.begin();
113 return makeDecisionItem(getDecisionItemFromTree(node, tokens, iterator));
116 template <typename T, typename P = typename type_helper<T>::policy_type>
117 ldp_xml_parser::DecisionItem getDecisionItemMaybeNull(const T &item, const P *policyPair) {
118 if (nullptr == policyPair)
119 return ldp_xml_parser::Decision::ANY;
120 return getDecisionItem(item, policyPair->policy());
123 } // anonymous namespace
125 class StorageBackendSerialized::StorageBackendSerializedImpl {
127 uint8_t *mem{static_cast<decltype(mem)>(MAP_FAILED)};
129 const FB::File *file{nullptr};
131 std::unique_ptr<ldp_xml_parser::Serializer> serializer;
136 typedef std::pair<const ItemSend *, unsigned> ItemWithScore; // a pair: Item, index of Item
137 typedef std::vector<ItemWithScore> ItemsWithScore; // items
138 typedef std::pair<unsigned, ItemsWithScore> HighestScoreWithItems; // value for index map: highest index for items, items
139 typedef std::map<boost::string_ref, HighestScoreWithItems> MapIndex;
140 typedef std::vector<ItemWithScore> SendPrefixIndex;
142 MapIndex sendIndex; // context default
143 SendPrefixIndex sendPrefixIndex; // context default prefix rules
144 std::map<uid_t, MapIndex> userSendIndex;
145 std::map<uid_t, SendPrefixIndex> userSendPrefixIndex;
148 bool init(const char *filename, bool verify);
149 bool init(const FB::File *f);
150 bool initFromXML(const char *config_name);
153 void createSendIndex();
154 ldp_xml_parser::DecisionItem getDecisionFromSendIndex(const MatchItemSend &item, const MapIndex &index, const SendPrefixIndex &prefixIndex);
155 ldp_xml_parser::DecisionItem getDecisionFromSendIndex(const MatchItemSend &item);
156 ldp_xml_parser::DecisionItem getDecisionFromSendIndex(const MatchItemSend &item, uid_t uid);
158 void printContent(const bool xml_format = false) const;
160 template <typename T, typename M = typename type_helper<T>::policy_set_type>
161 const M *getPolicySet();
164 ldp_xml_parser::DecisionItem StorageBackendSerialized::StorageBackendSerializedImpl::getDecisionFromSendIndex(const MatchItemSend &item,
165 const MapIndex &index, const SendPrefixIndex &prefixIndex) {
166 ldp_xml_parser::DecisionItem decision(ldp_xml_parser::Decision::ANY);
168 ItemWithScore currentBest(nullptr, 0);
170 auto updateCurrentBest = [¤tBest, &item, &index](boost::string_ref name) {
171 // check if there are any rules for the name
172 auto fit = index.find(name);
173 if (fit == index.end())
176 // check if there's any chance to get better score
177 // fit->second.first is the highest score from vector fit->second.second
178 if (fit->second.first <= currentBest.second)
181 // look for better score
182 for (const auto &it: fit->second.second) {
183 if (it.second > currentBest.second && match(item, it.first))
188 // iterate over names
189 for (const auto &name: item.getNames()) {
190 // find and check the no-prefix rules
191 updateCurrentBest(name);
193 // check the prefix rules
194 for (const auto &prefixItem: prefixIndex) {
195 if (prefixItem.second > currentBest.second && match(item, prefixItem.first))
196 currentBest = prefixItem;
200 // check no-name rules
201 updateCurrentBest("");
203 if (currentBest.first)
204 decision = makeDecisionItem(currentBest.first->decision());
209 ldp_xml_parser::DecisionItem StorageBackendSerialized::StorageBackendSerializedImpl::getDecisionFromSendIndex(const MatchItemSend &item) {
210 return getDecisionFromSendIndex(item, sendIndex, sendPrefixIndex);
213 ldp_xml_parser::DecisionItem StorageBackendSerialized::StorageBackendSerializedImpl::getDecisionFromSendIndex(const MatchItemSend &item, uid_t uid) {
214 return getDecisionFromSendIndex(item, userSendIndex[uid], userSendPrefixIndex[uid]);
217 void StorageBackendSerialized::StorageBackendSerializedImpl::createSendIndex() {
218 // helper for adding items to indexes
219 auto add = [](MapIndex &index, SendPrefixIndex &prefixIndex, boost::string_ref key, ItemWithScore value) {
220 if (value.first->is_name_prefix()) {
221 prefixIndex.push_back(value);
223 index[key].second.push_back(value);
224 // we insert items in increasing score order, so we just update the highest score on each add
225 index[key].first = value.second;
229 // context default index
230 const auto *policy = file->m_send_set()->context_default();
233 const auto *v = policy->items();
234 for (auto it = v->begin(); it != v->end(); ++it)
235 add(sendIndex, sendPrefixIndex,
236 boost::string_ref(it->name()->c_str(), it->name()->size()),
237 ItemWithScore(*it, cnt++));
240 for (const auto &uidPolicy: *file->m_send_set()->user()) {
242 for (const auto it: *uidPolicy->policy()->items()) {
243 add(userSendIndex[uidPolicy->id()],
244 userSendPrefixIndex[uidPolicy->id()],
245 boost::string_ref(it->name()->c_str(), it->name()->size()),
246 ItemWithScore(it, cnt++));
251 void StorageBackendSerialized::StorageBackendSerializedImpl::releaseMMap() {
252 assert(MAP_FAILED != mem);
255 if (munmap(mem, length) != 0)
256 tslog::log_error("munmap(): ", tslog::print_errno(errno), "\n");
258 mem = static_cast<decltype(mem)>(MAP_FAILED);
262 void StorageBackendSerialized::StorageBackendSerializedImpl::releaseFD() {
266 tslog::log_error("close(): ", tslog::print_errno(errno), "\n");
271 void StorageBackendSerialized::StorageBackendSerializedImpl::release() {
272 if (-1 != fd) { // we need to check it, because we may have initialized the storage directly from File *
277 if (nullptr != serializer.get()) {
278 serializer.reset(nullptr);
284 bool StorageBackendSerialized::StorageBackendSerializedImpl::init(const char *filename, bool verify) {
285 assert(nullptr == file);
287 auto err = [filename] (const char *what) {
288 tslog::log_error("Can't ", what, " ", filename, ": ", tslog::print_errno(errno), "\n");
292 fd = open(filename, O_RDONLY);
296 auto openGuard = transaction_guard::makeGuard([&] () { releaseFD(); });
300 if (fstat(fd, &buf) == -1)
303 length = buf.st_size;
304 if (length > MAX_SFILE_SIZE) {
305 tslog::log_error("Serialized file size(", length, ") is too large. (>", MAX_SFILE_SIZE, ") bytes.\n");
309 mem = reinterpret_cast<uint8_t*>(mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, 0));
310 if (MAP_FAILED == mem)
313 auto mmapGuard = transaction_guard::makeGuard([&] () { releaseMMap(); });
316 auto verifier = flatbuffers::Verifier(mem, length);
317 if (!FB::VerifyFileBuffer(verifier) || !FB::FileBufferHasIdentifier(mem)) {
318 tslog::log_error("verification of serialized data: failed\n");
327 bool res = file != nullptr;
333 bool StorageBackendSerialized::StorageBackendSerializedImpl::init(const FB::File *f) {
334 assert(nullptr == file);
341 bool StorageBackendSerialized::StorageBackendSerializedImpl::initFromXML(const char *config_name) {
342 assert(nullptr == file);
343 assert(nullptr == serializer.get());
345 serializer.reset(new ldp_xml_parser::Serializer());
347 size_t serialized_size;
348 uint8_t *data = serializer->serialize(config_name, serialized_size);
352 return init(FB::GetFile(data));
355 void StorageBackendSerialized::StorageBackendSerializedImpl::printContent(const bool xml_format) const {
356 print_content::use_xml_format(xml_format);
360 /*************************************************/
362 #define TYPE_HELPER(T, t) \
364 struct type_helper<ldp_xml_parser::MatchItem##T> { \
365 typedef FB::T##Set policy_set_type; \
366 typedef FB::Policy##T policy_type; \
369 auto StorageBackendSerialized::StorageBackendSerializedImpl::getPolicySet<ldp_xml_parser::MatchItem##T>() \
370 -> const typename type_helper<ldp_xml_parser::MatchItem##T>::policy_set_type * { \
372 return file->m_##t##_set(); \
375 TYPE_HELPER(Own, own)
376 TYPE_HELPER(Send, send)
377 TYPE_HELPER(Receive, receive)
378 TYPE_HELPER(Access, access)
380 bool StorageBackendSerialized::init(const char *filename, bool verify) {
381 return pimpl->init(filename, verify);
384 bool StorageBackendSerialized::init(const FB::File *f) {
385 return pimpl->init(f);
388 bool StorageBackendSerialized::initFromXML(const char *config_name) {
389 return pimpl->initFromXML(config_name);
392 void StorageBackendSerialized::release() {
396 void StorageBackendSerialized::printContent(const bool xml_format) const {
397 pimpl->printContent(xml_format);
400 template <typename T>
401 ldp_xml_parser::DecisionItem StorageBackendSerialized::getDecisionItemContextMandatory(const T &item) const {
402 return getDecisionItem(item, pimpl->getPolicySet<T>()->context_mandatory());
406 ldp_xml_parser::DecisionItem StorageBackendSerialized::getDecisionItemContextDefault(const MatchItemSend &item) const {
407 return pimpl->getDecisionFromSendIndex(item);
411 ldp_xml_parser::DecisionItem StorageBackendSerialized::getDecisionItemUser(uid_t uid, const MatchItemSend &item) const {
412 auto *policyPair = pimpl->getPolicySet<MatchItemSend>()->user()->LookupByKey(uid);
413 if (nullptr == policyPair)
414 return ldp_xml_parser::Decision::ANY;
415 return pimpl->getDecisionFromSendIndex(item, uid);
418 template <typename T>
419 ldp_xml_parser::DecisionItem StorageBackendSerialized::getDecisionItemContextDefault(const T &item) const {
420 return getDecisionItem(item, pimpl->getPolicySet<T>()->context_default());
423 template <typename T>
424 ldp_xml_parser::DecisionItem StorageBackendSerialized::getDecisionItemUser(uid_t uid, const T &item) const {
425 return getDecisionItemMaybeNull(item, pimpl->getPolicySet<T>()->user()->LookupByKey(uid));
428 template <typename T>
429 ldp_xml_parser::DecisionItem StorageBackendSerialized::getDecisionItemGroup(gid_t gid, const T &item) const {
430 return getDecisionItemMaybeNull(item, pimpl->getPolicySet<T>()->group()->LookupByKey(gid));
433 template <typename T>
434 bool StorageBackendSerialized::existsPolicyForGroup(gid_t gid) const {
435 return pimpl->getPolicySet<T>()->group()->LookupByKey(gid) != nullptr;
438 #define T_INSTANTIATION(T) \
439 template ldp_xml_parser::DecisionItem StorageBackendSerialized::getDecisionItemContextMandatory(const ldp_xml_parser::MatchItem##T &item) const; \
440 template ldp_xml_parser::DecisionItem StorageBackendSerialized::getDecisionItemContextDefault(const ldp_xml_parser::MatchItem##T &item) const;
443 T_INSTANTIATION(Send)
444 T_INSTANTIATION(Receive)
445 T_INSTANTIATION(Access)
447 #undef T_INSTANTIATION
449 #define T_INSTANTIATION2(T) \
450 template ldp_xml_parser::DecisionItem StorageBackendSerialized::getDecisionItemUser(uid_t uid, const ldp_xml_parser::MatchItem##T &item) const; \
451 template ldp_xml_parser::DecisionItem StorageBackendSerialized::getDecisionItemGroup(gid_t gid, const ldp_xml_parser::MatchItem##T &item) const; \
452 template bool StorageBackendSerialized::existsPolicyForGroup<ldp_xml_parser::MatchItem##T>(gid_t) const;
454 T_INSTANTIATION2(Own)
455 T_INSTANTIATION2(Send)
456 T_INSTANTIATION2(Receive)
458 #undef T_INSTANTIATION2
460 StorageBackendSerialized::StorageBackendSerialized()
461 : pimpl{new StorageBackendSerializedImpl} {
464 StorageBackendSerialized::~StorageBackendSerialized() {