daemon: add NameServer

Change-Id: I64b82a0e9351bcc15691279470c807399480a474
diff --git a/.gitignore b/.gitignore
index 866494e..fca965a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,3 +6,4 @@
 build/
 VERSION
 *.db
+unit-tests.log4cxx
diff --git a/.jenkins.d/30-unit-tests.sh b/.jenkins.d/30-unit-tests.sh
index 4109bd5..b05ec4a 100755
--- a/.jenkins.d/30-unit-tests.sh
+++ b/.jenkins.d/30-unit-tests.sh
@@ -2,4 +2,15 @@
 set -x
 set -e
 
+# Prepare environment
+sudo rm -Rf ~/.ndn
+
+IS_OSX=$( python -c "print 'yes' if 'OSX' in '$NODE_LABELS'.strip().split(' ') else 'no'" )
+IS_LINUX=$( python -c "print 'yes' if 'Linux' in '$NODE_LABELS'.strip().split(' ') else 'no'" )
+
+if [ $IS_OSX = "yes" ]; then
+    security unlock-keychain -p "named-data"
+fi
+
+# Run unit tests
 ./build/unit-tests -l test_suite
diff --git a/ndns.conf.sample.in b/ndns.conf.sample.in
new file mode 100644
index 0000000..71e26a2
--- /dev/null
+++ b/ndns.conf.sample.in
@@ -0,0 +1,25 @@
+zones
+{
+  ; dbFile /usr/local/var/ndns/ndns.db
+
+  zone
+  {
+    ; name / ; name of the zone
+             ; KeyChain must have a identity with this name
+    ; cert  /KEY/dsk-123/ID-CERT/%FD00 ; certificate to sign data
+             ; omit cert to select the default certificate of above identity
+  }
+
+  ; zone
+  ; {
+    ; name /ndn ; name of the zone, zone should not have the same name
+             ; KeyChain must have a identity with this name
+    ; cert  /ndn/KEY/dsk-234/ID-CERT/%FD00 ; certificate to sign data
+             ; omit cert to select the default certificate of above identity
+  ; }
+}
+hints
+{
+  ; hint /ucla
+  ; hint /att
+}
diff --git a/src/clients/response.hpp b/src/clients/response.hpp
index fc49846..240659b 100644
--- a/src/clients/response.hpp
+++ b/src/clients/response.hpp
@@ -38,23 +38,7 @@
 namespace ndns {
 
 /**
- * @brief content when update succeeds
- */
-const Block UPDATE_OK = dataBlock(ndn::tlv::Content, "Update OK", 9);
-
-/**
- * @brief content when update fails because of the out-dated update message
- */
-const Block UPDATE_FAIL_OLD_VERSION = dataBlock(ndn::tlv::Content,
-                                                "Update Fails. Error: old version update", 39);
-
-/**
- * @brief string prefix to judge Update fails or not
- */
-const std::string UPDATE_FAIL("Update Fails. Error: ");
-
-/**
- *@brief Default life time of resource record
+ * @brief Default life time of resource record
  */
 const time::seconds DEFAULT_RR_FRESHNESS_PERIOD(3600);
 
diff --git a/src/daemon/config-file.cpp b/src/daemon/config-file.cpp
new file mode 100644
index 0000000..0522176
--- /dev/null
+++ b/src/daemon/config-file.cpp
@@ -0,0 +1,166 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014, Regents of the University of California.
+ *
+ * This file is part of NDNS (Named Data Networking Domain Name Service).
+ * See AUTHORS.md for complete list of NDNS authors and contributors.
+ *
+ * NDNS 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.
+ *
+ * NDNS 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
+ * NDNS, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ * Copyright (c) 2014  Regents of the University of California,
+ *                     Arizona Board of Regents,
+ *                     Colorado State University,
+ *                     University Pierre & Marie Curie, Sorbonne University,
+ *                     Washington University in St. Louis,
+ *                     Beijing Institute of Technology
+ *
+ * This file is part of NFD (Named Data Networking Forwarding Daemon).
+ * See AUTHORS.md for complete list of NFD authors and contributors.
+ *
+ * NFD 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.
+ *
+ * NFD 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
+ * NFD, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+#include "config-file.hpp"
+#include "logger.hpp"
+
+#include <boost/property_tree/info_parser.hpp>
+#include <fstream>
+
+
+namespace ndn {
+namespace ndns {
+
+NDNS_LOG_INIT("ConfigFile");
+
+void
+ConfigFile::throwErrorOnUnknownSection(const std::string& filename,
+                                       const std::string& sectionName,
+                                       const ConfigSection& section,
+                                       bool isDryRun)
+{
+  std::string msg = "Error processing configuration file ";
+  msg += filename;
+  msg += ": no module subscribed for section \"" + sectionName + "\"";
+
+  throw ConfigFile::Error(msg);
+}
+
+void
+ConfigFile::ignoreUnknownSection(const std::string& filename,
+                                 const std::string& sectionName,
+                                 const ConfigSection& section,
+                                 bool isDryRun)
+{
+  // do nothing
+}
+
+ConfigFile::ConfigFile(UnknownConfigSectionHandler unknownSectionCallback)
+  : m_unknownSectionCallback(unknownSectionCallback)
+{
+}
+
+void
+ConfigFile::addSectionHandler(const std::string& sectionName,
+                              ConfigSectionHandler subscriber)
+{
+  m_subscriptions[sectionName] = subscriber;
+}
+
+void
+ConfigFile::parse(const std::string& filename, bool isDryRun)
+{
+  BOOST_ASSERT(isDryRun == false);
+  std::ifstream inputFile;
+  inputFile.open(filename.c_str());
+  if (!inputFile.good() || !inputFile.is_open())
+    {
+      std::string msg = "Failed to read configuration file: ";
+      msg += filename;
+      throw Error(msg);
+    }
+  parse(inputFile, isDryRun, filename);
+  inputFile.close();
+}
+
+void
+ConfigFile::parse(const std::string& input, bool isDryRun, const std::string& filename)
+{
+  std::istringstream inputStream(input);
+  parse(inputStream, isDryRun, filename);
+}
+
+
+void
+ConfigFile::parse(std::istream& input, bool isDryRun, const std::string& filename)
+{
+  try
+    {
+      boost::property_tree::read_info(input, m_global);
+    }
+  catch (const boost::property_tree::info_parser_error& error)
+    {
+      std::stringstream msg;
+      msg << "Failed to parse configuration file";
+      msg << " " << filename;
+      msg << " " << error.message() << " line " << error.line();
+      throw Error(msg.str());
+    }
+
+  process(isDryRun, filename);
+}
+
+void
+ConfigFile::process(bool isDryRun, const std::string& filename)
+{
+  BOOST_ASSERT(isDryRun == false);
+  BOOST_ASSERT(!filename.empty());
+  // NFD_LOG_DEBUG("processing..." << ((isDryRun)?("dry run"):("")));
+
+  if (m_global.begin() == m_global.end())
+    {
+      std::string msg = "Error processing configuration file: ";
+      msg += filename;
+      msg += " no data";
+      throw Error(msg);
+    }
+
+  for (ConfigSection::const_iterator i = m_global.begin(); i != m_global.end(); ++i)
+    {
+      const std::string& sectionName = i->first;
+      const ConfigSection& section = i->second;
+
+      SubscriptionTable::iterator subscriberIt = m_subscriptions.find(sectionName);
+      if (subscriberIt != m_subscriptions.end())
+        {
+          ConfigSectionHandler subscriber = subscriberIt->second;
+          subscriber(section, isDryRun, filename);
+        }
+      else
+        {
+          m_unknownSectionCallback(filename, sectionName, section, isDryRun);
+        }
+    }
+}
+
+} // namespace ndns
+} // namespace ndn
diff --git a/src/daemon/config-file.hpp b/src/daemon/config-file.hpp
new file mode 100644
index 0000000..fca4af2
--- /dev/null
+++ b/src/daemon/config-file.hpp
@@ -0,0 +1,150 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014, Regents of the University of California.
+ *
+ * This file is part of NDNS (Named Data Networking Domain Name Service).
+ * See AUTHORS.md for complete list of NDNS authors and contributors.
+ *
+ * NDNS 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.
+ *
+ * NDNS 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
+ * NDNS, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ * Copyright (c) 2014  Regents of the University of California,
+ *                     Arizona Board of Regents,
+ *                     Colorado State University,
+ *                     University Pierre & Marie Curie, Sorbonne University,
+ *                     Washington University in St. Louis,
+ *                     Beijing Institute of Technology
+ *
+ * This file is part of NFD (Named Data Networking Forwarding Daemon).
+ * See AUTHORS.md for complete list of NFD authors and contributors.
+ *
+ * NFD 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.
+ *
+ * NFD 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
+ * NFD, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+#ifndef NDNS_DAEMON_CONFIG_FILE_HPP
+#define NDNS_DAEMON_CONFIG_FILE_HPP
+
+#include "common.hpp"
+#include <functional>
+#include <map>
+#include <boost/noncopyable.hpp>
+#include <boost/property_tree/ptree.hpp>
+
+
+namespace ndn {
+namespace ndns {
+
+typedef boost::property_tree::ptree ConfigSection;
+
+/// \brief callback for config file sections
+typedef std::function<void(const ConfigSection& /*section*/,
+                      bool /*isDryRun*/,
+                      const std::string& /*filename*/)> ConfigSectionHandler;
+
+/// \brief callback for config file sections without a subscribed handler
+typedef std::function<void(const std::string& /*filename*/,
+                      const std::string& /*sectionName*/,
+                      const ConfigSection& /*section*/,
+                      bool /*isDryRun*/)> UnknownConfigSectionHandler;
+
+class ConfigFile : boost::noncopyable
+{
+public:
+
+  class Error : public std::runtime_error
+  {
+  public:
+    explicit
+    Error(const std::string& what)
+      : std::runtime_error(what)
+    {
+
+    }
+  };
+
+  ConfigFile(UnknownConfigSectionHandler unknownSectionCallback = throwErrorOnUnknownSection);
+
+  static void
+  throwErrorOnUnknownSection(const std::string& filename,
+                             const std::string& sectionName,
+                             const ConfigSection& section,
+                             bool isDryRun);
+
+  static void
+  ignoreUnknownSection(const std::string& filename,
+                       const std::string& sectionName,
+                       const ConfigSection& section,
+                       bool isDryRun);
+
+  /// \brief setup notification of configuration file sections
+  void
+  addSectionHandler(const std::string& sectionName,
+                    ConfigSectionHandler subscriber);
+
+
+  /**
+   * \param filename file to parse
+   * \param isDryRun true if performing a dry run of configuration, false otherwise
+   * \throws ConfigFile::Error if file not found
+   * \throws ConfigFile::Error if parse error
+   */
+  void
+  parse(const std::string& filename, bool isDryRun);
+
+  /**
+   * \param input configuration (as a string) to parse
+   * \param isDryRun true if performing a dry run of configuration, false otherwise
+   * \param filename optional convenience argument to provide more detailed error messages
+   * \throws ConfigFile::Error if file not found
+   * \throws ConfigFile::Error if parse error
+   */
+  void
+  parse(const std::string& input, bool isDryRun, const std::string& filename);
+
+  /**
+   * \param input stream to parse
+   * \param isDryRun true if performing a dry run of configuration, false otherwise
+   * \param filename optional convenience argument to provide more detailed error messages
+   * \throws ConfigFile::Error if parse error
+   */
+  void
+  parse(std::istream& input, bool isDryRun, const std::string& filename);
+
+private:
+
+  void
+  process(bool isDryRun, const std::string& filename);
+
+private:
+  UnknownConfigSectionHandler m_unknownSectionCallback;
+
+  typedef std::map<std::string, ConfigSectionHandler> SubscriptionTable;
+
+  SubscriptionTable m_subscriptions;
+
+  ConfigSection m_global;
+};
+
+} // namespace ndns
+} // namespace ndn
+
+#endif // NDNS_DAEMON_CONFIG_FILE_HPP
diff --git a/src/daemon/name-server.cpp b/src/daemon/name-server.cpp
new file mode 100644
index 0000000..072e889
--- /dev/null
+++ b/src/daemon/name-server.cpp
@@ -0,0 +1,224 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014, Regents of the University of California.
+ *
+ * This file is part of NDNS (Named Data Networking Domain Name Service).
+ * See AUTHORS.md for complete list of NDNS authors and contributors.
+ *
+ * NDNS 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.
+ *
+ * NDNS 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
+ * NDNS, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "name-server.hpp"
+#include "logger.hpp"
+#include "clients/response.hpp"
+#include <ndn-cxx/encoding/encoding-buffer.hpp>
+
+namespace ndn {
+namespace ndns {
+NDNS_LOG_INIT("NameServer")
+
+const time::milliseconds NAME_SERVER_DEFAULT_CONTENT_FRESHNESS(4000);
+
+NameServer::NameServer(const Name& zoneName, const Name& certName, Face& face, DbMgr& dbMgr,
+                       KeyChain& keyChain, Validator& validator)
+  : m_zone(zoneName)
+  , m_dbMgr(dbMgr)
+  , m_ndnsPrefix(zoneName)
+  , m_keyPrefix(zoneName)
+  , m_certName(certName)
+  , m_contentFreshness(NAME_SERVER_DEFAULT_CONTENT_FRESHNESS)
+  , m_face(face)
+  , m_keyChain(keyChain)
+  , m_validator(validator)
+{
+  if (!m_keyChain.doesCertificateExist(m_certName)) {
+    NDNS_LOG_FATAL("Certificate: " << m_certName << " does not exist");
+    throw Error("certificate does not exist in the KeyChain: " + m_certName.toUri());
+  }
+
+  m_dbMgr.find(m_zone);
+
+  if (m_zone.getId() == 0) {
+    NDNS_LOG_FATAL("m_zone does not exist: " << zoneName);
+    throw Error("Zone " + zoneName.toUri() + " does not exist in the database");
+  }
+
+  m_ndnsPrefix.append(ndns::label::NDNS_ITERATIVE_QUERY);
+  m_keyPrefix.append(ndns::label::NDNS_CERT_QUERY);
+
+  m_face.setInterestFilter(m_ndnsPrefix,
+                           bind(&NameServer::onInterest, this, _1, _2),
+                           bind(&NameServer::onRegisterFailed, this, _1, _2)
+                           );
+
+  m_face.setInterestFilter(m_keyPrefix,
+                           bind(&NameServer::onInterest, this, _1, _2),
+                           bind(&NameServer::onRegisterFailed, this, _1, _2)
+                           );
+
+  NDNS_LOG_INFO("Zone: " << m_zone.getName() << " binds "
+                << "Prefix: " << m_ndnsPrefix << " and " << m_keyPrefix
+                << " with Certificate: " << m_certName
+                );
+}
+
+void
+NameServer::onInterest(const Name& prefix, const Interest& interest)
+{
+  label::MatchResult re;
+  if (!label::matchName(interest, "", m_zone.getName(), re))
+    return;
+
+  if (re.rrType == ndns::label::NDNS_UPDATE_LABEL) {
+    this->handleUpdate(prefix, interest, re); // NDNS Update
+  }
+  else {
+    this->handleQuery(prefix, interest, re);  // NDNS Iterative query
+  }
+}
+
+void
+NameServer::handleQuery(const Name& prefix, const Interest& interest, const label::MatchResult& re)
+{
+  Rrset rrset(&m_zone);
+  rrset.setLabel(re.rrLabel);
+  rrset.setType(re.rrType);
+
+  NDNS_LOG_TRACE("query record: " << interest.getName());
+
+  if (m_dbMgr.find(rrset)) {
+    // find the record: NDNS-RESP, NDNS-AUTH, NDNS-RAW, or NDNS-NACK
+    shared_ptr<Data> answer = make_shared<Data>(rrset.getData());
+    NDNS_LOG_TRACE("answer query with existing Data: " << answer->getName());
+    m_face.put(*answer);
+  }
+  else {
+    // no record, construct NACK
+    Block block = nonNegativeIntegerBlock(::ndn::ndns::tlv::NdnsType, NDNS_NACK);
+    MetaInfo info;
+    info.addAppMetaInfo(block);
+    info.setFreshnessPeriod(this->getContentFreshness());
+    Name name = interest.getName();
+    name.appendVersion();
+    shared_ptr<Data> answer = make_shared<Data>(name);
+    answer->setMetaInfo(info);
+
+    m_keyChain.sign(*answer, m_certName);
+    NDNS_LOG_TRACE("answer query with NDNS-NACK: " << answer->getName());
+    m_face.put(*answer);
+  }
+}
+
+void
+NameServer::handleUpdate(const Name& prefix, const Interest& interest, const label::MatchResult& re)
+{
+  if (re.rrLabel.size() == 1) {
+    // for current, we only allow Update message contains one Data, and ignore others
+    auto it = re.rrLabel.begin();
+    shared_ptr<Data> data;
+    try {
+      // blockFromValue may throw exception, which should not lead to failure of name server
+      const Block& block = it->blockFromValue();
+      data = make_shared<Data>(block);
+    }
+    catch (std::exception& e) {
+      NDNS_LOG_WARN("exception when getting update info: " << e.what());
+      return;
+    }
+    m_validator.validate(*data,
+                         bind(&NameServer::doUpdate, this, interest.shared_from_this(), data),
+                         [this] (const shared_ptr<const Data>& data, const std::string& msg) {
+                           NDNS_LOG_WARN("Ignoring update that did not pass the verification");
+                         });
+  }
+}
+
+void
+NameServer::onRegisterFailed(const ndn::Name& prefix, const std::string& reason)
+{
+  NDNS_LOG_FATAL("fail to register prefix=" << prefix << ". Due to: " << reason);
+  throw Error("zone " + m_zone.getName().toUri() + " register prefix: " +
+              prefix.toUri() + " fails. due to: " + reason);
+}
+
+void
+NameServer::doUpdate(const shared_ptr<const Interest>& interest,
+                     const shared_ptr<const Data>& data)
+{
+  label::MatchResult re;
+  try {
+    if (!label::matchName(*data, "", m_zone.getName(), re))
+      return;
+  }
+  catch (std::exception& e) {
+    NDNS_LOG_INFO("Error while name/certificate matching: " << e.what());
+  }
+
+  Rrset rrset(&m_zone);
+  rrset.setLabel(re.rrLabel);
+  rrset.setType(re.rrType);
+
+  Block ndnsType = nonNegativeIntegerBlock(::ndn::ndns::tlv::NdnsType, NDNS_RESP);
+  MetaInfo info;
+  info.addAppMetaInfo(ndnsType);
+  info.setFreshnessPeriod(this->getContentFreshness());
+  Name name = interest->getName();
+  name.appendVersion();
+  shared_ptr<Data> answer = make_shared<Data>(name);
+  answer->setMetaInfo(info);
+
+  Block blk(ndn::ndns::tlv::RrData);
+  try {
+    if (m_dbMgr.find(rrset)) {
+      const name::Component& newVersion = re.version;
+      if (newVersion > rrset.getVersion()) {
+        // update existing record
+        rrset.setVersion(newVersion);
+        rrset.setData(data->wireEncode());
+        m_dbMgr.update(rrset);
+        blk.push_back(nonNegativeIntegerBlock(ndn::ndns::tlv::UpdateReturnCode, UPDATE_OK));
+        blk.encode(); // must
+        answer->setContent(blk);
+        NDNS_LOG_TRACE("replace old record and answer update with UPDATE_OK");
+      }
+      else {
+        blk.push_back(nonNegativeIntegerBlock(ndn::ndns::tlv::UpdateReturnCode, UPDATE_FAILURE));
+        blk.encode();
+        answer->setContent(blk);
+        NDNS_LOG_TRACE("answer update with UPDATE_FAILURE");
+      }
+    }
+    else {
+      // insert new record
+      rrset.setVersion(re.version);
+      rrset.setData(data->wireEncode());
+      rrset.setTtl(m_zone.getTtl());
+      m_dbMgr.insert(rrset);
+      blk.push_back(nonNegativeIntegerBlock(ndn::ndns::tlv::UpdateReturnCode, UPDATE_OK));
+      blk.encode();
+      answer->setContent(blk);
+      NDNS_LOG_TRACE("insert new record and answer update with UPDATE_OK");
+    }
+  }
+  catch (std::exception& e) {
+    blk.push_back(nonNegativeIntegerBlock(ndn::ndns::tlv::UpdateReturnCode, UPDATE_FAILURE));
+    blk.encode(); // must
+    answer->setContent(blk);
+    NDNS_LOG_INFO("Error processing the update: " << e.what());
+    NDNS_LOG_TRACE("exception happens and answer update with UPDATE_FAILURE");
+  }
+  m_keyChain.sign(*answer, m_certName);
+  m_face.put(*answer);
+}
+
+} // namespace ndns
+} // namespace ndn
diff --git a/src/daemon/name-server.hpp b/src/daemon/name-server.hpp
new file mode 100644
index 0000000..09c3101
--- /dev/null
+++ b/src/daemon/name-server.hpp
@@ -0,0 +1,141 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014, Regents of the University of California.
+ *
+ * This file is part of NDNS (Named Data Networking Domain Name Service).
+ * See AUTHORS.md for complete list of NDNS authors and contributors.
+ *
+ * NDNS 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.
+ *
+ * NDNS 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
+ * NDNS, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef NDNS_DAEMON_NAME_SERVER_HPP
+#define NDNS_DAEMON_NAME_SERVER_HPP
+
+#include "zone.hpp"
+#include "rrset.hpp"
+#include "db-mgr.hpp"
+#include "ndns-label.hpp"
+#include "ndns-tlv.hpp"
+#include "validator.hpp"
+#include "common.hpp"
+
+#include <ndn-cxx/security/key-chain.hpp>
+#include <ndn-cxx/face.hpp>
+
+#include <boost/asio.hpp>
+#include <boost/bind.hpp>
+#include <boost/noncopyable.hpp>
+
+#include <sstream>
+#include <stdexcept>
+
+namespace ndn {
+namespace ndns {
+
+/**
+ * @brief provides authoritative name server.
+ *
+ * The authoritative name server handles NDNS query and update.
+ */
+class NameServer : noncopyable
+{
+  DEFINE_ERROR(Error, std::runtime_error);
+
+public:
+  explicit
+  NameServer(const Name& zoneName, const Name& certName, Face& face, DbMgr& dbMgr,
+             KeyChain& keyChain, Validator& validator);
+
+NDNS_PUBLIC_WITH_TESTS_ELSE_PRIVATE:
+  void
+  onInterest(const Name& prefix, const Interest &interest);
+
+  /**
+   * @brief handle NDNS query message
+   */
+  void
+  handleQuery(const Name& prefix, const Interest& interest, const label::MatchResult& re);
+
+  /**
+   * @brief handle NDNS update message
+   */
+  void
+  handleUpdate(const Name& prefix, const Interest& interest, const label::MatchResult& re);
+
+  void
+  onRegisterFailed(const ndn::Name& prefix, const std::string& reason);
+
+  void
+  doUpdate(const shared_ptr<const Interest>& interest, const shared_ptr<const Data>& data);
+
+public:
+  const Name&
+  getNdnsPrefix()
+  {
+    return m_ndnsPrefix;
+  }
+
+  const Name&
+  getKeyPrefix() const
+  {
+    return m_keyPrefix;
+  }
+
+  void
+  setKeyPrefix(const Name& keyPrefix)
+  {
+    m_keyPrefix = keyPrefix;
+  }
+
+  const Zone&
+  getZone() const
+  {
+    return m_zone;
+  }
+
+  const time::milliseconds&
+  getContentFreshness() const
+  {
+    return m_contentFreshness;
+  }
+
+  /**
+   * @brief set the Data fresh period
+   */
+  void
+  setContentFreshness(const time::milliseconds& contentFreshness)
+  {
+    BOOST_ASSERT(contentFreshness > time::milliseconds::zero());
+    m_contentFreshness = contentFreshness;
+  }
+
+private:
+  Zone m_zone;
+  DbMgr& m_dbMgr;
+
+  // Name m_hint;
+
+  Name m_ndnsPrefix;
+  Name m_keyPrefix;
+  Name m_certName;
+
+  time::milliseconds m_contentFreshness;
+
+  Face& m_face;
+  KeyChain& m_keyChain;
+  Validator& m_validator;
+};
+
+} // namespace ndns
+} // namespace ndn
+
+#endif // NDNS_DAEMON_NAME_SERVER_HPP
diff --git a/src/daemon/rrset.cpp b/src/daemon/rrset.cpp
index 4559479..96ffce7 100644
--- a/src/daemon/rrset.cpp
+++ b/src/daemon/rrset.cpp
@@ -32,7 +32,7 @@
 operator<<(std::ostream& os, const Rrset& rrset)
 {
   os << "Rrset: Id=" << rrset.getId();
-  if (rrset.getZone() != 0)
+  if (rrset.getZone() != nullptr)
     os << " Zone=(" << *rrset.getZone() << ")";
 
   os << " Label=" << rrset.getLabel()
@@ -41,5 +41,21 @@
   return os;
 }
 
+bool
+Rrset::operator==(const Rrset& other) const
+{
+  if (getZone() == nullptr && other.getZone() != nullptr)
+    return false;
+  else if (getZone() != nullptr && other.getZone() == nullptr)
+    return false;
+  else if (getZone() == nullptr && other.getZone() == nullptr)
+    return (getLabel() == other.getLabel() &&
+            getType() == other.getType() && getVersion() == other.getVersion());
+  else
+    return (*getZone() == *other.getZone() && getLabel() == other.getLabel() &&
+            getType() == other.getType() && getVersion() == other.getVersion());
+
+}
+
 } // namespace ndns
 } // namespace ndn
diff --git a/src/daemon/rrset.hpp b/src/daemon/rrset.hpp
index 69b311b..aaedcfe 100644
--- a/src/daemon/rrset.hpp
+++ b/src/daemon/rrset.hpp
@@ -17,8 +17,8 @@
  * NDNS, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
  */
 
-#ifndef NDNS_RRSET_HPP
-#define NDNS_RRSET_HPP
+#ifndef NDNS_DAEMON_RRSET_HPP
+#define NDNS_DAEMON_RRSET_HPP
 
 #include "zone.hpp"
 
@@ -36,7 +36,7 @@
 {
 public:
   explicit
-  Rrset(Zone* zone = 0);
+  Rrset(Zone* zone = nullptr);
 
   /**
    * @brief get the id
@@ -174,11 +174,7 @@
    * Note that comparison ignores id, TTL, and Data when comparing RR sets
    */
   bool
-  operator==(const Rrset& other) const
-  {
-    return (getZone() == other.getZone() && getLabel() == other.getLabel() &&
-            getType() == other.getType() && getVersion() == other.getVersion());
-  }
+  operator==(const Rrset& other) const;
 
   /**
    * @brief compare two rrset instance
@@ -207,4 +203,4 @@
 } // namespace ndns
 } // namespace ndn
 
-#endif // NDNS_RRSET_HPP
+#endif // NDNS_DAEMON_RRSET_HPP
diff --git a/src/daemon/zone.hpp b/src/daemon/zone.hpp
index 4eab6a9..e3a15d4 100644
--- a/src/daemon/zone.hpp
+++ b/src/daemon/zone.hpp
@@ -17,8 +17,8 @@
  * NDNS, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
  */
 
-#ifndef NDNS_ZONE_HPP
-#define NDNS_ZONE_HPP
+#ifndef NDNS_DAEMON_ZONE_HPP
+#define NDNS_DAEMON_ZONE_HPP
 
 #include <ndn-cxx/name.hpp>
 
@@ -133,4 +133,4 @@
 } // namespace ndns
 } // namespace ndn
 
-#endif // NDNS_ZONE_HPP
+#endif // NDNS_DAEMON_ZONE_HPP
diff --git a/src/ndns-enum.hpp b/src/ndns-enum.hpp
index be48bd1..39e77b0 100644
--- a/src/ndns-enum.hpp
+++ b/src/ndns-enum.hpp
@@ -40,6 +40,14 @@
 std::ostream&
 operator<<(std::ostream& os, const NdnsType ndnsType);
 
+/**
+ * @brief define Return code of Update's Response
+ */
+enum UpdateReturnCode {
+  UPDATE_OK = 0, ///< Update succeeds
+  UPDATE_FAILURE = 1 ///< Update fails
+};
+
 } // namespace ndns
 } // namespace ndn
 
diff --git a/src/ndns-tlv.hpp b/src/ndns-tlv.hpp
index 3575ab0..3f8399d 100644
--- a/src/ndns-tlv.hpp
+++ b/src/ndns-tlv.hpp
@@ -32,7 +32,10 @@
 enum {
   NdnsType = 180, ///< Detailed Types are defined in NdnsType in ndns-enum.hpp
   Rr = 190,
-  RrData = 191
+  RrData = 191,
+
+  UpdateReturnCode = 160,
+  UpdateReturnMsg = 161
 };
 
 } // namespace tlv
diff --git a/tests/unit/daemon/name-server.cpp b/tests/unit/daemon/name-server.cpp
new file mode 100644
index 0000000..578533d
--- /dev/null
+++ b/tests/unit/daemon/name-server.cpp
@@ -0,0 +1,246 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014, Regents of the University of California.
+ *
+ * This file is part of NDNS (Named Data Networking Domain Name Service).
+ * See AUTHORS.md for complete list of NDNS authors and contributors.
+ *
+ * NDNS 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.
+ *
+ * NDNS 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
+ * NDNS, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "daemon/db-mgr.hpp"
+#include "daemon/name-server.hpp"
+#include "clients/response.hpp"
+#include "clients/query.hpp"
+#include "logger.hpp"
+
+#include "../database-test-data.hpp"
+#include "../../boost-test.hpp"
+
+#include <boost/filesystem.hpp>
+#include <ndn-cxx/face.hpp>
+#include <ndn-cxx/util/dummy-client-face.hpp>
+
+namespace ndn {
+namespace ndns {
+namespace tests {
+
+NDNS_LOG_INIT("NameServerTest");
+
+class NameServerFixture : public DbTestData
+{
+public:
+  NameServerFixture()
+    : face(ndn::util::makeDummyClientFace({ false, true }))
+    , zone(m_net.getName())
+    , validator(*face)
+    , server(zone, m_certName, *face, m_session, m_keyChain, validator)
+  {
+    // ensure prefix is registered
+    run();
+  }
+
+  void
+  run()
+  {
+    face->getIoService().poll();
+    face->getIoService().reset();
+  }
+
+public:
+  shared_ptr<ndn::util::DummyClientFace> face;
+  Name hint;
+  const Name& zone;
+  Validator validator;
+  ndns::NameServer server;
+};
+
+BOOST_FIXTURE_TEST_SUITE(NameServer, NameServerFixture)
+
+BOOST_AUTO_TEST_CASE(NdnsQuery)
+{
+  Query q(hint, zone, ndns::label::NDNS_ITERATIVE_QUERY);
+  q.setRrLabel(Name("ndnsim"));
+  q.setRrType(ndns::label::NS_RR_TYPE);
+
+  bool hasDataBack = false;
+
+  face->onData += [&] (const Data& data) {
+    hasDataBack = true;
+    NDNS_LOG_TRACE("get Data back");
+    BOOST_CHECK_EQUAL(data.getName().getPrefix(-1), q.toInterest().getName());
+
+    Response resp;
+    BOOST_CHECK_NO_THROW(resp.fromData(hint, zone, data));
+    BOOST_CHECK_EQUAL(resp.getNdnsType(), NDNS_RESP);
+  };
+
+  face->receive(q.toInterest());
+
+  run();
+
+  BOOST_CHECK_EQUAL(hasDataBack, true);
+}
+
+BOOST_AUTO_TEST_CASE(KeyQuery)
+{
+  Query q(hint, zone, ndns::label::NDNS_ITERATIVE_QUERY);
+  q.setQueryType(ndns::label::NDNS_CERT_QUERY);
+  q.setRrType(ndns::label::CERT_RR_TYPE);
+
+  size_t nDataBack = 0;
+
+  // will ask for non-existing record
+  face->onData += [&] (const Data& data) {
+    ++nDataBack;
+    NDNS_LOG_TRACE("get Data back");
+    BOOST_CHECK_EQUAL(data.getName().getPrefix(-1), q.toInterest().getName());
+
+    Response resp;
+    BOOST_CHECK_NO_THROW(resp.fromData(hint, zone, data));
+    BOOST_CHECK_EQUAL(resp.getNdnsType(), NDNS_NACK);
+  };
+
+  face->receive(q.toInterest());
+  run();
+
+  // will ask for the existing record (will have type NDNS_RAW, as it is certificate)
+  face->onData.clear();
+  face->onData += [&] (const Data& data) {
+    ++nDataBack;
+    NDNS_LOG_TRACE("get Data back");
+    BOOST_CHECK_EQUAL(data.getName().getPrefix(-1), q.toInterest().getName());
+
+    Response resp;
+    BOOST_CHECK_NO_THROW(resp.fromData(hint, zone, data));
+    BOOST_CHECK_EQUAL(resp.getNdnsType(), NDNS_RAW);
+  };
+
+  q.setRrLabel("dsk-3");
+
+  face->receive(q.toInterest());
+  run();
+
+  BOOST_CHECK_EQUAL(nDataBack, 2);
+}
+
+BOOST_AUTO_TEST_CASE(UpdateReplaceRr)
+{
+  Response re;
+  re.setZone(zone);
+  re.setQueryType(label::NDNS_ITERATIVE_QUERY);
+  re.setRrLabel(Name("ndnsim"));
+  re.setRrType(label::NS_RR_TYPE);
+  re.setNdnsType(NDNS_RESP);
+
+  std::string str = "ns1.ndnsim.net";
+  re.addRr(dataBlock(ndns::tlv::RrData, str.c_str(), str.size()));
+  str = "ns2.ndnsim.net";
+  re.addRr(dataBlock(ndns::tlv::RrData, str.c_str(), str.size()));
+
+  shared_ptr<Data> data = re.toData();
+  m_keyChain.sign(*data, m_certName);
+
+  Query q(Name(hint), Name(zone), ndns::label::NDNS_ITERATIVE_QUERY);
+  const Block& block = data->wireEncode();
+  Name name;
+  name.append(block);
+
+  q.setRrLabel(name);
+  q.setRrType(label::NDNS_UPDATE_LABEL);
+
+  bool hasDataBack = false;
+
+  face->onData += [&] (const Data& data) {
+    hasDataBack = true;
+    NDNS_LOG_TRACE("get Data back");
+    BOOST_CHECK_EQUAL(data.getName().getPrefix(-1), q.toInterest().getName());
+    Response resp;
+
+    BOOST_CHECK_NO_THROW(resp.fromData(hint, zone, data));
+    std::cout << resp << std::endl;
+    BOOST_CHECK_EQUAL(resp.getNdnsType(), NDNS_RESP); // by default NDNS_RAW is enough
+    BOOST_CHECK_GT(resp.getRrs().size(), 0);
+    Block block = resp.getRrs()[0];
+    block.parse();
+    int ret = -1;
+    BOOST_CHECK_EQUAL(block.type(), ndns::tlv::RrData);
+    Block::element_const_iterator val = block.elements_begin();
+    BOOST_CHECK_EQUAL(val->type(), ndns::tlv::UpdateReturnCode); // the first must be return code
+    ret = readNonNegativeInteger(*val);
+    BOOST_CHECK_EQUAL(ret, 0);
+  };
+
+  face->receive(q.toInterest());
+  run();
+
+  BOOST_CHECK_EQUAL(hasDataBack, true);
+}
+
+BOOST_AUTO_TEST_CASE(UpdateInsertNewRr)
+{
+  Response re;
+  re.setZone(zone);
+  re.setQueryType(label::NDNS_ITERATIVE_QUERY);
+  re.setRrLabel(Name("ndnsim-XYZ")); // insert new records
+  re.setRrType(label::NS_RR_TYPE);
+  re.setNdnsType(NDNS_RESP);
+
+  std::string str = "ns1.ndnsim.net";
+  re.addRr(dataBlock(ndns::tlv::RrData, str.c_str(), str.size()));
+  str = "ns2.ndnsim.net";
+  re.addRr(dataBlock(ndns::tlv::RrData, str.c_str(), str.size()));
+
+  shared_ptr<Data> data = re.toData();
+  m_keyChain.sign(*data, m_certName);
+
+  Query q(Name(hint), Name(zone), ndns::label::NDNS_ITERATIVE_QUERY);
+  const Block& block = data->wireEncode();
+  Name name;
+  name.append(block);
+
+  q.setRrLabel(name);
+  q.setRrType(label::NDNS_UPDATE_LABEL);
+
+  bool hasDataBack = false;
+
+  face->onData += [&] (const Data& data) {
+    hasDataBack = true;
+    NDNS_LOG_TRACE("get Data back");
+    BOOST_CHECK_EQUAL(data.getName().getPrefix(-1), q.toInterest().getName());
+    Response resp;
+
+    BOOST_CHECK_NO_THROW(resp.fromData(hint, zone, data));
+    std::cout << resp << std::endl;
+    BOOST_CHECK_EQUAL(resp.getNdnsType(), NDNS_RESP); // by default NDNS_RAW is enough
+    BOOST_CHECK_GT(resp.getRrs().size(), 0);
+    Block block = resp.getRrs()[0];
+    block.parse();
+    int ret = -1;
+    BOOST_CHECK_EQUAL(block.type(), ndns::tlv::RrData);
+    Block::element_const_iterator val = block.elements_begin();
+    BOOST_CHECK_EQUAL(val->type(), ndns::tlv::UpdateReturnCode); // the first must be return code
+    ret = readNonNegativeInteger(*val);
+    BOOST_CHECK_EQUAL(ret, 0);
+  };
+
+  face->receive(q.toInterest());
+  run();
+
+  BOOST_CHECK_EQUAL(hasDataBack, true);
+}
+
+BOOST_AUTO_TEST_SUITE_END()
+
+} // namespace tests
+} // namespace ndns
+} // namespace ndn
diff --git a/tests/unit/daemon/rrset.cpp b/tests/unit/daemon/rrset.cpp
index db51d27..ddcff15 100644
--- a/tests/unit/daemon/rrset.cpp
+++ b/tests/unit/daemon/rrset.cpp
@@ -32,7 +32,7 @@
 {
   ndns::Rrset rrset1;
   rrset1.setId(1);
-  rrset1.setZone(0);
+  rrset1.setZone(nullptr);
   rrset1.setLabel("/www/1");
   rrset1.setType(name::Component("NS"));
   rrset1.setVersion(name::Component::fromVersion(1));
@@ -40,29 +40,36 @@
   rrset1.setData(Name("/test/1").wireEncode());
 
   BOOST_CHECK_EQUAL(rrset1.getId(), 1);
-  BOOST_CHECK_EQUAL(rrset1.getZone(), static_cast<Zone*>(0));
+  BOOST_CHECK_EQUAL(rrset1.getZone() == nullptr, true);
   BOOST_CHECK_EQUAL(rrset1.getLabel(), Name("/www/1"));
   BOOST_CHECK_EQUAL(rrset1.getType(), name::Component("NS"));
   BOOST_CHECK_EQUAL(rrset1.getVersion(), name::Component::fromVersion(1));
   BOOST_CHECK_EQUAL(rrset1.getTtl(), time::seconds(10));
   BOOST_CHECK(rrset1.getData() == Name("/test/1").wireEncode());
 
-  Name zoneName("/net/ndnsim");
-
   ndns::Rrset rrset2(rrset1);
-  BOOST_CHECK_EQUAL(rrset1, rrset2);
+  // rrset2.setZone(nullptr);
+  BOOST_CHECK_EQUAL(rrset1, rrset2); // zone point to nullptr
 
   rrset2.setId(2);
-  BOOST_CHECK_EQUAL(rrset1, rrset2);
-  rrset2 = rrset1;
+  BOOST_CHECK_EQUAL(rrset1, rrset2); // with different Id
 
-  Zone zone;
+  Zone zone("/ndn");
+  Zone zone2("/ndn2");
   rrset2.setZone(&zone);
+  BOOST_CHECK_NE(rrset1, rrset2); // with different zone name
+
+  rrset1.setZone(&zone);
+  BOOST_CHECK_EQUAL(rrset1, rrset2);
+
+  Zone zone3("/ndn");
+  rrset1.setZone(&zone3);
+  BOOST_CHECK_EQUAL(rrset1, rrset2);
+
+  rrset1.setZone(&zone2);
   BOOST_CHECK_NE(rrset1, rrset2);
 
   rrset2 = rrset1;
-  BOOST_CHECK_EQUAL(rrset1, rrset2);
-
   rrset2.setLabel(Name("/www/2"));
   BOOST_CHECK_NE(rrset1, rrset2);
   rrset2 = rrset1;
diff --git a/tests/unit/database-test-data.cpp b/tests/unit/database-test-data.cpp
index 3db2335..bee2cd9 100644
--- a/tests/unit/database-test-data.cpp
+++ b/tests/unit/database-test-data.cpp
@@ -28,53 +28,42 @@
 NDNS_LOG_INIT("TestFakeData")
 
 const boost::filesystem::path DbTestData::TEST_DATABASE = TEST_CONFIG_PATH "/" "test-ndns.db";
-const Name DbTestData::TEST_IDENTITY_NAME("/");
+const Name DbTestData::TEST_IDENTITY_NAME("/test19");
 const boost::filesystem::path DbTestData::TEST_CERT =
   TEST_CONFIG_PATH "/" "anchors/root.cert";
 
 DbTestData::DbTestData()
-  : doesTestIdentityExist(false)
-  , m_session(TEST_DATABASE.string())
+  : m_session(TEST_DATABASE.string())
 {
   NDNS_LOG_TRACE("start creating test data");
-  // m_session.clearAllData();
 
   ndns::Validator::VALIDATOR_CONF_FILE = TEST_CONFIG_PATH "/" "validator.conf";
 
-  if (!m_keyChain.doesIdentityExist(TEST_IDENTITY_NAME)) {
-    m_keyChain.createIdentity(TEST_IDENTITY_NAME);
-  }
-  else {
-    doesTestIdentityExist = true;
-  }
+  m_certName = m_keyChain.createIdentity(TEST_IDENTITY_NAME);
 
-  m_keyName = m_keyChain.generateRsaKeyPair(TEST_IDENTITY_NAME, false);
-
-  shared_ptr<IdentityCertificate> scert = m_keyChain.selfSign(m_keyName);
-  m_keyChain.addCertificate(*scert);
-  m_certName = scert->getName();
-
-  ndn::io::save(*scert, TEST_CERT.string());
-  NDNS_LOG_TRACE("test key: " << m_keyName);
-  NDNS_LOG_TRACE("save test root cert " << m_certName << " to: " << TEST_CERT.string());
+  ndn::io::save(*(m_keyChain.getCertificate(m_certName)), TEST_CERT.string());
+  NDNS_LOG_INFO("save test root cert " << m_certName << " to: " << TEST_CERT.string());
 
   BOOST_CHECK_GT(m_certName.size(), 0);
   NDNS_LOG_TRACE("test certName: " << m_certName);
 
-  Zone root("/");
-  Zone net("/net");
-  Zone ndnsim("/net/ndnsim");
+  m_root = Zone(TEST_IDENTITY_NAME);
+  Name name(TEST_IDENTITY_NAME);
+    name.append("net");
+  m_net = Zone(name);
+  name.append("ndnsim");
+  m_ndnsim =Zone(name);
 
-  m_session.insert(root);
-  BOOST_CHECK_GT(root.getId(), 0);
-  m_session.insert(net);
-  BOOST_CHECK_GT(net.getId(), 0);
-  m_session.insert(ndnsim);
-  BOOST_CHECK_GT(ndnsim.getId(), 0);
+  m_session.insert(m_root);
+  BOOST_CHECK_GT(m_root.getId(), 0);
+  m_session.insert(m_net);
+  BOOST_CHECK_GT(m_net.getId(), 0);
+  m_session.insert(m_ndnsim);
+  BOOST_CHECK_GT(m_ndnsim.getId(), 0);
 
-  m_zones.push_back(root);
-  m_zones.push_back(net);
-  m_zones.push_back(ndnsim);
+  m_zones.push_back(m_root);
+  m_zones.push_back(m_net);
+  m_zones.push_back(m_ndnsim);
 
   int certificateIndex = 0;
   function<void(const Name&,Zone&,const name::Component&)> addQueryRrset =
@@ -93,26 +82,26 @@
 
     addRrset(zone, label, type, ttl, version, qType, ndnsType, os.str());
   };
-  addQueryRrset("/dsk-1", root, label::CERT_RR_TYPE);
-  addQueryRrset("/net/ksk-2", root, label::CERT_RR_TYPE);
-  addQueryRrset("/dsk-3", net, label::CERT_RR_TYPE);
-  addQueryRrset("/ndnsim/ksk-4", net, label::CERT_RR_TYPE);
-  addQueryRrset("/dsk-5", ndnsim, label::CERT_RR_TYPE);
 
-  addQueryRrset("net", root, label::NS_RR_TYPE);
-  addQueryRrset("ndnsim", net, label::NS_RR_TYPE);
-  addQueryRrset("www", ndnsim, label::TXT_RR_TYPE);
-  addQueryRrset("doc/www", ndnsim, label::TXT_RR_TYPE);
+  addQueryRrset("/dsk-1", m_root, label::CERT_RR_TYPE);
+  addQueryRrset("/net/ksk-2", m_root, label::CERT_RR_TYPE);
+  addQueryRrset("/dsk-3", m_net, label::CERT_RR_TYPE);
+  addQueryRrset("/ndnsim/ksk-4", m_net, label::CERT_RR_TYPE);
+  addQueryRrset("/dsk-5", m_ndnsim, label::CERT_RR_TYPE);
+
+  addQueryRrset("net", m_root, label::NS_RR_TYPE);
+  addQueryRrset("ndnsim", m_net, label::NS_RR_TYPE);
+  addQueryRrset("www", m_ndnsim, label::TXT_RR_TYPE);
+  addQueryRrset("doc/www", m_ndnsim, label::TXT_RR_TYPE);
 
 
-  addRrset(ndnsim, Name("doc"), label::NS_RR_TYPE , time::seconds(2000),
-    name::Component("1234"), label::NDNS_ITERATIVE_QUERY, NDNS_AUTH, std::string(""));
+  addRrset(m_ndnsim, Name("doc"), label::NS_RR_TYPE , time::seconds(2000),
+           name::Component::fromVersion(1234), label::NDNS_ITERATIVE_QUERY, NDNS_AUTH,
+           std::string(""));
 
   NDNS_LOG_INFO("insert testing data: OK");
 }
 
-
-
 void
 DbTestData::addRrset(Zone& zone, const Name& label, const name::Component& type,
                      const time::seconds& ttl, const name::Component& version,
@@ -163,14 +152,7 @@
   boost::filesystem::remove(TEST_DATABASE);
   boost::filesystem::remove(TEST_CERT);
 
-  if (doesTestIdentityExist) {
-    m_keyChain.deleteCertificate(m_certName);
-    m_keyChain.deleteKey(m_keyName);
-    NDNS_LOG_TRACE("delete key: " << m_keyName << " and certificate: " << m_certName);
-  }
-  else{
-    m_keyChain.deleteIdentity(TEST_IDENTITY_NAME);
-  }
+  // m_keyChain.deleteIdentity(TEST_IDENTITY_NAME);
 
   NDNS_LOG_INFO("remove database: " << TEST_DATABASE);
 }
diff --git a/tests/unit/database-test-data.hpp b/tests/unit/database-test-data.hpp
index 38b1d43..f79d6a5 100644
--- a/tests/unit/database-test-data.hpp
+++ b/tests/unit/database-test-data.hpp
@@ -26,8 +26,8 @@
 #include "validator.hpp"
 
 #include "../boost-test.hpp"
-
 #include <ndn-cxx/security/key-chain.hpp>
+#include <ndn-cxx/util/dummy-client-face.hpp>
 #include <boost/filesystem.hpp>
 
 namespace ndn {
@@ -48,15 +48,16 @@
 private:
   void
   addRrset(Zone& zone, const Name& label, const name::Component& type,
-                       const time::seconds& ttl, const name::Component& version,
-                       const name::Component& qType, NdnsType ndnsType, const std::string& msg);
+           const time::seconds& ttl, const name::Component& version,
+           const name::Component& qType, NdnsType ndnsType, const std::string& msg);
 public:
   Name m_certName;
-  Name m_keyName;
   std::vector<Zone>  m_zones;
   std::vector<Rrset> m_rrsets;
 
-  bool doesTestIdentityExist;
+  Zone m_root;
+  Zone m_net;
+  Zone m_ndnsim;
   DbMgr m_session;
   KeyChain m_keyChain;
 };
diff --git a/tools/ndns-daemon.cpp b/tools/ndns-daemon.cpp
new file mode 100644
index 0000000..463022a
--- /dev/null
+++ b/tools/ndns-daemon.cpp
@@ -0,0 +1,215 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014, Regents of the University of California.
+ *
+ * This file is part of NDNS (Named Data Networking Domain Name Service).
+ * See AUTHORS.md for complete list of NDNS authors and contributors.
+ *
+ * NDNS 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.
+ *
+ * NDNS 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
+ * NDNS, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "daemon/name-server.hpp"
+#include "logger.hpp"
+#include "config.hpp"
+#include "daemon/config-file.hpp"
+#include "ndn-cxx/security/key-chain.hpp"
+#include <boost/program_options.hpp>
+
+namespace ndn {
+namespace ndns {
+
+NDNS_LOG_INIT("NdnsDaemon");
+
+/**
+ * @brief Name Server Daemon
+ * @note NdnsDaemon allows multiple name servers hosted by the same daemon, and they
+ * share same KeyChain, DbMgr, Validator and Face
+ */
+class NdnsDaemon : noncopyable
+{
+  DEFINE_ERROR(Error, std::runtime_error);
+
+public:
+  explicit
+  NdnsDaemon(const std::string& configFile, Face& face)
+    : m_configFile(configFile)
+    , m_face(face)
+    , m_validator(face)
+  {
+    try {
+      ConfigFile config;
+      NDNS_LOG_TRACE("configFile: " << configFile);
+
+      config.addSectionHandler("zones",
+                               bind(&NdnsDaemon::processZonesSection, this, _1, _3));
+      config.addSectionHandler("hints",
+                               bind(&NdnsDaemon::processHintsSection, this, _1, _3));
+
+      config.parse(configFile, false);
+
+    }
+    catch (boost::filesystem::filesystem_error& e) {
+      if (e.code() == boost::system::errc::permission_denied) {
+        NDNS_LOG_FATAL("Permissions denied for " << e.path1());
+      }
+      else {
+        NDNS_LOG_FATAL(e.what());
+      }
+    }
+    catch (const std::exception& e) {
+      NDNS_LOG_FATAL(e.what());
+    }
+  }
+
+  void
+  processHintsSection(const ndn::ndns::ConfigSection& section, const std::string& filename)
+  {
+    // hint is not supported yet
+    ;
+  }
+
+  void
+  processZonesSection(const ndn::ndns::ConfigSection& section, const std::string& filename)
+  {
+    using namespace boost::filesystem;
+    using namespace ndn::ndns;
+    using ndn::ndns::ConfigSection;
+
+    if (section.begin() == section.end()) {
+      throw Error("zones section is empty");
+    }
+
+    ConfigSection::const_assoc_iterator item = section.find("dbFile");
+    if (item != section.not_found()) {
+      m_dbFile = item->second.get_value<std::string>();
+    }
+    else {
+      m_dbFile = "/usr/local/var/ndns/ndns.db";
+    }
+    NDNS_LOG_TRACE("dbFile " << m_dbFile);
+
+    m_dbMgr = make_shared<DbMgr>(m_dbFile);
+
+    for (const auto& option : section) {
+      Name name;
+      Name cert;
+      if (option.first == "zone") {
+        try {
+          name = option.second.get<Name>("name"); // exception leads to exit
+        }
+        catch (const std::exception& e) {
+          NDNS_LOG_ERROR("Required `name' attribute missing in `zone' section");
+          throw Error("Required `name' attribute missing in `zone' section");
+        }
+        try {
+          cert = option.second.get<Name>("cert");
+        }
+        catch (std::exception&) {
+          ;
+        }
+
+        if (cert.empty()) {
+          cert = m_keyChain.getDefaultCertificateNameForIdentity(name);
+        }
+        else {
+          if (!m_keyChain.doesCertificateExist(cert)) {
+            throw Error("Certificate `" + cert.toUri() + "` does not exist in the KeyChain");
+          }
+        }
+        NDNS_LOG_TRACE("name = " << name << " cert = " << cert);
+        m_servers.push_back(make_shared<NameServer>(name, cert, m_face, *m_dbMgr,
+                                                    m_keyChain, m_validator));
+      }
+    } // for
+  }
+
+private:
+  std::string m_configFile;
+  Face& m_face;
+  Validator m_validator;
+  std::string m_dbFile;
+  shared_ptr<DbMgr> m_dbMgr;
+  std::vector<shared_ptr<NameServer> > m_servers;
+  KeyChain m_keyChain;
+};
+
+} // namespace ndns
+} // namespace ndn
+
+int
+main(int argc, char* argv[])
+{
+  using std::string;
+  using ndn::ndns::ConfigFile;
+  using namespace ndn::ndns;
+
+  ndn::ndns::log::init();
+  string configFile = DEFAULT_CONFIG_PATH "/" "ndns.conf";
+
+  try {
+    namespace po = boost::program_options;
+    po::variables_map vm;
+
+    po::options_description generic("Generic Options");
+    generic.add_options()("help,h", "print help message");
+
+    po::options_description config("Configuration");
+    config.add_options()
+      ("config,c", po::value<string>(&configFile), "set the path of configuration file")
+      ;
+
+    po::options_description cmdline_options;
+    cmdline_options.add(generic).add(config);
+
+    po::parsed_options parsed =
+      po::command_line_parser(argc, argv).options(cmdline_options).run();
+
+    po::store(parsed, vm);
+    po::notify(vm);
+
+    if (vm.count("help")) {
+      std::cout << "Usage:\n"
+                << "  ndns-daemon [-c configFile]\n"
+                << std::endl;
+      std::cout << generic << config << std::endl;
+      return 0;
+    }
+  }
+  catch (const std::exception& ex) {
+    std::cerr << "Parameter Error: " << ex.what() << std::endl;
+
+    return 1;
+  }
+  catch (...) {
+    std::cerr << "Parameter Unknown error" << std::endl;
+    return 1;
+  }
+
+  try {
+    ndn::Face face;
+    NdnsDaemon nsd(configFile, face);
+
+    boost::asio::signal_set signalSet(face.getIoService(), SIGINT, SIGTERM);
+
+    signalSet.async_wait([&face] (const boost::system::error_code&, const int) {
+        face.getIoService().stop();
+      });
+
+    face.processEvents();
+  }
+  catch (std::exception& e) {
+    NDNS_LOG_FATAL("ERROR: " << e.what());
+    return 2;
+  }
+
+  return 0;
+}
diff --git a/wscript b/wscript
index 6a3c29b..dd3807e 100644
--- a/wscript
+++ b/wscript
@@ -92,8 +92,8 @@
     bld.recurse('tools')
 
     bld(features='subst',
-        source='validator.conf.sample.in',
-        target='validator.conf',
+        source=['validator.conf.sample.in', 'ndns.conf.sample.in'],
+        target=['validator.conf.sample', 'ndns.conf.sample'],
         install_path='${SYSCONFDIR}/ndns',
         name='validator-sample',
         ANCHORPATH='anchors/root.cert',