nlsr: accept NFD-RIB-style register/unregister commands

refs: #3818

Change-Id: I7a5455bdec815bdcbe53ad535dab44249d1a18ce
diff --git a/src/nlsr.cpp b/src/nlsr.cpp
index 2a57e0f..58d5cf7 100644
--- a/src/nlsr.cpp
+++ b/src/nlsr.cpp
@@ -73,6 +73,10 @@
                             m_certificateCache,
                             m_certStore)
   , m_dispatcher(m_nlsrFace, m_keyChain, m_signingInfo)
+  , m_nfdRibCommandProcessor(m_dispatcher,
+                             m_namePrefixList,
+                             m_nlsrLsdb,
+                             m_syncLogicHandler)
   , m_faceMonitor(m_nlsrFace)
   , m_firstHelloInterval(FIRST_HELLO_INTERVAL_DEFAULT)
 {
@@ -104,6 +108,16 @@
 
   m_prefixUpdateProcessor.startListening();
   m_lsdbDatasetHandler.startListeningOnLocalhost();
+  // Dispatcher prefix registrations
+  m_nfdRibCommandProcessor.startListening();
+  // All dispatcher-related sub-prefixes *must* be registered before
+  // the top-level prefixes are added.
+  try {
+    m_dispatcher.addTopPrefix(LOCALHOST_PREFIX, false, m_signingInfo);
+  }
+  catch (const std::exception& e) {
+    _LOG_ERROR("Error setting top-level prefix in dispatcher: " << e.what() << "\n");
+  }
 }
 
 void
@@ -281,16 +295,6 @@
 void
 Nlsr::registerLocalhostPrefix()
 {
-  _LOG_TRACE("Registering prefix with dispatcher and Face: " << LOCALHOST_PREFIX);
-  // All dispatcher-related sub-prefixes *must* be registered before
-  // the top-level prefixes are added.
-  try {
-    m_dispatcher.addTopPrefix(LOCALHOST_PREFIX, false, m_signingInfo);
-  }
-  catch (const std::exception& e) {
-    _LOG_ERROR("Error setting top-level prefix in dispatcher: " << e.what() << "\n");
-    registrationFailed(LOCALHOST_PREFIX);
-  }
   m_nlsrFace.registerPrefix(LOCALHOST_PREFIX,
                             std::bind(&Nlsr::onLocalhostRegistrationSuccess, this, _1),
                             std::bind(&Nlsr::registrationFailed, this, _1));
diff --git a/src/nlsr.hpp b/src/nlsr.hpp
index 5399ed8..eb9132d 100644
--- a/src/nlsr.hpp
+++ b/src/nlsr.hpp
@@ -50,6 +50,7 @@
 #include "route/routing-table.hpp"
 #include "security/certificate-store.hpp"
 #include "update/prefix-update-processor.hpp"
+#include "update/nfd-rib-command-processor.hpp"
 #include "utility/name-helper.hpp"
 
 
@@ -290,6 +291,12 @@
     return m_prefixUpdateProcessor;
   }
 
+  update::NfdRibCommandProcessor&
+  getNfdRibCommandProcessor()
+  {
+    return m_nfdRibCommandProcessor;
+  }
+
   ndn::mgmt::Dispatcher&
   getDispatcher()
   {
@@ -394,6 +401,7 @@
   ndn::Name m_defaultCertName;
   update::PrefixUpdateProcessor m_prefixUpdateProcessor;
   ndn::mgmt::Dispatcher m_dispatcher;
+  update::NfdRibCommandProcessor m_nfdRibCommandProcessor;
 
   ndn::nfd::FaceMonitor m_faceMonitor;
 
diff --git a/src/route/fib.hpp b/src/route/fib.hpp
index 32eba00..2c2ad4c 100644
--- a/src/route/fib.hpp
+++ b/src/route/fib.hpp
@@ -55,15 +55,15 @@
   {
   }
 
-  void
-  update(const ndn::Name& name, NexthopList& allHops);
-
   FibEntry*
   processUpdate(const ndn::Name& name, NexthopList& allHops);
 
-  void
+  VIRTUAL_WITH_TESTS void
   remove(const ndn::Name& name);
 
+  VIRTUAL_WITH_TESTS void
+  update(const ndn::Name& name, NexthopList& allHops);
+
   void
   clean();
 
diff --git a/src/update/nfd-rib-command-processor.cpp b/src/update/nfd-rib-command-processor.cpp
new file mode 100644
index 0000000..f4baeb5
--- /dev/null
+++ b/src/update/nfd-rib-command-processor.cpp
@@ -0,0 +1,118 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014-2017,  The University of Memphis,
+ *                           Regents of the University of California,
+ *                           Arizona Board of Regents.
+ *
+ * This file is part of NLSR (Named-data Link State Routing).
+ * See AUTHORS.md for complete list of NLSR authors and contributors.
+ *
+ * NLSR is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * NLSR 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 General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * NLSR, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+#include "nfd-rib-command-processor.hpp"
+#include "logger.hpp"
+
+namespace nlsr {
+namespace update {
+
+INIT_LOGGER("NfdRibProcessor");
+
+const ndn::PartialName REGISTER_VERB = ndn::PartialName("rib/register");
+const ndn::PartialName UNREGISTER_VERB = ndn::PartialName("rib/unregister");
+const ndn::Name COMMAND_PREFIX = ndn::Name("/localhost/nlsr");
+
+NfdRibCommandProcessor::NfdRibCommandProcessor(ndn::mgmt::Dispatcher& dispatcher,
+                                               NamePrefixList& namePrefixes,
+                                               Lsdb& lsdb,
+                                               SyncLogicHandler& sync)
+  : m_dispatcher(dispatcher)
+  , m_namePrefixList(namePrefixes)
+  , m_lsdb(lsdb)
+  , m_sync(sync)
+{
+}
+
+void
+NfdRibCommandProcessor::startListening()
+{
+  _LOG_DEBUG("Registering control command prefixes for: " << REGISTER_VERB <<
+             " and " << UNREGISTER_VERB);
+  m_dispatcher.addControlCommand<ndn::nfd::ControlParameters>(REGISTER_VERB,
+                                 ndn::mgmt::makeAcceptAllAuthorization(),
+                                 std::bind(&NfdRibCommandProcessor::validate<NfdRibRegisterCommand>,
+                                           this, _1, REGISTER_VERB),
+                                 [this] (const ndn::Name& prefix, const ndn::Interest& interest,
+                                         const ndn::mgmt::ControlParameters& parameters,
+                                         const ndn::mgmt::CommandContinuation& done) {
+                                   _LOG_DEBUG("Params verified, calling insertPrefix()");
+                                   this->insertPrefix(parameters);
+                                 });
+  m_dispatcher.addControlCommand<ndn::nfd::ControlParameters>(UNREGISTER_VERB,
+                                 ndn::mgmt::makeAcceptAllAuthorization(),
+                                 std::bind(&NfdRibCommandProcessor::validate<NfdRibUnregisterCommand>,
+                                           this, _1, UNREGISTER_VERB),
+                                 [this] (const ndn::Name& prefix, const ndn::Interest& interest,
+                                         const ndn::mgmt::ControlParameters& parameters,
+                                         const ndn::mgmt::CommandContinuation& done) {
+                                   _LOG_DEBUG("Params verified, calling removePrefix()");
+                                   this->removePrefix(parameters);
+                                 });
+}
+
+template<typename T>
+bool
+NfdRibCommandProcessor::validate(const ndn::mgmt::ControlParameters& parameters,
+                                 const ndn::PartialName& command)
+{
+  _LOG_DEBUG("Attempting to verify incoming params for " << command <<
+             " command...");
+  bool wasValidated = true;
+  try {
+      wasValidated = this->validateParameters<T>(parameters);
+  } catch (const ndn::nfd::ControlCommand::ArgumentError& ae) {
+    _LOG_DEBUG("Could not parse params. Message: " << ae.what());
+    wasValidated = false;
+  }
+  return wasValidated;
+}
+
+void
+NfdRibCommandProcessor::insertPrefix(const ndn::mgmt::ControlParameters& parameters)
+{
+  const ndn::nfd::ControlParameters& castParams =
+    static_cast<const ndn::nfd::ControlParameters&>(parameters);
+
+  _LOG_DEBUG("Inserting prefix into the FIB: " << castParams.getName() << "\n");
+
+  if (m_namePrefixList.insert(castParams.getName())) {
+    m_lsdb.buildAndInstallOwnNameLsa();
+    m_sync.publishRoutingUpdate();
+  }
+}
+
+void
+NfdRibCommandProcessor::removePrefix(const ndn::mgmt::ControlParameters& parameters)
+{
+  const ndn::nfd::ControlParameters& castParams =
+    static_cast<const ndn::nfd::ControlParameters&>(parameters);
+
+  _LOG_DEBUG("Removing prefix from the FIB: " << castParams.getName() << "\n");
+
+  if (m_namePrefixList.remove(castParams.getName())) {
+    m_lsdb.buildAndInstallOwnNameLsa();
+    m_sync.publishRoutingUpdate();
+  }
+}
+
+} // namespace update
+} // namespace nlsr
diff --git a/src/update/nfd-rib-command-processor.hpp b/src/update/nfd-rib-command-processor.hpp
new file mode 100644
index 0000000..8d9cba6
--- /dev/null
+++ b/src/update/nfd-rib-command-processor.hpp
@@ -0,0 +1,124 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014-2017,  The University of Memphis,
+ *                           Regents of the University of California,
+ *                           Arizona Board of Regents.
+ *
+ * This file is part of NLSR (Named-data Link State Routing).
+ * See AUTHORS.md for complete list of NLSR authors and contributors.
+ *
+ * NLSR is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * NLSR 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 General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * NLSR, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+#ifndef UPDATE_NFD_RIB_COMMAND_PROCESSOR_HPP
+#define UPDATE_NFD_RIB_COMMAND_PROCESSOR_HPP
+
+#include "route/fib.hpp"
+#include "nfd-rib-commands.hpp"
+#include "name-prefix-list.hpp"
+#include "lsdb.hpp"
+#include "communication/sync-logic-handler.hpp"
+
+#include <ndn-cxx/mgmt/nfd/control-command.hpp>
+#include <ndn-cxx/mgmt/nfd/control-parameters.hpp>
+#include <ndn-cxx/encoding/tlv-nfd.hpp>
+
+#include <boost/noncopyable.hpp>
+#include <typeinfo>
+
+namespace nlsr {
+namespace update {
+
+class NfdRibCommandProcessor : boost::noncopyable
+{
+public:
+  class Error : public std::runtime_error
+  {
+  public:
+    explicit
+    Error(const std::string& what)
+      : std::runtime_error(what)
+    {
+    }
+  };
+
+public:
+  NfdRibCommandProcessor(ndn::mgmt::Dispatcher& dispatcher,
+                         NamePrefixList& namePrefixes,
+                         Lsdb& lsdb,
+                         SyncLogicHandler& sync);
+
+  /*! \brief Registers an Interest filter with face
+
+    Registers with face an Interest filter that reacts to any
+    interests on COMMAND_PREFIX.
+   */
+  void
+  startListening();
+
+PUBLIC_WITH_TESTS_ELSE_PRIVATE:
+
+  /*! \brief inserts a prefix into the FIB if parameters is valid.
+
+    We consider parameters to be valid if origin is set to CLIENT and
+    a name is present.
+   */
+  void
+  insertPrefix(const ndn::mgmt::ControlParameters& parameters);
+
+  /*! \brief remove a prefix from the FIB if parameters is valid.
+
+    We consider parameters to be valid if origin is set to CLIENT and
+    a name is present.
+   */
+  void
+  removePrefix(const ndn::mgmt::ControlParameters& parameters);
+
+  /*! \brief uses command's validator to check that parameters is valid.
+
+    The command's validator's behavior is defined per command.
+   */
+  template<typename T>
+  bool
+  validateParameters(const ndn::mgmt::ControlParameters& parameters)
+  {
+    BOOST_ASSERT(dynamic_cast<const ndn::nfd::ControlParameters*>(&parameters) != nullptr);
+    const ndn::nfd::ControlParameters& castParams =
+      static_cast<const ndn::nfd::ControlParameters&>(parameters);
+    T command;
+    try {
+      command.validateRequest(castParams);
+    }
+    catch (const ndn::nfd::ControlCommand::ArgumentError& ae) {
+      throw ae;
+    }
+    catch (...) {
+      return false;
+    }
+    return true;
+  }
+
+private:
+  template<typename T>
+  bool
+  validate(const ndn::mgmt::ControlParameters& parameters, const ndn::PartialName& command);
+
+  ndn::mgmt::Dispatcher& m_dispatcher;
+  NamePrefixList& m_namePrefixList;
+  Lsdb& m_lsdb;
+  SyncLogicHandler& m_sync;
+};
+
+} // namespace update
+} // namespace nlsr
+
+#endif // UPDATE_NFD_RIB_COMMAND_PROCESSOR_HPP
diff --git a/src/update/nfd-rib-commands.cpp b/src/update/nfd-rib-commands.cpp
new file mode 100644
index 0000000..fd2c2af
--- /dev/null
+++ b/src/update/nfd-rib-commands.cpp
@@ -0,0 +1,42 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014-2017,  The University of Memphis,
+ *                           Regents of the University of California,
+ *                           Arizona Board of Regents.
+ *
+ * This file is part of NLSR (Named-data Link State Routing).
+ * See AUTHORS.md for complete list of NLSR authors and contributors.
+ *
+ * NLSR is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * NLSR 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 General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * NLSR, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+#include "nfd-rib-commands.hpp"
+
+namespace nlsr {
+namespace update {
+
+NfdRibRegisterCommand::NfdRibRegisterCommand()
+  : ControlCommand("nlsr", "register")
+{
+  m_requestValidator.required(ndn::nfd::CONTROL_PARAMETER_NAME);
+  m_requestValidator.optional(ndn::nfd::CONTROL_PARAMETER_ORIGIN);
+}
+
+NfdRibUnregisterCommand::NfdRibUnregisterCommand()
+  : ControlCommand("nlsr", "unregister")
+{
+  m_requestValidator.required(ndn::nfd::CONTROL_PARAMETER_NAME);
+  m_requestValidator.optional(ndn::nfd::CONTROL_PARAMETER_ORIGIN);
+}
+
+} // namespace update
+} // namespace nlsr
diff --git a/src/update/nfd-rib-commands.hpp b/src/update/nfd-rib-commands.hpp
new file mode 100644
index 0000000..39ecb5f
--- /dev/null
+++ b/src/update/nfd-rib-commands.hpp
@@ -0,0 +1,45 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014-2017,  The University of Memphis,
+ *                           Regents of the University of California,
+ *                           Arizona Board of Regents.
+ *
+ * This file is part of NLSR (Named-data Link State Routing).
+ * See AUTHORS.md for complete list of NLSR authors and contributors.
+ *
+ * NLSR is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * NLSR 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 General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * NLSR, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+#ifndef UPDATE_NFD_RIB_COMMANDS_HPP
+#define UPDATE_NFD_RIB_COMMANDS_HPP
+
+#include <ndn-cxx/mgmt/nfd/control-command.hpp>
+
+namespace nlsr {
+namespace update {
+
+class NfdRibRegisterCommand : public ndn::nfd::ControlCommand
+{
+public:
+  NfdRibRegisterCommand();
+};
+
+class NfdRibUnregisterCommand : public ndn::nfd::ControlCommand
+{
+public:
+  NfdRibUnregisterCommand();
+};
+
+} // namespace update
+} // namespace nlsr
+
+#endif // UPDATE_NFD_RIB_COMMANDS_HPP