1 // Boost pinger (c) 2011 by Guilherme Maciel Ferreira / Intra2net AG
2 // Based upon work copyright (c) 2003-2010 Christopher M. Kohlhoff (ping.cpp)
4 // Distributed under the Boost Software License, Version 1.0.
5 // (See accompanying file LICENSE_1_0.txt or copy at
6 // http://www.boost.org/LICENSE_1_0.txt)
7 #include "icmp/icmppinger.h"
13 #include <boost/bind.hpp>
14 #include <boost/date_time/posix_time/posix_time.hpp>
15 #include <boost/date_time/posix_time/posix_time_types.hpp>
16 #include <boost/uuid/uuid.hpp>
17 #include <boost/uuid/uuid_generators.hpp>
18 #include <boost/foreach.hpp>
20 #include <logfunc.hpp>
22 #include "boost_assert_handler.h"
23 #include "icmp/icmppacketfactory.h"
24 #include "host/networkinterface.hpp"
27 using boost::asio::const_buffers_1;
28 using boost::asio::io_service;
29 using boost::asio::ip::address;
30 using boost::asio::ip::icmp;
31 using boost::function;
32 using boost::posix_time::microsec_clock;
33 using boost::posix_time::seconds;
34 using boost::shared_ptr;
35 using I2n::Logger::GlobalLogger;
37 using boost::asio::ip::icmp;
39 //-----------------------------------------------------------------------------
41 //-----------------------------------------------------------------------------
44 * @brief factory function for IcmpPingers, ensures that set_myself is set
46 * @returns a shared pointer to a Pinger
48 PingerItem IcmpPinger::create(
49 const IoServiceItem io_serv,
50 const icmp::socket::protocol_type &protocol,
51 const string &source_network_interface,
52 const int echo_reply_timeout_in_sec )
55 IcmpPacketDistributorItem distributor = IcmpPacketDistributor::get_distributor(
56 protocol, source_network_interface, io_serv);
59 IcmpPinger *ptr = new IcmpPinger(io_serv, protocol, echo_reply_timeout_in_sec, distributor);
60 IcmpPingerItem shared_ptr_(ptr);
62 // keep weak pointer to self
63 //shared_ptr_->set_myself( weak_ptr ); //Error: Pinger::set_myself is protected
64 ptr->set_myself( shared_ptr_ );
66 // register in distributor
67 distributor->register_pinger(shared_ptr_);
69 // done, return shared ptr
74 * @brief Parameterized constructor.
76 * @param io_serv The one @c io_service object that controls async processing
77 * @param protocol The network layer protocol to use.
78 * @param source_network_interface The network interface name from where to
80 * @param echo_reply_timeout_in_sec The amount of time to wait for a reply.
82 IcmpPinger::IcmpPinger(
83 const IoServiceItem io_serv,
84 const icmp::socket::protocol_type &protocol,
85 const int echo_reply_timeout_in_sec,
86 const IcmpPacketDistributorItem distributor
88 PacketDistributor( distributor ),
89 DestinationEndpoint(),
91 IcmpPacketReceiveTimer( *io_serv ),
94 TimeSent( microsec_clock::universal_time() ),
95 ReplyReceived( false ),
96 EchoReplyTimeoutInSec( echo_reply_timeout_in_sec ),
97 PingerStatus( PingStatus_NotSent ),
99 LogPrefix("IcmpPinger")
101 // Create "unique" identifier
102 boost::uuids::random_generator random_gen;
103 boost::uuids::uuid random_tag = random_gen();
105 BOOST_ASSERT( sizeof(Identifier) <= random_tag.size() );
106 memcpy( &Identifier, random_tag.data, sizeof(Identifier) );
108 LogPrefix = "IPing(no IP yet): ";
114 IcmpPinger::~IcmpPinger()
119 * @brief Ping a destination address from an available local source.
121 * @param destination_ip The address of the host to ping.
122 * @param destination_port The port at the destination host to ping.
123 * @param done_handler Done handler will be called on successful ping or timeout.
127 void IcmpPinger::ping(
128 const address &destination_ip,
129 const uint16_t /*destination_port*/, // the ICMP protocol does not use ports
130 function<void(PingStatus,long)> ping_done_callback
133 PingDoneCallback = ping_done_callback;
136 set_ping_status( PingStatus_NotSent );
138 set_destination_endpoint( destination_ip );
143 void IcmpPinger::stop_pinging()
145 GlobalLogger.debug() << LogPrefix << "stop_pinging" << endl;
147 GlobalLogger.debug() << LogPrefix << "cancel timer" << endl;
148 IcmpPacketReceiveTimer.cancel();
150 GlobalLogger.debug() << LogPrefix << "unregister" << endl;
152 IcmpPingerItem icmp_item = boost::static_pointer_cast<IcmpPinger>( get_myself().lock() );
155 PacketDistributor->unregister_pinger( icmp_item );
158 GlobalLogger.warning() << LogPrefix
159 << "weak pointer to pinger broken is empty. Huh?" << endl;
164 void IcmpPinger::set_destination_endpoint( const address &destination_ip )
167 DestinationEndpoint = icmp::endpoint( destination_ip, port );
170 std::stringstream temp;
171 temp << "IPing(" << DestinationEndpoint.address().to_string() << "): ";
172 LogPrefix = temp.str();
175 bool IcmpPinger::start_send()
179 IcmpPacketItem icmp_packet_echo_request = IcmpPacketFactory::create_icmp_packet_echo_request(
180 Protocol, Identifier, SequenceNumber );
182 BOOST_ASSERT( PingerStatus == PingStatus_NotSent );
183 return send_echo_request( icmp_packet_echo_request );
186 bool IcmpPinger::send_echo_request( const IcmpPacketItem icmp_packet )
188 boost::asio::streambuf request_buffer;
189 ostream os( &request_buffer );
190 if ( !icmp_packet->write( os ) )
192 GlobalLogger.error() << LogPrefix << "fail writing ping data." << endl;
195 TimeSent = microsec_clock::universal_time();
197 string dest_address_string = DestinationEndpoint.address().to_string();
198 BOOST_ASSERT( !dest_address_string.empty() );
201 size_t bytes_sent = 0;
204 GlobalLogger.info() << LogPrefix << "sending ping" << endl;
205 const_buffers_1 data = request_buffer.data();
207 // Block until send the data
208 bytes_sent = PacketDistributor->get_socket()->send_to( data, DestinationEndpoint );
209 if ( bytes_sent != buffer_size( data ) )
211 GlobalLogger.error() << LogPrefix << "fail sending ping data."
215 catch ( const exception &ex )
217 GlobalLogger.error() << LogPrefix << "fail sending ping data. "
218 << ex.what() << endl;
221 ReplyReceived = false;
222 schedule_timeout_echo_reply();
224 return (bytes_sent > 0);
227 void IcmpPinger::schedule_timeout_echo_reply()
229 // Wait up to N seconds for a reply.
230 (void) IcmpPacketReceiveTimer.expires_at(
231 TimeSent + seconds( EchoReplyTimeoutInSec )
233 IcmpPacketReceiveTimer.async_wait(
234 boost::bind( &IcmpPinger::handle_timeout, this, boost::asio::placeholders::error )
239 * @brief Gets called when the ping is finished: Either on timeout or on ping reply
241 * @return void (but calls PingDoneCallback)
243 void IcmpPinger::handle_timeout(const boost::system::error_code& error)
247 if ( error == boost::asio::error::operation_aborted )
251 GlobalLogger.notice() << LogPrefix
252 << "Timer waiting for ICMP echo reply was cancelled!"
254 set_ping_status( PingStatus_FailureAsyncCancel );
256 // otherwise probably called by IcmpPacketReceiveTimer.cancel in
257 // handle_receive_icmp_packet!
261 GlobalLogger.notice() << LogPrefix << "Error " << error
262 << " waiting for ICMP echo reply!" << endl;
263 set_ping_status( PingStatus_FailureAsyncError );
266 // Still continue with rest of function, so PingStatus is updated and Callback executed
267 // when timer was cancelled
269 else if ( !ReplyReceived )
270 { // Check ReplyReceived since the timer handler is also called by Timer.cancel();
271 GlobalLogger.info() << LogPrefix << "Request timed out" << endl;
273 set_ping_status( PingStatus_FailureTimeout );
276 // Call ping-done handler
277 PingDoneCallback( PingerStatus,
278 (microsec_clock::universal_time()
279 - TimeSent).total_microseconds() );
284 * @brief Receive ICMP packets
285 * @param bytes_transferred Number of bytes transferred.
286 * @return true if packet matches a request from this pinger, false otherwise
288 bool IcmpPinger::handle_receive_icmp_packet(const IcmpPacketItem icmp_packet,
289 const size_t bytes_transferred )
291 bool does_match = false;
295 // continue, might be an old packet
296 // or return false right away, do not want packet anyway...
299 else if ( DestinationEndpoint.address() == address() )
300 { // we have no IP set yet
304 // We can receive all ICMP packets received by the host, so we need to
305 // filter out only the echo replies that match our identifier,
306 // expected sequence number, and destination host address (receive just
307 // the ICMP packets from the host we had ping).
311 if ( icmp_packet->match_echo_reply(
312 Identifier, SequenceNumber,
313 DestinationEndpoint.address() ) )
315 GlobalLogger.info() << LogPrefix << "Received reply" << endl;
317 ReplyReceived = true;
320 icmp_packet->print( bytes_transferred, TimeSent );
322 set_ping_status( PingStatus_SuccessReply );
324 IcmpPacketReceiveTimer.cancel(); //lint !e534
326 else if ( icmp_packet->match_destination_unreachable(
327 Identifier, SequenceNumber,
328 DestinationEndpoint.address() ) )
330 GlobalLogger.info() << LogPrefix
331 << "Received destination unreachable" << endl;
333 ReplyReceived = true;
336 icmp_packet->print( bytes_transferred, TimeSent );
338 set_ping_status( PingStatus_FailureDestinationUnreachable );
340 IcmpPacketReceiveTimer.cancel(); //lint !e534
342 else if ( icmp_packet->match_time_exceeded(
343 Identifier, SequenceNumber,
344 DestinationEndpoint.address() ) )
346 GlobalLogger.info() << LogPrefix
347 << "Received time exceeded" << endl;
349 ReplyReceived = true;
352 icmp_packet->print( bytes_transferred, TimeSent );
354 set_ping_status( PingStatus_FailureDestinationUnreachable );
356 IcmpPacketReceiveTimer.cancel(); //lint !e534
360 GlobalLogger.debug() << LogPrefix
361 << "Received packet that does not match or has wrong seq.nr"
365 catch ( std::exception &exc)
367 GlobalLogger.warning() << LogPrefix
368 << "Caught exception in packet interpretation: " << exc.what()
370 if ( IcmpPacketFactory::PacketDumpMode == DUMP_ALWAYS ||
371 IcmpPacketFactory::PacketDumpMode == DUMP_IF_ERROR )
372 IcmpPacketFactory::dump_packet(*icmp_packet);
373 does_match = true; // avoid the same procedure in all other pingers
377 GlobalLogger.warning() << LogPrefix
378 << "Caught unspecified exception in packet interpretation!"
380 if ( IcmpPacketFactory::PacketDumpMode == DUMP_ALWAYS ||
381 IcmpPacketFactory::PacketDumpMode == DUMP_IF_ERROR )
382 IcmpPacketFactory::dump_packet(*icmp_packet);
383 does_match = true; // avoid the same procedure in all other pingers
389 void IcmpPinger::set_ping_status( PingStatus ping_status )
391 PingerStatus = ping_status;
394 //------------------------------------------------------------------------
395 // IcmpPacketDistributor
396 //------------------------------------------------------------------------
398 static const std::size_t SOCKET_BUFFER_SIZE = 65536; // 64kB
400 typedef std::set<IcmpPingerItem>::iterator PingerListIterator;
403 bool IcmpPacketDistributor::InstanceIdentifierComparator::operator() (
404 const IcmpPacketDistributor::DistributorInstanceIdentifier &a,
405 const IcmpPacketDistributor::DistributorInstanceIdentifier &b )
408 if ( a.first == boost::asio::ip::icmp::v4() )
410 if ( b.first == boost::asio::ip::icmp::v4() )
411 return a.second < b.second; // v4 == v4
413 BOOST_ASSERT( b.first == boost::asio::ip::icmp::v6() );
414 return true; // a(v4) < b(b6)
418 BOOST_ASSERT( a.first == boost::asio::ip::icmp::v6() );
420 if ( b.first == boost::asio::ip::icmp::v4() )
421 return false; // a(v6) > b(v4)
423 BOOST_ASSERT( b.first == boost::asio::ip::icmp::v6() );
424 return a.second < b.second; // v6 == v6
428 //-----------------------------------------------------------------------------
429 // Definition of IcmpPacketDistributor
430 //-----------------------------------------------------------------------------
432 IcmpPacketDistributor::map_type IcmpPacketDistributor::Instances; // initialize
435 IcmpPacketDistributorItem IcmpPacketDistributor::get_distributor(
436 const icmp::socket::protocol_type &protocol,
437 const std::string &network_interface,
438 const IoServiceItem io_serv )
440 IcmpPacketDistributor::DistributorInstanceIdentifier identifier(
441 protocol, network_interface);
443 // check if there is an instance for this protocol and interface
444 if ( Instances.count(identifier) == 0 )
445 { // need to create an instance for this protocol and network interface
446 std::string protocol_str;
447 if (protocol == icmp::v4())
448 protocol_str = "ICMPv4";
449 else if (protocol == icmp::v6())
450 protocol_str = "ICMPv6";
452 protocol_str = "unknown protocol!";
454 GlobalLogger.info() << "Creating IcmpPacketDistributor for interface "
455 << network_interface << " and protocol "
456 << protocol_str << std::endl;
457 IcmpPacketDistributorItem new_instance( new IcmpPacketDistributor(
458 protocol, network_interface, io_serv ) );
459 Instances[identifier] = new_instance;
462 BOOST_ASSERT( Instances.count(identifier) == 1 );
464 // return the one instance for this protocol and interface
465 return Instances[identifier];
469 IcmpPacketDistributorItem IcmpPacketDistributor::get_distributor(
470 const icmp::socket::protocol_type &protocol,
471 const std::string &network_interface )
473 IcmpPacketDistributor::DistributorInstanceIdentifier identifier(
474 protocol, network_interface);
476 BOOST_ASSERT( Instances.count(identifier) == 1 );
478 // return the one instance for this protocol and interface
479 return Instances[identifier];
483 IcmpPacketDistributor::IcmpPacketDistributor(
484 const icmp::socket::protocol_type &protocol,
485 const std::string &network_interface,
486 const IoServiceItem io_serv ):
487 Protocol( protocol ),
488 Socket( new icmp::socket(*io_serv, protocol) ),
492 // set TTL for testing
493 //const boost::asio::ip::unicast::hops option( 3 );
494 //Socket->set_option(option);
496 NetworkInterface<icmp::socket, boost::asio::ip::icmp>
497 NetInterface( network_interface, *Socket );
499 if ( !NetInterface.bind() )
502 << "Trouble creating IcmpPacketDistributor for interface "
503 << network_interface// << " and protocol " << protocol
504 << ": could not bind the socket with the local interface. "
505 << ::strerror( errno ) << std::endl;
508 register_receive_handler();
512 void IcmpPacketDistributor::register_receive_handler()
514 // wait for reply, prepare buffer to receive up to SOCKET_BUFFER_SIZE bytes
515 Socket->async_receive(
516 ReplyBuffer.prepare( SOCKET_BUFFER_SIZE ),
517 boost::bind( &IcmpPacketDistributor::handle_receive, this,
518 boost::asio::placeholders::error,
519 boost::asio::placeholders::bytes_transferred )
523 void IcmpPacketDistributor::handle_receive(
524 const boost::system::error_code &error,
525 const size_t &bytes_transferred )
529 GlobalLogger.warning()
530 << ": Received error " << error
531 << " in ICMP packet distributor; end handler and schedule another.";
532 register_receive_handler();
536 // The actual number of bytes received is committed to the buffer so that we
537 // can extract it using a std::istream object.
538 ReplyBuffer.commit( bytes_transferred );
540 GlobalLogger.info() << "received packet in distributor" << std::endl;
542 std::istream is( &ReplyBuffer );
545 GlobalLogger.error() << "Can't handle ReplyBuffer" << std::endl;
549 // Decode the reply packet.
550 IcmpPacketItem icmp_packet = IcmpPacketFactory::create_icmp_packet(
554 GlobalLogger.warning() << "Ignoring broken ICMP packet"
559 GlobalLogger.debug() << "Succesfully parsed ICMP packet"
562 // check which pinger wants this packet
563 bool packet_matches = false;
564 BOOST_FOREACH( const IcmpPingerItem &pinger, PingerList )
566 packet_matches = pinger->handle_receive_icmp_packet(
567 icmp_packet, bytes_transferred);
572 GlobalLogger.info() << "Packet did not match any pinger"
576 // re-register receive handler
577 register_receive_handler();
580 bool IcmpPacketDistributor::register_pinger( const IcmpPingerItem &new_pinger )
582 std::pair<PingerListIterator, bool> result = PingerList.insert(new_pinger);
583 bool was_new = result.second;
585 GlobalLogger.info() << "Register new pinger with IcmpPacketDistributor"
588 GlobalLogger.warning()
589 << "Pinger to register was already known in IcmpPacketDistributor"
595 bool IcmpPacketDistributor::unregister_pinger( const IcmpPingerItem &old_pinger )
597 int n_erased = PingerList.erase(old_pinger);
598 bool was_erased = n_erased > 0;
600 GlobalLogger.info() << "Removed pinger from IcmpPacketDistributor"
603 GlobalLogger.warning()
604 << "Could not find pinger to remove from IcmpPacketDistributor"
610 * @brief for all instances: close sockets, unregister all pingers
612 void IcmpPacketDistributor::clean_up_all()
614 BOOST_FOREACH( IcmpPacketDistributor::map_type::value_type &instance,
617 instance.second->clean_up();
623 void IcmpPacketDistributor::clean_up()
625 if (PingerList.size() == 0)
626 GlobalLogger.info() << "All IcmpPingers have de-registered"
629 GlobalLogger.warning() << "There were still " << PingerList.size()
630 << " pingers registered in IcmpPacketDistributor!" << std::endl;
633 boost::system::error_code error;
634 //Socket->shutdown(icmp::socket::shutdown_both, error); //both=send&receive
636 // GlobalLogger.warning() << "Received error " << error
637 // << " when shutting down ICMP socket";
638 // always gave an error system:9 (probably EBADF: Bad file descriptor)
640 Socket->close(error);
642 GlobalLogger.warning() << "Received error " << error
643 << " when closing ICMP socket";
646 IcmpPacketDistributor::~IcmpPacketDistributor()
648 GlobalLogger.info() << "Destroying IcmpPacketDistributor" << std::endl;
651 SocketItem IcmpPacketDistributor::get_socket() const