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