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