Connection.hh
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2012-2016 Open Source Robotics Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16 */
17 #ifndef _CONNECTION_HH_
18 #define _CONNECTION_HH_
19 
20 #include <tbb/task.h>
21 #include <google/protobuf/message.h>
22 
23 #include <boost/asio.hpp>
24 #include <boost/bind.hpp>
25 #include <boost/function.hpp>
26 #include <boost/thread.hpp>
27 #include <boost/tuple/tuple.hpp>
28 
29 #include <string>
30 #include <vector>
31 #include <iostream>
32 #include <iomanip>
33 #include <deque>
34 #include <utility>
35 
36 #include "gazebo/common/Event.hh"
37 #include "gazebo/common/Console.hh"
39 #include "gazebo/util/system.hh"
40 
41 #define HEADER_LENGTH 8
42 
43 namespace gazebo
44 {
45  namespace transport
46  {
47  extern GZ_TRANSPORT_VISIBLE bool is_stopped();
48 
49  class IOManager;
50  class Connection;
51  typedef boost::shared_ptr<Connection> ConnectionPtr;
52 
56  class GZ_TRANSPORT_VISIBLE ConnectionReadTask : public tbb::task
57  {
62  public: ConnectionReadTask(
63  boost::function<void (const std::string &)> _func,
64  const std::string &_data)
65  {
66  this->func = _func;
67  this->data = _data;
68  }
69 
72  public: tbb::task *execute()
73  {
74  this->func(this->data);
75  return NULL;
76  }
77 
79  private: boost::function<void (const std::string &)> func;
80 
82  private: std::string data;
83  };
85 
100  class GZ_TRANSPORT_VISIBLE Connection :
101  public boost::enable_shared_from_this<Connection>
102  {
104  public: Connection();
105 
107  public: virtual ~Connection();
108 
113  public: bool Connect(const std::string &_host, unsigned int _port);
114 
116  typedef boost::function<void(const ConnectionPtr&)> AcceptCallback;
117 
122  public: void Listen(unsigned int _port, const AcceptCallback &_acceptCB);
123 
125  typedef boost::function<void(const std::string &_data)> ReadCallback;
126 
130  public: void StartRead(const ReadCallback &_cb);
131 
133  public: void StopRead();
134 
136  public: void Shutdown();
137 
140  public: bool IsOpen() const;
141 
143  private: void Close();
144 
146  public: void Cancel();
147 
151  public: bool Read(std::string &_data);
152 
160  public: void EnqueueMsg(const std::string &_buffer,
161  boost::function<void(uint32_t)> _cb, uint32_t _id,
162  bool _force = false);
163 
168  public: void EnqueueMsg(const std::string &_buffer, bool _force = false);
169 
172  public: std::string GetLocalURI() const;
173 
176  public: std::string GetRemoteURI() const;
177 
180  public: std::string GetLocalAddress() const;
181 
184  public: unsigned int GetLocalPort() const;
185 
188  public: std::string GetRemoteAddress() const;
189 
192  public: unsigned int GetRemotePort() const;
193 
196  public: std::string GetRemoteHostname() const;
197 
200  public: static std::string GetLocalHostname();
201 
204  public: template<typename Handler>
205  void AsyncRead(Handler _handler)
206  {
207  boost::mutex::scoped_lock lock(this->socketMutex);
208  if (!this->IsOpen())
209  {
210  gzerr << "AsyncRead on a closed socket\n";
211  return;
212  }
213 
214  void (Connection::*f)(const boost::system::error_code &,
215  boost::tuple<Handler>) = &Connection::OnReadHeader<Handler>;
216 
217  this->inboundHeader.resize(HEADER_LENGTH);
218  boost::asio::async_read(*this->socket,
219  boost::asio::buffer(this->inboundHeader),
220  boost::bind(f, this,
221  boost::asio::placeholders::error,
222  boost::make_tuple(_handler)));
223  }
224 
232  private: template<typename Handler>
233  void OnReadHeader(const boost::system::error_code &_e,
234  boost::tuple<Handler> _handler)
235  {
236  if (_e)
237  {
238  if (_e.message() == "End of file")
239  this->isOpen = false;
240  }
241  else
242  {
243  std::size_t inboundData_size = 0;
244  std::string header(&this->inboundHeader[0],
245  this->inboundHeader.size());
246  this->inboundHeader.clear();
247 
248  inboundData_size = this->ParseHeader(header);
249 
250  if (inboundData_size > 0)
251  {
252  // Start the asynchronous call to receive data
253  this->inboundData.resize(inboundData_size);
254 
255  void (Connection::*f)(const boost::system::error_code &e,
256  boost::tuple<Handler>) =
257  &Connection::OnReadData<Handler>;
258 
259  boost::asio::async_read(*this->socket,
260  boost::asio::buffer(this->inboundData),
261  boost::bind(f, this,
262  boost::asio::placeholders::error,
263  _handler));
264  }
265  else
266  {
267  gzerr << "Header is empty\n";
268  boost::get<0>(_handler)("");
269  // This code tries to read the header again. We should
270  // never get here.
271  // this->inboundHeader.resize(HEADER_LENGTH);
272 
273  // void (Connection::*f)(const boost::system::error_code &,
274  // boost::tuple<Handler>) =
275  // &Connection::OnReadHeader<Handler>;
276 
277  // boost::asio::async_read(*this->socket,
278  // boost::asio::buffer(this->inboundHeader),
279  // boost::bind(f, this,
280  // boost::asio::placeholders::error, _handler));
281  }
282  }
283  }
284 
292  private: template<typename Handler>
293  void OnReadData(const boost::system::error_code &_e,
294  boost::tuple<Handler> _handler)
295  {
296  if (_e)
297  {
298  if (_e.message() == "End of file")
299  this->isOpen = false;
300  }
301 
302  // Inform caller that data has been received
303  std::string data(&this->inboundData[0],
304  this->inboundData.size());
305  this->inboundData.clear();
306 
307  if (data.empty())
308  gzerr << "OnReadData got empty data!!!\n";
309 
310  if (!_e && !transport::is_stopped())
311  {
312  ConnectionReadTask *task = new(tbb::task::allocate_root())
313  ConnectionReadTask(boost::get<0>(_handler), data);
314  tbb::task::enqueue(*task);
315 
316  // Non-tbb version:
317  // boost::get<0>(_handler)(data);
318  }
319  }
320 
324  public: event::ConnectionPtr ConnectToShutdown(boost::function<void()>
325  _subscriber)
326  { return this->shutdown.Connect(_subscriber); }
327 
331  public: void DisconnectShutdown(event::ConnectionPtr _subscriber)
332  {this->shutdown.Disconnect(_subscriber);}
333 
335  public: void ProcessWriteQueue(bool _blocking = false);
336 
339  public: unsigned int GetId() const;
340 
344  public: static bool ValidateIP(const std::string &_ip);
345 
349  public: std::string GetIPWhiteList() const;
350 
354  private: void OnWrite(const boost::system::error_code &_e);
355 
358  private: void OnAccept(const boost::system::error_code &_e);
359 
362  private: std::size_t ParseHeader(const std::string &_header);
363 
365  private: void ReadLoop(const ReadCallback &_cb);
366 
369  private: static boost::asio::ip::tcp::endpoint GetLocalEndpoint();
370 
373  private: boost::asio::ip::tcp::endpoint GetRemoteEndpoint() const;
374 
377  private: static std::string GetHostname(
378  boost::asio::ip::tcp::endpoint _ep);
379 
383  private: void OnConnect(const boost::system::error_code &_error,
384  boost::asio::ip::tcp::resolver::iterator _endPointIter);
385 
387  private: boost::asio::ip::tcp::socket *socket;
388 
390  private: boost::asio::ip::tcp::acceptor *acceptor;
391 
393  private: std::deque<std::string> writeQueue;
394 
397  private: std::deque<
398  std::pair<boost::function<void(uint32_t)>, uint32_t> > callbacks;
399 
401  private: boost::mutex connectMutex;
402 
404  private: boost::recursive_mutex writeMutex;
405 
407  private: boost::recursive_mutex readMutex;
408 
410  private: mutable boost::mutex socketMutex;
411 
413  private: boost::condition_variable connectCondition;
414 
416  private: AcceptCallback acceptCB;
417 
419  private: std::vector<char> inboundHeader;
420 
422  private: std::vector<char> inboundData;
423 
425  private: bool readQuit;
426 
428  private: unsigned int id;
429 
431  private: static unsigned int idCounter;
432 
434  private: ConnectionPtr acceptConn;
435 
438 
440  private: static IOManager *iomanager;
441 
443  private: unsigned int writeCount;
444 
446  private: std::string localURI;
447 
449  private: std::string localAddress;
450 
452  private: std::string remoteURI;
453 
455  private: std::string remoteAddress;
456 
458  private: bool connectError;
459 
461  private: std::string ipWhiteList;
462 
464  private: char *headerBuffer;
465 
467  private: bool dropMsgLogged;
468 
471  private: unsigned int callbackIndex;
472 
474  private: bool isOpen;
475  };
477  }
478 }
479 #endif
boost::function< void(const ConnectionPtr &)> AcceptCallback
The signature of a connection accept callback.
Definition: Connection.hh:116
boost::function< void(const std::string &_data)> ReadCallback
The signature of a connection read callback.
Definition: Connection.hh:125
void DisconnectShutdown(event::ConnectionPtr _subscriber)
Unregister a function to be called when the connection is shut down.
Definition: Connection.hh:331
#define HEADER_LENGTH
Definition: Connection.hh:41
#define gzerr
Output an error message.
Definition: Console.hh:50
Manages boost::asio IO.
Definition: IOManager.hh:33
event::ConnectionPtr ConnectToShutdown(boost::function< void()> _subscriber)
Register a function to be called when the connection is shut down.
Definition: Connection.hh:324
boost::shared_ptr< Connection > ConnectionPtr
Definition: Connection.hh:50
GAZEBO_VISIBLE bool shutdown()
Stop and cleanup simulation.
boost::shared_ptr< Connection > ConnectionPtr
Definition: CommonTypes.hh:153
#define NULL
Definition: CommonTypes.hh:31
void AsyncRead(Handler _handler)
Peform an asyncronous read param[in] _handler Callback to invoke on received data.
Definition: Connection.hh:205
bool is_stopped()
Is the transport system stopped?
Single TCP/IP connection manager.
Definition: Connection.hh:100