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>
19 #include <boost/system/system_error.hpp>
21 #include <logfunc.hpp>
23 #include "boost_assert_handler.h"
24 #include "icmp/icmppacketfactory.h"
25 #include "host/networkinterface.hpp"
28 using boost::asio::const_buffers_1;
29 using boost::asio::io_service;
30 using boost::asio::ip::address;
31 using boost::asio::ip::icmp;
32 using boost::function;
33 using boost::posix_time::microsec_clock;
34 using boost::posix_time::seconds;
35 using boost::shared_ptr;
36 using I2n::Logger::GlobalLogger;
38 using boost::asio::ip::icmp;
40 //-----------------------------------------------------------------------------
42 //-----------------------------------------------------------------------------
45 * @brief factory function for IcmpPingers, ensures that set_myself is set
47 * @returns a shared pointer to a Pinger
49 PingerItem IcmpPinger::create(
50 const IoServiceItem io_serv,
51 const icmp::socket::protocol_type &protocol,
52 const string &source_network_interface,
53 const int echo_reply_timeout_in_sec )
56 IcmpPacketDistributorItem distributor = IcmpPacketDistributor::get_distributor(
57 protocol, source_network_interface, io_serv);
60 IcmpPinger *ptr = new IcmpPinger(io_serv, protocol, echo_reply_timeout_in_sec, distributor);
61 IcmpPingerItem shared_ptr_(ptr);
63 // keep weak pointer to self
64 //shared_ptr_->set_myself( weak_ptr ); //Error: Pinger::set_myself is protected
65 ptr->set_myself( shared_ptr_ );
67 // register in distributor
68 distributor->register_pinger(shared_ptr_);
70 // done, return shared ptr
75 * @brief Parameterized constructor.
77 * @param io_serv The one @c io_service object that controls async processing
78 * @param protocol The network layer protocol to use.
79 * @param source_network_interface The network interface name from where to
81 * @param echo_reply_timeout_in_sec The amount of time to wait for a reply.
83 IcmpPinger::IcmpPinger(
84 const IoServiceItem io_serv,
85 const icmp::socket::protocol_type &protocol,
86 const int echo_reply_timeout_in_sec,
87 const IcmpPacketDistributorItem distributor
89 PacketDistributor( distributor ),
90 DestinationEndpoint(),
92 IcmpPacketReceiveTimer( *io_serv ),
95 TimeSent( microsec_clock::universal_time() ),
96 ReplyReceived( false ),
97 EchoReplyTimeoutInSec( echo_reply_timeout_in_sec ),
98 PingerStatus( PingStatus_NotSent ),
100 LogPrefix("IcmpPinger")
102 // Create "unique" identifier
103 boost::uuids::random_generator random_gen;
104 boost::uuids::uuid random_tag = random_gen();
106 BOOST_ASSERT( sizeof(Identifier) <= random_tag.size() );
107 memcpy( &Identifier, random_tag.data, sizeof(Identifier) );
109 LogPrefix = "IPing(no IP yet): ";
115 IcmpPinger::~IcmpPinger()
120 * @brief Ping a destination address from an available local source.
122 * @param destination_ip The address of the host to ping.
123 * @param destination_port The port at the destination host to ping.
124 * @param done_handler Done handler will be called on successful ping or timeout.
128 void IcmpPinger::ping(
129 const address &destination_ip,
130 const uint16_t /*destination_port*/, // the ICMP protocol does not use ports
131 function<void(PingStatus,long)> ping_done_callback
134 PingDoneCallback = ping_done_callback;
137 set_ping_status( PingStatus_NotSent );
139 set_destination_endpoint( destination_ip );
144 void IcmpPinger::stop_pinging()
146 GlobalLogger.debug() << LogPrefix << "stop_pinging" << endl;
148 GlobalLogger.debug() << LogPrefix << "cancel timer" << endl;
149 IcmpPacketReceiveTimer.cancel();
151 GlobalLogger.debug() << LogPrefix << "unregister" << endl;
153 IcmpPingerItem icmp_item = boost::static_pointer_cast<IcmpPinger>( get_myself().lock() );
156 PacketDistributor->unregister_pinger( icmp_item );
159 GlobalLogger.warning() << LogPrefix
160 << "weak pointer to pinger broken is empty. Huh?" << endl;
165 void IcmpPinger::set_destination_endpoint( const address &destination_ip )
168 DestinationEndpoint = icmp::endpoint( destination_ip, port );
171 std::stringstream temp;
172 temp << "IPing(" << DestinationEndpoint.address().to_string() << "): ";
173 LogPrefix = temp.str();
176 bool IcmpPinger::start_send()
180 IcmpPacketItem icmp_packet_echo_request = IcmpPacketFactory::create_icmp_packet_echo_request(
181 Protocol, Identifier, SequenceNumber );
183 BOOST_ASSERT( PingerStatus == PingStatus_NotSent );
184 return send_echo_request( icmp_packet_echo_request );
187 bool IcmpPinger::send_echo_request( const IcmpPacketItem icmp_packet )
189 boost::asio::streambuf request_buffer;
190 ostream os( &request_buffer );
191 if ( !icmp_packet->write( os ) )
193 GlobalLogger.error() << LogPrefix << "fail writing ping data." << endl;
196 TimeSent = microsec_clock::universal_time();
198 string dest_address_string = DestinationEndpoint.address().to_string();
199 BOOST_ASSERT( !dest_address_string.empty() );
202 size_t bytes_sent = 0;
205 GlobalLogger.info() << LogPrefix << "sending ping" << endl;
206 const_buffers_1 data = request_buffer.data();
208 // Block until send the data
209 bytes_sent = PacketDistributor->get_socket()->send_to( data, DestinationEndpoint );
210 if ( bytes_sent != buffer_size( data ) )
212 GlobalLogger.error() << LogPrefix << "fail sending ping data. Only"
213 << bytes_sent << " of " << buffer_size(data)
214 << " bytes were sent!" << endl;
217 ReplyReceived = false;
218 schedule_timeout_echo_reply();
220 catch ( const boost::system::system_error &boost_err )
222 boost::system::error_code err_code = boost_err.code();
223 GlobalLogger.error() << LogPrefix << "fail sending ping data: "
224 << boost_err.what() << " (code " << err_code.value()
225 << ", category " << err_code.category().name() << ")" << endl;
227 // do not wait for timeout but fail at once
228 set_ping_status(PingStatus_SendFailed);
229 ReplyReceived = true; // flag for handler to leave ping status as is
230 //handle_timeout( err_code );
231 handle_timeout( boost::system::error_code() );
233 catch ( const exception &ex )
235 GlobalLogger.error() << LogPrefix << "fail sending ping data: "
236 << ex.what() << endl;
238 // do not wait for timeout but fail at once
239 set_ping_status(PingStatus_SendFailed);
240 ReplyReceived = true; // flag for handler to leave ping status as is
241 handle_timeout( boost::system::error_code() );
245 GlobalLogger.error() << LogPrefix << "fail sending ping data: "
246 << "Unknown exception" << endl;
248 // do not wait for timeout but fail at once
249 set_ping_status(PingStatus_SendFailed);
250 ReplyReceived = true; // flag for handler to leave ping status as is
251 handle_timeout( boost::system::error_code() );
254 return (bytes_sent > 0);
257 void IcmpPinger::schedule_timeout_echo_reply()
259 // Wait up to N seconds for a reply.
260 (void) IcmpPacketReceiveTimer.expires_at(
261 TimeSent + seconds( EchoReplyTimeoutInSec )
263 IcmpPacketReceiveTimer.async_wait(
264 boost::bind( &IcmpPinger::handle_timeout, this, boost::asio::placeholders::error )
269 * @brief Gets called when the ping is finished: Either on timeout or on ping reply
271 * @return void (but calls PingDoneCallback)
273 void IcmpPinger::handle_timeout(const boost::system::error_code& error)
277 if ( error == boost::asio::error::operation_aborted )
281 GlobalLogger.notice() << LogPrefix
282 << "Timer waiting for ICMP echo reply was cancelled!"
284 set_ping_status( PingStatus_FailureAsyncCancel );
286 // otherwise probably called by IcmpPacketReceiveTimer.cancel in
287 // handle_receive_icmp_packet!
291 GlobalLogger.notice() << LogPrefix << "Error " << error
292 << " waiting for ICMP echo reply!" << endl;
293 set_ping_status( PingStatus_FailureAsyncError );
295 // could check here for more details if error is forwarded from
298 // Still continue with rest of function, so PingStatus is updated and Callback executed
299 // when timer was cancelled
301 else if ( !ReplyReceived )
302 { // Check ReplyReceived since the timer handler is also called by Timer.cancel();
303 GlobalLogger.info() << LogPrefix << "Request timed out" << endl;
305 set_ping_status( PingStatus_FailureTimeout );
307 // otherwise assume that ping status was set already
309 // Call ping-done handler
310 PingDoneCallback( PingerStatus, static_cast<long>(
311 (microsec_clock::universal_time()
312 - TimeSent).total_microseconds()) );
317 * @brief Receive ICMP packets
318 * @param bytes_transferred Number of bytes transferred.
319 * @return true if packet matches a request from this pinger, false otherwise
321 bool IcmpPinger::handle_receive_icmp_packet(const IcmpPacketItem icmp_packet,
322 const size_t bytes_transferred )
324 bool does_match = false;
328 // continue, might be an old packet
329 // or return false right away, do not want packet anyway...
332 else if ( DestinationEndpoint.address() == address() )
333 { // we have no IP set yet
337 // We can receive all ICMP packets received by the host, so we need to
338 // filter out only the echo replies that match our identifier,
339 // expected sequence number, and destination host address (receive just
340 // the ICMP packets from the host we had ping).
344 if ( icmp_packet->match_echo_reply(
345 Identifier, SequenceNumber,
346 DestinationEndpoint.address() ) )
348 GlobalLogger.info() << LogPrefix << "Received reply" << endl;
350 ReplyReceived = true;
353 icmp_packet->print( bytes_transferred, TimeSent );
355 set_ping_status( PingStatus_SuccessReply );
357 IcmpPacketReceiveTimer.cancel(); //lint !e534
359 else if ( icmp_packet->match_destination_unreachable(
360 Identifier, SequenceNumber,
361 DestinationEndpoint.address() ) )
363 GlobalLogger.info() << LogPrefix
364 << "Received destination unreachable" << endl;
366 ReplyReceived = true;
369 icmp_packet->print( bytes_transferred, TimeSent );
371 set_ping_status( PingStatus_FailureDestinationUnreachable );
373 IcmpPacketReceiveTimer.cancel(); //lint !e534
375 else if ( icmp_packet->match_time_exceeded(
376 Identifier, SequenceNumber,
377 DestinationEndpoint.address() ) )
379 GlobalLogger.info() << LogPrefix
380 << "Received time exceeded" << endl;
382 ReplyReceived = true;
385 icmp_packet->print( bytes_transferred, TimeSent );
387 set_ping_status( PingStatus_FailureDestinationUnreachable );
389 IcmpPacketReceiveTimer.cancel(); //lint !e534
393 GlobalLogger.debug() << LogPrefix
394 << "Received packet that does not match or has wrong seq.nr"
398 catch ( std::exception &exc)
400 GlobalLogger.warning() << LogPrefix
401 << "Caught exception in packet interpretation: " << exc.what()
403 if ( IcmpPacketFactory::PacketDumpMode == DUMP_ALWAYS ||
404 IcmpPacketFactory::PacketDumpMode == DUMP_IF_ERROR )
405 IcmpPacketFactory::dump_packet(*icmp_packet);
406 does_match = true; // avoid the same procedure in all other pingers
410 GlobalLogger.warning() << LogPrefix
411 << "Caught unspecified exception in packet interpretation!"
413 if ( IcmpPacketFactory::PacketDumpMode == DUMP_ALWAYS ||
414 IcmpPacketFactory::PacketDumpMode == DUMP_IF_ERROR )
415 IcmpPacketFactory::dump_packet(*icmp_packet);
416 does_match = true; // avoid the same procedure in all other pingers
422 void IcmpPinger::set_ping_status( PingStatus ping_status )
424 PingerStatus = ping_status;
427 //------------------------------------------------------------------------
428 // IcmpPacketDistributor
429 //------------------------------------------------------------------------
431 static const std::size_t SOCKET_BUFFER_SIZE = 65536; // 64kB
433 typedef std::set<IcmpPingerItem>::iterator PingerListIterator;
436 bool IcmpPacketDistributor::InstanceIdentifierComparator::operator() (
437 const IcmpPacketDistributor::DistributorInstanceIdentifier &a,
438 const IcmpPacketDistributor::DistributorInstanceIdentifier &b )
441 if ( a.first == boost::asio::ip::icmp::v4() )
443 if ( b.first == boost::asio::ip::icmp::v4() )
444 return a.second < b.second; // v4 == v4
446 BOOST_ASSERT( b.first == boost::asio::ip::icmp::v6() );
447 return true; // a(v4) < b(b6)
451 BOOST_ASSERT( a.first == boost::asio::ip::icmp::v6() );
453 if ( b.first == boost::asio::ip::icmp::v4() )
454 return false; // a(v6) > b(v4)
456 BOOST_ASSERT( b.first == boost::asio::ip::icmp::v6() );
457 return a.second < b.second; // v6 == v6
461 //-----------------------------------------------------------------------------
462 // Definition of IcmpPacketDistributor
463 //-----------------------------------------------------------------------------
465 IcmpPacketDistributor::map_type IcmpPacketDistributor::Instances; // initialize
468 IcmpPacketDistributorItem IcmpPacketDistributor::get_distributor(
469 const icmp::socket::protocol_type &protocol,
470 const std::string &network_interface,
471 const IoServiceItem io_serv )
473 IcmpPacketDistributor::DistributorInstanceIdentifier identifier(
474 protocol, network_interface);
476 // check if there is an instance for this protocol and interface
477 if ( Instances.count(identifier) == 0 )
478 { // need to create an instance for this protocol and network interface
479 std::string protocol_str;
480 if (protocol == icmp::v4())
481 protocol_str = "ICMPv4";
482 else if (protocol == icmp::v6())
483 protocol_str = "ICMPv6";
485 protocol_str = "unknown protocol!";
487 GlobalLogger.info() << "Creating IcmpPacketDistributor for interface "
488 << network_interface << " and protocol "
489 << protocol_str << std::endl;
490 IcmpPacketDistributorItem new_instance( new IcmpPacketDistributor(
491 protocol, network_interface, io_serv ) );
492 Instances[identifier] = new_instance;
495 BOOST_ASSERT( Instances.count(identifier) == 1 );
497 // return the one instance for this protocol and interface
498 return Instances[identifier];
502 IcmpPacketDistributorItem IcmpPacketDistributor::get_distributor(
503 const icmp::socket::protocol_type &protocol,
504 const std::string &network_interface )
506 IcmpPacketDistributor::DistributorInstanceIdentifier identifier(
507 protocol, network_interface);
509 BOOST_ASSERT( Instances.count(identifier) == 1 );
511 // return the one instance for this protocol and interface
512 return Instances[identifier];
516 IcmpPacketDistributor::IcmpPacketDistributor(
517 const icmp::socket::protocol_type &protocol,
518 const std::string &network_interface,
519 const IoServiceItem io_serv ):
520 Protocol( protocol ),
521 Socket( new icmp::socket(*io_serv, protocol) ),
525 // set TTL for testing
526 //const boost::asio::ip::unicast::hops option( 3 );
527 //Socket->set_option(option);
529 NetworkInterface<icmp::socket, boost::asio::ip::icmp>
530 NetInterface( network_interface, *Socket );
532 if ( !NetInterface.bind() )
535 << "Trouble creating IcmpPacketDistributor for interface "
536 << network_interface// << " and protocol " << protocol
537 << ": could not bind the socket with the local interface. "
538 << ::strerror( errno ) << std::endl;
541 register_receive_handler();
545 void IcmpPacketDistributor::register_receive_handler()
547 // wait for reply, prepare buffer to receive up to SOCKET_BUFFER_SIZE bytes
548 Socket->async_receive(
549 ReplyBuffer.prepare( SOCKET_BUFFER_SIZE ),
550 boost::bind( &IcmpPacketDistributor::handle_receive, this,
551 boost::asio::placeholders::error,
552 boost::asio::placeholders::bytes_transferred )
556 void IcmpPacketDistributor::handle_receive(
557 const boost::system::error_code &error,
558 const size_t &bytes_transferred )
562 GlobalLogger.warning()
563 << ": Received error " << error
564 << " in ICMP packet distributor; end handler and schedule another.";
565 register_receive_handler();
569 // The actual number of bytes received is committed to the buffer so that we
570 // can extract it using a std::istream object.
571 ReplyBuffer.commit( bytes_transferred );
573 GlobalLogger.info() << "received packet in distributor" << std::endl;
575 std::istream is( &ReplyBuffer );
578 GlobalLogger.error() << "Can't handle ReplyBuffer" << std::endl;
582 // Decode the reply packet.
583 IcmpPacketItem icmp_packet = IcmpPacketFactory::create_icmp_packet(
587 GlobalLogger.warning() << "Ignoring broken ICMP packet"
592 GlobalLogger.debug() << "Succesfully parsed ICMP packet"
595 // check which pinger wants this packet
596 bool packet_matches = false;
597 BOOST_FOREACH( const IcmpPingerItem &pinger, PingerList )
599 packet_matches = pinger->handle_receive_icmp_packet(
600 icmp_packet, bytes_transferred);
605 GlobalLogger.info() << "Packet did not match any pinger"
609 // re-register receive handler
610 register_receive_handler();
613 bool IcmpPacketDistributor::register_pinger( const IcmpPingerItem &new_pinger )
615 std::pair<PingerListIterator, bool> result = PingerList.insert(new_pinger);
616 bool was_new = result.second;
618 GlobalLogger.info() << "Register new pinger with IcmpPacketDistributor"
621 GlobalLogger.warning()
622 << "Pinger to register was already known in IcmpPacketDistributor"
628 bool IcmpPacketDistributor::unregister_pinger( const IcmpPingerItem &old_pinger )
630 int n_erased = PingerList.erase(old_pinger);
631 bool was_erased = n_erased > 0;
633 GlobalLogger.info() << "Removed pinger from IcmpPacketDistributor"
636 GlobalLogger.warning()
637 << "Could not find pinger to remove from IcmpPacketDistributor"
643 * @brief for all instances: close sockets, unregister all pingers
645 void IcmpPacketDistributor::clean_up_all()
647 BOOST_FOREACH( IcmpPacketDistributor::map_type::value_type &instance,
650 instance.second->clean_up();
656 void IcmpPacketDistributor::clean_up()
658 if (PingerList.size() == 0)
659 GlobalLogger.info() << "All IcmpPingers have de-registered"
662 GlobalLogger.warning() << "There were still " << PingerList.size()
663 << " pingers registered in IcmpPacketDistributor!" << std::endl;
666 boost::system::error_code error;
667 //Socket->shutdown(icmp::socket::shutdown_both, error); //both=send&receive
669 // GlobalLogger.warning() << "Received error " << error
670 // << " when shutting down ICMP socket";
671 // always gave an error system:9 (probably EBADF: Bad file descriptor)
673 Socket->close(error);
675 GlobalLogger.warning() << "Received error " << error
676 << " when closing ICMP socket";
679 IcmpPacketDistributor::~IcmpPacketDistributor()
681 GlobalLogger.info() << "Destroying IcmpPacketDistributor" << std::endl;
684 SocketItem IcmpPacketDistributor::get_socket() const