Connection.hh
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2012 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  func(_func),
66  data(_data)
67  {
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.value() == boost::asio::error::eof)
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.value() == boost::asio::error::eof)
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 
329  public: void ProcessWriteQueue(bool _blocking = false);
330 
333  public: unsigned int GetId() const;
334 
338  public: static bool ValidateIP(const std::string &_ip);
339 
343  public: std::string GetIPWhiteList() const;
344 
347  private: void PostWrite();
348 
352  private: void OnWrite(const boost::system::error_code &_e);
353 
356  private: void OnAccept(const boost::system::error_code &_e);
357 
360  private: std::size_t ParseHeader(const std::string &_header);
361 
363  private: void ReadLoop(const ReadCallback &_cb);
364 
367  private: static boost::asio::ip::tcp::endpoint GetLocalEndpoint();
368 
371  private: boost::asio::ip::tcp::endpoint GetRemoteEndpoint() const;
372 
375  private: static std::string GetHostname(
376  boost::asio::ip::tcp::endpoint _ep);
377 
381  private: void OnConnect(const boost::system::error_code &_error,
382  boost::asio::ip::tcp::resolver::iterator _endPointIter);
383 
385  private: boost::asio::ip::tcp::socket *socket;
386 
388  private: boost::asio::ip::tcp::acceptor *acceptor;
389 
391  private: std::deque<std::string> writeQueue;
392 
395  private: std::deque< std::vector<
396  std::pair<boost::function<void(uint32_t)>, uint32_t> > >
397  callbacks;
398 
400  private: boost::mutex connectMutex;
401 
403  private: boost::recursive_mutex writeMutex;
404 
406  private: boost::recursive_mutex readMutex;
407 
409  private: mutable boost::mutex socketMutex;
410 
412  private: boost::condition_variable connectCondition;
413 
415  private: AcceptCallback acceptCB;
416 
418  private: std::vector<char> inboundHeader;
419 
421  private: std::vector<char> inboundData;
422 
424  private: bool readQuit;
425 
427  private: unsigned int id;
428 
430  private: static unsigned int idCounter;
431 
433  private: ConnectionPtr acceptConn;
434 
437 
439  private: static IOManager *iomanager;
440 
442  private: unsigned int writeCount;
443 
445  private: std::string localURI;
446 
448  private: std::string localAddress;
449 
451  private: std::string remoteURI;
452 
454  private: std::string remoteAddress;
455 
457  private: bool connectError;
458 
460  private: std::string ipWhiteList;
461 
463  private: bool dropMsgLogged;
464 
466  private: bool isOpen;
467  };
469  }
470 }
471 #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
#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:134
#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