Add command line tools

Change-Id: I5bce4074324b35e5079b330dc20e14c22fc74c6b
diff --git a/ca.conf.sample b/ca.conf.sample
new file mode 100644
index 0000000..50b160c
--- /dev/null
+++ b/ca.conf.sample
@@ -0,0 +1,15 @@
+{
+  "ca-list":
+  [
+    {
+        "ca-prefix": "/example",
+        "issuing-freshness": "720",
+        "validity-period": "360",
+        "ca-anchor": "/example/KEY/%9A%E0%C6%C6%09%7C%92i/self/%FD%00%00%01Z%B0%2AJ%B4",
+        "supported-challenges":
+        [
+            { "type": "PIN" }
+        ]
+    }
+  ]
+}
\ No newline at end of file
diff --git a/client.conf.sample b/client.conf.sample
new file mode 100644
index 0000000..3c5513a
--- /dev/null
+++ b/client.conf.sample
@@ -0,0 +1,15 @@
+{
+  "ca-list":
+  [
+    {
+        "ca-prefix": "/example/CA",
+        "ca-info": "example",
+        "probe": "example",
+        "certificate": "Bv0CJAcsCANuZG4IBXNpdGUxCANLRVkICBG8IvRjFf8XCARzZWxmCAn9AAABWcgU2aUUCRgBAhkEADbugBX9AU8wggFLMIIBAwYHKoZIzj0CATCB9wIBATAsBgcqhkjOPQEBAiEA/////wAAAAEAAAAAAAAAAAAAAAD///////////////8wWwQg/////wAAAAEAAAAAAAAAAAAAAAD///////////////wEIFrGNdiqOpPns+u9VXaYhrxlHQawzFOw9jvOPD4n0mBLAxUAxJ02CIbnBJNqZnjhE50mt4GffpAEQQRrF9Hy4SxCR/i85uVjpEDydwN9gS3rM6D0oTlF2JjClk/jQuL+Gn+bjufrSnwPnhYrzjNXazFezsu2QGg3v1H1AiEA/////wAAAAD//////////7zm+q2nF56E87nKwvxjJVECAQEDQgAES9Cb9iANUNYmwt5bjwNW1mZgjzIkDJb6FTCdiYWnkMMIVxh2YDllphoWDEAPS6kqJczzCuhnGYpZCp9tTaYKGxZMGwEDHB0HGwgDbmRuCAVzaXRlMQgDS0VZCAgRvCL0YxX/F/0A/Sb9AP4PMTk3MDAxMDFUMDAwMDAw/QD/DzIwMzcwMTE3VDIxMjg0NhdIMEYCIQDXkR1hF3GiP7yLXq+0JBJfi9QC+hhAu/1Bykx+MWz6RAIhANwelBTxxZr2C5bD15mjfhWudK4I1tOb4b/9xWCHyM7F",
+        "supported-challenges":
+        [
+            { "type": "PIN" }
+        ]
+    }
+  ]
+}
\ No newline at end of file
diff --git a/src/challenge-module/challenge-pin.cpp b/src/challenge-module/challenge-pin.cpp
index d21420c..8507bcf 100644
--- a/src/challenge-module/challenge-pin.cpp
+++ b/src/challenge-module/challenge-pin.cpp
@@ -19,12 +19,15 @@
  */
 
 #include "challenge-pin.hpp"
+#include "logging.hpp"
 #include "json-helper.hpp"
 #include <ndn-cxx/util/random.hpp>
 
 namespace ndn {
 namespace ndncert {
 
+_LOG_INIT(ndncert.challenge-pin);
+
 NDNCERT_REGISTER_CHALLENGE(ChallengePin, "PIN");
 
 const std::string ChallengePin::NEED_CODE = "need-code";
@@ -49,9 +52,11 @@
   // interest format: /caName/CA/_SELECT/{"request-id":"id"}/PIN/<signature>
   request.setStatus(NEED_CODE);
   request.setChallengeType(CHALLENGE_TYPE);
+  std::string secretCode = generateSecretCode();
   request.setChallengeSecrets(generateStoredSecrets(time::system_clock::now(),
-                                                    generateSecretCode(),
+                                                    secretCode,
                                                     m_maxAttemptTimes));
+  _LOG_TRACE("Secret for request " << request.getRequestId() << " : " << secretCode);
   return genResponseChallengeJson(request.getRequestId(), CHALLENGE_TYPE, NEED_CODE);
 }
 
diff --git a/tools/ndncert-ca-server.cpp b/tools/ndncert-ca-server.cpp
new file mode 100644
index 0000000..e61f5b5
--- /dev/null
+++ b/tools/ndncert-ca-server.cpp
@@ -0,0 +1,73 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2017, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert 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.
+ *
+ * ndncert 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 copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#include "ca-module.hpp"
+
+#include <boost/program_options/options_description.hpp>
+#include <boost/program_options/variables_map.hpp>
+#include <boost/program_options/parsers.hpp>
+
+namespace ndn {
+namespace ndncert {
+
+int
+main(int argc, char* argv[])
+{
+  namespace po = boost::program_options;
+  std::string configFilePath = std::string(SYSCONFDIR) + "/ndncert/ca.conf";
+  po::options_description description("General Usage\n  ndncert-ca [-h] [-f] configFilePath-file\n");
+  description.add_options()
+    ("help,h", "produce help message")
+    ("config-file,f", po::value<std::string>(&configFilePath), "config file name");
+  po::positional_options_description p;
+  po::variables_map vm;
+  try {
+    po::store(po::command_line_parser(argc, argv).options(description).positional(p).run(), vm);
+    po::notify(vm);
+  }
+  catch (const std::exception& e) {
+    std::cerr << "ERROR: " << e.what() << std::endl;
+    return 1;
+  }
+  if (vm.count("help") != 0) {
+    std::cerr << description << std::endl;
+    return 0;
+  }
+
+  Face face;
+  security::v2::KeyChain keyChain;
+  CaModule ca(face, keyChain, configFilePath);
+
+  ca.setProbeHandler([&] (const std::string& probeInfo) {
+      return probeInfo;
+    });
+  face.processEvents();
+
+  return 0;
+}
+
+} // namespace ndncert
+} // namespace ndn
+
+int
+main(int argc, char* argv[])
+{
+  return ndn::ndncert::main(argc, argv);
+}
diff --git a/tools/ndncert-client.cpp b/tools/ndncert-client.cpp
new file mode 100644
index 0000000..97b03bb
--- /dev/null
+++ b/tools/ndncert-client.cpp
@@ -0,0 +1,211 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2017, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert 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.
+ *
+ * ndncert 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 copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#include "client-module.hpp"
+#include "challenge-module.hpp"
+#include "logging.hpp"
+
+#include <boost/program_options/options_description.hpp>
+#include <boost/program_options/variables_map.hpp>
+#include <boost/program_options/parsers.hpp>
+
+namespace ndn {
+namespace ndncert {
+
+_LOG_INIT(ndncert.clientTool);
+
+class ClientTool
+{
+public:
+  ClientTool(ClientModule& clientModule)
+    : client(clientModule)
+  {
+  }
+
+  void
+  errorCb(const std::string& errorInfo)
+  {
+    _LOG_TRACE("Error: " << errorInfo);
+  }
+
+  void
+  validateCb(const shared_ptr<RequestState> state, int& nStep)
+  {
+    if (state->m_status == ChallengeModule::SUCCESS) {
+      _LOG_TRACE("Certificate has already been issued");
+      return;
+    }
+
+    auto challenge = ChallengeModule::createChallengeModule(state->m_challengeType);
+    auto requirementList = challenge->getRequirementForValidate(state->m_status);
+
+    std::cerr << "Step" << nStep++ << ": Please satisfy following instruction(s)" << std::endl;
+    for (auto requirement : requirementList) {
+      std::cerr << "\t" << requirement << std::endl;
+    }
+    std::list<std::string> paraList;
+    for (size_t i = 0; i < requirementList.size(); i++) {
+      std::string tempParam;
+      std::cin >> tempParam;
+      paraList.push_back(tempParam);
+    }
+    auto paramJson = challenge->genValidateParamsJson(state->m_status, paraList);
+    client.sendValidate(state, paramJson,
+                        bind(&ClientTool::validateCb, this, _1, nStep),
+                        bind(&ClientTool::errorCb, this, _1));
+  }
+
+  void
+  selectCb(const shared_ptr<RequestState> state, int& nStep)
+  {
+    auto challenge = ChallengeModule::createChallengeModule(state->m_challengeType);
+    auto requirementList = challenge->getRequirementForValidate(state->m_status);
+
+    std::cerr << "Step" << nStep++ << ": Please satisfy following instruction(s)" << std::endl;
+    for (auto item : requirementList) {
+      std::cerr << "\t" << item << std::endl;
+    }
+    std::list<std::string> paraList;
+    for (size_t i = 0; i < requirementList.size(); i++) {
+      std::string tempParam;
+      std::cin >> tempParam;
+      paraList.push_back(tempParam);
+    }
+
+    auto paramJson = challenge->genValidateParamsJson(state->m_status, paraList);
+    client.sendValidate(state, paramJson,
+                        bind(&ClientTool::validateCb, this, _1, nStep),
+                        bind(&ClientTool::errorCb, this, _1));
+  }
+
+  void
+  newCb(const shared_ptr<RequestState> state, int& nStep)
+  {
+    std::cerr << "Step" << nStep++ << ": Please select one challenge from following types." << std::endl;
+    for (auto item : state->m_challengeList) {
+      std::cerr << "\t" << item << std::endl;
+    }
+    std::string choice;
+    std::cin >> choice;
+
+    auto challenge = ChallengeModule::createChallengeModule(choice);
+    auto requirementList = challenge->getRequirementForSelect();
+    std::list<std::string> paraList;
+    if (requirementList.size() != 0) {
+      std::cerr << "Step" << nStep++ << ": Please satisfy following instruction(s)" << std::endl;
+      for (auto item : requirementList) {
+        std::cerr << "\t" << item << std::endl;
+      }
+      for (size_t i = 0; i < requirementList.size(); i++) {
+        std::string tempParam;
+        std::cin >> tempParam;
+        paraList.push_back(tempParam);
+      }
+    }
+    auto paramJson = challenge->genSelectParamsJson(state->m_status, paraList);
+    client.sendSelect(state, choice, paramJson,
+                      bind(&ClientTool::selectCb, this, _1, nStep),
+                      bind(&ClientTool::errorCb, this, _1));
+  }
+
+public:
+  ClientModule& client;
+};
+
+int
+main(int argc, char* argv[])
+{
+  namespace po = boost::program_options;
+  std::string configFilePath = std::string(SYSCONFDIR) + "/ndncert/client.conf";
+  po::options_description description("General Usage\n  ndncert-client [-h] [-f] configFilePath-file\n");
+  description.add_options()
+    ("help,h", "produce help message")
+    ("config-file,f", po::value<std::string>(&configFilePath), "config file name");
+  po::positional_options_description p;
+
+  po::variables_map vm;
+  try {
+    po::store(po::command_line_parser(argc, argv).options(description).positional(p).run(), vm);
+    po::notify(vm);
+  }
+  catch (const std::exception& e) {
+    std::cerr << "ERROR: " << e.what() << std::endl;
+    return 1;
+  }
+  if (vm.count("help") != 0) {
+    std::cerr << description << std::endl;
+    return 0;
+  }
+
+  Face face;
+  security::v2::KeyChain keyChain;
+  ClientModule client(face, keyChain);
+  client.getClientConf().load(configFilePath);
+
+  ClientTool tool(client);
+
+  auto caList = client.getClientConf().m_caItems;
+  std::cerr << "Index \t CA Namespace \t CA Introduction" << std::endl;
+  int count = 0;
+  for (auto item : caList) {
+    std::cerr << count++ << "\t"
+              << item.m_caName << "\t"
+              << item.m_caInfo << std::endl;
+  }
+  std::vector<ClientCaItem> caVector{std::begin(caList), std::end(caList)};
+  int nStep = 0;
+  std::cerr << "Step" << nStep++ << ": Please type in the CA namespace index that you want to apply" << std::endl;
+  std::string caIndexS;
+  std::cin >> caIndexS;
+  int caIndex = std::stoi(caIndexS);
+
+  BOOST_ASSERT(caIndex <= count);
+
+  auto targetCaItem = caVector[caIndex];
+  if (targetCaItem.m_probe != "") {
+    std::cerr <<"Step" << nStep++ << ": Probe Requirement-" << targetCaItem.m_probe << std::endl;
+    std::string probeInfo;
+    std::cin >> probeInfo;
+    client.sendProbe(targetCaItem, probeInfo,
+                     bind(&ClientTool::newCb, &tool, _1, nStep),
+                     bind(&ClientTool::errorCb, &tool, _1));
+  }
+  else {
+    std::cerr <<"Step" << nStep++ << ": Please type in the identity name" << std::endl;
+    std::string nameComponent;
+    std::cin >> nameComponent;
+    Name identityName(targetCaItem.m_caName);
+    identityName.append(nameComponent);
+    client.sendNew(targetCaItem, identityName,
+                   bind(&ClientTool::newCb, &tool, _1, nStep),
+                   bind(&ClientTool::errorCb, &tool, _1));
+  }
+  face.processEvents();
+  return 0;
+}
+
+} // namespace ndncert
+} // namespace ndn
+
+int
+main(int argc, char* argv[])
+{
+  return ndn::ndncert::main(argc, argv);
+}
diff --git a/tools/wscript b/tools/wscript
new file mode 100644
index 0000000..957a837
--- /dev/null
+++ b/tools/wscript
@@ -0,0 +1,15 @@
+# -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
+
+top = '..'
+
+def build(bld):
+
+    bld(features='cxx cxxprogram',
+        target='../bin/ndncert-client',
+        source='ndncert-client.cpp',
+        use='ndn-cert')
+
+    bld(features='cxx cxxprogram',
+        target='../bin/ndncert-ca-server',
+        source='ndncert-ca-server.cpp',
+        use='ndn-cert')
diff --git a/wscript b/wscript
index 0333e48..2f86766 100644
--- a/wscript
+++ b/wscript
@@ -48,6 +48,8 @@
 
     conf.load('sanitizers')
 
+    conf.define('SYSCONFDIR', conf.env['SYSCONFDIR'])
+
     # If there happens to be a static library, waf will put the corresponding -L flags
     # before dynamic library flags.  This can result in compilation failure when the
     # system has a different version of the ndncert library installed.
@@ -67,6 +69,8 @@
         export_includes=['src'],
     )
 
+    bld.recurse('tools')
+
     bld.recurse('tests')
 
     bld.install_files(
@@ -83,6 +87,10 @@
         relative_trick = False,
         )
 
+    bld.install_files("${SYSCONFDIR}/ndncert", "ca.conf.sample")
+
+    bld.install_files("${SYSCONFDIR}/ndncert", "client.conf.sample")
+
     bld(features = "subst",
         source='libndn-cert.pc.in',
         target='libndn-cert.pc',