Make the exit status consistent across all programs

(except nfdc)

Change-Id: Ia3edb11b3f4284df5db8279b06e6fb708ae454e9
diff --git a/daemon/main.cpp b/daemon/main.cpp
index 2ad3d45..3ba5bce 100644
--- a/daemon/main.cpp
+++ b/daemon/main.cpp
@@ -26,18 +26,19 @@
 #include "nfd.hpp"
 #include "rib/service.hpp"
 
-#include "core/version.hpp"
+#include "core/extended-error-message.hpp"
 #include "core/global-io.hpp"
 #include "core/logger.hpp"
+#include "core/logger-factory.hpp"
 #include "core/privilege-helper.hpp"
-#include "core/extended-error-message.hpp"
+#include "core/version.hpp"
 
 #include <string.h>
 
 #include <boost/filesystem.hpp>
 #include <boost/program_options/options_description.hpp>
-#include <boost/program_options/variables_map.hpp>
 #include <boost/program_options/parsers.hpp>
+#include <boost/program_options/variables_map.hpp>
 
 // boost::thread is used instead of std::thread to guarantee proper cleanup of thread local storage,
 // see http://www.boost.org/doc/libs/1_54_0/doc/html/thread/thread_local_storage.html
@@ -47,10 +48,12 @@
 #include <condition_variable>
 #include <iostream>
 
-namespace nfd {
+namespace po = boost::program_options;
 
 NFD_LOG_INIT("NFD");
 
+namespace nfd {
+
 /** \brief Executes NFD with RIB manager
  *
  *  NFD (main forwarding procedure) and RIB manager execute in two different threads.
@@ -78,33 +81,6 @@
     m_reloadSignalSet.async_wait(bind(&NfdRunner::reload, this, _1, _2));
   }
 
-  static void
-  printUsage(std::ostream& os, const std::string& programName)
-  {
-    os << "Usage: \n"
-       << "  " << programName << " [options]\n"
-       << "\n"
-       << "Run NFD forwarding daemon\n"
-       << "\n"
-       << "Options:\n"
-       << "  [--help]    - print this help message\n"
-       << "  [--version] - print version and exit\n"
-       << "  [--modules] - list available logging modules\n"
-       << "  [--config /path/to/nfd.conf] - path to configuration file "
-       << "(default: " << DEFAULT_CONFIG_FILE << ")\n"
-      ;
-  }
-
-  static void
-  printModules(std::ostream& os)
-  {
-    os << "Available logging modules: \n";
-
-    for (const auto& module : LoggerFactory::getInstance().getModules()) {
-      os << module << "\n";
-    }
-  }
-
   void
   initialize()
   {
@@ -114,10 +90,8 @@
   int
   run()
   {
-    /** \brief return value
-     *  A non-zero value is assigned when either NFD or RIB manager (running in a separate
-     *  thread) fails.
-     */
+    // Return value: a non-zero value is assigned when either NFD or RIB manager (running in
+    // a separate thread) fails.
     std::atomic_int retval(0);
 
     boost::asio::io_service* const mainIo = &getGlobalIoService();
@@ -148,7 +122,7 @@
         }
         catch (const std::exception& e) {
           NFD_LOG_FATAL(e.what());
-          retval = 6;
+          retval = 1;
           mainIo->stop();
         }
 
@@ -170,11 +144,11 @@
     }
     catch (const std::exception& e) {
       NFD_LOG_FATAL(getExtendedErrorMessage(e));
-      retval = 4;
+      retval = 1;
     }
     catch (const PrivilegeHelper::Error& e) {
       NFD_LOG_FATAL(e.what());
-      retval = 5;
+      retval = 4;
     }
 
     {
@@ -221,6 +195,25 @@
   boost::asio::signal_set m_reloadSignalSet;
 };
 
+static void
+printUsage(std::ostream& os, const char* programName,
+           const po::options_description& opts)
+{
+  os << "Usage: " << programName << " [options]\n"
+     << "Run the NDN Forwarding Daemon (NFD)\n"
+     << "\n"
+     << opts;
+}
+
+static void
+printLogModules(std::ostream& os)
+{
+  const auto& factory = LoggerFactory::getInstance();
+  for (const auto& module : factory.getModules()) {
+    os << module << "\n";
+  }
+}
+
 } // namespace nfd
 
 int
@@ -228,33 +221,32 @@
 {
   using namespace nfd;
 
-  namespace po = boost::program_options;
-
-  po::options_description description;
-
   std::string configFile = DEFAULT_CONFIG_FILE;
+
+  po::options_description description("Options");
   description.add_options()
-    ("help,h",    "print this help message")
-    ("version,V", "print version and exit")
+    ("help,h",    "print this message and exit")
+    ("version,V", "show version information and exit")
+    ("config,c",  po::value<std::string>(&configFile),
+                  "path to configuration file (default: " DEFAULT_CONFIG_FILE ")")
     ("modules,m", "list available logging modules")
-    ("config,c",  po::value<std::string>(&configFile), "path to configuration file")
     ;
 
   po::variables_map vm;
   try {
-    po::store(po::command_line_parser(argc, argv).options(description).run(), vm);
+    po::store(po::parse_command_line(argc, argv, description), vm);
     po::notify(vm);
   }
   catch (const std::exception& e) {
     // avoid NFD_LOG_FATAL to ensure that errors related to command-line parsing always appear on the
     // terminal and are not littered with timestamps and other things added by the logging subsystem
-    std::cerr << "ERROR: " << e.what() << std::endl;
-    NfdRunner::printUsage(std::cerr, argv[0]);
-    return 1;
+    std::cerr << "ERROR: " << e.what() << "\n\n";
+    printUsage(std::cerr, argv[0], description);
+    return 2;
   }
 
   if (vm.count("help") > 0) {
-    NfdRunner::printUsage(std::cout, argv[0]);
+    printUsage(std::cout, argv[0], description);
     return 0;
   }
 
@@ -264,36 +256,36 @@
   }
 
   if (vm.count("modules") > 0) {
-    NfdRunner::printModules(std::cout);
+    printLogModules(std::cout);
     return 0;
   }
 
-  NfdRunner runner(configFile);
+  NFD_LOG_INFO("Version " NFD_VERSION_BUILD_STRING " starting");
 
+  NfdRunner runner(configFile);
   try {
     runner.initialize();
   }
   catch (const boost::filesystem::filesystem_error& e) {
     if (e.code() == boost::system::errc::permission_denied) {
-      NFD_LOG_FATAL("Permissions denied for " << e.path1() << ". " <<
-                    argv[0] << " should be run as superuser");
-      return 3;
+      NFD_LOG_FATAL("Permission denied for " << e.path1() <<
+                    ". This program should be run as superuser");
+      return 4;
     }
     else {
       NFD_LOG_FATAL(getExtendedErrorMessage(e));
-      return 2;
+      return 1;
     }
   }
   catch (const std::exception& e) {
     NFD_LOG_FATAL(getExtendedErrorMessage(e));
-    return 2;
+    return 1;
   }
   catch (const PrivilegeHelper::Error& e) {
     // PrivilegeHelper::Errors do not inherit from std::exception
     // and represent seteuid/gid failures
-
     NFD_LOG_FATAL(e.what());
-    return 3;
+    return 4;
   }
 
   return runner.run();
diff --git a/docs/manpages/ndn-autoconfig-server.rst b/docs/manpages/ndn-autoconfig-server.rst
index 14525e3..d5b14d7 100644
--- a/docs/manpages/ndn-autoconfig-server.rst
+++ b/docs/manpages/ndn-autoconfig-server.rst
@@ -10,7 +10,6 @@
 
     ndn-autoconfig-server [-h] [-p <PREFIX>] [-p <PREFIX>] ... <FACEURI>
 
-
 Description
 -----------
 
@@ -21,9 +20,6 @@
 satisfies them with a Data packet that contains a TLV-encoded FaceUri block.  The value of
 this block is the ``Uri`` for the HUB, preferably a UDP tunnel.
 
-``-h``
-  print usage and exit.
-
 ``<FACEURI>``
   FaceUri for this NDN hub.
 
@@ -34,6 +30,23 @@
   as described in :ref:`local-prefix-discovery`.  If no prefix is specified,
   auto-config-server will not serve any local prefix discovery data.
 
+``-h``
+  Print usage and exit.
+
+``-V``
+  Print version number and exit.
+
+Exit status
+-----------
+
+0: No error.
+
+1: An unspecified error occurred.
+
+2: Malformed command line, e.g., invalid, missing, or unknown argument.
+
+4: Insufficient privileges.
+
 Examples
 --------
 
@@ -43,7 +56,6 @@
 
     ndn-autoconfig-server -p /ndn/edu/ucla tcp://spurs.cs.ucla.edu
 
-
 See also
 --------
 
diff --git a/docs/manpages/ndn-autoconfig.rst b/docs/manpages/ndn-autoconfig.rst
index 4ea69d4..9520bed 100644
--- a/docs/manpages/ndn-autoconfig.rst
+++ b/docs/manpages/ndn-autoconfig.rst
@@ -18,9 +18,6 @@
 Options
 -------
 
-``-h`` or ``--help``
-  Print usage information.
-
 ``-d`` or ``--daemon``
   Run ndn-autoconfig in daemon mode, detecting network change events and re-running
   auto-discovery procedure.  In addition, the auto-discovery procedure is unconditionally
@@ -36,8 +33,11 @@
   Use the specified URL to find the closest hub (NDN-FCH protocol).  If not specified,
   ``http://ndn-fch.named-data.net`` will be used.  Only ``http://`` URLs are supported.
 
+``-h`` or ``--help``
+  Print help message and exit.
+
 ``-V`` or ``--version``
-  Print version information.
+  Show version information and exit.
 
 .. _NDN hub discovery procedure:
 
@@ -179,6 +179,16 @@
   If this query is answered, connect to the home HUB and terminate auto-discovery.
   Otherwise, the auto-discovery fails.
 
+Exit status
+-----------
+
+0: No error.
+
+1: An unspecified error occurred.
+
+2: Malformed command line, e.g., invalid, missing, or unknown argument.
+
+4: Insufficient privileges.
 
 See also
 --------
diff --git a/docs/manpages/nfd-autoreg.rst b/docs/manpages/nfd-autoreg.rst
index d2fb303..33e94bd 100644
--- a/docs/manpages/nfd-autoreg.rst
+++ b/docs/manpages/nfd-autoreg.rst
@@ -1,4 +1,4 @@
-ndn-autoreg
+nfd-autoreg
 ===========
 
 Usage
@@ -11,23 +11,20 @@
 Description
 -----------
 
-``autoreg-server`` is a daemon application that automatically registers the specified
-prefix(es) when new on-demand Faces are created (i.e., when a new UDP face is created as
+``nfd-autoreg`` is a daemon application that automatically registers the specified
+prefix(es) when new on-demand faces are created (i.e., when a new UDP face is created as
 the result of an incoming packet or when a new TCP face is created as the result of an
 incoming connection).
 
 Options
 -------
 
-``-h`` or ``--help``
-  Produce help message.
-
 ``-i`` or ``--prefix``
   Prefix that should be automatically registered when a new remote face is created.
-  Can be repeated multiple to specify additional prefixes.
+  Can be repeated multiple times to specify additional prefixes.
 
 ``-c`` or ``--cost``
-  RIB cost to be assigned to auto-registered prefixes.   if not specified, default cost
+  RIB cost to be assigned to auto-registered prefixes.   If not specified, default cost
   is set to 255.
 
 ``-w`` or ``--whitelist``
@@ -48,10 +45,27 @@
 
   Default: none
 
+``-h`` or ``--help``
+  Print help message and exit.
+
+``-V`` or ``--version``
+  Show version information and exit.
+
+Exit status
+-----------
+
+0: No error.
+
+1: An unspecified error occurred.
+
+2: Malformed command line, e.g., invalid, missing, or unknown argument.
+
+4: Insufficient privileges.
+
 Examples
 --------
 
-Auto-register two prefixes for any newly created on-demand Face, except those that has
+Auto-register two prefixes for any newly created on-demand face, except those that has
 source IP address in ``10.0.0.0/8`` network::
 
     nfd-autoreg --prefix=/app1/video --prefix=/app2/pictures -b 10.0.0.0/8
diff --git a/docs/manpages/nfd.rst b/docs/manpages/nfd.rst
index 0fa0ef8..b87c0f3 100644
--- a/docs/manpages/nfd.rst
+++ b/docs/manpages/nfd.rst
@@ -8,25 +8,37 @@
 
     nfd [options]
 
-
 Description
 -----------
 
 NFD forwarding daemon.
 
+Options
+-------
 
-Options:
---------
-
-``--help``
-  Print this help message.
-
-``--modules``
-  List available logging modules
-
-``--config <path/to/nfd.conf>``
+``-c <path/to/nfd.conf>`` or ``--config <path/to/nfd.conf>``
   Specify the path to nfd configuration file (default: ``${SYSCONFDIR}/ndn/nfd.conf``).
 
+``-m`` or ``--modules``
+  List available logging modules.
+
+``-h`` or ``--help``
+  Print help message and exit.
+
+``-V`` or ``--version``
+  Show version information and exit.
+
+Exit status
+-----------
+
+0: No error.
+
+1: An unspecified error occurred.
+
+2: Malformed command line, e.g., invalid, missing, or unknown argument.
+
+4: Insufficient privileges.
+
 Examples
 --------
 
diff --git a/tools/ndn-autoconfig-server/main.cpp b/tools/ndn-autoconfig-server/main.cpp
index ba836db..1077a8d 100644
--- a/tools/ndn-autoconfig-server/main.cpp
+++ b/tools/ndn-autoconfig-server/main.cpp
@@ -37,16 +37,16 @@
 static void
 usage(const char* programName)
 {
-  std::cout << "Usage:\n" << programName  << " [-h] [-V] [-p prefix] [-p prefix] ... hub-face\n"
+  std::cout << "Usage: " << programName << " [-h] [-V] [-p prefix]... <hub-face>\n"
+            << "\n"
+            << "Options:\n"
             << "  -h        - print usage and exit\n"
             << "  -V        - print version number and exit\n"
             << "  -p prefix - a local prefix of the HUB\n"
-            << "\n"
-            << "  hub-face  - a FaceUri to reach the HUB\n"
-            << std::endl;
+            << "  hub-face  - a FaceUri to reach the HUB\n";
 }
 
-int
+static int
 main(int argc, char** argv)
 {
   Options options;
@@ -75,7 +75,7 @@
   }
 
   if (!options.hubFaceUri.parse(argv[::optind])) {
-    std::cerr << "ERROR: cannot parse HUB FaceUri\n";
+    std::cerr << "ERROR: cannot parse HUB FaceUri" << std::endl;
     return 2;
   }
 
diff --git a/tools/ndn-autoconfig/main.cpp b/tools/ndn-autoconfig/main.cpp
index b7340a3..6a2a03f 100644
--- a/tools/ndn-autoconfig/main.cpp
+++ b/tools/ndn-autoconfig/main.cpp
@@ -43,11 +43,11 @@
 #pragma clang diagnostic ignored "-Wundefined-func-template"
 #endif
 
+// ndn-autoconfig is an NDN tool not an NFD tool, so it uses ndn::tools::autoconfig namespace.
+// It lives in NFD repository because nfd-start can automatically start ndn-autoconfig in daemon mode.
 namespace ndn {
 namespace tools {
 namespace autoconfig {
-// ndn-autoconfig is an NDN tool not an NFD tool, so it uses ndn::tools::autoconfig namespace.
-// It lives in NFD repository because nfd-start can automatically start ndn-autoconfig in daemon mode.
 
 static const time::nanoseconds DAEMON_INITIAL_DELAY = time::milliseconds(100);
 static const time::nanoseconds DAEMON_UNCONDITIONAL_INTERVAL = time::hours(1);
@@ -57,13 +57,12 @@
 
 static void
 usage(std::ostream& os,
-      const po::options_description& optionsDescription,
+      const po::options_description& opts,
       const char* programName)
 {
-  os << "Usage:\n"
-     << "  " << programName << " [options]\n"
-     << "\n";
-  os << optionsDescription;
+  os << "Usage: " << programName << " [options]\n"
+     << "\n"
+     << opts;
 }
 
 static void
@@ -77,7 +76,7 @@
       return;
     }
     const char* signalName = ::strsignal(signalNo);
-    std::cerr << "Exit on signal ";
+    std::cerr << "Exiting on signal ";
     if (signalName == nullptr) {
       std::cerr << signalNo;
     }
@@ -115,15 +114,15 @@
   po::options_description optionsDescription("Options");
   optionsDescription.add_options()
     ("help,h", "print this message and exit")
-    ("version,V", "display version and exit")
+    ("version,V", "show version information and exit")
     ("daemon,d", po::bool_switch(&isDaemon)->default_value(isDaemon),
-     "run in daemon mode, detecting network change events and re-running auto-discovery procedure. "
+     "Run in daemon mode, detecting network change events and re-running the auto-discovery procedure. "
      "In addition, the auto-discovery procedure is unconditionally re-run every hour.\n"
-     "NOTE: if connection to NFD fails, the daemon will be terminated.")
+     "NOTE: if the connection to NFD fails, the daemon will exit.")
     ("ndn-fch-url", po::value<std::string>(&options.ndnFchUrl)->default_value(options.ndnFchUrl),
      "URL for NDN-FCH (Find Closest Hub) service")
     ("config,c", po::value<std::string>(&configFile),
-     "configuration file. Exit immediately if `enabled = true` is not specified in config file.")
+     "Configuration file. Exit immediately unless 'enabled = true' is specified in the config file.")
     ;
 
   po::variables_map vm;
@@ -132,7 +131,7 @@
     po::notify(vm);
   }
   catch (const std::exception& e) {
-    std::cerr << "ERROR: " << e.what() << "\n" << "\n\n";
+    std::cerr << "ERROR: " << e.what() << "\n\n";
     usage(std::cerr, optionsDescription, argv[0]);
     return 2;
   }
@@ -177,7 +176,7 @@
       runDaemon(proc);
     }
     else {
-      proc.onComplete.connect([&exitCode] (bool isSuccess) { exitCode = isSuccess ? 0 : 3; });
+      proc.onComplete.connect([&exitCode] (bool isSuccess) { exitCode = isSuccess ? 0 : 1; });
       proc.runOnce();
       face.processEvents();
     }
@@ -186,6 +185,7 @@
     std::cerr << ::nfd::getExtendedErrorMessage(e) << std::endl;
     return 1;
   }
+
   return exitCode;
 }
 
diff --git a/tools/nfd-autoreg.cpp b/tools/nfd-autoreg.cpp
index 5c7473f..5d74e4d 100644
--- a/tools/nfd-autoreg.cpp
+++ b/tools/nfd-autoreg.cpp
@@ -23,6 +23,7 @@
  * NFD, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
  */
 
+#include "core/extended-error-message.hpp"
 #include "core/network.hpp"
 #include "core/version.hpp"
 
@@ -75,19 +76,19 @@
   /**
    * \return true if uri has schema allowed to do auto-registrations
    */
-  bool
+  static bool
   hasAllowedSchema(const FaceUri& uri)
   {
     const std::string& scheme = uri.getScheme();
-    return (scheme == "udp4" || scheme == "tcp4" ||
-            scheme == "udp6" || scheme == "tcp6");
+    return scheme == "udp4" || scheme == "tcp4" ||
+           scheme == "udp6" || scheme == "tcp6";
   }
 
   /**
    * \return true if address is blacklisted
    */
   bool
-  isBlacklisted(const boost::asio::ip::address& address)
+  isBlacklisted(const boost::asio::ip::address& address) const
   {
     return std::any_of(m_blackList.begin(), m_blackList.end(),
                        bind(&Network::doesContain, _1, address));
@@ -97,7 +98,7 @@
    * \return true if address is whitelisted
    */
   bool
-  isWhitelisted(const boost::asio::ip::address& address)
+  isWhitelisted(const boost::asio::ip::address& address) const
   {
     return std::any_of(m_whiteList.begin(), m_whiteList.end(),
                        bind(&Network::doesContain, _1, address));
@@ -160,15 +161,14 @@
     m_face.shutdown();
   }
 
-  void
+  static void
   usage(std::ostream& os,
         const boost::program_options::options_description& desc,
         const char* programName)
   {
-    os << "Usage:\n"
-       << "  " << programName << " --prefix=</autoreg/prefix> [--prefix=/another/prefix] ...\n"
-       << "\n";
-    os << desc;
+    os << "Usage: " << programName << " [--prefix=</autoreg/prefix>]... [options]\n"
+       << "\n"
+       << desc;
   }
 
   void
@@ -222,41 +222,40 @@
   {
     namespace po = boost::program_options;
 
-    po::options_description optionDesciption;
-    optionDesciption.add_options()
-      ("help,h", "produce help message")
+    po::options_description optionsDesc("Options");
+    optionsDesc.add_options()
+      ("help,h", "print this message and exit")
+      ("version,V", "show version information and exit")
       ("prefix,i", po::value<std::vector<Name>>(&m_autoregPrefixes)->composing(),
-       "prefix that should be automatically registered when new a remote non-local face is "
-       "established")
+       "prefix that should be automatically registered when a new non-local face is created")
       ("all-faces-prefix,a", po::value<std::vector<Name>>(&m_allFacesPrefixes)->composing(),
        "prefix that should be automatically registered for all TCP and UDP non-local faces "
        "(blacklists and whitelists do not apply to this prefix)")
       ("cost,c", po::value<uint64_t>(&m_cost)->default_value(255),
-       "FIB cost which should be assigned to autoreg nexthops")
+       "FIB cost that should be assigned to autoreg nexthops")
       ("whitelist,w", po::value<std::vector<Network>>(&m_whiteList)->composing(),
        "Whitelisted network, e.g., 192.168.2.0/24 or ::1/128")
       ("blacklist,b", po::value<std::vector<Network>>(&m_blackList)->composing(),
        "Blacklisted network, e.g., 192.168.2.32/30 or ::1/128")
-      ("version,V", "show version and exit")
       ;
 
     po::variables_map options;
     try {
-      po::store(po::command_line_parser(argc, argv).options(optionDesciption).run(), options);
+      po::store(po::parse_command_line(argc, argv, optionsDesc), options);
       po::notify(options);
     }
     catch (const std::exception& e) {
       std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
-      usage(std::cerr, optionDesciption, argv[0]);
-      return 1;
+      usage(std::cerr, optionsDesc, argv[0]);
+      return 2;
     }
 
-    if (options.count("help")) {
-      usage(std::cout, optionDesciption, argv[0]);
+    if (options.count("help") > 0) {
+      usage(std::cout, optionsDesc, argv[0]);
       return 0;
     }
 
-    if (options.count("version")) {
+    if (options.count("version") > 0) {
       std::cout << NFD_VERSION_BUILD_STRING << std::endl;
       return 0;
     }
@@ -264,7 +263,7 @@
     if (m_autoregPrefixes.empty() && m_allFacesPrefixes.empty()) {
       std::cerr << "ERROR: at least one --prefix or --all-faces-prefix must be specified"
                 << std::endl << std::endl;
-      usage(std::cerr, optionDesciption, argv[0]);
+      usage(std::cerr, optionsDesc, argv[0]);
       return 2;
     }
 
@@ -279,8 +278,8 @@
       startProcessing();
     }
     catch (const std::exception& e) {
-      std::cerr << "ERROR: " << e.what() << std::endl;
-      return 2;
+      std::cerr << "ERROR: " << ::nfd::getExtendedErrorMessage(e) << std::endl;
+      return 1;
     }
 
     return 0;