12832d6b017ecdca88f45c0d9e848d50600f84d0
[pingcheck] / src / icmp / icmppinger.cpp
1 // Boost pinger (c) 2011 by Guilherme Maciel Ferreira / Intra2net AG
2 // Based upon work copyright (c) 2003-2010 Christopher M. Kohlhoff (ping.cpp)
3 //
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"
8
9 #include <errno.h>
10
11 #include <ostream>
12
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
20 #include <logfunc.hpp>
21
22 #include "boost_assert_handler.h"
23 #include "icmp/icmppacketfactory.h"
24 #include "host/networkinterface.hpp"
25
26 using namespace std;
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;
36
37 using boost::asio::ip::icmp;
38
39 //-----------------------------------------------------------------------------
40 // IcmpPinger
41 //-----------------------------------------------------------------------------
42
43 /**
44  * @brief factory function for IcmpPingers, ensures that set_myself is set
45  *
46  * @returns a shared pointer to a Pinger
47  */
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 )
53 {
54     // get distributor
55     IcmpPacketDistributorItem distributor = IcmpPacketDistributor::get_distributor(
56             protocol, source_network_interface, io_serv);
57
58     // create pinger
59     IcmpPinger *ptr = new IcmpPinger(io_serv, protocol, echo_reply_timeout_in_sec, distributor);
60     IcmpPingerItem shared_ptr_(ptr);
61
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_ );
65
66     // register in distributor
67     distributor->register_pinger(shared_ptr_);
68
69     // done, return shared ptr
70     return shared_ptr_;
71 }
72
73 /**
74  * @brief Parameterized constructor.
75  *
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
79  * send the packets.
80  * @param echo_reply_timeout_in_sec The amount of time to wait for a reply.
81  */
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
87 ) :
88     PacketDistributor( distributor ),
89     DestinationEndpoint(),
90     Protocol( protocol ),
91     IcmpPacketReceiveTimer( *io_serv ),
92     Identifier( 0 ),
93     SequenceNumber( 0 ),
94     TimeSent( microsec_clock::universal_time() ),
95     ReplyReceived( false ),
96     EchoReplyTimeoutInSec( echo_reply_timeout_in_sec ),
97     PingerStatus( PingStatus_NotSent ),
98     PingDoneCallback(),
99     LogPrefix("IcmpPinger")
100 {
101     // Create "unique" identifier
102     boost::uuids::random_generator random_gen;
103     boost::uuids::uuid random_tag = random_gen();
104
105     BOOST_ASSERT( sizeof(Identifier) <= random_tag.size() );
106     memcpy( &Identifier, random_tag.data, sizeof(Identifier) );
107
108     LogPrefix = "IPing(no IP yet): ";
109 }
110
111 /**
112  * @brief Destructor.
113  */
114 IcmpPinger::~IcmpPinger()
115 {
116 }
117
118 /**
119  * @brief Ping a destination address from an available local source.
120  *
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.
124  *
125  * @return void.
126  */
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)> ping_done_callback
131 )
132 {
133     PingDoneCallback = ping_done_callback;
134
135     // Prepare ping
136     set_ping_status( PingStatus_NotSent );
137
138     set_destination_endpoint( destination_ip );
139
140     start_send();
141 }
142
143 void IcmpPinger::stop_pinging()
144 {
145     GlobalLogger.debug() << LogPrefix << "stop_pinging" << endl;
146
147     GlobalLogger.debug() << LogPrefix << "cancel timer" << endl;
148     IcmpPacketReceiveTimer.cancel();
149
150     GlobalLogger.debug() << LogPrefix << "unregister" << endl;
151
152     IcmpPingerItem icmp_item = boost::static_pointer_cast<IcmpPinger>( get_myself().lock() );
153     if ( icmp_item )
154     {
155         PacketDistributor->unregister_pinger( icmp_item );
156     } else
157     {
158         GlobalLogger.warning() << LogPrefix
159             << "weak pointer to pinger broken is empty. Huh?" << endl;
160     }
161 }
162
163
164 void IcmpPinger::set_destination_endpoint( const address &destination_ip )
165 {
166     uint16_t port = 0;
167     DestinationEndpoint = icmp::endpoint( destination_ip, port );
168
169     // update LogPrefix
170     std::stringstream temp;
171     temp << "IPing(" << DestinationEndpoint.address().to_string() << "): ";
172     LogPrefix = temp.str();
173 }
174
175 bool IcmpPinger::start_send()
176 {
177     ++SequenceNumber;
178
179     IcmpPacketItem icmp_packet_echo_request = IcmpPacketFactory::create_icmp_packet_echo_request(
180             Protocol, Identifier, SequenceNumber );
181
182     BOOST_ASSERT( PingerStatus == PingStatus_NotSent );
183     return send_echo_request( icmp_packet_echo_request );
184 }
185
186 bool IcmpPinger::send_echo_request( const IcmpPacketItem icmp_packet )
187 {
188     boost::asio::streambuf request_buffer;
189     ostream os( &request_buffer );
190     if ( !icmp_packet->write( os ) )
191     {
192         GlobalLogger.error() << LogPrefix << "fail writing ping data." << endl;
193     }
194
195     TimeSent = microsec_clock::universal_time();
196
197     string dest_address_string = DestinationEndpoint.address().to_string();
198     BOOST_ASSERT( !dest_address_string.empty() );
199
200     // Send the request
201     size_t bytes_sent = 0;
202     try
203     {
204         GlobalLogger.info() << LogPrefix << "sending ping" << endl;
205         const_buffers_1 data = request_buffer.data();
206
207         // Block until send the data
208         bytes_sent = PacketDistributor->get_socket()->send_to( data, DestinationEndpoint );
209         if ( bytes_sent != buffer_size( data ) )
210         {
211             GlobalLogger.error() << LogPrefix << "fail sending ping data."
212                                  << endl;
213         }
214     }
215     catch ( const exception &ex )
216     {
217         GlobalLogger.error() << LogPrefix << "fail sending ping data. "
218                              << ex.what() << endl;
219     }
220
221     ReplyReceived = false;
222     schedule_timeout_echo_reply();
223
224     return (bytes_sent > 0);
225 }
226
227 void IcmpPinger::schedule_timeout_echo_reply()
228 {
229     // Wait up to N seconds for a reply.
230     (void) IcmpPacketReceiveTimer.expires_at(
231             TimeSent + seconds( EchoReplyTimeoutInSec )
232     );
233     IcmpPacketReceiveTimer.async_wait(
234             boost::bind( &IcmpPinger::handle_timeout, this, boost::asio::placeholders::error )
235     );
236 }
237
238 /**
239  * @brief Gets called when the ping is finished: Either on timeout or on ping reply
240  *
241  * @return void (but calls PingDoneCallback)
242  **/
243 void IcmpPinger::handle_timeout(const boost::system::error_code& error)
244 {
245     if (error)
246     {
247         if ( error ==  boost::asio::error::operation_aborted )
248         {
249             if (! ReplyReceived)
250             {
251                 GlobalLogger.notice() << LogPrefix
252                     << "Timer waiting for ICMP echo reply was cancelled!"
253                     << endl;
254                 set_ping_status( PingStatus_FailureAsyncCancel );
255             }
256             // otherwise probably called by IcmpPacketReceiveTimer.cancel in
257             // handle_receive_icmp_packet!
258         }
259         else
260         {
261             GlobalLogger.notice() << LogPrefix << "Error " << error
262                 << " waiting for ICMP echo reply!" << endl;
263             set_ping_status( PingStatus_FailureAsyncError );
264         }
265
266         // Still continue with rest of function, so PingStatus is updated and Callback executed
267         //   when timer was cancelled
268     }
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;
272
273         set_ping_status( PingStatus_FailureTimeout );
274     }
275
276     // Call ping-done handler
277     PingDoneCallback( PingerStatus );
278 }
279
280
281 /**
282  * @brief Receive ICMP packets
283  * @param bytes_transferred Number of bytes transferred.
284  * @return true if packet matches a request from this pinger, false otherwise
285  **/
286 bool IcmpPinger::handle_receive_icmp_packet(const IcmpPacketItem icmp_packet,
287                                             const size_t bytes_transferred )
288 {
289     bool does_match = false;
290
291     if ( ReplyReceived )
292     {
293         // continue, might be an old packet
294         // or return false right away, do not want packet anyway...
295         return does_match;
296     }
297     else if ( DestinationEndpoint.address() == address() )
298     {   // we have no IP set yet
299         return does_match;
300     }
301
302     // We can receive all ICMP packets received by the host, so we need to
303     // filter out only the echo replies that match our identifier,
304     // expected sequence number, and destination host address (receive just
305     // the ICMP packets from the host we had ping).
306
307     try
308     {
309         if ( icmp_packet->match_echo_reply(
310                                 Identifier, SequenceNumber,
311                                 DestinationEndpoint.address() ) )
312         {
313             GlobalLogger.info() << LogPrefix << "Received reply" << endl;
314
315             ReplyReceived = true;
316             does_match = true;
317
318             icmp_packet->print( bytes_transferred, TimeSent );
319
320             set_ping_status( PingStatus_SuccessReply );
321
322             IcmpPacketReceiveTimer.cancel();                            //lint !e534
323         }
324         else if ( icmp_packet->match_destination_unreachable(
325                                      Identifier, SequenceNumber,
326                                      DestinationEndpoint.address() ) )
327         {
328             GlobalLogger.info() << LogPrefix
329                                 << "Received destination unreachable" << endl;
330
331             ReplyReceived = true;
332             does_match = true;
333
334             icmp_packet->print( bytes_transferred, TimeSent );
335
336             set_ping_status( PingStatus_FailureDestinationUnreachable );
337
338             IcmpPacketReceiveTimer.cancel();                            //lint !e534
339         }
340         else if ( icmp_packet->match_time_exceeded(
341                                      Identifier, SequenceNumber,
342                                      DestinationEndpoint.address() ) )
343         {
344             GlobalLogger.info() << LogPrefix
345                                 << "Received time exceeded" << endl;
346
347             ReplyReceived = true;
348             does_match = true;
349
350             icmp_packet->print( bytes_transferred, TimeSent );
351
352             set_ping_status( PingStatus_FailureDestinationUnreachable );
353
354             IcmpPacketReceiveTimer.cancel();                            //lint !e534
355         }
356         else
357         {
358             GlobalLogger.debug() << LogPrefix
359                << "Received packet that does not match or has wrong seq.nr"
360                << endl;
361         }
362     }
363     catch ( std::exception &exc)
364     {
365         GlobalLogger.warning() << LogPrefix
366             << "Caught exception in packet interpretation: " << exc.what()
367             << std::endl;
368         if ( IcmpPacketFactory::PacketDumpMode == DUMP_ALWAYS ||
369              IcmpPacketFactory::PacketDumpMode == DUMP_IF_ERROR )
370             IcmpPacketFactory::dump_packet(*icmp_packet);
371         does_match = true;   // avoid the same procedure in all other pingers
372     }
373     catch ( ... )
374     {
375         GlobalLogger.warning() << LogPrefix
376             << "Caught unspecified exception in packet interpretation!"
377             << std::endl;
378         if ( IcmpPacketFactory::PacketDumpMode == DUMP_ALWAYS ||
379              IcmpPacketFactory::PacketDumpMode == DUMP_IF_ERROR )
380             IcmpPacketFactory::dump_packet(*icmp_packet);
381         does_match = true;   // avoid the same procedure in all other pingers
382     }
383
384     return does_match;
385 }
386
387 void IcmpPinger::set_ping_status( PingStatus ping_status )
388 {
389     PingerStatus = ping_status;
390 }
391
392 //------------------------------------------------------------------------
393 // IcmpPacketDistributor
394 //------------------------------------------------------------------------
395
396 static const std::size_t SOCKET_BUFFER_SIZE = 65536;   // 64kB
397
398 typedef std::set<IcmpPingerItem>::iterator PingerListIterator;
399
400
401 bool IcmpPacketDistributor::InstanceIdentifierComparator::operator() (
402                 const IcmpPacketDistributor::DistributorInstanceIdentifier &a,
403                 const IcmpPacketDistributor::DistributorInstanceIdentifier &b )
404                                                                           const
405 {
406     if ( a.first == boost::asio::ip::icmp::v4() )
407     {
408         if ( b.first == boost::asio::ip::icmp::v4() )
409             return a.second < b.second;   // v4 == v4
410         else
411             BOOST_ASSERT( b.first == boost::asio::ip::icmp::v6() );
412             return true;    // a(v4) < b(b6)
413     }
414     else
415     {
416         BOOST_ASSERT( a.first == boost::asio::ip::icmp::v6() );
417
418         if ( b.first == boost::asio::ip::icmp::v4() )
419             return false;   // a(v6) > b(v4)
420         else
421             BOOST_ASSERT( b.first == boost::asio::ip::icmp::v6() );
422             return a.second < b.second;    // v6 == v6
423     }
424 }
425
426 //-----------------------------------------------------------------------------
427 // Definition of IcmpPacketDistributor
428 //-----------------------------------------------------------------------------
429
430 IcmpPacketDistributor::map_type IcmpPacketDistributor::Instances; // initialize
431
432
433 IcmpPacketDistributorItem IcmpPacketDistributor::get_distributor(
434         const icmp::socket::protocol_type &protocol,
435         const std::string &network_interface,
436         const IoServiceItem io_serv )
437 {
438     IcmpPacketDistributor::DistributorInstanceIdentifier identifier(
439                                                   protocol, network_interface);
440
441     // check if there is an instance for this protocol and interface
442     if ( Instances.count(identifier) == 0 )
443     {   // need to create an instance for this protocol and network interface
444         std::string protocol_str;
445         if (protocol == icmp::v4())
446             protocol_str = "ICMPv4";
447         else if (protocol == icmp::v6())
448             protocol_str = "ICMPv6";
449         else
450             protocol_str = "unknown protocol!";
451
452         GlobalLogger.info() << "Creating IcmpPacketDistributor for interface "
453                             << network_interface << " and protocol "
454                             << protocol_str << std::endl;
455         IcmpPacketDistributorItem new_instance( new IcmpPacketDistributor(
456                     protocol, network_interface, io_serv ) );
457         Instances[identifier] = new_instance;
458     }
459
460     BOOST_ASSERT( Instances.count(identifier) == 1 );
461
462     // return the one instance for this protocol and interface
463     return Instances[identifier];
464 }
465
466
467 IcmpPacketDistributorItem IcmpPacketDistributor::get_distributor(
468         const icmp::socket::protocol_type &protocol,
469         const std::string &network_interface )
470 {
471     IcmpPacketDistributor::DistributorInstanceIdentifier identifier(
472                                                   protocol, network_interface);
473
474     BOOST_ASSERT( Instances.count(identifier) == 1 );
475
476     // return the one instance for this protocol and interface
477     return Instances[identifier];
478 }
479
480
481 IcmpPacketDistributor::IcmpPacketDistributor(
482             const icmp::socket::protocol_type &protocol,
483             const std::string &network_interface,
484             const IoServiceItem io_serv ):
485     Protocol( protocol ),
486     Socket( new icmp::socket(*io_serv, protocol) ),
487     ReplyBuffer(),
488     PingerList()
489 {
490     // set TTL for testing
491     //const boost::asio::ip::unicast::hops option( 3 );
492     //Socket->set_option(option);
493
494     NetworkInterface<icmp::socket, boost::asio::ip::icmp>
495                   NetInterface( network_interface, *Socket );
496
497     if ( !NetInterface.bind() )
498     {
499         GlobalLogger.error()
500            << "Trouble creating IcmpPacketDistributor for interface "
501            << network_interface// << " and protocol " << protocol
502            << ": could not bind the socket with the local interface. "
503            << ::strerror( errno )  << std::endl;
504     }
505
506     register_receive_handler();
507 }
508
509
510 void IcmpPacketDistributor::register_receive_handler()
511 {
512     // wait for reply, prepare buffer to receive up to SOCKET_BUFFER_SIZE bytes
513     Socket->async_receive(
514             ReplyBuffer.prepare( SOCKET_BUFFER_SIZE ),
515             boost::bind( &IcmpPacketDistributor::handle_receive, this,
516                          boost::asio::placeholders::error,
517                          boost::asio::placeholders::bytes_transferred )
518     );
519 }
520
521 void IcmpPacketDistributor::handle_receive(
522                                         const boost::system::error_code &error,
523                                         const size_t &bytes_transferred )
524 {
525     if ( error )
526     {
527         GlobalLogger.warning()
528            << ": Received error " << error
529            << " in ICMP packet distributor; end handler and schedule another.";
530         register_receive_handler();
531         return;
532     }
533
534     // The actual number of bytes received is committed to the buffer so that we
535     // can extract it using a std::istream object.
536     ReplyBuffer.commit( bytes_transferred );
537
538     GlobalLogger.info() << "received packet in distributor" << std::endl;
539
540     std::istream is( &ReplyBuffer );
541     if ( !is )
542     {
543         GlobalLogger.error() << "Can't handle ReplyBuffer" << std::endl;
544         return;
545     }
546
547     // Decode the reply packet.
548     IcmpPacketItem icmp_packet = IcmpPacketFactory::create_icmp_packet(
549                                                              Protocol, is );
550     if ( !icmp_packet )
551     {
552         GlobalLogger.warning() << "Ignoring broken ICMP packet"
553                                << std::endl;
554     }
555     else
556     {
557         GlobalLogger.debug() << "Succesfully parsed ICMP packet"
558                              << std::endl;
559
560         // check which pinger wants this packet
561         bool packet_matches = false;
562         BOOST_FOREACH( const IcmpPingerItem &pinger, PingerList )
563         {
564             packet_matches = pinger->handle_receive_icmp_packet(
565                                             icmp_packet, bytes_transferred);
566             if (packet_matches)
567                 break;
568         }
569         if (!packet_matches)
570             GlobalLogger.info() << "Packet did not match any pinger"
571                                 << std::endl;
572     }
573
574     // re-register receive handler
575     register_receive_handler();
576 }
577
578 bool IcmpPacketDistributor::register_pinger( const IcmpPingerItem &new_pinger )
579 {
580     std::pair<PingerListIterator, bool> result = PingerList.insert(new_pinger);
581     bool was_new = result.second;
582     if (was_new)
583         GlobalLogger.info() << "Register new pinger with IcmpPacketDistributor"
584                             << std::endl;
585     else
586         GlobalLogger.warning()
587             << "Pinger to register was already known in IcmpPacketDistributor"
588             << std::endl;
589     return was_new;
590 }
591
592
593 bool IcmpPacketDistributor::unregister_pinger( const IcmpPingerItem &old_pinger )
594 {
595     int n_erased = PingerList.erase(old_pinger);
596     bool was_erased = n_erased > 0;
597     if (was_erased)
598         GlobalLogger.info() << "Removed pinger from IcmpPacketDistributor"
599                             << std::endl;
600     else
601         GlobalLogger.warning()
602             << "Could not find pinger to remove from IcmpPacketDistributor"
603             << std::endl;
604     return was_erased;
605 }
606
607 /**
608  * @brief for all instances: close sockets, unregister all pingers
609  */
610 void IcmpPacketDistributor::clean_up_all()
611 {
612     BOOST_FOREACH( IcmpPacketDistributor::map_type::value_type &instance,
613                                                                     Instances )
614     {
615         instance.second->clean_up();
616     }
617
618     Instances.clear();
619 }
620
621 void IcmpPacketDistributor::clean_up()
622 {
623     if (PingerList.size() == 0)
624         GlobalLogger.info() << "All IcmpPingers have de-registered"
625                             << std::endl;
626     else
627         GlobalLogger.warning() << "There were still " << PingerList.size()
628             << " pingers registered in IcmpPacketDistributor!" << std::endl;
629     PingerList.clear();
630
631     boost::system::error_code error;
632     //Socket->shutdown(icmp::socket::shutdown_both, error);  //both=send&receive
633     //if ( error )
634     //    GlobalLogger.warning() << "Received error " << error
635     //                           << " when shutting down ICMP socket";
636     // always gave an error system:9 (probably EBADF: Bad file descriptor)
637
638     Socket->close(error);
639     if ( error )
640         GlobalLogger.warning() << "Received error " << error
641                                << " when closing ICMP socket";
642 }
643
644 IcmpPacketDistributor::~IcmpPacketDistributor()
645 {
646     GlobalLogger.info() << "Destroying IcmpPacketDistributor" << std::endl;
647 }
648
649 SocketItem IcmpPacketDistributor::get_socket() const
650 {
651     return Socket;
652 }