blob: 1c9b720b9135cfd0e28461084130b3b7f305a0df [file] [log] [blame]
Yukai Tu74c895d2015-09-21 01:11:51 -07001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2/**
3 * Copyright (c) 2014-2015, 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#ifndef NFD_DAEMON_FACE_STREAM_TRANSPORT_HPP
27#define NFD_DAEMON_FACE_STREAM_TRANSPORT_HPP
28
29#include "transport.hpp"
30#include "core/global-io.hpp"
31
32#include <queue>
33
34namespace nfd {
35namespace face {
36
37/** \brief Implements Transport for stream-based protocols.
38 *
39 * \tparam Protocol a stream-based protocol in Boost.Asio
40 */
41template<class Protocol>
42class StreamTransport : public Transport
43{
44public:
45 typedef Protocol protocol;
46
47 /** \brief Construct stream transport.
48 *
49 * \param socket Protocol-specific socket for the created transport
50 */
51 explicit
52 StreamTransport(typename protocol::socket&& socket);
53
Davide Pesavento8728a252015-11-06 04:01:22 +010054protected:
Yukai Tu74c895d2015-09-21 01:11:51 -070055 virtual void
56 doClose() DECL_OVERRIDE;
57
Yukai Tu74c895d2015-09-21 01:11:51 -070058 void
59 deferredClose();
60
Davide Pesavento8728a252015-11-06 04:01:22 +010061 virtual void
62 doSend(Transport::Packet&& packet) DECL_OVERRIDE;
63
Yukai Tu74c895d2015-09-21 01:11:51 -070064 void
65 sendFromQueue();
66
67 void
68 handleSend(const boost::system::error_code& error,
69 size_t nBytesSent);
70
71 void
72 handleReceive(const boost::system::error_code& error,
73 size_t nBytesReceived);
74
75 void
76 processErrorCode(const boost::system::error_code& error);
77
78protected:
79 typename protocol::socket m_socket;
80
81 NFD_LOG_INCLASS_DECLARE();
82
83private:
Davide Pesavento8728a252015-11-06 04:01:22 +010084 uint8_t m_receiveBuffer[ndn::MAX_NDN_PACKET_SIZE];
85 size_t m_receiveBufferSize;
Yukai Tu74c895d2015-09-21 01:11:51 -070086 std::queue<Block> m_sendQueue;
87};
88
Yukai Tu74c895d2015-09-21 01:11:51 -070089
90template<class T>
Yukai Tu74c895d2015-09-21 01:11:51 -070091StreamTransport<T>::StreamTransport(typename StreamTransport::protocol::socket&& socket)
92 : m_socket(std::move(socket))
Davide Pesavento8728a252015-11-06 04:01:22 +010093 , m_receiveBufferSize(0)
Yukai Tu74c895d2015-09-21 01:11:51 -070094{
Davide Pesavento8728a252015-11-06 04:01:22 +010095 m_socket.async_receive(boost::asio::buffer(m_receiveBuffer, ndn::MAX_NDN_PACKET_SIZE),
Yukai Tu74c895d2015-09-21 01:11:51 -070096 bind(&StreamTransport<T>::handleReceive, this,
97 boost::asio::placeholders::error,
98 boost::asio::placeholders::bytes_transferred));
99}
100
101template<class T>
Davide Pesavento8728a252015-11-06 04:01:22 +0100102void
Yukai Tu74c895d2015-09-21 01:11:51 -0700103StreamTransport<T>::doClose()
104{
105 NFD_LOG_FACE_TRACE(__func__);
106
107 if (m_socket.is_open()) {
108 // Cancel all outstanding operations and shutdown the socket
109 // so that no further sends or receives are possible.
110 // Use the non-throwing variants and ignore errors, if any.
111 boost::system::error_code error;
112 m_socket.cancel(error);
113 m_socket.shutdown(protocol::socket::shutdown_both, error);
114 }
115
116 // Ensure that the Transport stays alive at least until
117 // all pending handlers are dispatched
118 getGlobalIoService().post(bind(&StreamTransport<T>::deferredClose, this));
119
120 // Some bug or feature of Boost.Asio (see http://redmine.named-data.net/issues/1856):
121 //
122 // When doClose is called from a socket event handler (e.g., from handleReceive),
123 // m_socket.shutdown() does not trigger the cancellation of the handleSend callback.
124 // Instead, handleSend is invoked as nothing bad happened.
125 //
126 // In order to prevent the assertion in handleSend from failing, we clear the queue
127 // and close the socket in deferredClose, i.e., after all callbacks scheduled up to
128 // this point have been executed. If more send operations are scheduled after this
129 // point, they will fail because the socket has been shutdown, and their callbacks
130 // will be invoked with error code == asio::error::shut_down.
131}
132
133template<class T>
Davide Pesavento8728a252015-11-06 04:01:22 +0100134void
Yukai Tu74c895d2015-09-21 01:11:51 -0700135StreamTransport<T>::deferredClose()
136{
137 NFD_LOG_FACE_TRACE(__func__);
138
139 // clear send queue
140 std::queue<Block> emptyQueue;
141 std::swap(emptyQueue, m_sendQueue);
142
143 // use the non-throwing variant and ignore errors, if any
144 boost::system::error_code error;
145 m_socket.close(error);
146
147 this->setState(TransportState::CLOSED);
148}
149
150template<class T>
Davide Pesavento8728a252015-11-06 04:01:22 +0100151void
152StreamTransport<T>::doSend(Transport::Packet&& packet)
153{
154 NFD_LOG_FACE_TRACE(__func__);
155
156 bool wasQueueEmpty = m_sendQueue.empty();
157 m_sendQueue.push(packet.packet);
158
159 if (wasQueueEmpty)
160 sendFromQueue();
161}
162
163template<class T>
164void
Yukai Tu74c895d2015-09-21 01:11:51 -0700165StreamTransport<T>::sendFromQueue()
166{
167 boost::asio::async_write(m_socket, boost::asio::buffer(m_sendQueue.front()),
168 bind(&StreamTransport<T>::handleSend, this,
169 boost::asio::placeholders::error,
170 boost::asio::placeholders::bytes_transferred));
171}
172
173template<class T>
Davide Pesavento8728a252015-11-06 04:01:22 +0100174void
Yukai Tu74c895d2015-09-21 01:11:51 -0700175StreamTransport<T>::handleSend(const boost::system::error_code& error,
176 size_t nBytesSent)
177{
178 if (error)
179 return processErrorCode(error);
180
181 NFD_LOG_FACE_TRACE("Successfully sent: " << nBytesSent << " bytes");
182
183 BOOST_ASSERT(!m_sendQueue.empty());
184 m_sendQueue.pop();
185
186 if (!m_sendQueue.empty())
187 sendFromQueue();
188}
189
190template<class T>
Davide Pesavento8728a252015-11-06 04:01:22 +0100191void
Yukai Tu74c895d2015-09-21 01:11:51 -0700192StreamTransport<T>::handleReceive(const boost::system::error_code& error,
193 size_t nBytesReceived)
194{
195 if (error)
196 return processErrorCode(error);
197
198 NFD_LOG_FACE_TRACE("Received: " << nBytesReceived << " bytes");
199
Davide Pesavento8728a252015-11-06 04:01:22 +0100200 m_receiveBufferSize += nBytesReceived;
Yukai Tu74c895d2015-09-21 01:11:51 -0700201
202 size_t offset = 0;
203
204 bool isOk = true;
205 Block element;
Davide Pesavento8728a252015-11-06 04:01:22 +0100206 while (m_receiveBufferSize - offset > 0) {
207 std::tie(isOk, element) = Block::fromBuffer(m_receiveBuffer + offset, m_receiveBufferSize - offset);
Yukai Tu74c895d2015-09-21 01:11:51 -0700208 if (!isOk)
209 break;
210
211 offset += element.size();
Davide Pesavento8728a252015-11-06 04:01:22 +0100212 BOOST_ASSERT(offset <= m_receiveBufferSize);
Yukai Tu74c895d2015-09-21 01:11:51 -0700213
Davide Pesavento8728a252015-11-06 04:01:22 +0100214 this->receive(Transport::Packet(std::move(element)));
Yukai Tu74c895d2015-09-21 01:11:51 -0700215 }
216
Davide Pesavento8728a252015-11-06 04:01:22 +0100217 if (!isOk && m_receiveBufferSize == ndn::MAX_NDN_PACKET_SIZE && offset == 0) {
Yukai Tu74c895d2015-09-21 01:11:51 -0700218 NFD_LOG_FACE_WARN("Failed to parse incoming packet or packet too large to process");
219 this->setState(TransportState::FAILED);
220 doClose();
221 return;
222 }
223
224 if (offset > 0) {
Davide Pesavento8728a252015-11-06 04:01:22 +0100225 if (offset != m_receiveBufferSize) {
226 std::copy(m_receiveBuffer + offset, m_receiveBuffer + m_receiveBufferSize, m_receiveBuffer);
227 m_receiveBufferSize -= offset;
Yukai Tu74c895d2015-09-21 01:11:51 -0700228 }
229 else {
Davide Pesavento8728a252015-11-06 04:01:22 +0100230 m_receiveBufferSize = 0;
Yukai Tu74c895d2015-09-21 01:11:51 -0700231 }
232 }
233
Davide Pesavento8728a252015-11-06 04:01:22 +0100234 m_socket.async_receive(boost::asio::buffer(m_receiveBuffer + m_receiveBufferSize,
235 ndn::MAX_NDN_PACKET_SIZE - m_receiveBufferSize),
Yukai Tu74c895d2015-09-21 01:11:51 -0700236 bind(&StreamTransport<T>::handleReceive, this,
237 boost::asio::placeholders::error,
238 boost::asio::placeholders::bytes_transferred));
239}
240
241template<class T>
Davide Pesavento8728a252015-11-06 04:01:22 +0100242void
Yukai Tu74c895d2015-09-21 01:11:51 -0700243StreamTransport<T>::processErrorCode(const boost::system::error_code& error)
244{
245 NFD_LOG_FACE_TRACE(__func__);
246
247 if (getState() == TransportState::CLOSING ||
248 getState() == TransportState::FAILED ||
249 getState() == TransportState::CLOSED ||
250 error == boost::asio::error::operation_aborted || // when cancel() is called
251 error == boost::asio::error::shut_down) // after shutdown() is called
252 // transport is shutting down, ignore any errors
253 return;
254
255 if (error != boost::asio::error::eof)
256 NFD_LOG_FACE_WARN("Send or receive operation failed: " << error.message());
257
258 this->setState(TransportState::FAILED);
259 doClose();
260}
261
262} // namespace face
263} // namespace nfd
264
265#endif // NFD_DAEMON_FACE_STREAM_TRANSPORT_HPP