security: Change the ownership model of Pib and its related entities

Change-Id: I6816a0fd5c7af490f7e98db196e0214219f4b05c
Refs: #3349
diff --git a/src/security/pib/detail/identity-impl.cpp b/src/security/pib/detail/identity-impl.cpp
new file mode 100644
index 0000000..af01dc5
--- /dev/null
+++ b/src/security/pib/detail/identity-impl.cpp
@@ -0,0 +1,122 @@
+/* -*- 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 "identity-impl.hpp"
+#include "../pib-impl.hpp"
+#include "../pib.hpp"
+
+namespace ndn {
+namespace security {
+namespace pib {
+namespace detail {
+
+IdentityImpl::IdentityImpl(const Name& identityName, shared_ptr<PibImpl> impl, bool needInit)
+  : m_name(identityName)
+  , m_isDefaultKeyLoaded(false)
+  , m_keys(identityName, impl)
+  , m_impl(impl)
+{
+  BOOST_ASSERT(impl != nullptr);
+
+  if (needInit) {
+    m_impl->addIdentity(m_name);
+  }
+  else if (!m_impl->hasIdentity(m_name)) {
+    BOOST_THROW_EXCEPTION(Pib::Error("Identity " + m_name.toUri() + " does not exist"));
+  }
+}
+
+Key
+IdentityImpl::addKey(const uint8_t* key, size_t keyLen, const Name& keyName)
+{
+  BOOST_ASSERT(m_keys.isConsistent());
+
+  if (m_keys.find(keyName) != m_keys.end()) {
+    BOOST_THROW_EXCEPTION(Pib::Error("Cannot overwrite existing key " + keyName.toUri()));
+  }
+
+  return m_keys.add(key, keyLen, keyName);
+}
+
+void
+IdentityImpl::removeKey(const Name& keyName)
+{
+  BOOST_ASSERT(m_keys.isConsistent());
+
+  if (m_isDefaultKeyLoaded && m_defaultKey.getName() == keyName)
+    m_isDefaultKeyLoaded = false;
+
+  m_keys.remove(keyName);
+}
+
+Key
+IdentityImpl::getKey(const Name& keyName) const
+{
+  BOOST_ASSERT(m_keys.isConsistent());
+
+  return m_keys.get(keyName);
+}
+
+const KeyContainer&
+IdentityImpl::getKeys() const
+{
+  BOOST_ASSERT(m_keys.isConsistent());
+
+  return m_keys;
+}
+
+const Key&
+IdentityImpl::setDefaultKey(const Name& keyName)
+{
+  BOOST_ASSERT(m_keys.isConsistent());
+
+  m_defaultKey = m_keys.get(keyName);
+  m_isDefaultKeyLoaded = true;
+  m_impl->setDefaultKeyOfIdentity(m_name, keyName);
+  return m_defaultKey;
+}
+
+const Key&
+IdentityImpl::setDefaultKey(const uint8_t* key, size_t keyLen, const Name& keyName)
+{
+  addKey(key, keyLen, keyName);
+  return setDefaultKey(keyName);
+}
+
+const Key&
+IdentityImpl::getDefaultKey() const
+{
+  BOOST_ASSERT(m_keys.isConsistent());
+
+  if (!m_isDefaultKeyLoaded) {
+    m_defaultKey = m_keys.get(m_impl->getDefaultKeyOfIdentity(m_name));
+    m_isDefaultKeyLoaded = true;
+  }
+
+  BOOST_ASSERT(m_impl->getDefaultKeyOfIdentity(m_name) == m_defaultKey.getName());
+
+  return m_defaultKey;
+}
+
+} // namespace detail
+} // namespace pib
+} // namespace security
+} // namespace ndn
diff --git a/src/security/pib/detail/identity-impl.hpp b/src/security/pib/detail/identity-impl.hpp
new file mode 100644
index 0000000..b654348
--- /dev/null
+++ b/src/security/pib/detail/identity-impl.hpp
@@ -0,0 +1,138 @@
+/* -*- 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_PIB_DETAIL_IDENTITY_IMPL_HPP
+#define NDN_SECURITY_PIB_DETAIL_IDENTITY_IMPL_HPP
+
+#include "../key-container.hpp"
+
+namespace ndn {
+namespace security {
+namespace pib {
+
+class PibImpl;
+
+namespace detail {
+
+/**
+ * @brief Backend instance of Identity
+ *
+ * An Identity has only one backend instance, but may have multiple frontend handles.
+ * Each frontend handle is associated with the only one backend IdentityImpl.
+ *
+ * @throw PibImpl::Error when underlying implementation has non-semantic error.
+ */
+class IdentityImpl : noncopyable
+{
+public:
+  /**
+   * @brief Create an Identity with @p identityName.
+   *
+   * @param identityName The name of the Identity.
+   * @param impl The PIB backend implementation.
+   * @param needInit If true, create the identity in backend when the identity does not exist.
+   *                 Otherwise, throw Pib::Error when the identity does not exist.
+   */
+  IdentityImpl(const Name& identityName, shared_ptr<PibImpl> impl, bool needInit = false);
+
+  /// @brief Get the name of the identity.
+  const Name&
+  getName() const
+  {
+    return m_name;
+  }
+
+  /**
+   * @brief Add a @p key of @p keyLen bytes with @p keyName (in PKCS#8 format).
+   *
+   * If no default key is set before, the new key will be set as the default key of the identity.
+   *
+   * @return the added key.
+   * @throw std::invalid_argument key name does not match identity
+   * @throw Pib::Error a key with the same name already exists
+   */
+  Key
+  addKey(const uint8_t* key, size_t keyLen, const Name& keyName);
+
+  /**
+   * @brief Remove a key with @p keyName
+   * @throw std::invalid_argument @p keyName does not match identity
+   */
+  void
+  removeKey(const Name& keyName);
+
+  /**
+   * @brief Get a key with id @p keyName.
+   *
+   * @throw std::invalid_argument @p keyName does not match identity
+   * @throw Pib::Error the key does not exist.
+   */
+  Key
+  getKey(const Name& keyName) const;
+
+  /**
+   * @brief Get all keys for this Identity.
+   */
+  const KeyContainer&
+  getKeys() const;
+
+  /**
+   * @brief Set the key with id @p keyName.
+   * @throw std::invalid_argument @p keyName does not match identity
+   * @throw Pib::Error the key does not exist.
+   * @return The default key
+   */
+  const Key&
+  setDefaultKey(const Name& keyName);
+
+  /**
+   * @brief Add @p key of @p keyLen bytes with @p keyName and set it as the default key
+   * @throw std::invalid_argument @p keyName does not match identity
+   * @throw Pib::Error the key with the same name already exists
+   * @return the default key
+   */
+  const Key&
+  setDefaultKey(const uint8_t* key, size_t keyLen, const Name& keyName);
+
+  /**
+   * @brief Get the default key for this Identity.
+   * @throw Pib::Error the default key does not exist.
+   */
+  const Key&
+  getDefaultKey() const;
+
+private:
+  Name m_name;
+
+  mutable bool m_isDefaultKeyLoaded;
+  mutable Key m_defaultKey;
+
+  mutable KeyContainer m_keys;
+
+  shared_ptr<PibImpl> m_impl;
+};
+
+} // namespace detail
+} // namespace pib
+} // namespace security
+} // namespace ndn
+
+#endif // NDN_SECURITY_PIB_DETAIL_IDENTITY_IMPL_HPP
diff --git a/src/security/pib/detail/key-impl.cpp b/src/security/pib/detail/key-impl.cpp
new file mode 100644
index 0000000..35a0de6
--- /dev/null
+++ b/src/security/pib/detail/key-impl.cpp
@@ -0,0 +1,149 @@
+/* -*- 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 "key-impl.hpp"
+#include "../pib-impl.hpp"
+#include "../pib.hpp"
+#include "../../transform/public-key.hpp"
+
+namespace ndn {
+namespace security {
+namespace pib {
+namespace detail {
+
+KeyImpl::KeyImpl(const Name& keyName, const uint8_t* key, size_t keyLen, shared_ptr<PibImpl> impl)
+  : m_identity(v2::extractIdentityFromKeyName(keyName))
+  , m_keyName(keyName)
+  , m_key(key, keyLen)
+  , m_isDefaultCertificateLoaded(false)
+  , m_certificates(keyName, impl)
+  , m_impl(impl)
+{
+  BOOST_ASSERT(impl != nullptr);
+
+  if (m_impl->hasKey(m_keyName)) {
+    BOOST_THROW_EXCEPTION(Pib::Error("Cannot overwrite existing key " + m_keyName.toUri()));
+  }
+
+  transform::PublicKey publicKey;
+  try {
+    publicKey.loadPkcs8(key, keyLen);
+  }
+  catch (transform::PublicKey::Error&) {
+    BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid key bits"));
+  }
+  m_keyType = publicKey.getKeyType();
+
+  m_impl->addKey(m_identity, m_keyName, key, keyLen);
+}
+
+KeyImpl::KeyImpl(const Name& keyName, shared_ptr<PibImpl> impl)
+  : m_identity(v2::extractIdentityFromKeyName(keyName))
+  , m_keyName(keyName)
+  , m_isDefaultCertificateLoaded(false)
+  , m_certificates(keyName, impl)
+  , m_impl(impl)
+{
+  BOOST_ASSERT(impl != nullptr);
+
+  m_key = m_impl->getKeyBits(m_keyName);
+
+  transform::PublicKey key;
+  key.loadPkcs8(m_key.buf(), m_key.size());
+  m_keyType = key.getKeyType();
+}
+
+void
+KeyImpl::addCertificate(const v2::Certificate& certificate)
+{
+  BOOST_ASSERT(m_certificates.isConsistent());
+
+  if (m_certificates.find(certificate.getName()) != m_certificates.end()) {
+    BOOST_THROW_EXCEPTION(Pib::Error("Cannot overwrite existing certificate " + certificate.getName().toUri()));
+  }
+
+  m_certificates.add(certificate);
+}
+
+void
+KeyImpl::removeCertificate(const Name& certName)
+{
+  BOOST_ASSERT(m_certificates.isConsistent());
+
+  if (m_isDefaultCertificateLoaded && m_defaultCertificate.getName() == certName)
+    m_isDefaultCertificateLoaded = false;
+
+  m_certificates.remove(certName);
+}
+
+v2::Certificate
+KeyImpl::getCertificate(const Name& certName) const
+{
+  BOOST_ASSERT(m_certificates.isConsistent());
+
+  return m_certificates.get(certName);
+}
+
+const CertificateContainer&
+KeyImpl::getCertificates() const
+{
+  BOOST_ASSERT(m_certificates.isConsistent());
+
+  return m_certificates;
+}
+
+const v2::Certificate&
+KeyImpl::setDefaultCertificate(const Name& certName)
+{
+  BOOST_ASSERT(m_certificates.isConsistent());
+
+  m_defaultCertificate = m_certificates.get(certName);
+  m_impl->setDefaultCertificateOfKey(m_keyName, certName);
+  m_isDefaultCertificateLoaded = true;
+  return m_defaultCertificate;
+}
+
+const v2::Certificate&
+KeyImpl::setDefaultCertificate(const v2::Certificate& certificate)
+{
+  addCertificate(certificate);
+  return setDefaultCertificate(certificate.getName());
+}
+
+const v2::Certificate&
+KeyImpl::getDefaultCertificate() const
+{
+  BOOST_ASSERT(m_certificates.isConsistent());
+
+  if (!m_isDefaultCertificateLoaded) {
+    m_defaultCertificate = m_impl->getDefaultCertificateOfKey(m_keyName);
+    m_isDefaultCertificateLoaded = true;
+  }
+
+  BOOST_ASSERT(m_impl->getDefaultCertificateOfKey(m_keyName).wireEncode() == m_defaultCertificate.wireEncode());
+
+  return m_defaultCertificate;
+}
+
+} // namespace detail
+} // namespace pib
+} // namespace security
+} // namespace ndn
diff --git a/src/security/pib/detail/key-impl.hpp b/src/security/pib/detail/key-impl.hpp
new file mode 100644
index 0000000..c05e77e
--- /dev/null
+++ b/src/security/pib/detail/key-impl.hpp
@@ -0,0 +1,179 @@
+/* -*- 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_PIB_DETAIL_KEY_IMPL_HPP
+#define NDN_SECURITY_PIB_DETAIL_KEY_IMPL_HPP
+
+#include "../../../data.hpp"
+#include "../certificate-container.hpp"
+#include "../../security-common.hpp"
+
+namespace ndn {
+namespace security {
+namespace pib {
+
+class PibImpl;
+
+namespace detail {
+
+/**
+ * @brief Backend instance of Key
+ *
+ * An Key has only one backend instance, but may have multiple frontend handles.
+ * Each frontend handle is associated with the only one backend KeyImpl.
+ *
+ * @throw PibImpl::Error when underlying implementation has non-semantic error.
+ */
+class KeyImpl : noncopyable
+{
+public:
+  /**
+   * @brief Create a KeyImpl with @p keyName.
+   *
+   * If the key does not exist in the backend, create it in backend.
+   *
+   * @param keyName The name of the key.
+   * @param key The public key to add.
+   * @param keyLen The length of the key.
+   * @param impl The Pib backend implementation.
+   * @throw Pib::Error a key with the same @p keyName already exists.
+   */
+  KeyImpl(const Name& keyName, const uint8_t* key, size_t keyLen, shared_ptr<PibImpl> impl);
+
+  /**
+   * @brief Create a KeyImpl with @p keyName.
+   *
+   * @param keyName The name of the key.
+   * @param impl The Pib backend implementation.
+   * @throw Pib::Error the key does not exist.
+   */
+  KeyImpl(const Name& keyName, shared_ptr<PibImpl> impl);
+
+  /// @brief Get the name of the key.
+  const Name&
+  getName() const
+  {
+    return m_keyName;
+  }
+
+  /**
+   * @brief Get the name of the belonging identity.
+   */
+  const Name&
+  getIdentity() const
+  {
+    return m_identity;
+  }
+
+  /**
+   * @brief Get key type
+   */
+  KeyType
+  getKeyType() const
+  {
+    return m_keyType;
+  }
+
+  /**
+   * @brief Get public key bits
+   */
+  const Buffer&
+  getPublicKey() const
+  {
+    return m_key;
+  }
+
+  /**
+   * @brief Add @p certificate.
+   *
+   * If no default certificate is set before, the new certificate will be set as the default
+   * certificate of the key.
+   *
+   * @throw std::invalid_argument certificate name does not match key name
+   * @throw Pib::Error a certificate with the same name already exists
+   */
+  void
+  addCertificate(const v2::Certificate& certificate);
+
+  /**
+   * @brief Remove a certificate with @p certName
+   * @throw std::invalid_argument @p certName does not match key name
+   */
+  void
+  removeCertificate(const Name& certName);
+
+  /**
+   * @brief Get a certificate with @p certName
+   * @throw std::invalid_argument @p certName does not match key name
+   * @throw Pib::Error the certificate does not exist.
+   */
+  v2::Certificate
+  getCertificate(const Name& certName) const;
+
+  /// @brief Get all the certificates for this key.
+  const CertificateContainer&
+  getCertificates() const;
+
+  /**
+   * @brief Set an existing one with @p certName as the default certificate
+   * @throw std::invalid_argument @p certName does not match key name
+   * @throw Pib::Error the certificate does not exist.
+   * @return the default certificate
+   */
+  const v2::Certificate&
+  setDefaultCertificate(const Name& certName);
+
+  /**
+   * @brief Add @p certificate and set it as the default certificate of the key
+   * @throw std::invalid_argument @p certificate does not match key name
+   * @throw Pib::Error the certificate with the same name already exists.
+   * @return the default certificate
+   */
+  const v2::Certificate&
+  setDefaultCertificate(const v2::Certificate& certificate);
+
+  /**
+   * @brief Get the default certificate for this Key.
+   * @throw Pib::Error the default certificate does not exist.
+   */
+  const v2::Certificate&
+  getDefaultCertificate() const;
+
+private:
+  Name m_identity;
+  Name m_keyName;
+  Buffer m_key;
+  KeyType m_keyType;
+
+  mutable bool m_isDefaultCertificateLoaded;
+  mutable v2::Certificate m_defaultCertificate;
+
+  CertificateContainer m_certificates;
+
+  shared_ptr<PibImpl> m_impl;
+};
+
+} // namespace detail
+} // namespace pib
+} // namespace security
+} // namespace ndn
+
+#endif // NDN_SECURITY_PIB_DETAIL_KEY_IMPL_HPP