util: import Ethernet and FaceUri

refs #1994

Change-Id: I63a459c0620f9c229e690df05de1333a8dea2bdd
diff --git a/src/util/ethernet.cpp b/src/util/ethernet.cpp
new file mode 100644
index 0000000..d23a5da
--- /dev/null
+++ b/src/util/ethernet.cpp
@@ -0,0 +1,140 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2014 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library 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 Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, 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.
+ */
+
+#include "ethernet.hpp"
+
+#include <stdio.h>
+
+namespace ndn {
+namespace util {
+namespace ethernet {
+
+Address
+getBroadcastAddress()
+{
+  static Address bcast(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF);
+  return bcast;
+}
+
+Address
+getDefaultMulticastAddress()
+{
+  static Address mcast(0x01, 0x00, 0x5E, 0x00, 0x17, 0xAA);
+  return mcast;
+}
+
+Address::Address()
+{
+  assign(0);
+}
+
+Address::Address(uint8_t a1, uint8_t a2, uint8_t a3, uint8_t a4, uint8_t a5, uint8_t a6)
+{
+  elems[0] = a1;
+  elems[1] = a2;
+  elems[2] = a3;
+  elems[3] = a4;
+  elems[4] = a5;
+  elems[5] = a6;
+}
+
+Address::Address(const uint8_t octets[])
+{
+  std::copy(octets, octets + size(), begin());
+}
+
+Address::Address(const Address& address)
+{
+  std::copy(address.begin(), address.end(), begin());
+}
+
+bool
+Address::isBroadcast() const
+{
+  return elems[0] == 0xFF && elems[1] == 0xFF && elems[2] == 0xFF &&
+         elems[3] == 0xFF && elems[4] == 0xFF && elems[5] == 0xFF;
+}
+
+bool
+Address::isMulticast() const
+{
+  return (elems[0] & 1) != 0;
+}
+
+bool
+Address::isNull() const
+{
+  return elems[0] == 0x0 && elems[1] == 0x0 && elems[2] == 0x0 &&
+         elems[3] == 0x0 && elems[4] == 0x0 && elems[5] == 0x0;
+}
+
+std::string
+Address::toString(char sep) const
+{
+  char s[18]; // 12 digits + 5 separators + null terminator
+  ::snprintf(s, sizeof(s), "%02x%c%02x%c%02x%c%02x%c%02x%c%02x",
+             elems[0], sep, elems[1], sep, elems[2], sep,
+             elems[3], sep, elems[4], sep, elems[5]);
+  return std::string(s);
+}
+
+Address
+Address::fromString(const std::string& str)
+{
+  unsigned short temp[ADDR_LEN];
+  char sep[5][2]; // 5 * (1 separator char + 1 null terminator)
+  int n = 0; // num of chars read from the input string
+
+  // ISO C++98 does not support the 'hh' type modifier
+  /// \todo use SCNx8 (cinttypes) when we enable C++11
+  int ret = ::sscanf(str.c_str(), "%2hx%1[:-]%2hx%1[:-]%2hx%1[:-]%2hx%1[:-]%2hx%1[:-]%2hx%n",
+                     &temp[0], &sep[0][0], &temp[1], &sep[1][0], &temp[2], &sep[2][0],
+                     &temp[3], &sep[3][0], &temp[4], &sep[4][0], &temp[5], &n);
+
+  if (ret < 11 || static_cast<size_t>(n) != str.length())
+    return Address();
+
+  Address a;
+  for (size_t i = 0; i < ADDR_LEN; ++i)
+    {
+      // check that all separators are actually the same char (: or -)
+      if (i < 5 && sep[i][0] != sep[0][0])
+        return Address();
+
+      // check that each value fits into a uint8_t
+      if (temp[i] > 0xFF)
+        return Address();
+
+      a[i] = static_cast<uint8_t>(temp[i]);
+    }
+
+  return a;
+}
+
+std::ostream&
+operator<<(std::ostream& o, const Address& a)
+{
+  return o << a.toString();
+}
+
+} // namespace ethernet
+} // namespace util
+} // namespace ndn
diff --git a/src/util/ethernet.hpp b/src/util/ethernet.hpp
new file mode 100644
index 0000000..7a8cff1
--- /dev/null
+++ b/src/util/ethernet.hpp
@@ -0,0 +1,111 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2014 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library 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 Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, 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.
+ */
+
+#ifndef NDN_UTIL_ETHERNET_HPP
+#define NDN_UTIL_ETHERNET_HPP
+
+#include "common.hpp"
+
+#include <boost/array.hpp>
+
+namespace ndn {
+namespace util {
+namespace ethernet {
+
+static const uint16_t ETHERTYPE_NDN = 0x8624;
+
+const size_t ADDR_LEN     = 6;      ///< Octets in one Ethernet address
+const size_t TYPE_LEN     = 2;      ///< Octets in Ethertype field
+const size_t HDR_LEN      = 14;     ///< Total octets in Ethernet header (without 802.1Q tag)
+const size_t TAG_LEN      = 4;      ///< Octets in 802.1Q tag (TPID + priority + VLAN)
+const size_t MIN_DATA_LEN = 46;     ///< Min octets in Ethernet payload (assuming no 802.1Q tag)
+const size_t MAX_DATA_LEN = 1500;   ///< Max octets in Ethernet payload
+const size_t CRC_LEN      = 4;      ///< Octets in Ethernet frame check sequence
+
+
+/** \brief represents an Ethernet hardware address
+ */
+class Address : public boost::array<uint8_t, ADDR_LEN>
+{
+public:
+  /// Constructs a null Ethernet address (00:00:00:00:00:00)
+  Address();
+
+  /// Constructs a new Ethernet address with the given octets
+  Address(uint8_t a1, uint8_t a2, uint8_t a3,
+          uint8_t a4, uint8_t a5, uint8_t a6);
+
+  /// Constructs a new Ethernet address with the given octets
+  explicit
+  Address(const uint8_t octets[ADDR_LEN]);
+
+  /// Copy constructor
+  Address(const Address& address);
+
+  /// True if this is a broadcast address (ff:ff:ff:ff:ff:ff)
+  bool
+  isBroadcast() const;
+
+  /// True if this is a multicast address
+  bool
+  isMulticast() const;
+
+  /// True if this is a null address (00:00:00:00:00:00)
+  bool
+  isNull() const;
+
+  /**
+   * \brief Converts the address to a human-readable string
+   *
+   * \param sep A character used to visually separate the octets,
+   *            usually ':' (the default value) or '-'
+   */
+  std::string
+  toString(char sep = ':') const;
+
+  /**
+   * \brief Creates an Address from a string containing an Ethernet address
+   *        in hexadecimal notation, with colons or hyphens as separators
+   *
+   * \param str The string to be parsed
+   * \return Always an instance of Address, which will be null
+   *         if the parsing fails
+   */
+  static Address
+  fromString(const std::string& str);
+};
+
+/// Returns the Ethernet broadcast address (ff:ff:ff:ff:ff:ff)
+Address
+getBroadcastAddress();
+
+/// Returns the default Ethernet multicast address for NDN
+Address
+getDefaultMulticastAddress();
+
+std::ostream&
+operator<<(std::ostream& o, const Address& a);
+
+} // namespace ethernet
+} // namespace util
+} // namespace ndn
+
+#endif // NDN_UTIL_ETHERNET_HPP
diff --git a/src/util/face-uri.cpp b/src/util/face-uri.cpp
new file mode 100644
index 0000000..ad0ee1f
--- /dev/null
+++ b/src/util/face-uri.cpp
@@ -0,0 +1,199 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2014 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library 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 Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, 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.
+ */
+
+#include "face-uri.hpp"
+
+#include <boost/concept_check.hpp>
+#include <boost/regex.hpp>
+
+namespace ndn {
+namespace util {
+
+BOOST_CONCEPT_ASSERT((boost::EqualityComparable<FaceUri>));
+
+FaceUri::FaceUri()
+  : m_isV6(false)
+{
+}
+
+FaceUri::FaceUri(const std::string& uri)
+{
+  if (!parse(uri)) {
+    throw Error("Malformed URI: " + uri);
+  }
+}
+
+FaceUri::FaceUri(const char* uri)
+{
+  if (!parse(uri)) {
+    throw Error("Malformed URI: " + std::string(uri));
+  }
+}
+
+bool
+FaceUri::parse(const std::string& uri)
+{
+  m_scheme.clear();
+  m_host.clear();
+  m_isV6 = false;
+  m_port.clear();
+  m_path.clear();
+
+  static const boost::regex protocolExp("(\\w+\\d?)://([^/]*)(\\/[^?]*)?");
+  boost::smatch protocolMatch;
+  if (!boost::regex_match(uri, protocolMatch, protocolExp)) {
+    return false;
+  }
+  m_scheme = protocolMatch[1];
+  const std::string& authority = protocolMatch[2];
+  m_path = protocolMatch[3];
+
+  // pattern for IPv6 address enclosed in [ ], with optional port number
+  static const boost::regex v6Exp("^\\[([a-fA-F0-9:]+)\\](?:\\:(\\d+))?$");
+  // pattern for Ethernet address in standard hex-digits-and-colons notation
+  static const boost::regex etherExp("^\\[((?:[a-fA-F0-9]{1,2}\\:){5}(?:[a-fA-F0-9]{1,2}))\\]$");
+  // pattern for IPv4-mapped IPv6 address, with optional port number
+  static const boost::regex v4MappedV6Exp("^\\[::ffff:(\\d+(?:\\.\\d+){3})\\](?:\\:(\\d+))?$");
+  // pattern for IPv4/hostname/fd/ifname, with optional port number
+  static const boost::regex v4HostExp("^([^:]+)(?:\\:(\\d+))?$");
+
+  if (authority.empty()) {
+    // UNIX, internal
+  }
+  else {
+    boost::smatch match;
+    m_isV6 = boost::regex_match(authority, match, v6Exp);
+    if (m_isV6 ||
+        boost::regex_match(authority, match, etherExp) ||
+        boost::regex_match(authority, match, v4MappedV6Exp) ||
+        boost::regex_match(authority, match, v4HostExp)) {
+      m_host = match[1];
+      m_port = match[2];
+    }
+    else {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+FaceUri::FaceUri(const boost::asio::ip::udp::endpoint& endpoint)
+{
+  m_isV6 = endpoint.address().is_v6();
+  m_scheme = m_isV6 ? "udp6" : "udp4";
+  m_host = endpoint.address().to_string();
+  m_port = boost::lexical_cast<std::string>(endpoint.port());
+}
+
+FaceUri::FaceUri(const boost::asio::ip::tcp::endpoint& endpoint)
+{
+  m_isV6 = endpoint.address().is_v6();
+  m_scheme = m_isV6 ? "tcp6" : "tcp4";
+  m_host = endpoint.address().to_string();
+  m_port = boost::lexical_cast<std::string>(endpoint.port());
+}
+
+FaceUri::FaceUri(const boost::asio::ip::tcp::endpoint& endpoint, const std::string& scheme)
+  : m_scheme(scheme)
+{
+  m_isV6 = endpoint.address().is_v6();
+  m_host = endpoint.address().to_string();
+  m_port = boost::lexical_cast<std::string>(endpoint.port());
+}
+
+#ifdef BOOST_ASIO_HAS_LOCAL_SOCKETS
+FaceUri::FaceUri(const boost::asio::local::stream_protocol::endpoint& endpoint)
+  : m_isV6(false)
+{
+  m_scheme = "unix";
+  m_path = endpoint.path();
+}
+#endif // BOOST_ASIO_HAS_LOCAL_SOCKETS
+
+FaceUri
+FaceUri::fromFd(int fd)
+{
+  FaceUri uri;
+  uri.m_scheme = "fd";
+  uri.m_host = boost::lexical_cast<std::string>(fd);
+  return uri;
+}
+
+FaceUri::FaceUri(const ethernet::Address& address)
+  : m_isV6(true)
+{
+  m_scheme = "ether";
+  m_host = address.toString();
+}
+
+FaceUri
+FaceUri::fromDev(const std::string& ifname)
+{
+  FaceUri uri;
+  uri.m_scheme = "dev";
+  uri.m_host = ifname;
+  return uri;
+}
+
+bool
+FaceUri::operator==(const FaceUri& rhs) const
+{
+  return (m_scheme == rhs.m_scheme &&
+          m_host == rhs.m_host &&
+          m_isV6 == rhs.m_isV6 &&
+          m_port == rhs.m_port &&
+          m_path == rhs.m_path);
+}
+
+bool
+FaceUri::operator!=(const FaceUri& rhs) const
+{
+  return !(*this == rhs);
+}
+
+std::string
+FaceUri::toString() const
+{
+  std::ostringstream os;
+  os << *this;
+  return os.str();
+}
+
+std::ostream&
+operator<<(std::ostream& os, const FaceUri& uri)
+{
+  os << uri.m_scheme << "://";
+  if (uri.m_isV6) {
+    os << "[" << uri.m_host << "]";
+  }
+  else {
+    os << uri.m_host;
+  }
+  if (!uri.m_port.empty()) {
+    os << ":" << uri.m_port;
+  }
+  os << uri.m_path;
+  return os;
+}
+
+} // namespace util
+} // namespace ndn
diff --git a/src/util/face-uri.hpp b/src/util/face-uri.hpp
new file mode 100644
index 0000000..6c4ac7e
--- /dev/null
+++ b/src/util/face-uri.hpp
@@ -0,0 +1,156 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2014 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library 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 Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, 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.
+ */
+
+#ifndef NDN_UTIL_FACE_URI_HPP
+#define NDN_UTIL_FACE_URI_HPP
+
+#include "common.hpp"
+#include <boost/asio/ip/udp.hpp>
+#include <boost/asio/ip/tcp.hpp>
+#include <boost/asio/local/stream_protocol.hpp>
+#include "ethernet.hpp"
+
+namespace ndn {
+namespace util {
+
+/** \brief represents the underlying protocol and address used by a Face
+ *  \sa http://redmine.named-data.net/projects/nfd/wiki/FaceMgmt#FaceUri
+ */
+class FaceUri
+{
+public:
+  class Error : public std::invalid_argument
+  {
+  public:
+    explicit
+    Error(const std::string& what)
+      : std::invalid_argument(what)
+    {
+    }
+  };
+
+  FaceUri();
+
+  /** \brief construct by parsing
+   *
+   *  \param uri scheme://host[:port]/path
+   *  \throw FaceUri::Error if URI cannot be parsed
+   */
+  explicit
+  FaceUri(const std::string& uri);
+
+  // This overload is needed so that calls with string literal won't be
+  // resolved to boost::asio::local::stream_protocol::endpoint overload.
+  explicit
+  FaceUri(const char* uri);
+
+  /// exception-safe parsing
+  bool
+  parse(const std::string& uri);
+
+public: // scheme-specific construction
+  /// construct udp4 or udp6 canonical FaceUri
+  explicit
+  FaceUri(const boost::asio::ip::udp::endpoint& endpoint);
+
+  /// construct tcp4 or tcp6 canonical FaceUri
+  explicit
+  FaceUri(const boost::asio::ip::tcp::endpoint& endpoint);
+
+  /// construct tcp canonical FaceUri with customized scheme
+  FaceUri(const boost::asio::ip::tcp::endpoint& endpoint, const std::string& scheme);
+
+#ifdef BOOST_ASIO_HAS_LOCAL_SOCKETS
+  /// construct unix canonical FaceUri
+  explicit
+  FaceUri(const boost::asio::local::stream_protocol::endpoint& endpoint);
+#endif // BOOST_ASIO_HAS_LOCAL_SOCKETS
+
+  /// create fd FaceUri from file descriptor
+  static FaceUri
+  fromFd(int fd);
+
+  /// construct ether canonical FaceUri
+  explicit
+  FaceUri(const ethernet::Address& address);
+
+  /// create dev FaceUri from network device name
+  static FaceUri
+  fromDev(const std::string& ifname);
+
+public: // getters
+  /// get scheme (protocol)
+  const std::string&
+  getScheme() const
+  {
+    return m_scheme;
+  }
+
+  /// get host (domain)
+  const std::string&
+  getHost() const
+  {
+    return m_host;
+  }
+
+  /// get port
+  const std::string&
+  getPort() const
+  {
+    return m_port;
+  }
+
+  /// get path
+  const std::string&
+  getPath() const
+  {
+    return m_path;
+  }
+
+  /// write as a string
+  std::string
+  toString() const;
+
+public: // EqualityComparable concept
+  bool
+  operator==(const FaceUri& rhs) const;
+
+  bool
+  operator!=(const FaceUri& rhs) const;
+
+private:
+  std::string m_scheme;
+  std::string m_host;
+  /// whether to add [] around host when writing string
+  bool m_isV6;
+  std::string m_port;
+  std::string m_path;
+
+  friend std::ostream& operator<<(std::ostream& os, const FaceUri& uri);
+};
+
+std::ostream&
+operator<<(std::ostream& os, const FaceUri& uri);
+
+} // namespace util
+} // namespace ndn
+
+#endif // NDN_UTIL_FACE_URI_HPP