security: Refactoring creation of SecPublicInfo and SecTpm during KeyChain creation

The objective of this refactoring is to allow KeyChains with custom PIB
and TPM.  As of this commit, KeyChain no longer hard-codes PIB and TPM
instance creation.  Instead, creation is delegated to factory functions,
which need to be statically registered, e.g., using
`NDN_CXX_KEYCHAIN_REGISTER_PIB` and `NDN_CXX_KEYCHAIN_REGISTER_TPM`
macros.

Change-Id: I0d29b5ed8d74d99d8a56c4a6e9024f2587dd125e
Refs: #2384
diff --git a/src/security/key-chain.cpp b/src/security/key-chain.cpp
index 758c2f5..4c7d08f 100644
--- a/src/security/key-chain.cpp
+++ b/src/security/key-chain.cpp
@@ -23,15 +23,16 @@
 
 #include "key-chain.hpp"
 
+#include "../util/random.hpp"
+#include "../util/config-file.hpp"
+
 #include "sec-public-info-sqlite3.hpp"
-#include "sec-tpm-file.hpp"
 
 #ifdef NDN_CXX_HAVE_OSX_SECURITY
 #include "sec-tpm-osx.hpp"
-#endif
+#endif // NDN_CXX_HAVE_OSX_SECURITY
 
-#include "../util/random.hpp"
-#include "../util/config-file.hpp"
+#include "sec-tpm-file.hpp"
 
 namespace ndn {
 
@@ -40,22 +41,71 @@
 
 const RsaKeyParams KeyChain::DEFAULT_KEY_PARAMS;
 
+const std::string DEFAULT_PIB_SCHEME = "pib-sqlite3";
+
+#if defined(NDN_CXX_HAVE_OSX_SECURITY) and defined(NDN_CXX_WITH_OSX_KEYCHAIN)
+const std::string DEFAULT_TPM_SCHEME = "tpm-osxkeychain";
+#else
+const std::string DEFAULT_TPM_SCHEME = "tpm-file";
+#endif // defined(NDN_CXX_HAVE_OSX_SECURITY) and defined(NDN_CXX_WITH_OSX_KEYCHAIN)
+
+// When static library is used, not everything is compiled into the resulting binary.
+// Therefore, the following standard PIB and TPMs need to be registered here.
+// http://stackoverflow.com/q/9459980/2150331
+//
+// Also, cannot use Type::SCHEME, as its value may be uninitialized
+NDN_CXX_KEYCHAIN_REGISTER_PIB(SecPublicInfoSqlite3, "pib-sqlite3", "sqlite3");
+
+#ifdef NDN_CXX_HAVE_OSX_SECURITY
+NDN_CXX_KEYCHAIN_REGISTER_TPM(SecTpmOsx, "tpm-osxkeychain", "osx-keychain");
+#endif // NDN_CXX_HAVE_OSX_SECURITY
+
+NDN_CXX_KEYCHAIN_REGISTER_TPM(SecTpmFile, "tpm-file", "file");
+
+static std::map<std::string, KeyChain::PibCreateFunc>&
+getPibFactories()
+{
+  static std::map<std::string, KeyChain::PibCreateFunc> pibFactories;
+  return pibFactories;
+}
+
+static std::map<std::string, KeyChain::TpmCreateFunc>&
+getTpmFactories()
+{
+  static std::map<std::string, KeyChain::TpmCreateFunc> tpmFactories;
+  return tpmFactories;
+}
+
+void
+KeyChain::registerPibImpl(std::initializer_list<std::string> schemes,
+                          KeyChain::PibCreateFunc createFunc)
+{
+  for (const std::string& scheme : schemes) {
+    getPibFactories()[scheme] = createFunc;
+  }
+}
+
+void
+KeyChain::registerTpmImpl(std::initializer_list<std::string> schemes,
+                          KeyChain::TpmCreateFunc createFunc)
+{
+  for (const std::string& scheme : schemes) {
+    getTpmFactories()[scheme] = createFunc;
+  }
+}
+
 KeyChain::KeyChain()
   : m_pib(nullptr)
   , m_tpm(nullptr)
   , m_lastTimestamp(time::toUnixTimestamp(time::system_clock::now()))
 {
-  initialize("", "", false);
-}
+  ConfigFile config;
+  const ConfigFile::Parsed& parsed = config.getParsedConfiguration();
 
-template<class T>
-inline
-KeyChain::KeyChain(T traits)
-  : m_pib(new typename T::Pib)
-  , m_tpm(nullptr)
-  , m_lastTimestamp(time::toUnixTimestamp(time::system_clock::now()))
-{
-  initialize(T::Pib::SCHEME, T::Tpm::SCHEME, false);
+  std::string pibLocator = parsed.get<std::string>("pib", "");
+  std::string tpmLocator = parsed.get<std::string>("tpm", "");
+
+  initialize(pibLocator, tpmLocator, false);
 }
 
 KeyChain::KeyChain(const std::string& pibName,
@@ -65,151 +115,80 @@
   , m_tpm(nullptr)
   , m_lastTimestamp(time::toUnixTimestamp(time::system_clock::now()))
 {
-  std::string pibLocator;
-  std::string tpmLocator;
-
-  if (tpmName == "file")
-    tpmLocator = SecTpmFile::SCHEME;
-#if defined(NDN_CXX_HAVE_OSX_SECURITY)
-  else if (tpmName == "osx-keychain")
-    tpmLocator = SecTpmOsx::SCHEME;
-#endif //NDN_CXX_HAVE_OSX_SECURITY
-  else
-    tpmLocator = tpmName;
-
-  if (pibName == "sqlite3")
-    pibLocator = SecPublicInfoSqlite3::SCHEME;
-  else
-    pibLocator = pibName;
-
-  initialize(pibLocator, tpmLocator, allowReset);
+  initialize(pibName, tpmName, allowReset);
 }
 
 KeyChain::~KeyChain()
 {
-  if (m_pib != nullptr)
-    delete m_pib;
+}
 
-  if (m_tpm != nullptr)
-    delete m_tpm;
+static inline std::tuple<std::string/*type*/, std::string/*location*/>
+parseUri(const std::string& uri)
+{
+  size_t pos = uri.find(':');
+  if (pos != std::string::npos) {
+    return std::make_tuple(uri.substr(0, pos),
+                           uri.substr(pos + 1));
+  }
+  else {
+    return std::make_tuple(uri, "");
+  }
 }
 
 void
-KeyChain::initialize(const std::string& pib,
-                     const std::string& tpm,
+KeyChain::initialize(const std::string& pibLocatorUri,
+                     const std::string& tpmLocatorUri,
                      bool allowReset)
 {
-  ConfigFile config;
-  const ConfigFile::Parsed& parsed = config.getParsedConfiguration();
+  BOOST_ASSERT(!getPibFactories().empty());
+  BOOST_ASSERT(!getTpmFactories().empty());
 
-  std::string defaultTpmLocator;
+  std::string pibScheme, pibLocation;
+  std::tie(pibScheme, pibLocation) = parseUri(pibLocatorUri);
+
+  std::string tpmScheme, tpmLocation;
+  std::tie(tpmScheme, tpmLocation) = parseUri(tpmLocatorUri);
+
+  // Find PIB and TPM factories
+  if (pibScheme.empty()) {
+    pibScheme = DEFAULT_PIB_SCHEME;
+  }
+  auto pibFactory = getPibFactories().find(pibScheme);
+  if (pibFactory == getPibFactories().end()) {
+    throw Error("PIB scheme '" + pibScheme + "' is not supported");
+  }
+
+  if (tpmScheme.empty()) {
+    tpmScheme = DEFAULT_TPM_SCHEME;
+  }
+  auto tpmFactory = getTpmFactories().find(tpmScheme);
+  if (tpmFactory == getTpmFactories().end()) {
+    throw Error("TPM scheme '" + tpmScheme + "' is not supported");
+  }
+
+  // Create PIB
+  m_pib = pibFactory->second(pibLocation);
+
+  std::string actualTpmLocator = tpmScheme + ":" + tpmLocation;
+
+  // Create TPM, checking that it matches to the previously associated one
   try {
-    defaultTpmLocator = parsed.get<std::string>("tpm");
-  }
-  catch (boost::property_tree::ptree_bad_path&) {
-    // tpm is not specified, take the default
-  }
-  catch (boost::property_tree::ptree_bad_data& error) {
-    throw ConfigFile::Error(error.what());
-  }
-
-  if (defaultTpmLocator.empty())
-#if defined(NDN_CXX_HAVE_OSX_SECURITY) and defined(NDN_CXX_WITH_OSX_KEYCHAIN)
-    defaultTpmLocator = SecTpmOsx::SCHEME;
-#else
-    defaultTpmLocator = SecTpmFile::SCHEME;
-#endif // defined(NDN_CXX_HAVE_OSX_SECURITY) and defined(NDN_CXX_WITH_OSX_KEYCHAIN)
-  else if (defaultTpmLocator == "osx-keychain")
-#if defined(NDN_CXX_HAVE_OSX_SECURITY)
-    defaultTpmLocator = SecTpmOsx::SCHEME;
-#else
-    throw Error("TPM Locator '" + defaultTpmLocator + "' is not supported on this platform");
-#endif // NDN_CXX_HAVE_OSX_SECURITY
-  else if (defaultTpmLocator == "file")
-    defaultTpmLocator = SecTpmFile::SCHEME;
-
-  std::string defaultPibLocator;
-  try {
-    defaultPibLocator = parsed.get<std::string>("pib");
-  }
-  catch (boost::property_tree::ptree_bad_path&) {
-    // pib is not specified, take the default
-  }
-  catch (boost::property_tree::ptree_bad_data& error) {
-    throw ConfigFile::Error(error.what());
-  }
-
-  if (defaultPibLocator.empty() || defaultPibLocator == "sqlite3")
-    defaultPibLocator = SecPublicInfoSqlite3::SCHEME;
-
-  std::string pibLocator = pib;
-  std::string tpmLocator = tpm;
-
-  if (pibLocator == "")
-    pibLocator = defaultPibLocator;
-
-  if (defaultPibLocator == pibLocator)
-    tpmLocator = defaultTpmLocator;
-
-  initializePib(pibLocator);
-
-  std::string currentTpmLocator;
-  try {
-    currentTpmLocator = m_pib->getTpmLocator();
-
-    if (currentTpmLocator != tpmLocator) {
-      if (!allowReset) {
-        // Tpm mismatch, but we do not want to reset PIB
-        throw MismatchError("TPM locator supplied and TPM locator in PIB mismatch: " +
-                            currentTpmLocator + " != " + tpmLocator);
-      }
-      else {
-        // reset is explicitly required
-        tpmLocator = currentTpmLocator;
-      }
-    }
+    if (!allowReset &&
+        !m_pib->getTpmLocator().empty() && m_pib->getTpmLocator() != actualTpmLocator)
+      // Tpm mismatch, but we do not want to reset PIB
+      throw MismatchError("TPM locator supplied does not match TPM locator in PIB: " +
+                          m_pib->getTpmLocator() + " != " + actualTpmLocator);
   }
   catch (SecPublicInfo::Error&) {
     // TPM locator is not set in PIB yet.
   }
 
-  initializeTpm(tpmLocator); // note that key mismatch may still happen
-                             // if the TPM locator is initially set to a wrong one
-                             // or if the PIB was shared by more than one TPMs before.
-                             // This is due to the old PIB does not have TPM info,
-                             // new pib should not have this problem.
+  // note that key mismatch may still happen if the TPM locator is initially set to a
+  // wrong one or if the PIB was shared by more than one TPMs before.  This is due to the
+  // old PIB does not have TPM info, new pib should not have this problem.
 
-  m_pib->setTpmLocator(tpmLocator);
-}
-
-void
-KeyChain::initializeTpm(const std::string& locator)
-{
-  size_t pos = locator.find(':');
-  std::string type = locator.substr(0, pos + 1);
-  std::string location = locator.substr(pos + 1);
-
-  if (type == SecTpmFile::SCHEME)
-    m_tpm = new SecTpmFile(location);
-#if defined(NDN_CXX_HAVE_OSX_SECURITY) and defined(NDN_CXX_WITH_OSX_KEYCHAIN)
-  else if (type == SecTpmOsx::SCHEME)
-    m_tpm = new SecTpmOsx(location);
-#endif
-  else
-    throw Error("Tpm locator error: Unsupported Tpm type: " + type);
-}
-
-void
-KeyChain::initializePib(const std::string& locator)
-{
-  size_t pos = locator.find(':');
-  std::string type = locator.substr(0, pos + 1);
-  std::string location = locator.substr(pos + 1);
-
-  if (type == SecPublicInfoSqlite3::SCHEME)
-    m_pib = new SecPublicInfoSqlite3(location);
-  else
-    throw Error("Pib locator error: Unsupported Pib type: " + type);
+  m_tpm = tpmFactory->second(tpmLocation);
+  m_pib->setTpmLocator(actualTpmLocator);
 }
 
 Name
diff --git a/src/security/key-chain.hpp b/src/security/key-chain.hpp
index 1973c77..cc45dc3 100644
--- a/src/security/key-chain.hpp
+++ b/src/security/key-chain.hpp
@@ -35,18 +35,11 @@
 #include "../interest.hpp"
 #include "../util/crypto.hpp"
 #include "../util/random.hpp"
+#include <initializer_list>
 
 
 namespace ndn {
 
-template<class TypePib, class TypeTpm>
-class KeyChainTraits
-{
-public:
-  typedef TypePib Pib;
-  typedef TypeTpm Tpm;
-};
-
 class KeyChain : noncopyable
 {
 public:
@@ -74,11 +67,34 @@
     }
   };
 
-  KeyChain();
+  typedef function<unique_ptr<SecPublicInfo> (const std::string&)> PibCreateFunc;
+  typedef function<unique_ptr<SecTpm>(const std::string&)> TpmCreateFunc;
 
-  template<class KeyChainTraits>
-  explicit
-  KeyChain(KeyChainTraits traits);
+  /**
+   * @brief Register a new PIB
+   * @param schemes List of scheme with which this PIB will be associated
+   */
+  template<class PibType>
+  static void
+  registerPib(std::initializer_list<std::string> schemes);
+
+  /**
+   * @brief Register a new TPM
+   * @param schemes List of scheme with which this TPM will be associated
+   */
+  template<class TpmType>
+  static void
+  registerTpm(std::initializer_list<std::string> schemes);
+
+  /**
+   * @brief Constructor to create KeyChain with default PIB and TPM
+   *
+   * Default PIB and TPM are platform-dependent and can be overriden system-wide or on
+   * per-use basis.
+   *
+   * @todo Add detailed description about config file behavior here
+   */
+  KeyChain();
 
   /**
    * @brief KeyChain constructor
@@ -658,16 +674,10 @@
 
 private:
   void
-  initialize(const std::string& pibLocator,
-             const std::string& tpmLocator,
+  initialize(const std::string& pibLocatorUri,
+             const std::string& tpmLocatorUri,
              bool needReset);
 
-  void
-  initializeTpm(const std::string& locator);
-
-  void
-  initializePib(const std::string& locator);
-
   /**
    * @brief Determine signature type
    *
@@ -732,14 +742,20 @@
   signPacketWrapper(Interest& interest, const Signature& signature,
                     const Name& keyName, DigestAlgorithm digestAlgorithm);
 
+  static void
+  registerPibImpl(std::initializer_list<std::string> schemes, PibCreateFunc createFunc);
+
+  static void
+  registerTpmImpl(std::initializer_list<std::string> schemes, TpmCreateFunc createFunc);
+
 public:
   static const Name DEFAULT_PREFIX;
   // RsaKeyParams is set to be default for backward compatibility.
   static const RsaKeyParams DEFAULT_KEY_PARAMS;
 
 private:
-  SecPublicInfo* m_pib;
-  SecTpm* m_tpm;
+  std::unique_ptr<SecPublicInfo> m_pib;
+  std::unique_ptr<SecTpm> m_tpm;
   time::milliseconds m_lastTimestamp;
 };
 
@@ -801,6 +817,56 @@
   return;
 }
 
+template<class PibType>
+inline void
+KeyChain::registerPib(std::initializer_list<std::string> schemes)
+{
+  registerPibImpl(schemes, [] (const std::string& locator) {
+      return unique_ptr<SecPublicInfo>(new PibType(locator));
+    });
+}
+
+template<class TpmType>
+inline void
+KeyChain::registerTpm(std::initializer_list<std::string> schemes)
+{
+  registerTpmImpl(schemes, [] (const std::string& locator) {
+      return unique_ptr<SecTpm>(new TpmType(locator));
+    });
+}
+
+/**
+ * \brief Register SecPib class in ndn-cxx KeyChain
+ *
+ * This macro should be placed once in the implementation file of the
+ * SecPib type within the namespace where the type is declared.
+ */
+#define NDN_CXX_KEYCHAIN_REGISTER_PIB(PibType, ...)  \
+static class NdnCxxAuto ## PibType ## PibRegistrationClass    \
+{                                                             \
+public:                                                       \
+  NdnCxxAuto ## PibType ## PibRegistrationClass()             \
+  {                                                           \
+    ::ndn::KeyChain::registerPib<PibType>({__VA_ARGS__});     \
+  }                                                           \
+} ndnCxxAuto ## PibType ## PibRegistrationVariable
+
+/**
+ * \brief Register SecTpm class in ndn-cxx KeyChain
+ *
+ * This macro should be placed once in the implementation file of the
+ * SecTpm type within the namespace where the type is declared.
+ */
+#define NDN_CXX_KEYCHAIN_REGISTER_TPM(TpmType, ...)  \
+static class NdnCxxAuto ## TpmType ## TpmRegistrationClass    \
+{                                                             \
+public:                                                       \
+  NdnCxxAuto ## TpmType ## TpmRegistrationClass()             \
+  {                                                           \
+    ::ndn::KeyChain::registerTpm<TpmType>({__VA_ARGS__});     \
+  }                                                           \
+} ndnCxxAuto ## TpmType ## TpmRegistrationVariable
+
 } // namespace ndn
 
 #endif // NDN_SECURITY_KEY_CHAIN_HPP
diff --git a/src/security/sec-public-info-sqlite3.cpp b/src/security/sec-public-info-sqlite3.cpp
index 99a3d4a..bfd091e 100644
--- a/src/security/sec-public-info-sqlite3.cpp
+++ b/src/security/sec-public-info-sqlite3.cpp
@@ -40,7 +40,7 @@
 using std::string;
 using std::vector;
 
-const std::string SecPublicInfoSqlite3::SCHEME("pib-sqlite3:");
+const std::string SecPublicInfoSqlite3::SCHEME("pib-sqlite3");
 
 static const string INIT_TPM_INFO_TABLE =
   "CREATE TABLE IF NOT EXISTS                "
diff --git a/src/security/sec-public-info.cpp b/src/security/sec-public-info.cpp
index 6b01758..d08ea28 100644
--- a/src/security/sec-public-info.cpp
+++ b/src/security/sec-public-info.cpp
@@ -35,7 +35,7 @@
 std::string
 SecPublicInfo::getPibLocator()
 {
-  return this->getScheme() + m_location;
+  return this->getScheme() + ":" + m_location;
 }
 
 void
diff --git a/src/security/sec-tpm-file.cpp b/src/security/sec-tpm-file.cpp
index 26862c5..fb3936f 100644
--- a/src/security/sec-tpm-file.cpp
+++ b/src/security/sec-tpm-file.cpp
@@ -23,9 +23,8 @@
  * @author Alexander Afanasyev <http://lasr.cs.ucla.edu/afanasyev/index.html>
  */
 
-#include "common.hpp"
-
 #include "sec-tpm-file.hpp"
+
 #include "../encoding/buffer-stream.hpp"
 
 #include <boost/filesystem.hpp>
@@ -44,7 +43,7 @@
 using std::ostringstream;
 using std::ofstream;
 
-const std::string SecTpmFile::SCHEME("tpm-file:");
+const std::string SecTpmFile::SCHEME("tpm-file");
 
 class SecTpmFile::Impl
 {
@@ -155,7 +154,7 @@
 
             const EcdsaKeyParams& ecdsaParams = static_cast<const EcdsaKeyParams&>(params);
 
-            OID curveName;
+            CryptoPP::OID curveName;
             switch (ecdsaParams.getKeySize())
               {
               case 256:
diff --git a/src/security/sec-tpm-osx.cpp b/src/security/sec-tpm-osx.cpp
index 593c586..1a30052 100644
--- a/src/security/sec-tpm-osx.cpp
+++ b/src/security/sec-tpm-osx.cpp
@@ -21,10 +21,9 @@
  * @author Yingdi Yu <http://irl.cs.ucla.edu/~yingdi/>
  */
 
-#include "common.hpp"
-
 #include "sec-tpm-osx.hpp"
 #include "public-key.hpp"
+
 #include "../encoding/oid.hpp"
 #include "../encoding/buffer-stream.hpp"
 #include "cryptopp.hpp"
@@ -47,7 +46,7 @@
 
 using std::string;
 
-const std::string SecTpmOsx::SCHEME("tpm-osxkeychain:");
+const std::string SecTpmOsx::SCHEME("tpm-osxkeychain");
 
 /**
  * @brief Helper class to wrap CoreFoundation object pointers
diff --git a/src/security/sec-tpm.cpp b/src/security/sec-tpm.cpp
index d8c6a4f..a4b27f1 100644
--- a/src/security/sec-tpm.cpp
+++ b/src/security/sec-tpm.cpp
@@ -43,7 +43,7 @@
 std::string
 SecTpm::getTpmLocator()
 {
-  return this->getScheme() + m_location;
+  return this->getScheme() + ":" + m_location;
 }
 
 ConstBufferPtr