security: Add trust anchor container

Change-Id: Ia527eee08b9e154eb2d3168182905ec082bd8441
Refs: #3292
diff --git a/src/security/v2/trust-anchor-container.cpp b/src/security/v2/trust-anchor-container.cpp
new file mode 100644
index 0000000..efb272f
--- /dev/null
+++ b/src/security/v2/trust-anchor-container.cpp
@@ -0,0 +1,119 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2017 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#include "trust-anchor-container.hpp"
+
+#include <boost/filesystem.hpp>
+
+namespace ndn {
+namespace security {
+namespace v2 {
+
+void
+TrustAnchorContainer::AnchorContainer::add(Certificate&& cert)
+{
+  AnchorContainerBase::insert(std::move(cert));
+}
+
+void
+TrustAnchorContainer::AnchorContainer::remove(const Name& certName)
+{
+  AnchorContainerBase::erase(certName);
+}
+
+void
+TrustAnchorContainer::insert(const std::string& groupId, Certificate&& cert)
+{
+  auto group = m_groups.find(groupId);
+  if (group == m_groups.end()) {
+    std::tie(group, std::ignore) = m_groups.insert(make_shared<StaticTrustAnchorGroup>(m_anchors, groupId));
+  }
+  auto* staticGroup = dynamic_cast<StaticTrustAnchorGroup*>(&**group);
+  if (staticGroup == nullptr) {
+    BOOST_THROW_EXCEPTION(Error("Cannot add static anchor to a non-static anchor group " + groupId));
+  }
+  staticGroup->add(std::move(cert));
+}
+
+void
+TrustAnchorContainer::insert(const std::string& groupId, const boost::filesystem::path& path,
+                             time::nanoseconds refreshPeriod, bool isDir)
+{
+  if (m_groups.count(groupId) != 0) {
+    BOOST_THROW_EXCEPTION(Error("Cannot create dynamic group, because group " + groupId + " already exists"));
+  }
+
+  m_groups.insert(make_shared<DynamicTrustAnchorGroup>(m_anchors, groupId, path, refreshPeriod, isDir));
+}
+
+const Certificate*
+TrustAnchorContainer::find(const Name& keyName) const
+{
+  const_cast<TrustAnchorContainer*>(this)->refresh();
+
+  auto cert = m_anchors.lower_bound(keyName);
+  if (cert == m_anchors.end() || !keyName.isPrefixOf(cert->getName()))
+    return nullptr;
+  return &*cert;
+}
+
+const Certificate*
+TrustAnchorContainer::find(const Interest& interest) const
+{
+  const_cast<TrustAnchorContainer*>(this)->refresh();
+
+  for (auto cert = m_anchors.lower_bound(interest.getName());
+       cert != m_anchors.end() && interest.getName().isPrefixOf(cert->getName());
+       ++cert) {
+    if (interest.matchesData(*cert)) {
+      return &*cert;
+    }
+  }
+  return nullptr;
+}
+
+TrustAnchorGroup&
+TrustAnchorContainer::getGroup(const std::string& groupId) const
+{
+  auto group = m_groups.find(groupId);
+  if (group == m_groups.end()) {
+    BOOST_THROW_EXCEPTION(Error("Trust anchor group " + groupId + " does not exist"));
+  }
+  return **group;
+}
+
+size_t
+TrustAnchorContainer::size() const
+{
+  return m_anchors.size();
+}
+
+void
+TrustAnchorContainer::refresh()
+{
+  for (auto it = m_groups.begin(); it != m_groups.end(); ++it) {
+    m_groups.modify(it, [] (shared_ptr<TrustAnchorGroup>& group) { group->refresh(); });
+  }
+}
+
+} // namespace v2
+} // namespace security
+} // namespace ndn
diff --git a/src/security/v2/trust-anchor-container.hpp b/src/security/v2/trust-anchor-container.hpp
new file mode 100644
index 0000000..49e4999
--- /dev/null
+++ b/src/security/v2/trust-anchor-container.hpp
@@ -0,0 +1,177 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2017 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#ifndef NDN_SECURITY_V2_TRUST_ANCHOR_CONTAINER_HPP
+#define NDN_SECURITY_V2_TRUST_ANCHOR_CONTAINER_HPP
+
+#include "trust-anchor-group.hpp"
+#include "certificate.hpp"
+#include "../../interest.hpp"
+
+#include <boost/multi_index_container.hpp>
+#include <boost/multi_index/hashed_index.hpp>
+#include <boost/multi_index/ordered_index.hpp>
+#include <boost/multi_index/mem_fun.hpp>
+
+namespace ndn {
+namespace security {
+namespace v2 {
+
+/**
+ * @brief represents a container for trust anchors.
+ *
+ * There are two kinds of anchors:
+ * - static anchors that are permanent for the lifetime of the container
+ * - dynamic anchors that are periodically updated.
+ *
+ * Trust anchors are organized in groups. Each group has a unique group id.  The same anchor
+ * certificate (same name without considering the implicit digest) can be inserted into
+ * multiple groups, but no more than once into each.
+ *
+ * Dynamic groups are created using the appropriate TrustAnchorContainer::insert method. Once
+ * created, the dynamic anchor group cannot be updated.
+ *
+ * The returned pointer to Certificate from `find` methods is only guaranteed to be valid until
+ * the next invocation of `find` and may be invalidated afterwards.
+ */
+class TrustAnchorContainer : noncopyable
+{
+public:
+  class Error : public std::runtime_error
+  {
+  public:
+    explicit
+    Error(const std::string& what)
+      : std::runtime_error(what)
+    {
+    }
+  };
+
+  /**
+   * @brief Insert a static trust anchor.
+   *
+   * @param groupId  Certificate group id.
+   * @param cert     Certificate to insert.
+   *
+   * If @p cert (same name without considering implicit digest) already exists in the group @p
+   * groupId, this method has no effect.
+   *
+   * @throw Error @p groupId is a dynamic anchor group .
+   */
+  void
+  insert(const std::string& groupId, Certificate&& cert);
+
+  /**
+   * @brief Insert dynamic trust anchors from path.
+   *
+   * @param groupId        Certificate group id, must not be empty.
+   * @param path           Specifies the path to load the trust anchors.
+   * @param refreshPeriod  Refresh period for the trust anchors, must be positive.
+   *                       Relevant trust anchors will only be updated when find is called
+   * @param isDir          Tells whether the path is a directory or a single file.
+   *
+   * @throw std::invalid_argument @p refreshPeriod is not positive
+   * @throw Error a group with @p groupId already exists
+   */
+  void
+  insert(const std::string& groupId, const boost::filesystem::path& path,
+         time::nanoseconds refreshPeriod, bool isDir = false);
+
+  /**
+   * @brief Search for certificate across all groups (longest prefix match)
+   * @param keyName  Key name prefix for searching the certificate.
+   * @return The found certificate, nullptr if not found.
+   *
+   * @note The returned value may be invalidated after next call to one of `find` methods.
+   */
+  const Certificate*
+  find(const Name& keyName) const;
+
+  /**
+   * @brief Find certificate given interest
+   * @param interest  The input interest packet.
+   * @return The found certificate, nullptr if not found.
+   *
+   * @note The returned value may be invalidated after next call to one of `find` methods.
+   *
+   * @note Interest with implicit digest is not supported.
+   *
+   * @note ChildSelector is not supported.
+   */
+  const Certificate*
+  find(const Interest& interest) const;
+
+  /**
+   * @brief Get trusted anchor group
+   * @throw Error @p groupId does not exist
+   */
+  TrustAnchorGroup&
+  getGroup(const std::string& groupId) const;
+
+  /**
+   * @brief Get number of trust anchors across all groups
+   */
+  size_t
+  size() const;
+
+private:
+  void
+  refresh();
+
+private:
+  using AnchorContainerBase = boost::multi_index::multi_index_container<
+    Certificate,
+    boost::multi_index::indexed_by<
+      boost::multi_index::ordered_unique<
+        boost::multi_index::const_mem_fun<Data, const Name&, &Data::getName>
+      >
+    >
+  >;
+
+  class AnchorContainer : public CertContainerInterface,
+                          public AnchorContainerBase
+  {
+  public:
+    void
+    add(Certificate&& cert) final;
+
+    void
+    remove(const Name& certName) final;
+  };
+
+  using GroupContainer = boost::multi_index::multi_index_container<
+    shared_ptr<TrustAnchorGroup>,
+    boost::multi_index::indexed_by<
+      boost::multi_index::hashed_unique<
+        boost::multi_index::const_mem_fun<TrustAnchorGroup, const std::string&, &TrustAnchorGroup::getId>
+      >
+    >
+  >;
+
+  GroupContainer m_groups;
+  AnchorContainer m_anchors;
+};
+
+} // namespace v2
+} // namespace security
+} // namespace ndn
+
+#endif // NDN_SECURITY_V2_TRUST_ANCHOR_CONTAINER_HPP
diff --git a/src/security/v2/trust-anchor-group.cpp b/src/security/v2/trust-anchor-group.cpp
new file mode 100644
index 0000000..6b94951
--- /dev/null
+++ b/src/security/v2/trust-anchor-group.cpp
@@ -0,0 +1,143 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2017 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#include "trust-anchor-group.hpp"
+
+#include "util/io.hpp"
+#include "util/logger.hpp"
+
+#include <set>
+#include <boost/filesystem.hpp>
+#include <boost/range/adaptor/map.hpp>
+#include <boost/range/algorithm/copy.hpp>
+#include <boost/range/iterator_range.hpp>
+
+namespace ndn {
+namespace security {
+namespace v2 {
+
+NDN_LOG_INIT(ndn.security.v2.TrustAnchorGroup);
+
+namespace fs = boost::filesystem;
+
+TrustAnchorGroup::TrustAnchorGroup(CertContainerInterface& certContainer, const std::string& id)
+  : m_certs(certContainer)
+  , m_id(id)
+{
+}
+
+size_t
+TrustAnchorGroup::size() const
+{
+  return m_anchorNames.size();
+}
+
+void
+TrustAnchorGroup::refresh()
+{
+  // base method does nothing
+}
+
+//////////////
+
+StaticTrustAnchorGroup::StaticTrustAnchorGroup(CertContainerInterface& certContainer, const std::string& id)
+  : TrustAnchorGroup(certContainer, id)
+{
+}
+
+void
+StaticTrustAnchorGroup::add(Certificate&& cert)
+{
+  if (m_anchorNames.count(cert.getName()) != 0) {
+    return;
+  }
+
+  m_anchorNames.insert(cert.getName());
+  m_certs.add(std::move(cert));
+}
+
+void
+StaticTrustAnchorGroup::remove(const Name& certName)
+{
+  m_anchorNames.erase(certName);
+  m_certs.remove(certName);
+}
+
+/////////////
+
+DynamicTrustAnchorGroup::DynamicTrustAnchorGroup(CertContainerInterface& certContainer, const std::string& id,
+                                                 const boost::filesystem::path& path,
+                                                 time::nanoseconds refreshPeriod, bool isDir)
+  : TrustAnchorGroup(certContainer, id)
+  , m_isDir(isDir)
+  , m_path(path)
+  , m_refreshPeriod(refreshPeriod)
+{
+  if (refreshPeriod <= time::nanoseconds::zero()) {
+    BOOST_THROW_EXCEPTION(std::runtime_error("Refresh period for the dynamic group must be positive"));
+  }
+
+  refresh();
+}
+
+void
+DynamicTrustAnchorGroup::refresh()
+{
+  if (m_expireTime > time::steady_clock::now()) {
+    return;
+  }
+  m_expireTime = time::steady_clock::now() + m_refreshPeriod;
+  NDN_LOG_TRACE("Reloading dynamic trust anchor group");
+
+  std::set<Name> oldAnchorNames = m_anchorNames;
+
+  auto loadCert = [this, &oldAnchorNames] (const fs::path& file) {
+    auto cert = io::load<Certificate>(file.string());
+    if (cert != nullptr) {
+      if (m_anchorNames.count(cert->getName()) == 0) {
+        m_anchorNames.insert(cert->getName());
+        m_certs.add(std::move(*cert));
+      }
+      else {
+        oldAnchorNames.erase(cert->getName());
+      }
+    }
+  };
+
+  if (!m_isDir) {
+    loadCert(m_path);
+  }
+  else {
+    if (fs::exists(m_path)) {
+      std::for_each(fs::directory_iterator(m_path), fs::directory_iterator(), loadCert);
+    }
+  }
+
+  // remove old certs
+  for (const auto& oldAnchorName : oldAnchorNames) {
+    m_anchorNames.erase(oldAnchorName);
+    m_certs.remove(oldAnchorName);
+  }
+}
+
+} // namespace v2
+} // namespace security
+} // namespace ndn
diff --git a/src/security/v2/trust-anchor-group.hpp b/src/security/v2/trust-anchor-group.hpp
new file mode 100644
index 0000000..356a2a3
--- /dev/null
+++ b/src/security/v2/trust-anchor-group.hpp
@@ -0,0 +1,164 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2017 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#ifndef NDN_SECURITY_V2_TRUST_ANCHOR_GROUP_HPP
+#define NDN_SECURITY_V2_TRUST_ANCHOR_GROUP_HPP
+
+#include "../../data.hpp"
+#include "certificate.hpp"
+
+#include <set>
+#include <boost/filesystem/path.hpp>
+
+namespace ndn {
+namespace security {
+namespace v2 {
+
+class CertContainerInterface
+{
+public:
+  virtual void
+  add(Certificate&& cert) = 0;
+
+  virtual void
+  remove(const Name& certName) = 0;
+};
+
+/**
+ * @brief A group of trust anchors
+ */
+class TrustAnchorGroup : noncopyable
+{
+public:
+  /**
+   * @brief Create an anchor group
+   */
+  explicit
+  TrustAnchorGroup(CertContainerInterface& certContainer, const std::string& id);
+
+  /**
+   * @return group id
+   */
+  const std::string&
+  getId() const
+  {
+    return m_id;
+  }
+
+  /**
+   * @return number of certificates in the group
+   */
+  size_t
+  size() const;
+
+  /**
+   * @brief Request certificate refresh
+   */
+  virtual void
+  refresh();
+
+protected:
+  CertContainerInterface& m_certs;
+  std::set<Name> m_anchorNames;
+
+private:
+  std::string m_id;
+};
+
+/**
+ * @brief Static trust anchor group
+ */
+class StaticTrustAnchorGroup : public TrustAnchorGroup
+{
+public:
+  /**
+   * @brief Create a static trust anchor group
+   * @param certContainer  Reference to CertContainerInterface instance
+   * @param id             Group id
+   */
+  StaticTrustAnchorGroup(CertContainerInterface& certContainer, const std::string& id);
+
+  /**
+   * @brief Load static anchor @p cert
+   */
+  void
+  add(Certificate&& cert);
+
+  /**
+   * @brief Remove static anchor @p certName
+   */
+  void
+  remove(const Name& certName);
+};
+
+/**
+ * @brief Dynamic trust anchor group
+ */
+class DynamicTrustAnchorGroup : public TrustAnchorGroup
+{
+public:
+  /**
+   * @brief Create a dynamic trust anchor group
+   *
+   * This contructor would load all the certificates from @p path and will be refreshing
+   * certificates every @p refreshPeriod time period.
+   *
+   * Note that refresh is not scheduled, but is performed upon "find" operations.
+   *
+   * When @p isDir is false and @p path doesn't point to a valid certificate (file doesn't
+   * exist or content is not a valid certificate), the dynamic anchor group will be empty until
+   * file gets created.  If file disappears or gets corrupted, the anchor group becomes empty.
+   *
+   * When @p idDir is true and @p path does't point to a valid folder, folder is empty, or
+   * doesn't contain valid certificates, the group will be empty until certificate files are
+   * placed in the folder.  If folder is removed, becomes empty, or no longer contains valid
+   * certificates, the anchor group becomes empty.
+   *
+   * Upon refresh, the existing certificates are not changed.
+   *
+   * @param certContainer  A certificate container into which trust anchors from the group will
+   *                       be added
+   * @param id             Group id
+   * @param path           File path for trust anchor(s), could be directory or file. If it is a
+   *                       directory, all the certificates in the directory will be loaded.
+   * @param refreshPeriod  Refresh time for the anchors under @p path, must be positive.
+   * @param isDir          Tells whether the path is a directory or a single file.
+   *
+   * @throw std::invalid_argument @p refreshPeriod is negative
+   */
+  DynamicTrustAnchorGroup(CertContainerInterface& certContainer, const std::string& id,
+                          const boost::filesystem::path& path, time::nanoseconds refreshPeriod, bool isDir = false);
+
+  void
+  refresh() override;
+
+private:
+  bool m_isDir;
+  boost::filesystem::path m_path;
+  time::nanoseconds m_refreshPeriod;
+  time::steady_clock::TimePoint m_expireTime;
+};
+
+} // namespace v2
+} // namespace security
+} // namespace ndn
+
+#endif // NDN_SECURITY_V2_TRUST_ANCHOR_GROUP_HPP