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 icmp::v4(), 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(bool)> 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
243 void IcmpPinger::handle_timeout(const boost::system::error_code& error)
247 if ( error == boost::asio::error::operation_aborted )
250 GlobalLogger.notice() << LogPrefix
251 << "Timer waiting for ICMP echo reply was cancelled!"
253 // otherwise probably called by IcmpPacketReceiveTimer.cancel in
254 // handle_receive_icmp_packet!
257 GlobalLogger.notice() << LogPrefix << "Error " << error
258 << " waiting for ICMP echo reply!" << endl;
260 // Still continue with rest of function, so PingStatus is updated and Callback executed
261 // when timer was cancelled
264 // Check ReplyReceived as the timer handler
265 // is also called by Timer.cancel();
266 if ( !ReplyReceived )
268 GlobalLogger.info() << LogPrefix << "Request timed out" << endl;
270 set_ping_status( PingStatus_FailureTimeout );
273 // Call ping-done handler
274 bool ping_success = (PingerStatus == PingStatus_SuccessReply);
275 PingDoneCallback( ping_success );
280 * @brief Receive ICMP packets
281 * @param bytes_transferred Number of bytes transferred.
282 * @return true if packet matches a request from this pinger, false otherwise
284 bool IcmpPinger::handle_receive_icmp_packet(const IcmpPacketItem icmp_packet,
285 const size_t bytes_transferred )
287 bool does_match = false;
291 // continue, might be an old packet
292 // or return false right away, do not want packet anyway...
295 else if ( DestinationEndpoint.address() == address() )
296 { // we have no IP set yet
300 // We can receive all ICMP packets received by the host, so we need to
301 // filter out only the echo replies that match our identifier,
302 // expected sequence number, and destination host address (receive just
303 // the ICMP packets from the host we had ping).
307 if ( icmp_packet->match_echo_reply(
308 Identifier, SequenceNumber,
309 DestinationEndpoint.address() ) )
311 GlobalLogger.info() << LogPrefix << "Received reply" << endl;
313 ReplyReceived = true;
316 icmp_packet->print( bytes_transferred, TimeSent );
318 set_ping_status( PingStatus_SuccessReply );
320 IcmpPacketReceiveTimer.cancel(); //lint !e534
322 else if ( icmp_packet->match_destination_unreachable(
323 Identifier, SequenceNumber,
324 DestinationEndpoint.address() ) )
326 GlobalLogger.info() << LogPrefix
327 << "Received destination unreachable" << endl;
329 ReplyReceived = true;
332 icmp_packet->print( bytes_transferred, TimeSent );
334 set_ping_status( PingStatus_FailureDestinationUnreachable );
336 IcmpPacketReceiveTimer.cancel(); //lint !e534
338 else if ( icmp_packet->match_time_exceeded(
339 Identifier, SequenceNumber,
340 DestinationEndpoint.address() ) )
342 GlobalLogger.info() << LogPrefix
343 << "Received time exceeded" << endl;
345 ReplyReceived = true;
348 icmp_packet->print( bytes_transferred, TimeSent );
350 set_ping_status( PingStatus_FailureDestinationUnreachable );
352 IcmpPacketReceiveTimer.cancel(); //lint !e534
356 GlobalLogger.debug() << LogPrefix
357 << "Received packet that does not match or has wrong seq.nr"
361 catch ( std::exception &exc)
363 GlobalLogger.warning() << LogPrefix
364 << "Caught exception in packet interpretation: " << exc.what()
366 if ( IcmpPacketFactory::PacketDumpMode == DUMP_ALWAYS ||
367 IcmpPacketFactory::PacketDumpMode == DUMP_IF_ERROR )
368 IcmpPacketFactory::dump_packet(*icmp_packet);
369 does_match = true; // avoid the same procedure in all other pingers
373 GlobalLogger.warning() << LogPrefix
374 << "Caught unspecified exception in packet interpretation!"
376 if ( IcmpPacketFactory::PacketDumpMode == DUMP_ALWAYS ||
377 IcmpPacketFactory::PacketDumpMode == DUMP_IF_ERROR )
378 IcmpPacketFactory::dump_packet(*icmp_packet);
379 does_match = true; // avoid the same procedure in all other pingers
385 void IcmpPinger::set_ping_status( PingStatus ping_status )
387 PingerStatus = ping_status;
390 //------------------------------------------------------------------------
391 // IcmpPacketDistributor
392 //------------------------------------------------------------------------
394 static const std::size_t SOCKET_BUFFER_SIZE = 65536; // 64kB
396 typedef std::set<IcmpPingerItem>::iterator PingerListIterator;
399 bool IcmpPacketDistributor::InstanceIdentifierComparator::operator() (
400 const IcmpPacketDistributor::DistributorInstanceIdentifier &a,
401 const IcmpPacketDistributor::DistributorInstanceIdentifier &b )
404 if ( a.first == boost::asio::ip::icmp::v4() )
406 if ( b.first == boost::asio::ip::icmp::v4() )
407 return a.second < b.second; // v4 == v4
409 BOOST_ASSERT( b.first == boost::asio::ip::icmp::v6() );
410 return true; // a(v4) < b(b6)
414 BOOST_ASSERT( a.first == boost::asio::ip::icmp::v6() );
416 if ( b.first == boost::asio::ip::icmp::v4() )
417 return false; // a(v6) > b(v4)
419 BOOST_ASSERT( b.first == boost::asio::ip::icmp::v6() );
420 return a.second < b.second; // v6 == v6
424 //-----------------------------------------------------------------------------
425 // Definition of IcmpPacketDistributor
426 //-----------------------------------------------------------------------------
428 IcmpPacketDistributor::map_type IcmpPacketDistributor::Instances; // initialize
431 IcmpPacketDistributorItem IcmpPacketDistributor::get_distributor(
432 const icmp::socket::protocol_type &protocol,
433 const std::string &network_interface,
434 const IoServiceItem io_serv )
436 IcmpPacketDistributor::DistributorInstanceIdentifier identifier(
437 protocol, network_interface);
439 // check if there is an instance for this protocol and interface
440 if ( Instances.count(identifier) == 0 )
441 { // need to create an instance for this protocol and network interface
442 GlobalLogger.info() << "Creating IcmpPacketDistributor for interface "
443 << network_interface << std::endl;
444 IcmpPacketDistributorItem new_instance( new IcmpPacketDistributor(
445 protocol, network_interface, io_serv ) );
446 Instances[identifier] = new_instance;
449 BOOST_ASSERT( Instances.count(identifier) == 1 );
451 // return the one instance for this protocol and interface
452 return Instances[identifier];
456 IcmpPacketDistributorItem IcmpPacketDistributor::get_distributor(
457 const icmp::socket::protocol_type &protocol,
458 const std::string &network_interface )
460 IcmpPacketDistributor::DistributorInstanceIdentifier identifier(
461 protocol, network_interface);
463 BOOST_ASSERT( Instances.count(identifier) == 1 );
465 // return the one instance for this protocol and interface
466 return Instances[identifier];
470 IcmpPacketDistributor::IcmpPacketDistributor(
471 const icmp::socket::protocol_type &protocol,
472 const std::string &network_interface,
473 const IoServiceItem io_serv ):
474 Protocol( protocol ),
475 Socket( new icmp::socket(*io_serv, protocol) ),
479 // set TTL for testing
480 //const boost::asio::ip::unicast::hops option( 3 );
481 //Socket->set_option(option);
483 NetworkInterface<icmp::socket, boost::asio::ip::icmp>
484 NetInterface( network_interface, *Socket );
486 if ( !NetInterface.bind() )
489 << "Trouble creating IcmpPacketDistributor for interface "
490 << network_interface// << " and protocol " << protocol
491 << ": could not bind the socket with the local interface. "
492 << ::strerror( errno ) << std::endl;
495 register_receive_handler();
499 void IcmpPacketDistributor::register_receive_handler()
501 // wait for reply, prepare buffer to receive up to SOCKET_BUFFER_SIZE bytes
502 Socket->async_receive(
503 ReplyBuffer.prepare( SOCKET_BUFFER_SIZE ),
504 boost::bind( &IcmpPacketDistributor::handle_receive, this,
505 boost::asio::placeholders::error,
506 boost::asio::placeholders::bytes_transferred )
510 void IcmpPacketDistributor::handle_receive(
511 const boost::system::error_code &error,
512 const size_t &bytes_transferred )
516 GlobalLogger.warning()
517 << ": Received error " << error
518 << " in ICMP packet distributor; end handler and schedule another.";
519 register_receive_handler();
523 // The actual number of bytes received is committed to the buffer so that we
524 // can extract it using a std::istream object.
525 ReplyBuffer.commit( bytes_transferred );
527 GlobalLogger.info() << "received packet in distributor" << std::endl;
529 std::istream is( &ReplyBuffer );
532 GlobalLogger.error() << "Can't handle ReplyBuffer" << std::endl;
536 // Decode the reply packet.
537 IcmpPacketItem icmp_packet = IcmpPacketFactory::create_icmp_packet(
541 GlobalLogger.warning() << "Ignoring broken ICMP packet"
546 GlobalLogger.debug() << "Succesfully parsed ICMP packet"
549 // check which pinger wants this packet
550 bool packet_matches = false;
551 BOOST_FOREACH( const IcmpPingerItem &pinger, PingerList )
553 packet_matches = pinger->handle_receive_icmp_packet(
554 icmp_packet, bytes_transferred);
559 GlobalLogger.info() << "Packet did not match any pinger"
563 // re-register receive handler
564 register_receive_handler();
567 bool IcmpPacketDistributor::register_pinger( const IcmpPingerItem &new_pinger )
569 std::pair<PingerListIterator, bool> result = PingerList.insert(new_pinger);
570 bool was_new = result.second;
572 GlobalLogger.info() << "Register new pinger with IcmpPacketDistributor"
575 GlobalLogger.warning()
576 << "Pinger to register was already known in IcmpPacketDistributor"
582 bool IcmpPacketDistributor::unregister_pinger( const IcmpPingerItem &old_pinger )
584 int n_erased = PingerList.erase(old_pinger);
585 bool was_erased = n_erased > 0;
587 GlobalLogger.info() << "Removed pinger from IcmpPacketDistributor"
590 GlobalLogger.warning()
591 << "Could not find pinger to remove from IcmpPacketDistributor"
597 * @brief for all instances: close sockets, unregister all pingers
599 void IcmpPacketDistributor::clean_up_all()
601 BOOST_FOREACH( IcmpPacketDistributor::map_type::value_type &instance,
604 instance.second->clean_up();
610 void IcmpPacketDistributor::clean_up()
612 if (PingerList.size() == 0)
613 GlobalLogger.info() << "All IcmpPingers have de-registered"
616 GlobalLogger.warning() << "There were still " << PingerList.size()
617 << " pingers registered in IcmpPacketDistributor!" << std::endl;
620 boost::system::error_code error;
621 //Socket->shutdown(icmp::socket::shutdown_both, error); //both=send&receive
623 // GlobalLogger.warning() << "Received error " << error
624 // << " when shutting down ICMP socket";
625 // always gave an error system:9 (probably EBADF: Bad file descriptor)
627 Socket->close(error);
629 GlobalLogger.warning() << "Received error " << error
630 << " when closing ICMP socket";
633 IcmpPacketDistributor::~IcmpPacketDistributor()
635 GlobalLogger.info() << "Destroying IcmpPacketDistributor" << std::endl;
638 SocketItem IcmpPacketDistributor::get_socket() const