unix-stream-channel.cpp
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2014-2024, Regents of the University of California,
4  * Arizona Board of Regents,
5  * Colorado State University,
6  * University Pierre & Marie Curie, Sorbonne University,
7  * Washington University in St. Louis,
8  * Beijing Institute of Technology,
9  * The University of Memphis.
10  *
11  * This file is part of NFD (Named Data Networking Forwarding Daemon).
12  * See AUTHORS.md for complete list of NFD authors and contributors.
13  *
14  * NFD is free software: you can redistribute it and/or modify it under the terms
15  * of the GNU General Public License as published by the Free Software Foundation,
16  * either version 3 of the License, or (at your option) any later version.
17  *
18  * NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
19  * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
20  * PURPOSE. See the GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License along with
23  * NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
24  */
25 
26 #include "unix-stream-channel.hpp"
27 #include "face.hpp"
28 #include "generic-link-service.hpp"
30 #include "common/global.hpp"
31 
32 #include <boost/filesystem/exception.hpp>
33 #include <boost/filesystem/operations.hpp>
34 #include <boost/filesystem/path.hpp>
35 
36 namespace nfd::face {
37 
38 NFD_LOG_INIT(UnixStreamChannel);
39 
41  bool wantCongestionMarking)
42  : m_endpoint(endpoint)
43  , m_wantCongestionMarking(wantCongestionMarking)
44  , m_acceptor(getGlobalIoService())
45 {
46  setUri(FaceUri(m_endpoint));
47  NFD_LOG_CHAN_INFO("Creating channel");
48 }
49 
51 {
52  if (isListening()) {
53  // use the non-throwing variants during destruction and ignore any errors
54  boost::system::error_code ec;
55  m_acceptor.close(ec);
56  NFD_LOG_CHAN_TRACE("Removing socket file");
57  boost::filesystem::remove(m_endpoint.path(), ec);
58  }
59 }
60 
61 void
63  const FaceCreationFailedCallback& onAcceptFailed,
64  int backlog)
65 {
66  if (isListening()) {
67  NFD_LOG_CHAN_WARN("Already listening");
68  return;
69  }
70 
71  namespace fs = boost::filesystem;
72 
73  fs::path socketPath = m_endpoint.path();
74  // ensure parent directory exists
75  fs::path parent = socketPath.parent_path();
76  if (!parent.empty() && fs::create_directories(parent)) {
77  NFD_LOG_CHAN_TRACE("Created directory " << parent);
78  }
79 
80  boost::system::error_code ec;
81  fs::file_type type = fs::symlink_status(socketPath).type();
82  if (type == fs::socket_file) {
83  // if the socket file already exists, there may be another instance
84  // of NFD running on the system: make sure we don't steal its socket
85  boost::asio::local::stream_protocol::socket socket(getGlobalIoService());
86  socket.connect(m_endpoint, ec);
87  NFD_LOG_CHAN_TRACE("connect() on existing socket file returned: " << ec.message());
88  if (!ec) {
89  // someone answered, leave the socket alone
90  ec = boost::system::errc::make_error_code(boost::system::errc::address_in_use);
91  NDN_THROW_NO_STACK(fs::filesystem_error("UnixStreamChannel::listen", socketPath, ec));
92  }
93  else if (ec == boost::asio::error::connection_refused ||
94  ec == boost::asio::error::timed_out) {
95  // no one is listening on the remote side, we can safely remove the stale socket
96  NFD_LOG_CHAN_DEBUG("Removing stale socket file");
97  fs::remove(socketPath);
98  }
99  }
100  else if (type != fs::file_not_found) {
101  // the file exists but is not a socket: this is a fatal error as we cannot
102  // safely overwrite the file without potentially risking data loss
103  ec = boost::system::errc::make_error_code(boost::system::errc::not_a_socket);
104  NDN_THROW_NO_STACK(fs::filesystem_error("UnixStreamChannel::listen", socketPath, ec));
105  }
106 
107  try {
108  m_acceptor.open();
109  m_acceptor.bind(m_endpoint);
110  m_acceptor.listen(backlog);
111  }
112  catch (const boost::system::system_error& e) {
113  // exceptions thrown by Boost.Asio are very terse, add more context
114  NDN_THROW_NO_STACK(fs::filesystem_error("UnixStreamChannel::listen: "s + e.std::runtime_error::what(),
115  socketPath, e.code()));
116  }
117 
118  // do this here so that, even if the calls below fail,
119  // the destructor will still remove the socket file
120  m_isListening = true;
121 
122  fs::permissions(socketPath, fs::owner_read | fs::group_read | fs::others_read |
123  fs::owner_write | fs::group_write | fs::others_write);
124 
125  accept(onFaceCreated, onAcceptFailed);
126  NFD_LOG_CHAN_DEBUG("Started listening");
127 }
128 
129 void
130 UnixStreamChannel::accept(const FaceCreatedCallback& onFaceCreated,
131  const FaceCreationFailedCallback& onAcceptFailed)
132 {
133  m_acceptor.async_accept([=] (const boost::system::error_code& error,
134  boost::asio::local::stream_protocol::socket socket) {
135  if (error) {
136  if (error != boost::asio::error::operation_aborted) {
137  NFD_LOG_CHAN_DEBUG("Accept failed: " << error.message());
138  if (onAcceptFailed)
139  onAcceptFailed(500, "Accept failed: " + error.message());
140  }
141  return;
142  }
143 
144  NFD_LOG_CHAN_TRACE("Incoming connection via fd " << socket.native_handle());
145 
147  options.allowCongestionMarking = m_wantCongestionMarking;
148  auto linkService = make_unique<GenericLinkService>(options);
149  auto transport = make_unique<UnixStreamTransport>(std::move(socket));
150  auto face = make_shared<Face>(std::move(linkService), std::move(transport));
151  face->setChannel(weak_from_this());
152 
153  ++m_size;
154  connectFaceClosedSignal(*face, [this] { --m_size; });
155 
156  onFaceCreated(face);
157 
158  // prepare accepting the next connection
159  accept(onFaceCreated, onAcceptFailed);
160  });
161 }
162 
163 } // namespace nfd::face
void setUri(const FaceUri &uri) noexcept
Definition: channel.cpp:34
bool isListening() const final
Returns whether the channel is listening.
UnixStreamChannel(const unix_stream::Endpoint &endpoint, bool wantCongestionMarking)
Create a UnixStream channel for the specified endpoint.
void listen(const FaceCreatedCallback &onFaceCreated, const FaceCreationFailedCallback &onAcceptFailed, int backlog=boost::asio::socket_base::max_listen_connections)
Start listening.
#define NFD_LOG_CHAN_DEBUG(msg)
Log a message at DEBUG level.
Definition: channel-log.hpp:49
#define NFD_LOG_CHAN_INFO(msg)
Log a message at INFO level.
Definition: channel-log.hpp:52
#define NFD_LOG_CHAN_WARN(msg)
Log a message at WARN level.
Definition: channel-log.hpp:55
#define NFD_LOG_CHAN_TRACE(msg)
Log a message at TRACE level.
Definition: channel-log.hpp:46
#define NFD_LOG_INIT(name)
Definition: logger.hpp:31
std::function< void(uint32_t status, const std::string &reason)> FaceCreationFailedCallback
Prototype for the callback that is invoked when a face fails to be created.
Definition: channel.hpp:94
std::function< void(const shared_ptr< Face > &)> FaceCreatedCallback
Prototype for the callback that is invoked when a face is created (in response to an incoming connect...
Definition: channel.hpp:90
void connectFaceClosedSignal(Face &face, std::function< void()> f)
Invokes a callback when a face is closed.
Definition: channel.cpp:46
boost::asio::local::stream_protocol::endpoint Endpoint
boost::asio::io_context & getGlobalIoService()
Returns the global io_context instance for the calling thread.
Definition: global.cpp:36