Rename ndnputchunks to ndnserve

Change-Id: Id1cc90c91ec0778ec07495b364546b05464410c8
diff --git a/tools/serve/README.md b/tools/serve/README.md
new file mode 100644
index 0000000..acaab8f
--- /dev/null
+++ b/tools/serve/README.md
@@ -0,0 +1,31 @@
+# ndnserve
+
+**ndnserve** is a producer program that reads a file from the standard input, and makes it
+available as a set of NDN Data segments. It appends version and segment number components
+to the specified name as needed, according to the [NDN naming conventions](
+https://named-data.net/publications/techreports/ndn-tr-22-3-ndn-memo-naming-conventions/).
+
+Files published by ndnserve can be fetched with [ndnget](../get/README.md).
+
+## Usage examples
+
+The following command will publish the text of the GPL-3 license under the `/localhost/demo/gpl3`
+prefix:
+
+    ndnserve /localhost/demo/gpl3 < /usr/share/common-licenses/GPL-3
+
+To find the published version you have to start ndnserve with the `-p` command line option,
+for example:
+
+    ndnserve -p /localhost/demo/gpl3 < /usr/share/common-licenses/GPL-3
+
+This command will print the published version to standard output.
+
+To publish Data with a specific version, you need to append a version component to the end of the
+prefix. The version component must follow the aforementioned NDN naming conventions. For example,
+the following command will publish the version 1449078495094 of the `/localhost/demo/gpl3` prefix:
+
+    ndnserve -Nt /localhost/demo/gpl3/v=1449078495094 < /usr/share/common-licenses/GPL-3
+
+If the specified version component is not valid, ndnserve will exit with an error. If no version
+component is specified, one will be generated and appended to the name.
diff --git a/tools/serve/main.cpp b/tools/serve/main.cpp
new file mode 100644
index 0000000..995d36e
--- /dev/null
+++ b/tools/serve/main.cpp
@@ -0,0 +1,173 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/*
+ * Copyright (c) 2016-2025, Regents of the University of California,
+ *                          Colorado State University,
+ *                          University Pierre & Marie Curie, Sorbonne University.
+ *
+ * This file is part of ndn-tools (Named Data Networking Essential Tools).
+ * See AUTHORS.md for complete list of ndn-tools authors and contributors.
+ *
+ * ndn-tools 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.
+ *
+ * ndn-tools 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
+ * ndn-tools, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ *
+ * @author Wentao Shang
+ * @author Steve DiBenedetto
+ * @author Andrea Tosatto
+ * @author Davide Pesavento
+ * @author Klaus Schneider
+ */
+
+#include "core/version.hpp"
+#include "producer.hpp"
+
+#include <boost/program_options/options_description.hpp>
+#include <boost/program_options/parsers.hpp>
+#include <boost/program_options/variables_map.hpp>
+
+#include <iostream>
+
+namespace ndn::serve {
+
+namespace po = boost::program_options;
+
+static void
+usage(std::ostream& os, std::string_view programName, const po::options_description& desc)
+{
+  os << "Usage: " << programName << " [options] ndn:/name\n"
+     << "\n"
+     << "Publish data under the specified prefix.\n"
+     << "Note: this tool expects data from the standard input.\n"
+     << "\n"
+     << desc;
+}
+
+static int
+main(int argc, char* argv[])
+{
+  const std::string programName(argv[0]);
+
+  Producer::Options opts;
+  std::string prefix, nameConv, signingStr;
+
+  po::options_description visibleDesc("Options");
+  visibleDesc.add_options()
+    ("help,h",      "print this help message and exit")
+    ("freshness,f", po::value<time::milliseconds::rep>()->default_value(opts.freshnessPeriod.count()),
+                    "FreshnessPeriod of the published Data packets, in milliseconds")
+    ("size,s",      po::value<size_t>(&opts.maxSegmentSize)->default_value(opts.maxSegmentSize),
+                    "maximum chunk size, in bytes")
+    ("naming-convention,N",  po::value<std::string>(&nameConv),
+                             "encoding convention to use for name components, either 'marker' or 'typed'")
+    ("signing-info,S",       po::value<std::string>(&signingStr), "see 'man ndnserve' for usage")
+    ("print-data-version,p", po::bool_switch(&opts.wantShowVersion),
+                             "print Data version to the standard output")
+    ("quiet,q",     po::bool_switch(&opts.isQuiet), "turn off all non-error output")
+    ("verbose,v",   po::bool_switch(&opts.isVerbose), "turn on verbose output (per Interest information)")
+    ("version,V",   "print program version and exit")
+    ;
+
+  po::options_description hiddenDesc;
+  hiddenDesc.add_options()
+    ("name", po::value<std::string>(&prefix), "NDN name for the served content");
+
+  po::options_description optDesc;
+  optDesc.add(visibleDesc).add(hiddenDesc);
+
+  po::positional_options_description p;
+  p.add("name", -1);
+
+  po::variables_map vm;
+  try {
+    po::store(po::command_line_parser(argc, argv).options(optDesc).positional(p).run(), vm);
+    po::notify(vm);
+  }
+  catch (const po::error& e) {
+    std::cerr << "ERROR: " << e.what() << "\n";
+    return 2;
+  }
+  catch (const boost::bad_any_cast& e) {
+    std::cerr << "ERROR: " << e.what() << "\n";
+    return 2;
+  }
+
+  if (vm.count("help") > 0) {
+    usage(std::cout, programName, visibleDesc);
+    return 0;
+  }
+
+  if (vm.count("version") > 0) {
+    std::cout << "ndnserve " << tools::VERSION << "\n";
+    return 0;
+  }
+
+  if (prefix.empty()) {
+    usage(std::cerr, programName, visibleDesc);
+    return 2;
+  }
+
+  if (nameConv == "marker" || nameConv == "m" || nameConv == "1") {
+    name::setConventionEncoding(name::Convention::MARKER);
+  }
+  else if (nameConv == "typed" || nameConv == "t" || nameConv == "2") {
+    name::setConventionEncoding(name::Convention::TYPED);
+  }
+  else if (!nameConv.empty()) {
+    std::cerr << "ERROR: '" << nameConv << "' is not a valid naming convention\n";
+    return 2;
+  }
+
+  opts.freshnessPeriod = time::milliseconds(vm["freshness"].as<time::milliseconds::rep>());
+  if (opts.freshnessPeriod < 0_ms) {
+    std::cerr << "ERROR: --freshness cannot be negative\n";
+    return 2;
+  }
+
+  if (opts.maxSegmentSize < 1 || opts.maxSegmentSize > MAX_NDN_PACKET_SIZE) {
+    std::cerr << "ERROR: --size must be between 1 and " << MAX_NDN_PACKET_SIZE << "\n";
+    return 2;
+  }
+
+  try {
+    opts.signingInfo = security::SigningInfo(signingStr);
+  }
+  catch (const std::invalid_argument& e) {
+    std::cerr << "ERROR: " << e.what() << "\n";
+    return 2;
+  }
+
+  if (opts.isQuiet && opts.isVerbose) {
+    std::cerr << "ERROR: cannot be quiet and verbose at the same time\n";
+    return 2;
+  }
+
+  try {
+    Face face;
+    KeyChain keyChain;
+    Producer producer(prefix, face, keyChain, std::cin, opts);
+    producer.run();
+  }
+  catch (const std::exception& e) {
+    std::cerr << "ERROR: " << e.what() << "\n";
+    return 1;
+  }
+
+  return 0;
+}
+
+} // namespace ndn::serve
+
+int
+main(int argc, char* argv[])
+{
+  return ndn::serve::main(argc, argv);
+}
diff --git a/tools/serve/producer.cpp b/tools/serve/producer.cpp
new file mode 100644
index 0000000..2c3ce8a
--- /dev/null
+++ b/tools/serve/producer.cpp
@@ -0,0 +1,161 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/*
+ * Copyright (c) 2016-2025, Regents of the University of California,
+ *                          Colorado State University,
+ *                          University Pierre & Marie Curie, Sorbonne University.
+ *
+ * This file is part of ndn-tools (Named Data Networking Essential Tools).
+ * See AUTHORS.md for complete list of ndn-tools authors and contributors.
+ *
+ * ndn-tools 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.
+ *
+ * ndn-tools 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
+ * ndn-tools, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ *
+ * @author Wentao Shang
+ * @author Steve DiBenedetto
+ * @author Andrea Tosatto
+ * @author Davide Pesavento
+ * @author Klaus Schneider
+ * @author Chavoosh Ghasemi
+ */
+
+#include "producer.hpp"
+
+#include <ndn-cxx/metadata-object.hpp>
+#include <ndn-cxx/util/segmenter.hpp>
+
+#include <iostream>
+
+namespace ndn::serve {
+
+Producer::Producer(const Name& prefix, Face& face, KeyChain& keyChain, std::istream& is,
+                   const Options& opts)
+  : m_face(face)
+  , m_keyChain(keyChain)
+  , m_options(opts)
+{
+  if (!prefix.empty() && prefix[-1].isVersion()) {
+    m_prefix = prefix.getPrefix(-1);
+    m_versionedPrefix = prefix;
+  }
+  else {
+    m_prefix = prefix;
+    m_versionedPrefix = Name(m_prefix).appendVersion();
+  }
+
+  if (!m_options.isQuiet) {
+    std::cerr << "Loading input ...\n";
+  }
+  Segmenter segmenter(m_keyChain, m_options.signingInfo);
+  m_store = segmenter.segment(is, m_versionedPrefix, m_options.maxSegmentSize, m_options.freshnessPeriod);
+
+  // register m_prefix without Interest handler
+  m_face.registerPrefix(m_prefix, nullptr, [this] (const Name& prefix, const auto& reason) {
+    std::cerr << "ERROR: Failed to register prefix '" << prefix << "' (" << reason << ")\n";
+    m_face.shutdown();
+  });
+
+  // match Interests whose name starts with m_versionedPrefix
+  face.setInterestFilter(m_versionedPrefix, [this] (const auto&, const auto& interest) {
+    processSegmentInterest(interest);
+  });
+
+  // match Interests whose name is exactly m_prefix
+  face.setInterestFilter(InterestFilter(m_prefix, ""), [this] (const auto&, const auto& interest) {
+    processSegmentInterest(interest);
+  });
+
+  // match discovery Interests
+  auto discoveryName = MetadataObject::makeDiscoveryInterest(m_prefix).getName();
+  face.setInterestFilter(discoveryName, [this] (const auto&, const auto& interest) {
+    processDiscoveryInterest(interest);
+  });
+
+  if (m_options.wantShowVersion) {
+    std::cout << m_versionedPrefix[-1] << "\n";
+  }
+  if (!m_options.isQuiet) {
+    std::cerr << "Published " << m_store.size() << " Data packet" << (m_store.size() > 1 ? "s" : "")
+              << " with prefix " << m_versionedPrefix << "\n";
+  }
+}
+
+void
+Producer::run()
+{
+  m_face.processEvents();
+}
+
+void
+Producer::processDiscoveryInterest(const Interest& interest)
+{
+  if (m_options.isVerbose)
+    std::cerr << "Discovery Interest: " << interest << "\n";
+
+  if (!interest.getCanBePrefix()) {
+    if (m_options.isVerbose) {
+      std::cerr << "Discovery Interest lacks CanBePrefix, sending Nack\n";
+    }
+    m_face.put(lp::Nack(interest));
+    return;
+  }
+
+  MetadataObject mobject;
+  mobject.setVersionedName(m_versionedPrefix);
+
+  // make a metadata packet based on the received discovery Interest name
+  auto mdata = mobject.makeData(interest.getName(), m_keyChain, m_options.signingInfo);
+
+  if (m_options.isVerbose)
+    std::cerr << "Sending metadata: " << mdata << "\n";
+
+  m_face.put(mdata);
+}
+
+void
+Producer::processSegmentInterest(const Interest& interest)
+{
+  BOOST_ASSERT(!m_store.empty());
+
+  if (m_options.isVerbose)
+    std::cerr << "Interest: " << interest << "\n";
+
+  const Name& name = interest.getName();
+  std::shared_ptr<Data> data;
+
+  if (name.size() == m_versionedPrefix.size() + 1 && name[-1].isSegment()) {
+    const auto segmentNo = static_cast<size_t>(interest.getName()[-1].toSegment());
+    // specific segment retrieval
+    if (segmentNo < m_store.size()) {
+      data = m_store[segmentNo];
+    }
+  }
+  else if (interest.matchesData(*m_store[0])) {
+    // unspecified version or segment number, return first segment
+    data = m_store[0];
+  }
+
+  if (data != nullptr) {
+    if (m_options.isVerbose) {
+      std::cerr << "Data: " << *data << "\n";
+    }
+    m_face.put(*data);
+  }
+  else {
+    if (m_options.isVerbose) {
+      std::cerr << "Interest cannot be satisfied, sending Nack\n";
+    }
+    m_face.put(lp::Nack(interest));
+  }
+}
+
+} // namespace ndn::serve
diff --git a/tools/serve/producer.hpp b/tools/serve/producer.hpp
new file mode 100644
index 0000000..48d19ca
--- /dev/null
+++ b/tools/serve/producer.hpp
@@ -0,0 +1,102 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/*
+ * Copyright (c) 2016-2025, Regents of the University of California,
+ *                          Colorado State University,
+ *                          University Pierre & Marie Curie, Sorbonne University.
+ *
+ * This file is part of ndn-tools (Named Data Networking Essential Tools).
+ * See AUTHORS.md for complete list of ndn-tools authors and contributors.
+ *
+ * ndn-tools 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.
+ *
+ * ndn-tools 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
+ * ndn-tools, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ *
+ * @author Wentao Shang
+ * @author Steve DiBenedetto
+ * @author Andrea Tosatto
+ * @author Davide Pesavento
+ * @author Klaus Schneider
+ */
+
+#ifndef NDN_TOOLS_SERVE_PRODUCER_HPP
+#define NDN_TOOLS_SERVE_PRODUCER_HPP
+
+#include "core/common.hpp"
+
+#include <ndn-cxx/face.hpp>
+#include <ndn-cxx/security/key-chain.hpp>
+
+#include <vector>
+
+namespace ndn::serve {
+
+/**
+ * @brief Segmented & versioned data publisher.
+ *
+ * Packetizes and publishes data from an input stream as `/prefix/<version>/<segment number>`.
+ * Unless another value is provided, the current time is used as the version number.
+ * The packet store always has at least one item, even when the input is empty.
+ */
+class Producer : noncopyable
+{
+public:
+  struct Options
+  {
+    security::SigningInfo signingInfo;
+    time::milliseconds freshnessPeriod = 10_s;
+    size_t maxSegmentSize = 8000;
+    bool isQuiet = false;
+    bool isVerbose = false;
+    bool wantShowVersion = false;
+  };
+
+  /**
+   * @brief Create the producer.
+   * @param prefix prefix used to publish data; if the last component is not a valid
+   *               version number, the current system time is used as version number.
+   */
+  Producer(const Name& prefix, Face& face, KeyChain& keyChain, std::istream& is,
+           const Options& opts);
+
+  /**
+   * @brief Run the producer.
+   */
+  void
+  run();
+
+private:
+  /**
+   * @brief Respond with a metadata packet containing the versioned content name.
+   */
+  void
+  processDiscoveryInterest(const Interest& interest);
+
+  /**
+   * @brief Respond with the requested segment of content.
+   */
+  void
+  processSegmentInterest(const Interest& interest);
+
+PUBLIC_WITH_TESTS_ELSE_PRIVATE:
+  std::vector<std::shared_ptr<Data>> m_store;
+
+private:
+  Name m_prefix;
+  Name m_versionedPrefix;
+  Face& m_face;
+  KeyChain& m_keyChain;
+  const Options m_options;
+};
+
+} // namespace ndn::serve
+
+#endif // NDN_TOOLS_SERVE_PRODUCER_HPP
diff --git a/tools/serve/wscript b/tools/serve/wscript
new file mode 100644
index 0000000..376f72c
--- /dev/null
+++ b/tools/serve/wscript
@@ -0,0 +1,17 @@
+# -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
+top = '../..'
+
+def build(bld):
+    bld.objects(
+        target='serve-objects',
+        source=bld.path.ant_glob('*.cpp', excl='main.cpp'),
+        use='core-objects')
+
+    bld.program(
+        target=f'{top}/bin/ndnserve',
+        name='ndnserve',
+        source='main.cpp',
+        use='serve-objects')
+
+    # backward compatibility
+    bld.symlink_as('${BINDIR}/ndnputchunks', 'ndnserve')