blob: f98b988a3658a19d8475ae76a5bf6e5458a46fe8 [file] [log] [blame]
Alexander Afanasyev5964fb72014-02-18 12:42:45 -08001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
2/**
3 * Copyright (C) 2013-2014 Regents of the University of California.
4 * See COPYING for copyright and distribution information.
5 */
6
7#ifndef NDN_TRANSPORT_STREAM_TRANSPORT_HPP
8#define NDN_TRANSPORT_STREAM_TRANSPORT_HPP
9
10#include "../common.hpp"
11
12namespace ndn {
13
14const size_t MAX_LENGTH = 9000;
15
16template<class BaseTransport, class Protocol>
17class StreamTransportImpl
18{
19public:
20 typedef BaseTransport base_transport;
21 typedef Protocol protocol;
22 typedef StreamTransportImpl<BaseTransport,Protocol> impl;
23
24 StreamTransportImpl(base_transport& transport, boost::asio::io_service& ioService)
25 : m_transport(transport)
26 , m_socket(ioService)
27 , m_partialDataSize(0)
28 , m_connectionInProgress(false)
29 , m_connectTimer(ioService)
30 {
31 }
32
33 void
34 connectHandler(const boost::system::error_code& error)
35 {
36 m_connectionInProgress = false;
37 m_connectTimer.cancel();
38
39 if (!error)
40 {
41 m_partialDataSize = 0;
42 m_socket.async_receive(boost::asio::buffer(m_inputBuffer, MAX_LENGTH), 0,
43 bind(&impl::handle_async_receive, this, _1, _2));
44
45 m_transport.m_isConnected = true;
46
47 for (std::list<Block>::iterator i = m_sendQueue.begin(); i != m_sendQueue.end(); ++i)
48 m_socket.async_send(boost::asio::buffer(i->wire(), i->size()),
49 bind(&impl::handle_async_send, this, _1, *i));
50
51 for (std::list< std::pair<Block,Block> >::iterator i = m_sendPairQueue.begin();
52 i != m_sendPairQueue.end(); ++i)
53 {
54 std::vector<boost::asio::const_buffer> buffer;
55 buffer.reserve(2);
56 buffer.push_back(boost::asio::buffer(i->first.wire(), i->first.size()));
57 buffer.push_back(boost::asio::buffer(i->second.wire(), i->second.size()));
58 m_socket.async_send(buffer,
59 bind(&impl::handle_async_send, this, _1, i->first, i->second));
60 }
61
62 m_sendQueue.clear();
63 m_sendPairQueue.clear();
64 }
65 else
66 {
67 // may need to throw exception
68 m_transport.m_isConnected = false;
69 m_transport.close();
70 throw Transport::Error(error, "error while connecting to the forwarder");
71 }
72 }
73
74 void
75 connectTimeoutHandler(const boost::system::error_code& error)
76 {
77 if (error) // e.g., cancelled timer
78 return;
79
80 m_connectionInProgress = false;
81 m_transport.m_isConnected = false;
82 m_socket.close();
83 throw Transport::Error(error, "error while connecting to the forwarder");
84 }
85
86 void
87 connect(const typename protocol::endpoint& endpoint)
88 {
89 if (!m_connectionInProgress) {
90 m_connectionInProgress = true;
91
92 // Wait at most 4 seconds to connect
93 /// @todo Decide whether this number should be configurable
94 m_connectTimer.expires_from_now(boost::posix_time::seconds(4));
95 m_connectTimer.async_wait(bind(&impl::connectTimeoutHandler, this, _1));
96
97 m_socket.open();
98 m_socket.async_connect(endpoint,
99 bind(&impl::connectHandler, this, _1));
100 }
101 }
102
103 void
104 close()
105 {
106 m_connectTimer.cancel();
107 m_socket.close();
108 m_transport.m_isConnected = false;
109 m_sendQueue.clear();
110 m_sendPairQueue.clear();
111 }
112
113 void
114 send(const Block& wire)
115 {
116 if (!m_transport.m_isConnected)
117 m_sendQueue.push_back(wire);
118 else
119 m_socket.async_send(boost::asio::buffer(wire.wire(), wire.size()),
120 bind(&impl::handle_async_send, this, _1, wire));
121 }
122
123 void
124 send(const Block& header, const Block& payload)
125 {
126 if (!m_transport.m_isConnected)
127 {
128 m_sendPairQueue.push_back(std::make_pair(header, payload));
129 }
130 else
131 {
132 std::vector<boost::asio::const_buffer> buffers;
133 buffers.reserve(2);
134 buffers.push_back(boost::asio::buffer(header.wire(), header.size()));
135 buffers.push_back(boost::asio::buffer(payload.wire(), payload.size()));
136
137 m_socket.async_send(buffers,
138 bind(&impl::handle_async_send, this, _1, header, payload));
139 }
140 }
141
142 inline void
143 processAll(uint8_t* buffer, size_t& offset, size_t availableSize)
144 {
145 while(offset < availableSize)
146 {
147 Block element(buffer + offset, availableSize - offset);
148 m_transport.receive(element);
149
150 offset += element.size();
151 }
152 }
153
154 void
155 handle_async_receive(const boost::system::error_code& error, std::size_t bytes_recvd)
156 {
157 /// @todo The socket is not datagram, so need to have internal buffer to handle partial data reception
158
159 if (error)
160 {
161 if (error == boost::system::errc::operation_canceled) {
162 // async receive has been explicitly cancelled (e.g., socket close)
163 return;
164 }
165
166 m_socket.close(); // closing at this point may not be that necessary
167 m_transport.m_isConnected = true;
168 throw Transport::Error(error, "error while receiving data from socket");
169 }
170
171 if (!error && bytes_recvd > 0)
172 {
173 // m_inputBuffer has bytes_recvd received bytes of data
174 if (m_partialDataSize > 0)
175 {
176 size_t newDataSize = std::min(bytes_recvd, MAX_LENGTH-m_partialDataSize);
177 std::copy(m_inputBuffer, m_inputBuffer + newDataSize, m_partialData + m_partialDataSize);
178
179 m_partialDataSize += newDataSize;
180
181 size_t offset = 0;
182 try
183 {
184 processAll(m_partialData, offset, m_partialDataSize);
185
186 // no exceptions => processed the whole thing
187 if (bytes_recvd - newDataSize > 0)
188 {
189 // there is a little bit more data available
190
191 offset = 0;
192 m_partialDataSize = bytes_recvd - newDataSize;
193 std::copy(m_inputBuffer + newDataSize, m_inputBuffer + newDataSize + m_partialDataSize, m_partialData);
194
195 processAll(m_partialData, offset, m_partialDataSize);
196
197 // no exceptions => processed the whole thing
198 m_partialDataSize = 0;
199 }
200 else
201 {
202 // done processing
203 m_partialDataSize = 0;
204 }
205 }
206 catch(Tlv::Error &)
207 {
208 if (offset > 0)
209 {
210 m_partialDataSize -= offset;
211 std::copy(m_partialData + offset, m_partialData + offset + m_partialDataSize, m_partialData);
212 }
213 else if (offset == 0 && m_partialDataSize == MAX_LENGTH)
214 {
215 // very bad... should close connection
216 m_socket.close();
217 m_transport.m_isConnected = true;
218 throw Transport::Error(boost::system::error_code(),
219 "input buffer full, but a valid TLV cannot be decoded");
220 }
221 }
222 }
223 else
224 {
225 size_t offset = 0;
226 try
227 {
228 processAll(m_inputBuffer, offset, bytes_recvd);
229 }
230 catch(Tlv::Error &error)
231 {
232 if (offset > 0)
233 {
234 m_partialDataSize = bytes_recvd - offset;
235 std::copy(m_inputBuffer + offset, m_inputBuffer + offset + m_partialDataSize, m_partialData);
236 }
237 }
238 }
239 }
240
241 m_socket.async_receive(boost::asio::buffer(m_inputBuffer, MAX_LENGTH), 0,
242 bind(&impl::handle_async_receive, this, _1, _2));
243 }
244
245 void
246 handle_async_send(const boost::system::error_code& error, const Block& wire)
247 {
248 // pass (needed to keep data block alive during the send)
249 }
250
251 void
252 handle_async_send(const boost::system::error_code& error,
253 const Block& header, const Block& payload)
254 {
255 // pass (needed to keep data blocks alive during the send)
256 }
257
258protected:
259 base_transport& m_transport;
260
261 typename protocol::socket m_socket;
262 uint8_t m_inputBuffer[MAX_LENGTH];
263
264 uint8_t m_partialData[MAX_LENGTH];
265 size_t m_partialDataSize;
266
267 std::list< Block > m_sendQueue;
268 std::list< std::pair<Block, Block> > m_sendPairQueue;
269 bool m_connectionInProgress;
270
271 boost::asio::deadline_timer m_connectTimer;
272};
273
274
275template<class BaseTransport, class Protocol>
276class StreamTransportWithResolverImpl : public StreamTransportImpl<BaseTransport, Protocol>
277{
278public:
279 typedef BaseTransport base_transport;
280 typedef Protocol protocol;
281 typedef StreamTransportWithResolverImpl<BaseTransport,Protocol> impl;
282
283 StreamTransportWithResolverImpl(base_transport& transport, boost::asio::io_service& ioService)
284 : StreamTransportImpl<base_transport, protocol>(transport, ioService)
285 {
286 }
287
288 void
289 resolveHandler(const boost::system::error_code& error,
290 typename protocol::resolver::iterator endpoint,
291 const shared_ptr<typename protocol::resolver>&)
292 {
293 if (error)
294 {
295 if (error == boost::system::errc::operation_canceled)
296 return;
297
298 throw Transport::Error(error, "Error during resolution of host or port");
299 }
300
301 typename protocol::resolver::iterator end;
302 if (endpoint == end)
303 {
304 this->m_connectionInProgress = false;
305 this->m_transport.m_isConnected = false;
306 this->m_socket.close();
307 throw Transport::Error(error, "Unable to resolve because host or port");
308 }
309
310 this->m_socket.async_connect(*endpoint,
311 bind(&impl::connectHandler, this, _1));
312 }
313
314 void
315 connect(const typename protocol::resolver::query& query)
316 {
317 if (!this->m_connectionInProgress) {
318 this->m_connectionInProgress = true;
319
320 // Wait at most 4 seconds to connect
321 /// @todo Decide whether this number should be configurable
322 this->m_connectTimer.expires_from_now(boost::posix_time::seconds(4));
323 this->m_connectTimer.async_wait(bind(&impl::connectTimeoutHandler, this, _1));
324
325 // typename boost::asio::ip::basic_resolver< protocol > resolver;
326 shared_ptr<typename protocol::resolver> resolver =
327 make_shared<typename protocol::resolver>(boost::ref(this->m_socket.get_io_service()));
328
329 resolver->async_resolve(query, bind(&impl::resolveHandler, this, _1, _2, resolver));
330 }
331 }
332};
333
334
335} // namespace ndn
336
337#endif // NDN_TRANSPORT_STREAM_TRANSPORT_HPP