diff --git a/.clang-format b/.clang-format index ca411edd..0ff68114 100644 --- a/.clang-format +++ b/.clang-format @@ -4,7 +4,7 @@ TabWidth: 4 AllowShortIfStatementsOnASingleLine: false BreakBeforeBraces: Attach AlignConsecutiveMacros: true -ColumnLimit: 140 +ColumnLimit: 100 IndentPPDirectives: AfterHash SortIncludes: Never AllowShortEnumsOnASingleLine: false diff --git a/lib/output.c b/lib/output.c index c408a2f5..b398c2ad 100644 --- a/lib/output.c +++ b/lib/output.c @@ -16,7 +16,8 @@ static mp_output_format output_format = MP_FORMAT_DEFAULT; static mp_output_detail_level level_of_detail = MP_DETAIL_ALL; // == Prototypes == -static char *fmt_subcheck_output(mp_output_format output_format, mp_subcheck check, unsigned int indentation); +static char *fmt_subcheck_output(mp_output_format output_format, mp_subcheck check, + unsigned int indentation); static inline cJSON *json_serialize_subcheck(mp_subcheck subcheck); // == Implementation == @@ -58,7 +59,9 @@ static inline char *fmt_subcheck_perfdata(mp_subcheck check) { * It sets useful defaults */ mp_check mp_check_init(void) { - mp_check check = {0}; + mp_check check = { + .evaluation_function = &mp_eval_check_default, + }; return check; } @@ -121,7 +124,8 @@ void mp_add_perfdata_to_subcheck(mp_subcheck check[static 1], const mp_perfdata */ int mp_add_subcheck_to_subcheck(mp_subcheck check[static 1], mp_subcheck subcheck) { if (subcheck.output == NULL) { - die(STATE_UNKNOWN, "%s - %s #%d: %s", __FILE__, __func__, __LINE__, "Sub check output is NULL"); + die(STATE_UNKNOWN, "%s - %s #%d: %s", __FILE__, __func__, __LINE__, + "Sub check output is NULL"); } mp_subcheck_list *tmp = NULL; @@ -194,18 +198,30 @@ char *get_subcheck_summary(mp_check check) { return result; } +mp_state_enum mp_compute_subcheck_state(const mp_subcheck subcheck) { + if (subcheck.evaluation_function == NULL) { + return mp_eval_subcheck_default(subcheck); + } + return subcheck.evaluation_function(subcheck); +} + /* - * Generate the result state of a mp_subcheck object based on it's own state and it's subchecks states + * Generate the result state of a mp_subcheck object based on its own state and its subchecks + * states */ -mp_state_enum mp_compute_subcheck_state(const mp_subcheck check) { - if (check.state_set_explicitly) { - return check.state; +mp_state_enum mp_eval_subcheck_default(mp_subcheck subcheck) { + if (subcheck.evaluation_function != NULL) { + return subcheck.evaluation_function(subcheck); } - mp_subcheck_list *scl = check.subchecks; + if (subcheck.state_set_explicitly) { + return subcheck.state; + } + + mp_subcheck_list *scl = subcheck.subchecks; if (scl == NULL) { - return check.default_state; + return subcheck.default_state; } mp_state_enum result = STATE_OK; @@ -218,10 +234,18 @@ mp_state_enum mp_compute_subcheck_state(const mp_subcheck check) { return result; } +mp_state_enum mp_compute_check_state(const mp_check check) { + // just a safety check + if (check.evaluation_function == NULL) { + return mp_eval_check_default(check); + } + return check.evaluation_function(check); +} + /* * Generate the result state of a mp_check object based on it's own state and it's subchecks states */ -mp_state_enum mp_compute_check_state(const mp_check check) { +mp_state_enum mp_eval_check_default(const mp_check check) { assert(check.subchecks != NULL); // a mp_check without subchecks is invalid, die here mp_subcheck_list *scl = check.subchecks; @@ -253,8 +277,10 @@ char *mp_fmt_output(mp_check check) { mp_subcheck_list *subchecks = check.subchecks; while (subchecks != NULL) { - if (level_of_detail == MP_DETAIL_ALL || mp_compute_subcheck_state(subchecks->subcheck) != STATE_OK) { - asprintf(&result, "%s\n%s", result, fmt_subcheck_output(MP_FORMAT_MULTI_LINE, subchecks->subcheck, 1)); + if (level_of_detail == MP_DETAIL_ALL || + mp_compute_subcheck_state(subchecks->subcheck) != STATE_OK) { + asprintf(&result, "%s\n%s", result, + fmt_subcheck_output(MP_FORMAT_MULTI_LINE, subchecks->subcheck, 1)); } subchecks = subchecks->next; } @@ -266,7 +292,8 @@ char *mp_fmt_output(mp_check check) { if (pd_string == NULL) { asprintf(&pd_string, "%s", fmt_subcheck_perfdata(subchecks->subcheck)); } else { - asprintf(&pd_string, "%s %s", pd_string, fmt_subcheck_perfdata(subchecks->subcheck)); + asprintf(&pd_string, "%s %s", pd_string, + fmt_subcheck_perfdata(subchecks->subcheck)); } subchecks = subchecks->next; @@ -335,19 +362,21 @@ static char *generate_indentation_string(unsigned int indentation) { /* * Helper function to generate the output string of mp_subcheck */ -static inline char *fmt_subcheck_output(mp_output_format output_format, mp_subcheck check, unsigned int indentation) { +static inline char *fmt_subcheck_output(mp_output_format output_format, mp_subcheck check, + unsigned int indentation) { char *result = NULL; mp_subcheck_list *subchecks = NULL; switch (output_format) { case MP_FORMAT_MULTI_LINE: - asprintf(&result, "%s\\_[%s] - %s", generate_indentation_string(indentation), state_text(mp_compute_subcheck_state(check)), - check.output); + asprintf(&result, "%s\\_[%s] - %s", generate_indentation_string(indentation), + state_text(mp_compute_subcheck_state(check)), check.output); subchecks = check.subchecks; while (subchecks != NULL) { - asprintf(&result, "%s\n%s", result, fmt_subcheck_output(output_format, subchecks->subcheck, indentation + 1)); + asprintf(&result, "%s\n%s", result, + fmt_subcheck_output(output_format, subchecks->subcheck, indentation + 1)); subchecks = subchecks->next; } return result; @@ -551,3 +580,23 @@ mp_output_format mp_get_format(void) { return output_format; } void mp_set_level_of_detail(mp_output_detail_level level) { level_of_detail = level; } mp_output_detail_level mp_get_level_of_detail(void) { return level_of_detail; } + +mp_state_enum mp_eval_ok(mp_check overall) { + (void)overall; + return STATE_OK; +} + +mp_state_enum mp_eval_warning(mp_check overall) { + (void)overall; + return STATE_WARNING; +} + +mp_state_enum mp_eval_critical(mp_check overall) { + (void)overall; + return STATE_CRITICAL; +} + +mp_state_enum mp_eval_unknown(mp_check overall) { + (void)overall; + return STATE_UNKNOWN; +} diff --git a/lib/output.h b/lib/output.h index 3bd91f90..c63c8e3f 100644 --- a/lib/output.h +++ b/lib/output.h @@ -7,15 +7,21 @@ /* * A partial check result */ -typedef struct { +typedef struct mp_subcheck mp_subcheck; +struct mp_subcheck { mp_state_enum state; // OK, Warning, Critical ... set explicitly mp_state_enum default_state; // OK, Warning, Critical .. if not set explicitly - bool state_set_explicitly; // was the state set explicitly (or should it be derived from subchecks) + bool state_set_explicitly; // was the state set explicitly (or should it be derived from + // subchecks) - char *output; // Text output for humans ("Filesystem xyz is fine", "Could not create TCP connection to..") - pd_list *perfdata; // Performance data for this check + char *output; // Text output for humans ("Filesystem xyz is fine", "Could not create TCP + // connection to..") + pd_list *perfdata; // Performance data for this check struct subcheck_list *subchecks; // subchecks deeper in the hierarchy -} mp_subcheck; + + // the evaluation_functions computes the state of subcheck + mp_state_enum (*evaluation_function)(mp_subcheck); +}; /* * A list of subchecks, used in subchecks and the main check @@ -57,10 +63,14 @@ mp_output_detail_level mp_get_level_of_detail(void); * The final result is always derived from the children and the "worst" state * in the first layer of subchecks */ -typedef struct { +typedef struct mp_check mp_check; +struct mp_check { char *summary; // Overall summary, if not set a summary will be automatically generated mp_subcheck_list *subchecks; -} mp_check; + + // the evaluation_functions computes the state of check + mp_state_enum (*evaluation_function)(mp_check); +}; mp_check mp_check_init(void); mp_subcheck mp_subcheck_init(void); @@ -78,6 +88,13 @@ void mp_add_summary(mp_check check[static 1], char *summary); mp_state_enum mp_compute_check_state(mp_check); mp_state_enum mp_compute_subcheck_state(mp_subcheck); +mp_state_enum mp_eval_ok(mp_check overall); +mp_state_enum mp_eval_warning(mp_check overall); +mp_state_enum mp_eval_critical(mp_check overall); +mp_state_enum mp_eval_unknown(mp_check overall); +mp_state_enum mp_eval_check_default(mp_check check); +mp_state_enum mp_eval_subcheck_default(mp_subcheck subcheck); + typedef struct { bool parsing_success; mp_output_format output_format; diff --git a/lib/perfdata.c b/lib/perfdata.c index f425ffcf..b87de7e0 100644 --- a/lib/perfdata.c +++ b/lib/perfdata.c @@ -257,6 +257,10 @@ mp_perfdata mp_set_pd_value_double(mp_perfdata pd, double value) { return pd; } +mp_perfdata mp_set_pd_value_char(mp_perfdata pd, char value) { return mp_set_pd_value_long_long(pd, (long long)value); } + +mp_perfdata mp_set_pd_value_u_char(mp_perfdata pd, unsigned char value) { return mp_set_pd_value_u_long_long(pd, (unsigned long long)value); } + mp_perfdata mp_set_pd_value_int(mp_perfdata pd, int value) { return mp_set_pd_value_long_long(pd, (long long)value); } mp_perfdata mp_set_pd_value_u_int(mp_perfdata pd, unsigned int value) { return mp_set_pd_value_u_long_long(pd, (unsigned long long)value); } @@ -288,6 +292,10 @@ mp_perfdata_value mp_create_pd_value_double(double value) { mp_perfdata_value mp_create_pd_value_float(float value) { return mp_create_pd_value_double((double)value); } +mp_perfdata_value mp_create_pd_value_char(char value) { return mp_create_pd_value_long_long((long long)value); } + +mp_perfdata_value mp_create_pd_value_u_char(unsigned char value) { return mp_create_pd_value_u_long_long((unsigned long long)value); } + mp_perfdata_value mp_create_pd_value_int(int value) { return mp_create_pd_value_long_long((long long)value); } mp_perfdata_value mp_create_pd_value_u_int(unsigned int value) { return mp_create_pd_value_u_long_long((unsigned long long)value); } diff --git a/lib/perfdata.h b/lib/perfdata.h index cb552678..7fd908a9 100644 --- a/lib/perfdata.h +++ b/lib/perfdata.h @@ -155,6 +155,8 @@ mp_perfdata mp_set_pd_value_u_long_long(mp_perfdata, unsigned long long); _Generic((V), \ float: mp_create_pd_value_float, \ double: mp_create_pd_value_double, \ + char: mp_create_pd_value_char, \ + unsigned char: mp_create_pd_value_u_char, \ int: mp_create_pd_value_int, \ unsigned int: mp_create_pd_value_u_int, \ long: mp_create_pd_value_long, \ @@ -164,6 +166,8 @@ mp_perfdata mp_set_pd_value_u_long_long(mp_perfdata, unsigned long long); mp_perfdata_value mp_create_pd_value_float(float); mp_perfdata_value mp_create_pd_value_double(double); +mp_perfdata_value mp_create_pd_value_char(char); +mp_perfdata_value mp_create_pd_value_u_char(unsigned char); mp_perfdata_value mp_create_pd_value_int(int); mp_perfdata_value mp_create_pd_value_u_int(unsigned int); mp_perfdata_value mp_create_pd_value_long(long); diff --git a/plugins-root/Makefile.am b/plugins-root/Makefile.am index a80229e2..fffc0575 100644 --- a/plugins-root/Makefile.am +++ b/plugins-root/Makefile.am @@ -24,7 +24,8 @@ noinst_PROGRAMS = check_dhcp check_icmp @EXTRAS_ROOT@ EXTRA_PROGRAMS = pst3 -EXTRA_DIST = t pst3.c +EXTRA_DIST = t pst3.c \ + check_icmp.d BASEOBJS = ../plugins/utils.o ../lib/libmonitoringplug.a ../gl/libgnu.a NETOBJS = ../plugins/netutils.o $(BASEOBJS) $(EXTRA_NETOBJS) @@ -82,6 +83,7 @@ install-exec-local: $(noinst_PROGRAMS) # the actual targets check_dhcp_LDADD = @LTLIBINTL@ $(NETLIBS) $(LIB_CRYPTO) check_icmp_LDADD = @LTLIBINTL@ $(NETLIBS) $(SOCKETLIBS) $(LIB_CRYPTO) +check_icmp_SOURCES = check_icmp.c check_icmp.d/check_icmp_helpers.c # -m64 needed at compiler and linker phase pst3_CFLAGS = @PST3CFLAGS@ @@ -89,7 +91,7 @@ pst3_LDFLAGS = @PST3CFLAGS@ # pst3 must not use monitoringplug/gnulib includes! pst3_CPPFLAGS = -check_dhcp_DEPENDENCIES = check_dhcp.c $(NETOBJS) $(DEPLIBS) +check_dhcp_DEPENDENCIES = check_dhcp.c $(NETOBJS) $(DEPLIBS) check_icmp_DEPENDENCIES = check_icmp.c $(NETOBJS) clean-local: diff --git a/plugins-root/check_icmp.c b/plugins-root/check_icmp.c index dcaceddb..55405b8a 100644 --- a/plugins-root/check_icmp.c +++ b/plugins-root/check_icmp.c @@ -46,6 +46,8 @@ const char *email = "devel@monitoring-plugins.org"; #include "../plugins/common.h" #include "netutils.h" #include "utils.h" +#include "output.h" +#include "perfdata.h" #if HAVE_SYS_SOCKIO_H # include @@ -65,6 +67,17 @@ const char *email = "devel@monitoring-plugins.org"; #include #include #include +#include +#include +#include +#include +#include +#include +#include + +#include "../lib/states.h" +#include "./check_icmp.d/config.h" +#include "./check_icmp.d/check_icmp_helpers.h" /** sometimes undefined system macros (quite a few, actually) **/ #ifndef MAXTTL @@ -96,56 +109,8 @@ const char *email = "devel@monitoring-plugins.org"; # define ICMP_UNREACH_PRECEDENCE_CUTOFF 15 #endif -typedef unsigned short range_t; /* type for get_range() -- unimplemented */ - -typedef struct rta_host { - unsigned short id; /* id in **table, and icmp pkts */ - char *name; /* arg used for adding this host */ - char *msg; /* icmp error message, if any */ - struct sockaddr_storage saddr_in; /* the address of this host */ - struct sockaddr_storage error_addr; /* stores address of error replies */ - unsigned long long time_waited; /* total time waited, in usecs */ - unsigned int icmp_sent, icmp_recv, icmp_lost; /* counters */ - unsigned char icmp_type, icmp_code; /* type and code from errors */ - unsigned short flags; /* control/status flags */ - double rta; /* measured RTA */ - int rta_status; // check result for RTA checks - double rtmax; /* max rtt */ - double rtmin; /* min rtt */ - double jitter; /* measured jitter */ - int jitter_status; // check result for Jitter checks - double jitter_max; /* jitter rtt maximum */ - double jitter_min; /* jitter rtt minimum */ - double EffectiveLatency; - double mos; /* Mean opnion score */ - int mos_status; // check result for MOS checks - double score; /* score */ - int score_status; // check result for score checks - u_int last_tdiff; - u_int last_icmp_seq; /* Last ICMP_SEQ to check out of order pkts */ - unsigned char pl; /* measured packet loss */ - int pl_status; // check result for packet loss checks - struct rta_host *next; /* linked list */ - int order_status; // check result for packet order checks -} rta_host; - #define FLAG_LOST_CAUSE 0x01 /* decidedly dead target. */ -/* threshold structure. all values are maximum allowed, exclusive */ -typedef struct threshold { - unsigned char pl; /* max allowed packet loss in percent */ - unsigned int rta; /* roundtrip time average, microseconds */ - double jitter; /* jitter time average, microseconds */ - double mos; /* MOS */ - double score; /* Score */ -} threshold; - -/* the data structure */ -typedef struct icmp_ping_data { - struct timeval stime; /* timestamp (saved in protocol struct as well) */ - unsigned short ping_id; -} icmp_ping_data; - typedef union ip_hdr { struct ip ip; struct ip6_hdr ip6; @@ -158,24 +123,6 @@ typedef union icmp_packet { u_short *cksum_in; } icmp_packet; -/* the different modes of this program are as follows: - * MODE_RTA: send all packets no matter what (mimic check_icmp and check_ping) - * MODE_HOSTCHECK: Return immediately upon any sign of life - * In addition, sends packets to ALL addresses assigned - * to this host (as returned by gethostbyname() or - * gethostbyaddr() and expects one host only to be checked at - * a time. Therefore, any packet response what so ever will - * count as a sign of life, even when received outside - * crit.rta limit. Do not misspell any additional IP's. - * MODE_ALL: Requires packets from ALL requested IP to return OK (default). - * MODE_ICMP: implement something similar to check_icmp (MODE_RTA without - * tcp and udp args does this) - */ -#define MODE_RTA 0 -#define MODE_HOSTCHECK 1 -#define MODE_ALL 2 -#define MODE_ICMP 3 - enum enum_threshold_mode { const_rta_mode, const_packet_loss_mode, @@ -186,89 +133,453 @@ enum enum_threshold_mode { typedef enum enum_threshold_mode threshold_mode; -/* the different ping types we can do - * TODO: investigate ARP ping as well */ -#define HAVE_ICMP 1 -#define HAVE_UDP 2 -#define HAVE_TCP 4 -#define HAVE_ARP 8 - -#define MIN_PING_DATA_SIZE sizeof(struct icmp_ping_data) -#define MAX_IP_PKT_SIZE 65536 /* (theoretical) max IP packet size */ -#define IP_HDR_SIZE 20 -#define MAX_PING_DATA (MAX_IP_PKT_SIZE - IP_HDR_SIZE - ICMP_MINLEN) -#define DEFAULT_PING_DATA_SIZE (MIN_PING_DATA_SIZE + 44) - -/* various target states */ -#define TSTATE_INACTIVE 0x01 /* don't ping this host anymore */ -#define TSTATE_WAITING 0x02 /* unanswered packets on the wire */ -#define TSTATE_ALIVE 0x04 /* target is alive (has answered something) */ -#define TSTATE_UNREACH 0x08 - /** prototypes **/ -void print_help(void); +void print_help(); void print_usage(void); -static u_int get_timevar(const char *); -static u_int get_timevaldiff(struct timeval *, struct timeval *); -static in_addr_t get_ip_address(const char *); -static int wait_for_reply(int, u_int); -static int recvfrom_wto(int, void *, unsigned int, struct sockaddr *, u_int *, struct timeval *); -static int send_icmp_ping(int, struct rta_host *); -static int get_threshold(char *str, threshold *th); -static bool get_threshold2(char *str, size_t length, threshold *, threshold *, threshold_mode mode); -static bool parse_threshold2_helper(char *s, size_t length, threshold *thr, threshold_mode mode); -static void run_checks(void); -static void set_source_ip(char *); -static int add_target(char *); -static int add_target_ip(char *, struct sockaddr_storage *); -static int handle_random_icmp(unsigned char *, struct sockaddr_storage *); -static void parse_address(struct sockaddr_storage *, char *, int); -static unsigned short icmp_checksum(uint16_t *, size_t); -static void finish(int); -static void crash(const char *, ...); -/** external **/ -extern int optind; -extern char *optarg; -extern char **environ; +/* Time related */ +typedef struct { + int error_code; + time_t time_range; +} get_timevar_wrapper; +static get_timevar_wrapper get_timevar(const char *str); +static time_t get_timevaldiff(struct timeval earlier, struct timeval later); +static time_t get_timevaldiff_to_now(struct timeval earlier); + +static in_addr_t get_ip_address(const char *ifname); +static void set_source_ip(char *arg, int icmp_sock, sa_family_t addr_family); + +/* Receiving data */ +static int wait_for_reply(check_icmp_socket_set sockset, time_t time_interval, + unsigned short icmp_pkt_size, time_t *pkt_interval, + time_t *target_interval, uint16_t sender_id, ping_target **table, + unsigned short packets, unsigned short number_of_targets, + check_icmp_state *program_state); + +typedef struct { + sa_family_t recv_proto; + ssize_t received; +} recvfrom_wto_wrapper; +static recvfrom_wto_wrapper recvfrom_wto(check_icmp_socket_set sockset, void *buf, unsigned int len, + struct sockaddr *saddr, time_t *timeout, + struct timeval *received_timestamp); +static int handle_random_icmp(unsigned char *packet, struct sockaddr_storage *addr, + time_t *pkt_interval, time_t *target_interval, uint16_t sender_id, + ping_target **table, unsigned short packets, + unsigned short number_of_targets, check_icmp_state *program_state); + +/* Sending data */ +static int send_icmp_ping(check_icmp_socket_set sockset, ping_target *host, + unsigned short icmp_pkt_size, uint16_t sender_id, + check_icmp_state *program_state); + +/* Threshold related */ +typedef struct { + int errorcode; + check_icmp_threshold threshold; +} get_threshold_wrapper; +static get_threshold_wrapper get_threshold(char *str, check_icmp_threshold threshold); + +typedef struct { + int errorcode; + check_icmp_threshold warn; + check_icmp_threshold crit; +} get_threshold2_wrapper; +static get_threshold2_wrapper get_threshold2(char *str, size_t length, check_icmp_threshold warn, + check_icmp_threshold crit, threshold_mode mode); + +typedef struct { + int errorcode; + check_icmp_threshold result; +} parse_threshold2_helper_wrapper; +static parse_threshold2_helper_wrapper parse_threshold2_helper(char *threshold_string, + size_t length, + check_icmp_threshold thr, + threshold_mode mode); + +/* main test function */ +static void run_checks(unsigned short icmp_pkt_size, time_t *pkt_interval, time_t *target_interval, + uint16_t sender_id, check_icmp_execution_mode mode, + time_t max_completion_time, struct timeval prog_start, ping_target **table, + unsigned short packets, check_icmp_socket_set sockset, + unsigned short number_of_targets, check_icmp_state *program_state); +mp_subcheck evaluate_target(ping_target target, check_icmp_mode_switches modes, + check_icmp_threshold warn, check_icmp_threshold crit); + +typedef struct { + int targets_ok; + int targets_warn; + mp_subcheck sc_host; +} evaluate_host_wrapper; +evaluate_host_wrapper evaluate_host(check_icmp_target_container host, + check_icmp_mode_switches modes, check_icmp_threshold warn, + check_icmp_threshold crit); + +/* Target acquisition */ +typedef struct { + int error_code; + check_icmp_target_container host; + bool has_v4; + bool has_v6; +} add_host_wrapper; +static add_host_wrapper add_host(char *arg, check_icmp_execution_mode mode, + sa_family_t enforced_proto); + +typedef struct { + int error_code; + ping_target *targets; + unsigned int number_of_targets; + bool has_v4; + bool has_v6; +} add_target_wrapper; +static add_target_wrapper add_target(char *arg, check_icmp_execution_mode mode, + sa_family_t enforced_proto); + +typedef struct { + int error_code; + ping_target *target; +} add_target_ip_wrapper; +static add_target_ip_wrapper add_target_ip(struct sockaddr_storage address); + +static void parse_address(const struct sockaddr_storage *addr, char *dst, socklen_t size); + +static unsigned short icmp_checksum(uint16_t *packet, size_t packet_size); + +/* End of run function */ +static void finish(int sign, check_icmp_mode_switches modes, int min_hosts_alive, + check_icmp_threshold warn, check_icmp_threshold crit, + unsigned short number_of_targets, check_icmp_state *program_state, + check_icmp_target_container host_list[], unsigned short number_of_hosts, + mp_check overall[static 1]); + +/* Error exit */ +static void crash(const char *fmt, ...) __attribute__((format(printf, 1, 2))); /** global variables **/ -static struct rta_host **table, *cursor, *list; +static int debug = 0; -static threshold crit = {.pl = 80, .rta = 500000, .jitter = 0.0, .mos = 0.0, .score = 0.0}; -static threshold warn = {.pl = 40, .rta = 200000, .jitter = 0.0, .mos = 0.0, .score = 0.0}; +extern unsigned int timeout; -static int mode, protocols, sockets, debug = 0, timeout = 10; -static unsigned short icmp_data_size = DEFAULT_PING_DATA_SIZE; -static unsigned short icmp_pkt_size = DEFAULT_PING_DATA_SIZE + ICMP_MINLEN; +/** the working code **/ +static inline unsigned short targets_alive(unsigned short targets, unsigned short targets_down) { + return targets - targets_down; +} +static inline unsigned int icmp_pkts_en_route(unsigned int icmp_sent, unsigned int icmp_recv, + unsigned int icmp_lost) { + return icmp_sent - (icmp_recv + icmp_lost); +} -static unsigned int icmp_sent = 0, icmp_recv = 0, icmp_lost = 0, ttl = 0; -#define icmp_pkts_en_route (icmp_sent - (icmp_recv + icmp_lost)) -static unsigned short targets_down = 0, targets = 0, packets = 0; -#define targets_alive (targets - targets_down) -static unsigned int retry_interval, pkt_interval, target_interval; -static int icmp_sock, tcp_sock, udp_sock, status = STATE_OK; -static pid_t pid; -static struct timezone tz; -static struct timeval prog_start; -static unsigned long long max_completion_time = 0; -static unsigned int warn_down = 1, crit_down = 1; /* host down threshold values */ -static int min_hosts_alive = -1; -static float pkt_backoff_factor = 1.5; -static float target_backoff_factor = 1.5; -static bool rta_mode = false; -static bool pl_mode = false; -static bool jitter_mode = false; -static bool score_mode = false; -static bool mos_mode = false; -static bool order_mode = false; +// Create configuration from cli parameters +typedef struct { + int errorcode; + check_icmp_config config; +} check_icmp_config_wrapper; +check_icmp_config_wrapper process_arguments(int argc, char **argv) { + /* get calling name the old-fashioned way for portability instead + * of relying on the glibc-ism __progname */ + char *ptr = strrchr(argv[0], '/'); + if (ptr) { + progname = &ptr[1]; + } else { + progname = argv[0]; + } + + check_icmp_config_wrapper result = { + .errorcode = OK, + .config = check_icmp_config_init(), + }; + + /* use the pid to mark packets as ours */ + /* Some systems have 32-bit pid_t so mask off only 16 bits */ + result.config.sender_id = getpid() & 0xffff; + + if (!strcmp(progname, "check_icmp") || !strcmp(progname, "check_ping")) { + result.config.mode = MODE_ICMP; + } else if (!strcmp(progname, "check_host")) { + result.config.mode = MODE_HOSTCHECK; + result.config.pkt_interval = 1000000; + result.config.number_of_packets = 5; + result.config.crit.rta = result.config.warn.rta = 1000000; + result.config.crit.pl = result.config.warn.pl = 100; + } else if (!strcmp(progname, "check_rta_multi")) { + result.config.mode = MODE_ALL; + result.config.target_interval = 0; + result.config.pkt_interval = 50000; + result.config.number_of_packets = 5; + } + /* support "--help" and "--version" */ + if (argc == 2) { + if (!strcmp(argv[1], "--help")) { + strcpy(argv[1], "-h"); + } + if (!strcmp(argv[1], "--version")) { + strcpy(argv[1], "-V"); + } + } + + sa_family_t enforced_ai_family = AF_UNSPEC; + + // Parse protocol arguments first + // and count hosts here + char *opts_str = "vhVw:c:n:p:t:H:s:i:b:I:l:m:P:R:J:S:M:O64"; + for (int i = 1; i < argc; i++) { + long int arg; + while ((arg = getopt(argc, argv, opts_str)) != EOF) { + switch (arg) { + case '4': + if (enforced_ai_family != AF_UNSPEC) { + crash("Multiple protocol versions not supported"); + } + enforced_ai_family = AF_INET; + break; + case '6': + if (enforced_ai_family != AF_UNSPEC) { + crash("Multiple protocol versions not supported"); + } + enforced_ai_family = AF_INET6; + break; + case 'H': { + result.config.number_of_hosts++; + break; + } + case 'v': + debug++; + break; + } + } + } + + char **tmp = &argv[optind]; + while (*tmp) { + result.config.number_of_hosts++; + tmp++; + } + + // Sanity check: if hostmode is selected,only a single host is allowed + if (result.config.mode == MODE_HOSTCHECK && result.config.number_of_hosts > 1) { + usage("check_host only allows a single host"); + } + + // Allocate hosts + result.config.hosts = + calloc(result.config.number_of_hosts, sizeof(check_icmp_target_container)); + if (result.config.hosts == NULL) { + crash("failed to allocate memory"); + } + + /* Reset argument scanning */ + optind = 1; + + int host_counter = 0; + /* parse the arguments */ + for (int i = 1; i < argc; i++) { + long int arg; + while ((arg = getopt(argc, argv, opts_str)) != EOF) { + switch (arg) { + case 'b': { + long size = strtol(optarg, NULL, 0); + if ((unsigned long)size >= (sizeof(struct icmp) + sizeof(struct icmp_ping_data)) && + size < MAX_PING_DATA) { + result.config.icmp_data_size = (unsigned short)size; + result.config.icmp_pkt_size = (unsigned short)(size + ICMP_MINLEN); + } else { + usage_va("ICMP data length must be between: %lu and %lu", + sizeof(struct icmp) + sizeof(struct icmp_ping_data), + MAX_PING_DATA - 1); + } + } break; + case 'i': { + get_timevar_wrapper parsed_time = get_timevar(optarg); + + if (parsed_time.error_code == OK) { + result.config.pkt_interval = parsed_time.time_range; + } else { + crash("failed to parse packet interval"); + } + } break; + case 'I': { + get_timevar_wrapper parsed_time = get_timevar(optarg); + + if (parsed_time.error_code == OK) { + result.config.target_interval = parsed_time.time_range; + } else { + crash("failed to parse target interval"); + } + } break; + case 'w': { + get_threshold_wrapper warn = get_threshold(optarg, result.config.warn); + if (warn.errorcode == OK) { + result.config.warn = warn.threshold; + } else { + crash("failed to parse warning threshold"); + } + } break; + case 'c': { + get_threshold_wrapper crit = get_threshold(optarg, result.config.crit); + if (crit.errorcode == OK) { + result.config.crit = crit.threshold; + } else { + crash("failed to parse critical threshold"); + } + } break; + case 'n': + case 'p': + result.config.number_of_packets = (unsigned short)strtoul(optarg, NULL, 0); + if (result.config.number_of_packets > 20) { + errno = 0; + crash("packets is > 20 (%d)", result.config.number_of_packets); + } + break; + case 't': + // WARNING Deprecated since execution time is determined by the other factors + break; + case 'H': { + add_host_wrapper host_add_result = + add_host(optarg, result.config.mode, enforced_ai_family); + if (host_add_result.error_code == OK) { + result.config.hosts[host_counter] = host_add_result.host; + host_counter++; + + if (result.config.targets != NULL) { + result.config.number_of_targets += ping_target_list_append( + result.config.targets, host_add_result.host.target_list); + } else { + result.config.targets = host_add_result.host.target_list; + result.config.number_of_targets += host_add_result.host.number_of_targets; + } + + if (host_add_result.has_v4) { + result.config.need_v4 = true; + } + if (host_add_result.has_v6) { + result.config.need_v6 = true; + } + } else { + // TODO adding host failed, crash here + } + } break; + case 'l': + result.config.ttl = strtoul(optarg, NULL, 0); + break; + case 'm': + result.config.min_hosts_alive = (int)strtoul(optarg, NULL, 0); + break; + case 's': /* specify source IP address */ + result.config.source_ip = optarg; + break; + case 'V': /* version */ + print_revision(progname, NP_VERSION); + exit(STATE_UNKNOWN); + case 'h': /* help */ + print_help(); + exit(STATE_UNKNOWN); + break; + case 'R': /* RTA mode */ { + get_threshold2_wrapper rta_th = get_threshold2( + optarg, strlen(optarg), result.config.warn, result.config.crit, const_rta_mode); + + if (rta_th.errorcode != OK) { + crash("Failed to parse RTA threshold"); + } + + result.config.warn = rta_th.warn; + result.config.crit = rta_th.crit; + result.config.modes.rta_mode = true; + } break; + case 'P': /* packet loss mode */ { + get_threshold2_wrapper pl_th = + get_threshold2(optarg, strlen(optarg), result.config.warn, result.config.crit, + const_packet_loss_mode); + if (pl_th.errorcode != OK) { + crash("Failed to parse packet loss threshold"); + } + + result.config.warn = pl_th.warn; + result.config.crit = pl_th.crit; + result.config.modes.pl_mode = true; + } break; + case 'J': /* jitter mode */ { + get_threshold2_wrapper jitter_th = + get_threshold2(optarg, strlen(optarg), result.config.warn, result.config.crit, + const_jitter_mode); + if (jitter_th.errorcode != OK) { + crash("Failed to parse jitter threshold"); + } + + result.config.warn = jitter_th.warn; + result.config.crit = jitter_th.crit; + result.config.modes.jitter_mode = true; + } break; + case 'M': /* MOS mode */ { + get_threshold2_wrapper mos_th = get_threshold2( + optarg, strlen(optarg), result.config.warn, result.config.crit, const_mos_mode); + if (mos_th.errorcode != OK) { + crash("Failed to parse MOS threshold"); + } + + result.config.warn = mos_th.warn; + result.config.crit = mos_th.crit; + result.config.modes.mos_mode = true; + } break; + case 'S': /* score mode */ { + get_threshold2_wrapper score_th = + get_threshold2(optarg, strlen(optarg), result.config.warn, result.config.crit, + const_score_mode); + if (score_th.errorcode != OK) { + crash("Failed to parse score threshold"); + } + + result.config.warn = score_th.warn; + result.config.crit = score_th.crit; + result.config.modes.score_mode = true; + } break; + case 'O': /* out of order mode */ + result.config.modes.order_mode = true; + break; + } + } + } + + argv = &argv[optind]; + while (*argv) { + add_target(*argv, result.config.mode, enforced_ai_family); + argv++; + } + + if (!result.config.number_of_targets) { + errno = 0; + crash("No hosts to check"); + } + + /* stupid users should be able to give whatever thresholds they want + * (nothing will break if they do), but some anal plugin maintainer + * will probably add some printf() thing here later, so it might be + * best to at least show them where to do it. ;) */ + if (result.config.warn.pl > result.config.crit.pl) { + result.config.warn.pl = result.config.crit.pl; + } + if (result.config.warn.rta > result.config.crit.rta) { + result.config.warn.rta = result.config.crit.rta; + } + if (result.config.warn.jitter > result.config.crit.jitter) { + result.config.crit.jitter = result.config.warn.jitter; + } + if (result.config.warn.mos < result.config.crit.mos) { + result.config.warn.mos = result.config.crit.mos; + } + if (result.config.warn.score < result.config.crit.score) { + result.config.warn.score = result.config.crit.score; + } + + return result; +} /** code start **/ static void crash(const char *fmt, ...) { - va_list ap; printf("%s: ", progname); + va_list ap; va_start(ap, fmt); vprintf(fmt, ap); va_end(ap); @@ -385,18 +696,20 @@ static const char *get_icmp_error_msg(unsigned char icmp_type, unsigned char icm return msg; } -static int handle_random_icmp(unsigned char *packet, struct sockaddr_storage *addr) { - struct icmp p, sent_icmp; - struct rta_host *host = NULL; - - memcpy(&p, packet, sizeof(p)); - if (p.icmp_type == ICMP_ECHO && ntohs(p.icmp_id) == pid) { +static int handle_random_icmp(unsigned char *packet, struct sockaddr_storage *addr, + time_t *pkt_interval, time_t *target_interval, + const uint16_t sender_id, ping_target **table, unsigned short packets, + const unsigned short number_of_targets, + check_icmp_state *program_state) { + struct icmp icmp_packet; + memcpy(&icmp_packet, packet, sizeof(icmp_packet)); + if (icmp_packet.icmp_type == ICMP_ECHO && ntohs(icmp_packet.icmp_id) == sender_id) { /* echo request from us to us (pinging localhost) */ return 0; } if (debug) { - printf("handle_random_icmp(%p, %p)\n", (void *)&p, (void *)addr); + printf("handle_random_icmp(%p, %p)\n", (void *)&icmp_packet, (void *)addr); } /* only handle a few types, since others can't possibly be replies to @@ -409,14 +722,17 @@ static int handle_random_icmp(unsigned char *packet, struct sockaddr_storage *ad * TIMXCEED actually sends a proper icmp response we will have passed * too many hops to have a hope of reaching it later, in which case it * indicates overconfidence in the network, poor routing or both. */ - if (p.icmp_type != ICMP_UNREACH && p.icmp_type != ICMP_TIMXCEED && p.icmp_type != ICMP_SOURCEQUENCH && p.icmp_type != ICMP_PARAMPROB) { + if (icmp_packet.icmp_type != ICMP_UNREACH && icmp_packet.icmp_type != ICMP_TIMXCEED && + icmp_packet.icmp_type != ICMP_SOURCEQUENCH && icmp_packet.icmp_type != ICMP_PARAMPROB) { return 0; } /* might be for us. At least it holds the original package (according * to RFC 792). If it isn't, just ignore it */ + struct icmp sent_icmp; memcpy(&sent_icmp, packet + 28, sizeof(sent_icmp)); - if (sent_icmp.icmp_type != ICMP_ECHO || ntohs(sent_icmp.icmp_id) != pid || ntohs(sent_icmp.icmp_seq) >= targets * packets) { + if (sent_icmp.icmp_type != ICMP_ECHO || ntohs(sent_icmp.icmp_id) != sender_id || + ntohs(sent_icmp.icmp_seq) >= number_of_targets * packets) { if (debug) { printf("Packet is no response to a packet we sent\n"); } @@ -424,14 +740,15 @@ static int handle_random_icmp(unsigned char *packet, struct sockaddr_storage *ad } /* it is indeed a response for us */ - host = table[ntohs(sent_icmp.icmp_seq) / packets]; + ping_target *host = table[ntohs(sent_icmp.icmp_seq) / packets]; if (debug) { char address[INET6_ADDRSTRLEN]; parse_address(addr, address, sizeof(address)); - printf("Received \"%s\" from %s for ICMP ECHO sent to %s.\n", get_icmp_error_msg(p.icmp_type, p.icmp_code), address, host->name); + printf("Received \"%s\" from %s for ICMP ECHO sent.\n", + get_icmp_error_msg(icmp_packet.icmp_type, icmp_packet.icmp_code), address); } - icmp_lost++; + program_state->icmp_lost++; host->icmp_lost++; /* don't spend time on lost hosts any more */ if (host->flags & FLAG_LOST_CAUSE) { @@ -440,305 +757,114 @@ static int handle_random_icmp(unsigned char *packet, struct sockaddr_storage *ad /* source quench means we're sending too fast, so increase the * interval and mark this packet lost */ - if (p.icmp_type == ICMP_SOURCEQUENCH) { - pkt_interval *= pkt_backoff_factor; - target_interval *= target_backoff_factor; + if (icmp_packet.icmp_type == ICMP_SOURCEQUENCH) { + *pkt_interval = (unsigned int)((double)*pkt_interval * PACKET_BACKOFF_FACTOR); + *target_interval = (unsigned int)((double)*target_interval * TARGET_BACKOFF_FACTOR); } else { - targets_down++; + program_state->targets_down++; host->flags |= FLAG_LOST_CAUSE; } - host->icmp_type = p.icmp_type; - host->icmp_code = p.icmp_code; + host->icmp_type = icmp_packet.icmp_type; + host->icmp_code = icmp_packet.icmp_code; host->error_addr = *addr; return 0; } -void parse_address(struct sockaddr_storage *addr, char *address, int size) { - switch (address_family) { +void parse_address(const struct sockaddr_storage *addr, char *dst, socklen_t size) { + switch (addr->ss_family) { case AF_INET: - inet_ntop(address_family, &((struct sockaddr_in *)addr)->sin_addr, address, size); + inet_ntop(AF_INET, &((struct sockaddr_in *)addr)->sin_addr, dst, size); break; case AF_INET6: - inet_ntop(address_family, &((struct sockaddr_in6 *)addr)->sin6_addr, address, size); + inet_ntop(AF_INET6, &((struct sockaddr_in6 *)addr)->sin6_addr, dst, size); break; + default: + assert(false); } } int main(int argc, char **argv) { - int i; - char *ptr; - long int arg; - int icmp_sockerrno, udp_sockerrno, tcp_sockerrno; - int result; - struct rta_host *host; -#ifdef HAVE_SIGACTION - struct sigaction sig_action; -#endif -#ifdef SO_TIMESTAMP - int on = 1; -#endif - char *source_ip = NULL; - char *opts_str = "vhVw:c:n:p:t:H:s:i:b:I:l:m:P:R:J:S:M:O64"; setlocale(LC_ALL, ""); bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); - /* we only need to be setsuid when we get the sockets, so do - * that before pointer magic (esp. on network data) */ - icmp_sockerrno = udp_sockerrno = tcp_sockerrno = sockets = 0; - - address_family = -1; - int icmp_proto = IPPROTO_ICMP; - - /* get calling name the old-fashioned way for portability instead - * of relying on the glibc-ism __progname */ - ptr = strrchr(argv[0], '/'); - if (ptr) { - progname = &ptr[1]; - } else { - progname = argv[0]; - } - - /* now set defaults. Use progname to set them initially (allows for - * superfast check_host program when target host is up */ - cursor = list = NULL; - table = NULL; - - mode = MODE_RTA; - /* Default critical thresholds */ - crit.rta = 500000; - crit.pl = 80; - crit.jitter = 50; - crit.mos = 3; - crit.score = 70; - /* Default warning thresholds */ - warn.rta = 200000; - warn.pl = 40; - warn.jitter = 40; - warn.mos = 3.5; - warn.score = 80; - - protocols = HAVE_ICMP | HAVE_UDP | HAVE_TCP; - pkt_interval = 80000; /* 80 msec packet interval by default */ - packets = 5; - - if (!strcmp(progname, "check_icmp") || !strcmp(progname, "check_ping")) { - mode = MODE_ICMP; - protocols = HAVE_ICMP; - } else if (!strcmp(progname, "check_host")) { - mode = MODE_HOSTCHECK; - pkt_interval = 1000000; - packets = 5; - crit.rta = warn.rta = 1000000; - crit.pl = warn.pl = 100; - } else if (!strcmp(progname, "check_rta_multi")) { - mode = MODE_ALL; - target_interval = 0; - pkt_interval = 50000; - packets = 5; - } - - /* support "--help" and "--version" */ - if (argc == 2) { - if (!strcmp(argv[1], "--help")) { - strcpy(argv[1], "-h"); - } - if (!strcmp(argv[1], "--version")) { - strcpy(argv[1], "-V"); - } - } - - /* Parse protocol arguments first */ - for (i = 1; i < argc; i++) { - while ((arg = getopt(argc, argv, opts_str)) != EOF) { - switch (arg) { - case '4': - if (address_family != -1) { - crash("Multiple protocol versions not supported"); - } - address_family = AF_INET; - break; - case '6': -#ifdef USE_IPV6 - if (address_family != -1) { - crash("Multiple protocol versions not supported"); - } - address_family = AF_INET6; -#else - usage(_("IPv6 support not available\n")); -#endif - break; - } - } - } - - /* Reset argument scanning */ - optind = 1; - - unsigned long size; - bool err; - /* parse the arguments */ - for (i = 1; i < argc; i++) { - while ((arg = getopt(argc, argv, opts_str)) != EOF) { - switch (arg) { - case 'v': - debug++; - break; - case 'b': - size = strtol(optarg, NULL, 0); - if (size >= (sizeof(struct icmp) + sizeof(struct icmp_ping_data)) && size < MAX_PING_DATA) { - icmp_data_size = size; - icmp_pkt_size = size + ICMP_MINLEN; - } else { - usage_va("ICMP data length must be between: %lu and %lu", sizeof(struct icmp) + sizeof(struct icmp_ping_data), - MAX_PING_DATA - 1); - } - break; - case 'i': - pkt_interval = get_timevar(optarg); - break; - case 'I': - target_interval = get_timevar(optarg); - break; - case 'w': - get_threshold(optarg, &warn); - break; - case 'c': - get_threshold(optarg, &crit); - break; - case 'n': - case 'p': - packets = strtoul(optarg, NULL, 0); - break; - case 't': - timeout = strtoul(optarg, NULL, 0); - if (!timeout) { - timeout = 10; - } - break; - case 'H': - add_target(optarg); - break; - case 'l': - ttl = (int)strtoul(optarg, NULL, 0); - break; - case 'm': - min_hosts_alive = (int)strtoul(optarg, NULL, 0); - break; - case 'd': /* implement later, for cluster checks */ - warn_down = (unsigned char)strtoul(optarg, &ptr, 0); - if (ptr) { - crit_down = (unsigned char)strtoul(ptr + 1, NULL, 0); - } - break; - case 's': /* specify source IP address */ - source_ip = optarg; - break; - case 'V': /* version */ - print_revision(progname, NP_VERSION); - exit(STATE_UNKNOWN); - case 'h': /* help */ - print_help(); - exit(STATE_UNKNOWN); - break; - case 'R': /* RTA mode */ - err = get_threshold2(optarg, strlen(optarg), &warn, &crit, const_rta_mode); - if (!err) { - crash("Failed to parse RTA threshold"); - } - - rta_mode = true; - break; - case 'P': /* packet loss mode */ - err = get_threshold2(optarg, strlen(optarg), &warn, &crit, const_packet_loss_mode); - if (!err) { - crash("Failed to parse packet loss threshold"); - } - - pl_mode = true; - break; - case 'J': /* jitter mode */ - err = get_threshold2(optarg, strlen(optarg), &warn, &crit, const_jitter_mode); - if (!err) { - crash("Failed to parse jitter threshold"); - } - - jitter_mode = true; - break; - case 'M': /* MOS mode */ - err = get_threshold2(optarg, strlen(optarg), &warn, &crit, const_mos_mode); - if (!err) { - crash("Failed to parse MOS threshold"); - } - - mos_mode = true; - break; - case 'S': /* score mode */ - err = get_threshold2(optarg, strlen(optarg), &warn, &crit, const_score_mode); - if (!err) { - crash("Failed to parse score threshold"); - } - - score_mode = true; - break; - case 'O': /* out of order mode */ - order_mode = true; - break; - } - } - } - /* POSIXLY_CORRECT might break things, so unset it (the portable way) */ environ = NULL; - /* use the pid to mark packets as ours */ - /* Some systems have 32-bit pid_t so mask off only 16 bits */ - pid = getpid() & 0xffff; - /* printf("pid = %u\n", pid); */ - /* Parse extra opts if any */ argv = np_extra_opts(&argc, argv, progname); - argv = &argv[optind]; - while (*argv) { - add_target(*argv); - argv++; + check_icmp_config_wrapper tmp_config = process_arguments(argc, argv); + + if (tmp_config.errorcode != OK) { + crash("failed to parse config"); } - if (!targets) { - errno = 0; - crash("No hosts to check"); - } + const check_icmp_config config = tmp_config.config; + // int icmp_proto = IPPROTO_ICMP; // add_target might change address_family - switch (address_family) { - case AF_INET: - icmp_proto = IPPROTO_ICMP; - break; - case AF_INET6: - icmp_proto = IPPROTO_ICMPV6; - break; - default: - crash("Address family not supported"); - } - if ((icmp_sock = socket(address_family, SOCK_RAW, icmp_proto)) != -1) { - sockets |= HAVE_ICMP; - } else { - icmp_sockerrno = errno; - } + // switch (address_family) { + // case AF_INET: + // icmp_proto = IPPROTO_ICMP; + // break; + // case AF_INET6: + // icmp_proto = IPPROTO_ICMPV6; + // break; + // default: + // crash("Address family not supported"); + // } - if (source_ip) { - set_source_ip(source_ip); - } + check_icmp_socket_set sockset = { + .socket4 = -1, + .socket6 = -1, + }; + + if (config.need_v4) { + sockset.socket4 = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); + if (sockset.socket4 == -1) { + crash("Failed to obtain ICMP v4 socket"); + } + + if (config.source_ip) { + + struct in_addr tmp = {}; + int error_code = inet_pton(AF_INET, config.source_ip, &tmp); + if (error_code == 1) { + set_source_ip(config.source_ip, sockset.socket4, AF_INET); + } else { + // just try this mindlessly if it's not a v4 address + set_source_ip(config.source_ip, sockset.socket6, AF_INET6); + } + } #ifdef SO_TIMESTAMP - if (setsockopt(icmp_sock, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on))) { - if (debug) { - printf("Warning: no SO_TIMESTAMP support\n"); + if (sockset.socket4 != -1) { + int on = 1; + if (setsockopt(sockset.socket4, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on))) { + if (debug) { + printf("Warning: no SO_TIMESTAMP support\n"); + } + } + } + if (sockset.socket6 != -1) { + int on = 1; + if (setsockopt(sockset.socket6, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on))) { + if (debug) { + printf("Warning: no SO_TIMESTAMP support\n"); + } + } + } +#endif // SO_TIMESTAMP + } + + if (config.need_v6) { + sockset.socket6 = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6); + if (sockset.socket6 == -1) { + crash("Failed to obtain ICMP v6 socket"); } } -#endif // SO_TIMESTAMP /* now drop privileges (no effect if not setsuid or geteuid() == 0) */ if (setuid(getuid()) == -1) { @@ -746,186 +872,184 @@ int main(int argc, char **argv) { return 1; } - if (!sockets) { - if (icmp_sock == -1) { - errno = icmp_sockerrno; - crash("Failed to obtain ICMP socket"); - return -1; - } - /* if(udp_sock == -1) { */ - /* errno = icmp_sockerrno; */ - /* crash("Failed to obtain UDP socket"); */ - /* return -1; */ - /* } */ - /* if(tcp_sock == -1) { */ - /* errno = icmp_sockerrno; */ - /* crash("Failed to obtain TCP socker"); */ - /* return -1; */ - /* } */ - } - if (!ttl) { - ttl = 64; - } - - if (icmp_sock) { - result = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl)); + if (sockset.socket4) { + int result = setsockopt(sockset.socket4, SOL_IP, IP_TTL, &config.ttl, sizeof(config.ttl)); if (debug) { if (result == -1) { printf("setsockopt failed\n"); } else { - printf("ttl set to %u\n", ttl); + printf("ttl set to %lu\n", config.ttl); } } } - /* stupid users should be able to give whatever thresholds they want - * (nothing will break if they do), but some anal plugin maintainer - * will probably add some printf() thing here later, so it might be - * best to at least show them where to do it. ;) */ - if (warn.pl > crit.pl) { - warn.pl = crit.pl; + if (sockset.socket6) { + int result = setsockopt(sockset.socket6, SOL_IP, IP_TTL, &config.ttl, sizeof(config.ttl)); + if (debug) { + if (result == -1) { + printf("setsockopt failed\n"); + } else { + printf("ttl set to %lu\n", config.ttl); + } + } } - if (warn.rta > crit.rta) { - warn.rta = crit.rta; - } - if (warn_down > crit_down) { - crit_down = warn_down; - } - if (warn.jitter > crit.jitter) { - crit.jitter = warn.jitter; - } - if (warn.mos < crit.mos) { - warn.mos = crit.mos; - } - if (warn.score < crit.score) { - warn.score = crit.score; - } - -#ifdef HAVE_SIGACTION - sig_action.sa_sigaction = NULL; - sig_action.sa_handler = finish; - sigfillset(&sig_action.sa_mask); - sig_action.sa_flags = SA_NODEFER | SA_RESTART; - sigaction(SIGINT, &sig_action, NULL); - sigaction(SIGHUP, &sig_action, NULL); - sigaction(SIGTERM, &sig_action, NULL); - sigaction(SIGALRM, &sig_action, NULL); -#else /* HAVE_SIGACTION */ - signal(SIGINT, finish); - signal(SIGHUP, finish); - signal(SIGTERM, finish); - signal(SIGALRM, finish); -#endif /* HAVE_SIGACTION */ - if (debug) { - printf("Setting alarm timeout to %u seconds\n", timeout); - } - alarm(timeout); /* make sure we don't wait any longer than necessary */ - gettimeofday(&prog_start, &tz); - max_completion_time = ((targets * packets * pkt_interval) + (targets * target_interval)) + (targets * packets * crit.rta) + crit.rta; + struct timeval prog_start; + gettimeofday(&prog_start, NULL); + + time_t max_completion_time = + ((config.pkt_interval * config.number_of_targets * config.number_of_packets) + + (config.target_interval * config.number_of_targets)) + + (config.crit.rta * config.number_of_targets * config.number_of_packets) + config.crit.rta; if (debug) { printf("packets: %u, targets: %u\n" "target_interval: %0.3f, pkt_interval %0.3f\n" "crit.rta: %0.3f\n" "max_completion_time: %0.3f\n", - packets, targets, (float)target_interval / 1000, (float)pkt_interval / 1000, (float)crit.rta / 1000, - (float)max_completion_time / 1000); + config.number_of_packets, config.number_of_targets, + (float)config.target_interval / 1000, (float)config.pkt_interval / 1000, + (float)config.crit.rta / 1000, (float)max_completion_time / 1000); } if (debug) { - if (max_completion_time > (u_int)timeout * 1000000) { - printf("max_completion_time: %llu timeout: %u\n", max_completion_time, timeout); - printf("Timeout must be at least %llu\n", max_completion_time / 1000000 + 1); + if (max_completion_time > (timeout * 1000000)) { + printf("max_completion_time: %ld timeout: %u\n", max_completion_time, timeout); + printf("Timeout must be at least %ld\n", (max_completion_time / 1000000) + 1); } } if (debug) { - printf("crit = {%u, %u%%}, warn = {%u, %u%%}\n", crit.rta, crit.pl, warn.rta, warn.pl); - printf("pkt_interval: %u target_interval: %u retry_interval: %u\n", pkt_interval, target_interval, retry_interval); - printf("icmp_pkt_size: %u timeout: %u\n", icmp_pkt_size, timeout); + printf("crit = {%ld, %u%%}, warn = {%ld, %u%%}\n", config.crit.rta, config.crit.pl, + config.warn.rta, config.warn.pl); + printf("pkt_interval: %ld target_interval: %ld\n", config.pkt_interval, + config.target_interval); + printf("icmp_pkt_size: %u timeout: %u\n", config.icmp_pkt_size, timeout); } - if (packets > 20) { + if (config.min_hosts_alive < -1) { errno = 0; - crash("packets is > 20 (%d)", packets); + crash("minimum alive hosts is negative (%i)", config.min_hosts_alive); } - if (min_hosts_alive < -1) { - errno = 0; - crash("minimum alive hosts is negative (%i)", min_hosts_alive); - } - - host = list; - table = malloc(sizeof(struct rta_host *) * targets); + // Build an index table of all targets + ping_target *host = config.targets; + ping_target **table = malloc(sizeof(ping_target *) * config.number_of_targets); if (!table) { crash("main(): malloc failed for host table"); } - i = 0; + unsigned short target_index = 0; while (host) { - host->id = i * packets; - table[i] = host; + host->id = target_index * config.number_of_packets; + table[target_index] = host; host = host->next; - i++; + target_index++; } - run_checks(); + time_t pkt_interval = config.pkt_interval; + time_t target_interval = config.target_interval; + + check_icmp_state program_state = check_icmp_state_init(); + + run_checks(config.icmp_data_size, &pkt_interval, &target_interval, config.sender_id, + config.mode, max_completion_time, prog_start, table, config.number_of_packets, + sockset, config.number_of_targets, &program_state); errno = 0; - finish(0); - return (0); + mp_check overall = mp_check_init(); + finish(0, config.modes, config.min_hosts_alive, config.warn, config.crit, + config.number_of_targets, &program_state, config.hosts, config.number_of_hosts, + &overall); + + if (sockset.socket4) { + close(sockset.socket4); + } + if (sockset.socket6) { + close(sockset.socket6); + } + + mp_exit(overall); } -static void run_checks(void) { - u_int i, t; - u_int final_wait, time_passed; - +static void run_checks(unsigned short icmp_pkt_size, time_t *pkt_interval, time_t *target_interval, + const uint16_t sender_id, const check_icmp_execution_mode mode, + const time_t max_completion_time, const struct timeval prog_start, + ping_target **table, const unsigned short packets, + const check_icmp_socket_set sockset, const unsigned short number_of_targets, + check_icmp_state *program_state) { /* this loop might actually violate the pkt_interval or target_interval * settings, but only if there aren't any packets on the wire which * indicates that the target can handle an increased packet rate */ - for (i = 0; i < packets; i++) { - for (t = 0; t < targets; t++) { + for (unsigned int packet_index = 0; packet_index < packets; packet_index++) { + for (unsigned int target_index = 0; target_index < number_of_targets; target_index++) { /* don't send useless packets */ - if (!targets_alive) { - finish(0); + if (!targets_alive(number_of_targets, program_state->targets_down)) { + return; } - if (table[t]->flags & FLAG_LOST_CAUSE) { + if (table[target_index]->flags & FLAG_LOST_CAUSE) { if (debug) { - printf("%s is a lost cause. not sending any more\n", table[t]->name); + + char address[INET6_ADDRSTRLEN]; + parse_address(&table[target_index]->address, address, sizeof(address)); + printf("%s is a lost cause. not sending any more\n", address); } continue; } /* we're still in the game, so send next packet */ - (void)send_icmp_ping(icmp_sock, table[t]); - wait_for_reply(icmp_sock, target_interval); + (void)send_icmp_ping(sockset, table[target_index], icmp_pkt_size, sender_id, + program_state); + + /* wrap up if all targets are declared dead */ + if (targets_alive(number_of_targets, program_state->targets_down) || + get_timevaldiff(prog_start, prog_start) < max_completion_time || + !(mode == MODE_HOSTCHECK && program_state->targets_down)) { + wait_for_reply(sockset, *target_interval, icmp_pkt_size, pkt_interval, + target_interval, sender_id, table, packets, number_of_targets, + program_state); + } + } + if (targets_alive(number_of_targets, program_state->targets_down) || + get_timevaldiff_to_now(prog_start) < max_completion_time || + !(mode == MODE_HOSTCHECK && program_state->targets_down)) { + wait_for_reply(sockset, *pkt_interval * number_of_targets, icmp_pkt_size, pkt_interval, + target_interval, sender_id, table, packets, number_of_targets, + program_state); } - wait_for_reply(icmp_sock, pkt_interval * targets); } - if (icmp_pkts_en_route && targets_alive) { - time_passed = get_timevaldiff(NULL, NULL); - final_wait = max_completion_time - time_passed; + if (icmp_pkts_en_route(program_state->icmp_sent, program_state->icmp_recv, + program_state->icmp_lost) && + targets_alive(number_of_targets, program_state->targets_down)) { + time_t time_passed = get_timevaldiff_to_now(prog_start); + time_t final_wait = max_completion_time - time_passed; if (debug) { - printf("time_passed: %u final_wait: %u max_completion_time: %llu\n", time_passed, final_wait, max_completion_time); + printf("time_passed: %ld final_wait: %ld max_completion_time: %ld\n", time_passed, + final_wait, max_completion_time); } if (time_passed > max_completion_time) { if (debug) { printf("Time passed. Finishing up\n"); } - finish(0); + return; } /* catch the packets that might come in within the timeframe, but * haven't yet */ if (debug) { - printf("Waiting for %u micro-seconds (%0.3f msecs)\n", final_wait, (float)final_wait / 1000); + printf("Waiting for %ld micro-seconds (%0.3f msecs)\n", final_wait, + (float)final_wait / 1000); + } + if (targets_alive(number_of_targets, program_state->targets_down) || + get_timevaldiff_to_now(prog_start) < max_completion_time || + !(mode == MODE_HOSTCHECK && program_state->targets_down)) { + wait_for_reply(sockset, final_wait, icmp_pkt_size, pkt_interval, target_interval, + sender_id, table, packets, number_of_targets, program_state); } - wait_for_reply(icmp_sock, final_wait); } } @@ -939,18 +1063,12 @@ static void run_checks(void) { * both: * icmp echo reply : the rest */ -static int wait_for_reply(int sock, u_int t) { - int n, hlen; - static unsigned char buf[65536]; - struct sockaddr_storage resp_addr; - union ip_hdr *ip; +static int wait_for_reply(check_icmp_socket_set sockset, const time_t time_interval, + unsigned short icmp_pkt_size, time_t *pkt_interval, + time_t *target_interval, uint16_t sender_id, ping_target **table, + const unsigned short packets, const unsigned short number_of_targets, + check_icmp_state *program_state) { union icmp_packet packet; - struct rta_host *host; - struct icmp_ping_data data; - struct timeval wait_start, now; - u_int tdiff, i, per_pkt_wait; - double jitter_tmp; - if (!(packet.buf = malloc(icmp_pkt_size))) { crash("send_icmp_ping(): failed to malloc %d bytes for send buffer", icmp_pkt_size); return -1; /* might be reached if we're in debug mode */ @@ -959,177 +1077,174 @@ static int wait_for_reply(int sock, u_int t) { memset(packet.buf, 0, icmp_pkt_size); /* if we can't listen or don't have anything to listen to, just return */ - if (!t || !icmp_pkts_en_route) { + if (!time_interval || !icmp_pkts_en_route(program_state->icmp_sent, program_state->icmp_recv, + program_state->icmp_lost)) { free(packet.buf); return 0; } - gettimeofday(&wait_start, &tz); + // Get current time stamp + struct timeval wait_start; + gettimeofday(&wait_start, NULL); - i = t; - per_pkt_wait = t / icmp_pkts_en_route; - while (icmp_pkts_en_route && get_timevaldiff(&wait_start, NULL) < i) { - t = per_pkt_wait; - - /* wrap up if all targets are declared dead */ - if (!targets_alive || get_timevaldiff(&prog_start, NULL) >= max_completion_time || (mode == MODE_HOSTCHECK && targets_down)) { - finish(0); - } + struct sockaddr_storage resp_addr; + time_t per_pkt_wait = + time_interval / icmp_pkts_en_route(program_state->icmp_sent, program_state->icmp_recv, + program_state->icmp_lost); + static unsigned char buf[65536]; + union ip_hdr *ip_header; + struct timeval packet_received_timestamp; + while (icmp_pkts_en_route(program_state->icmp_sent, program_state->icmp_recv, + program_state->icmp_lost) && + get_timevaldiff_to_now(wait_start) < time_interval) { + time_t loop_time_interval = per_pkt_wait; /* reap responses until we hit a timeout */ - n = recvfrom_wto(sock, buf, sizeof(buf), (struct sockaddr *)&resp_addr, &t, &now); - if (!n) { + recvfrom_wto_wrapper recv_foo = + recvfrom_wto(sockset, buf, sizeof(buf), (struct sockaddr *)&resp_addr, + &loop_time_interval, &packet_received_timestamp); + if (!recv_foo.received) { if (debug > 1) { - printf("recvfrom_wto() timed out during a %u usecs wait\n", per_pkt_wait); + printf("recvfrom_wto() timed out during a %ld usecs wait\n", per_pkt_wait); } continue; /* timeout for this one, so keep trying */ } - if (n < 0) { + + if (recv_foo.received < 0) { if (debug) { printf("recvfrom_wto() returned errors\n"); } free(packet.buf); - return n; + return (int)recv_foo.received; } - // FIXME: with ipv6 we don't have an ip header here - if (address_family != AF_INET6) { - ip = (union ip_hdr *)buf; + if (recv_foo.recv_proto != AF_INET6) { + ip_header = (union ip_hdr *)buf; if (debug > 1) { char address[INET6_ADDRSTRLEN]; parse_address(&resp_addr, address, sizeof(address)); - printf("received %u bytes from %s\n", address_family == AF_INET6 ? ntohs(ip->ip6.ip6_plen) : ntohs(ip->ip.ip_len), address); + printf("received %u bytes from %s\n", + address_family == AF_INET6 ? ntohs(ip_header->ip6.ip6_plen) + : ntohs(ip_header->ip.ip_len), + address); } } - /* obsolete. alpha on tru64 provides the necessary defines, but isn't broken */ - /* #if defined( __alpha__ ) && __STDC__ && !defined( __GLIBC__ ) */ - /* alpha headers are decidedly broken. Using an ansi compiler, - * they provide ip_vhl instead of ip_hl and ip_v, so we mask - * off the bottom 4 bits */ - /* hlen = (ip->ip_vhl & 0x0f) << 2; */ - /* #else */ - hlen = (address_family == AF_INET6) ? 0 : ip->ip.ip_hl << 2; - /* #endif */ + int hlen = (recv_foo.recv_proto == AF_INET6) ? 0 : ip_header->ip.ip_hl << 2; - if (n < (hlen + ICMP_MINLEN)) { + if (recv_foo.received < (hlen + ICMP_MINLEN)) { char address[INET6_ADDRSTRLEN]; parse_address(&resp_addr, address, sizeof(address)); - crash("received packet too short for ICMP (%d bytes, expected %d) from %s\n", n, hlen + icmp_pkt_size, address); + crash("received packet too short for ICMP (%ld bytes, expected %d) from %s\n", + recv_foo.received, hlen + icmp_pkt_size, address); } - /* else if(debug) { */ - /* printf("ip header size: %u, packet size: %u (expected %u, %u)\n", */ - /* hlen, ntohs(ip->ip_len) - hlen, */ - /* sizeof(struct ip), icmp_pkt_size); */ - /* } */ - /* check the response */ - memcpy(packet.buf, buf + hlen, icmp_pkt_size); - /* address_family == AF_INET6 ? sizeof(struct icmp6_hdr) - : sizeof(struct icmp));*/ - if ((address_family == PF_INET && (ntohs(packet.icp->icmp_id) != pid || packet.icp->icmp_type != ICMP_ECHOREPLY || - ntohs(packet.icp->icmp_seq) >= targets * packets)) || - (address_family == PF_INET6 && (ntohs(packet.icp6->icmp6_id) != pid || packet.icp6->icmp6_type != ICMP6_ECHO_REPLY || - ntohs(packet.icp6->icmp6_seq) >= targets * packets))) { + if ((recv_foo.recv_proto == AF_INET && + (ntohs(packet.icp->icmp_id) != sender_id || packet.icp->icmp_type != ICMP_ECHOREPLY || + ntohs(packet.icp->icmp_seq) >= number_of_targets * packets)) || + (recv_foo.recv_proto == AF_INET6 && + (ntohs(packet.icp6->icmp6_id) != sender_id || + packet.icp6->icmp6_type != ICMP6_ECHO_REPLY || + ntohs(packet.icp6->icmp6_seq) >= number_of_targets * packets))) { if (debug > 2) { printf("not a proper ICMP_ECHOREPLY\n"); } - handle_random_icmp(buf + hlen, &resp_addr); + + handle_random_icmp(buf + hlen, &resp_addr, pkt_interval, target_interval, sender_id, + table, packets, number_of_targets, program_state); + continue; } /* this is indeed a valid response */ - if (address_family == PF_INET) { + ping_target *target; + struct icmp_ping_data data; + if (address_family == AF_INET) { memcpy(&data, packet.icp->icmp_data, sizeof(data)); if (debug > 2) { - printf("ICMP echo-reply of len %lu, id %u, seq %u, cksum 0x%X\n", (unsigned long)sizeof(data), ntohs(packet.icp->icmp_id), - ntohs(packet.icp->icmp_seq), packet.icp->icmp_cksum); + printf("ICMP echo-reply of len %lu, id %u, seq %u, cksum 0x%X\n", sizeof(data), + ntohs(packet.icp->icmp_id), ntohs(packet.icp->icmp_seq), + packet.icp->icmp_cksum); } - host = table[ntohs(packet.icp->icmp_seq) / packets]; + target = table[ntohs(packet.icp->icmp_seq) / packets]; } else { memcpy(&data, &packet.icp6->icmp6_dataun.icmp6_un_data8[4], sizeof(data)); if (debug > 2) { - printf("ICMP echo-reply of len %lu, id %u, seq %u, cksum 0x%X\n", (unsigned long)sizeof(data), ntohs(packet.icp6->icmp6_id), - ntohs(packet.icp6->icmp6_seq), packet.icp6->icmp6_cksum); + printf("ICMP echo-reply of len %lu, id %u, seq %u, cksum 0x%X\n", sizeof(data), + ntohs(packet.icp6->icmp6_id), ntohs(packet.icp6->icmp6_seq), + packet.icp6->icmp6_cksum); } - host = table[ntohs(packet.icp6->icmp6_seq) / packets]; + target = table[ntohs(packet.icp6->icmp6_seq) / packets]; } - tdiff = get_timevaldiff(&data.stime, &now); + time_t tdiff = get_timevaldiff(data.stime, packet_received_timestamp); - if (host->last_tdiff > 0) { + if (target->last_tdiff > 0) { /* Calculate jitter */ - if (host->last_tdiff > tdiff) { - jitter_tmp = host->last_tdiff - tdiff; + double jitter_tmp; + if (target->last_tdiff > tdiff) { + jitter_tmp = (double)(target->last_tdiff - tdiff); } else { - jitter_tmp = tdiff - host->last_tdiff; + jitter_tmp = (double)(tdiff - target->last_tdiff); } - if (host->jitter == 0) { - host->jitter = jitter_tmp; - host->jitter_max = jitter_tmp; - host->jitter_min = jitter_tmp; + if (target->jitter == 0) { + target->jitter = jitter_tmp; + target->jitter_max = jitter_tmp; + target->jitter_min = jitter_tmp; } else { - host->jitter += jitter_tmp; + target->jitter += jitter_tmp; - if (jitter_tmp < host->jitter_min) { - host->jitter_min = jitter_tmp; + if (jitter_tmp < target->jitter_min) { + target->jitter_min = jitter_tmp; } - if (jitter_tmp > host->jitter_max) { - host->jitter_max = jitter_tmp; + if (jitter_tmp > target->jitter_max) { + target->jitter_max = jitter_tmp; } } /* Check if packets in order */ - if (host->last_icmp_seq >= packet.icp->icmp_seq) { - host->order_status = STATE_CRITICAL; + if (target->last_icmp_seq >= packet.icp->icmp_seq) { + target->found_out_of_order_packets = true; } } - host->last_tdiff = tdiff; + target->last_tdiff = tdiff; - host->last_icmp_seq = packet.icp->icmp_seq; + target->last_icmp_seq = packet.icp->icmp_seq; - host->time_waited += tdiff; - host->icmp_recv++; - icmp_recv++; + target->time_waited += tdiff; + target->icmp_recv++; + program_state->icmp_recv++; - if (tdiff > (unsigned int)host->rtmax) { - host->rtmax = tdiff; + if (tdiff > (unsigned int)target->rtmax) { + target->rtmax = (double)tdiff; } - if ((host->rtmin == INFINITY) || (tdiff < (unsigned int)host->rtmin)) { - host->rtmin = tdiff; + if ((target->rtmin == INFINITY) || (tdiff < (unsigned int)target->rtmin)) { + target->rtmin = (double)tdiff; } if (debug) { char address[INET6_ADDRSTRLEN]; parse_address(&resp_addr, address, sizeof(address)); - switch (address_family) { + switch (recv_foo.recv_proto) { case AF_INET: { - printf("%0.3f ms rtt from %s, outgoing ttl: %u, incoming ttl: %u, max: %0.3f, min: %0.3f\n", (float)tdiff / 1000, address, - ttl, ip->ip.ip_ttl, (float)host->rtmax / 1000, (float)host->rtmin / 1000); + printf("%0.3f ms rtt from %s, incoming ttl: %u, max: %0.3f, min: %0.3f\n", + (float)tdiff / 1000, address, ip_header->ip.ip_ttl, + (float)target->rtmax / 1000, (float)target->rtmin / 1000); break; }; case AF_INET6: { - printf("%0.3f ms rtt from %s, outgoing ttl: %u, max: %0.3f, min: %0.3f\n", (float)tdiff / 1000, address, ttl, - (float)host->rtmax / 1000, (float)host->rtmin / 1000); + printf("%0.3f ms rtt from %s, max: %0.3f, min: %0.3f\n", (float)tdiff / 1000, + address, (float)target->rtmax / 1000, (float)target->rtmin / 1000); }; } } - - /* if we're in hostcheck mode, exit with limited printouts */ - if (mode == MODE_HOSTCHECK) { - printf("OK - %s responds to ICMP. Packet %u, rta %0.3fms|" - "pkt=%u;;;0;%u rta=%0.3f;%0.3f;%0.3f;;\n", - host->name, icmp_recv, (float)tdiff / 1000, icmp_recv, packets, (float)tdiff / 1000, (float)warn.rta / 1000, - (float)crit.rta / 1000); - exit(STATE_OK); - } } free(packet.buf); @@ -1137,38 +1252,28 @@ static int wait_for_reply(int sock, u_int t) { } /* the ping functions */ -static int send_icmp_ping(int sock, struct rta_host *host) { - long int len; - size_t addrlen; - struct icmp_ping_data data; - struct msghdr hdr; - struct iovec iov; - struct timeval tv; - void *buf = NULL; - - if (sock == -1) { - errno = 0; - crash("Attempt to send on bogus socket"); - return -1; - } - +static int send_icmp_ping(const check_icmp_socket_set sockset, ping_target *host, + const unsigned short icmp_pkt_size, const uint16_t sender_id, + check_icmp_state *program_state) { + void *buf = calloc(1, icmp_pkt_size); if (!buf) { - if (!(buf = malloc(icmp_pkt_size))) { - crash("send_icmp_ping(): failed to malloc %d bytes for send buffer", icmp_pkt_size); - return -1; /* might be reached if we're in debug mode */ - } + crash("send_icmp_ping(): failed to malloc %d bytes for send buffer", icmp_pkt_size); + return -1; /* might be reached if we're in debug mode */ } - memset(buf, 0, icmp_pkt_size); - if ((gettimeofday(&tv, &tz)) == -1) { + struct timeval current_time; + if ((gettimeofday(¤t_time, NULL)) == -1) { free(buf); return -1; } + struct icmp_ping_data data; data.ping_id = 10; /* host->icmp.icmp_sent; */ - memcpy(&data.stime, &tv, sizeof(tv)); + memcpy(&data.stime, ¤t_time, sizeof(current_time)); - if (address_family == AF_INET) { + socklen_t addrlen = 0; + + if (host->address.ss_family == AF_INET) { struct icmp *icp = (struct icmp *)buf; addrlen = sizeof(struct sockaddr_in); @@ -1177,15 +1282,19 @@ static int send_icmp_ping(int sock, struct rta_host *host) { icp->icmp_type = ICMP_ECHO; icp->icmp_code = 0; icp->icmp_cksum = 0; - icp->icmp_id = htons(pid); + icp->icmp_id = htons((uint16_t)sender_id); icp->icmp_seq = htons(host->id++); icp->icmp_cksum = icmp_checksum((uint16_t *)buf, (size_t)icmp_pkt_size); if (debug > 2) { - printf("Sending ICMP echo-request of len %lu, id %u, seq %u, cksum 0x%X to host %s\n", (unsigned long)sizeof(data), - ntohs(icp->icmp_id), ntohs(icp->icmp_seq), icp->icmp_cksum, host->name); + char address[INET6_ADDRSTRLEN]; + parse_address((&host->address), address, sizeof(address)); + + printf("Sending ICMP echo-request of len %lu, id %u, seq %u, cksum 0x%X to host %s\n", + sizeof(data), ntohs(icp->icmp_id), ntohs(icp->icmp_seq), icp->icmp_cksum, + address); } - } else { + } else if (host->address.ss_family == AF_INET6) { struct icmp6_hdr *icp6 = (struct icmp6_hdr *)buf; addrlen = sizeof(struct sockaddr_in6); @@ -1194,659 +1303,439 @@ static int send_icmp_ping(int sock, struct rta_host *host) { icp6->icmp6_type = ICMP6_ECHO_REQUEST; icp6->icmp6_code = 0; icp6->icmp6_cksum = 0; - icp6->icmp6_id = htons(pid); + icp6->icmp6_id = htons((uint16_t)sender_id); icp6->icmp6_seq = htons(host->id++); // let checksum be calculated automatically if (debug > 2) { - printf("Sending ICMP echo-request of len %lu, id %u, seq %u, cksum 0x%X to host %s\n", (unsigned long)sizeof(data), - ntohs(icp6->icmp6_id), ntohs(icp6->icmp6_seq), icp6->icmp6_cksum, host->name); + char address[INET6_ADDRSTRLEN]; + parse_address((&host->address), address, sizeof(address)); + + printf("Sending ICMP echo-request of len %lu, id %u, seq %u, cksum 0x%X to target %s\n", + sizeof(data), ntohs(icp6->icmp6_id), ntohs(icp6->icmp6_seq), icp6->icmp6_cksum, + address); } + } else { + // unknown address family + crash("unknown address family in %s", __func__); } + struct iovec iov; memset(&iov, 0, sizeof(iov)); iov.iov_base = buf; iov.iov_len = icmp_pkt_size; + struct msghdr hdr; memset(&hdr, 0, sizeof(hdr)); - hdr.msg_name = (struct sockaddr *)&host->saddr_in; + hdr.msg_name = (struct sockaddr *)&host->address; hdr.msg_namelen = addrlen; hdr.msg_iov = &iov; hdr.msg_iovlen = 1; errno = 0; -/* MSG_CONFIRM is a linux thing and only available on linux kernels >= 2.3.15, see send(2) */ + long int len; + /* MSG_CONFIRM is a linux thing and only available on linux kernels >= 2.3.15, see send(2) */ + if (host->address.ss_family == AF_INET) { #ifdef MSG_CONFIRM - len = sendmsg(sock, &hdr, MSG_CONFIRM); + len = sendmsg(sockset.socket4, &hdr, MSG_CONFIRM); #else - len = sendmsg(sock, &hdr, 0); + len = sendmsg(sockset.socket4, &hdr, 0); #endif + } else if (host->address.ss_family == AF_INET6) { +#ifdef MSG_CONFIRM + len = sendmsg(sockset.socket6, &hdr, MSG_CONFIRM); +#else + len = sendmsg(sockset.socket6, &hdr, 0); +#endif + } else { + assert(false); + } free(buf); if (len < 0 || (unsigned int)len != icmp_pkt_size) { if (debug) { char address[INET6_ADDRSTRLEN]; - parse_address((struct sockaddr_storage *)&host->saddr_in, address, sizeof(address)); + parse_address((&host->address), address, sizeof(address)); printf("Failed to send ping to %s: %s\n", address, strerror(errno)); } errno = 0; return -1; } - icmp_sent++; + program_state->icmp_sent++; host->icmp_sent++; return 0; } -static int recvfrom_wto(int sock, void *buf, unsigned int len, struct sockaddr *saddr, u_int *timo, struct timeval *tv) { - u_int slen; - int n, ret; - struct timeval to, then, now; - fd_set rd, wr; +static recvfrom_wto_wrapper recvfrom_wto(const check_icmp_socket_set sockset, void *buf, + const unsigned int len, struct sockaddr *saddr, + time_t *timeout, struct timeval *received_timestamp) { #ifdef HAVE_MSGHDR_MSG_CONTROL char ans_data[4096]; #endif // HAVE_MSGHDR_MSG_CONTROL - struct msghdr hdr; - struct iovec iov; #ifdef SO_TIMESTAMP struct cmsghdr *chdr; #endif - if (!*timo) { + recvfrom_wto_wrapper result = { + .received = 0, + .recv_proto = AF_UNSPEC, + }; + + if (!*timeout) { if (debug) { - printf("*timo is not\n"); + printf("*timeout is not\n"); } - return 0; + return result; } - to.tv_sec = *timo / 1000000; - to.tv_usec = (*timo - (to.tv_sec * 1000000)); + struct timeval real_timeout; + real_timeout.tv_sec = *timeout / 1000000; + real_timeout.tv_usec = (*timeout - (real_timeout.tv_sec * 1000000)); + + // Dummy fds for select + fd_set dummy_write_fds; + FD_ZERO(&dummy_write_fds); + + // Read fds for select with the socket + fd_set read_fds; + FD_ZERO(&read_fds); + + if (sockset.socket4 != -1) { + FD_SET(sockset.socket4, &read_fds); + } + if (sockset.socket6 != -1) { + FD_SET(sockset.socket6, &read_fds); + } + + int nfds = (sockset.socket4 > sockset.socket6 ? sockset.socket4 : sockset.socket6) + 1; + + struct timeval then; + gettimeofday(&then, NULL); - FD_ZERO(&rd); - FD_ZERO(&wr); - FD_SET(sock, &rd); errno = 0; - gettimeofday(&then, &tz); - n = select(sock + 1, &rd, &wr, NULL, &to); - if (n < 0) { + int select_return = select(nfds, &read_fds, &dummy_write_fds, NULL, &real_timeout); + if (select_return < 0) { crash("select() in recvfrom_wto"); } - gettimeofday(&now, &tz); - *timo = get_timevaldiff(&then, &now); - if (!n) { - return 0; /* timeout */ + struct timeval now; + gettimeofday(&now, NULL); + *timeout = get_timevaldiff(then, now); + + if (!select_return) { + return result; /* timeout */ } - slen = sizeof(struct sockaddr_storage); + unsigned int slen = sizeof(struct sockaddr_storage); - memset(&iov, 0, sizeof(iov)); - iov.iov_base = buf; - iov.iov_len = len; + struct iovec iov = { + .iov_base = buf, + .iov_len = len, + }; - memset(&hdr, 0, sizeof(hdr)); - hdr.msg_name = saddr; - hdr.msg_namelen = slen; - hdr.msg_iov = &iov; - hdr.msg_iovlen = 1; + struct msghdr hdr = { + .msg_name = saddr, + .msg_namelen = slen, + .msg_iov = &iov, + .msg_iovlen = 1, #ifdef HAVE_MSGHDR_MSG_CONTROL - hdr.msg_control = ans_data; - hdr.msg_controllen = sizeof(ans_data); + .msg_control = ans_data, + .msg_controllen = sizeof(ans_data), #endif + }; + + ssize_t ret; + if (FD_ISSET(sockset.socket4, &read_fds)) { + ret = recvmsg(sockset.socket4, &hdr, 0); + result.recv_proto = AF_INET; + } else if (FD_ISSET(sockset.socket6, &read_fds)) { + ret = recvmsg(sockset.socket6, &hdr, 0); + result.recv_proto = AF_INET6; + } else { + assert(false); + } + + result.received = ret; - ret = recvmsg(sock, &hdr, 0); #ifdef SO_TIMESTAMP for (chdr = CMSG_FIRSTHDR(&hdr); chdr; chdr = CMSG_NXTHDR(&hdr, chdr)) { - if (chdr->cmsg_level == SOL_SOCKET && chdr->cmsg_type == SO_TIMESTAMP && chdr->cmsg_len >= CMSG_LEN(sizeof(struct timeval))) { - memcpy(tv, CMSG_DATA(chdr), sizeof(*tv)); + if (chdr->cmsg_level == SOL_SOCKET && chdr->cmsg_type == SO_TIMESTAMP && + chdr->cmsg_len >= CMSG_LEN(sizeof(struct timeval))) { + memcpy(received_timestamp, CMSG_DATA(chdr), sizeof(*received_timestamp)); break; } } - if (!chdr) + if (!chdr) { + gettimeofday(received_timestamp, NULL); + } +#else + gettimeofday(tv, NULL); #endif // SO_TIMESTAMP - gettimeofday(tv, &tz); - return (ret); + + return (result); } -static void finish(int sig) { - u_int i = 0; - unsigned char pl; - double rta; - struct rta_host *host; - const char *status_string[] = {"OK", "WARNING", "CRITICAL", "UNKNOWN", "DEPENDENT"}; - int hosts_ok = 0; - int hosts_warn = 0; - int this_status; - double R; - +static void finish(int sig, check_icmp_mode_switches modes, int min_hosts_alive, + check_icmp_threshold warn, check_icmp_threshold crit, + const unsigned short number_of_targets, check_icmp_state *program_state, + check_icmp_target_container host_list[], unsigned short number_of_hosts, + mp_check overall[static 1]) { + // Deactivate alarm alarm(0); + if (debug > 1) { printf("finish(%d) called\n", sig); } - if (icmp_sock != -1) { - close(icmp_sock); - } - if (udp_sock != -1) { - close(udp_sock); - } - if (tcp_sock != -1) { - close(tcp_sock); - } - if (debug) { - printf("icmp_sent: %u icmp_recv: %u icmp_lost: %u\n", icmp_sent, icmp_recv, icmp_lost); - printf("targets: %u targets_alive: %u\n", targets, targets_alive); + printf("icmp_sent: %u icmp_recv: %u icmp_lost: %u\n", program_state->icmp_sent, + program_state->icmp_recv, program_state->icmp_lost); + printf("targets: %u targets_alive: %u\n", number_of_targets, + targets_alive(number_of_targets, program_state->targets_down)); } - /* iterate thrice to calculate values, give output, and print perfparse */ - status = STATE_OK; - host = list; + // loop over targets to evaluate each one + int targets_ok = 0; + int targets_warn = 0; + for (unsigned short i = 0; i < number_of_hosts; i++) { + evaluate_host_wrapper host_check = evaluate_host(host_list[i], modes, warn, crit); - while (host) { - this_status = STATE_OK; + targets_ok += host_check.targets_ok; + targets_warn += host_check.targets_warn; - if (!host->icmp_recv) { - /* rta 0 is ofcourse not entirely correct, but will still show up - * conspicuously as missing entries in perfparse and cacti */ - pl = 100; - rta = 0; - status = STATE_CRITICAL; - /* up the down counter if not already counted */ - if (!(host->flags & FLAG_LOST_CAUSE) && targets_alive) { - targets_down++; - } - } else { - pl = ((host->icmp_sent - host->icmp_recv) * 100) / host->icmp_sent; - rta = (double)host->time_waited / host->icmp_recv; - } - - if (host->icmp_recv > 1) { - /* - * This algorithm is probably pretty much blindly copied from - * locations like this one: https://www.slac.stanford.edu/comp/net/wan-mon/tutorial.html#mos - * It calculates a MOS value (range of 1 to 5, where 1 is bad and 5 really good). - * According to some quick research MOS originates from the Audio/Video transport network area. - * Whether it can and should be computed from ICMP data, I can not say. - * - * Anyway the basic idea is to map a value "R" with a range of 0-100 to the MOS value - * - * MOS stands likely for Mean Opinion Score ( https://en.wikipedia.org/wiki/Mean_Opinion_Score ) - * - * More links: - * - https://confluence.slac.stanford.edu/display/IEPM/MOS - */ - host->jitter = (host->jitter / (host->icmp_recv - 1) / 1000); - - /* - * Take the average round trip latency (in milliseconds), add - * round trip jitter, but double the impact to latency - * then add 10 for protocol latencies (in milliseconds). - */ - host->EffectiveLatency = (rta / 1000) + host->jitter * 2 + 10; - - if (host->EffectiveLatency < 160) { - R = 93.2 - (host->EffectiveLatency / 40); - } else { - R = 93.2 - ((host->EffectiveLatency - 120) / 10); - } - - // Now, let us deduct 2.5 R values per percentage of packet loss (i.e. a - // loss of 5% will be entered as 5). - R = R - (pl * 2.5); - - if (R < 0) { - R = 0; - } - - host->score = R; - host->mos = 1 + ((0.035) * R) + ((.000007) * R * (R - 60) * (100 - R)); - } else { - host->jitter = 0; - host->jitter_min = 0; - host->jitter_max = 0; - host->mos = 0; - } - - host->pl = pl; - host->rta = rta; - - /* if no new mode selected, use old schema */ - if (!rta_mode && !pl_mode && !jitter_mode && !score_mode && !mos_mode && !order_mode) { - rta_mode = true; - pl_mode = true; - } - - /* Check which mode is on and do the warn / Crit stuff */ - if (rta_mode) { - if (rta >= crit.rta) { - this_status = STATE_CRITICAL; - status = STATE_CRITICAL; - host->rta_status = STATE_CRITICAL; - } else if (status != STATE_CRITICAL && (rta >= warn.rta)) { - this_status = (this_status <= STATE_WARNING ? STATE_WARNING : this_status); - status = STATE_WARNING; - host->rta_status = STATE_WARNING; - } - } - - if (pl_mode) { - if (pl >= crit.pl) { - this_status = STATE_CRITICAL; - status = STATE_CRITICAL; - host->pl_status = STATE_CRITICAL; - } else if (status != STATE_CRITICAL && (pl >= warn.pl)) { - this_status = (this_status <= STATE_WARNING ? STATE_WARNING : this_status); - status = STATE_WARNING; - host->pl_status = STATE_WARNING; - } - } - - if (jitter_mode) { - if (host->jitter >= crit.jitter) { - this_status = STATE_CRITICAL; - status = STATE_CRITICAL; - host->jitter_status = STATE_CRITICAL; - } else if (status != STATE_CRITICAL && (host->jitter >= warn.jitter)) { - this_status = (this_status <= STATE_WARNING ? STATE_WARNING : this_status); - status = STATE_WARNING; - host->jitter_status = STATE_WARNING; - } - } - - if (mos_mode) { - if (host->mos <= crit.mos) { - this_status = STATE_CRITICAL; - status = STATE_CRITICAL; - host->mos_status = STATE_CRITICAL; - } else if (status != STATE_CRITICAL && (host->mos <= warn.mos)) { - this_status = (this_status <= STATE_WARNING ? STATE_WARNING : this_status); - status = STATE_WARNING; - host->mos_status = STATE_WARNING; - } - } - - if (score_mode) { - if (host->score <= crit.score) { - this_status = STATE_CRITICAL; - status = STATE_CRITICAL; - host->score_status = STATE_CRITICAL; - } else if (status != STATE_CRITICAL && (host->score <= warn.score)) { - this_status = (this_status <= STATE_WARNING ? STATE_WARNING : this_status); - status = STATE_WARNING; - host->score_status = STATE_WARNING; - } - } - - if (this_status == STATE_WARNING) { - hosts_warn++; - } else if (this_status == STATE_OK) { - hosts_ok++; - } - - host = host->next; + mp_add_subcheck_to_check(overall, host_check.sc_host); } /* this is inevitable */ - if (!targets_alive) { - status = STATE_CRITICAL; - } - if (min_hosts_alive > -1) { - if (hosts_ok >= min_hosts_alive) { - status = STATE_OK; - } else if ((hosts_ok + hosts_warn) >= min_hosts_alive) { - status = STATE_WARNING; - } - } - printf("%s - ", status_string[status]); - - host = list; - while (host) { - if (debug) { - puts(""); - } - - if (i) { - if (i < targets) { - printf(" :: "); - } else { - printf("\n"); - } - } - - i++; - - if (!host->icmp_recv) { - status = STATE_CRITICAL; - host->rtmin = 0; - host->jitter_min = 0; - - if (host->flags & FLAG_LOST_CAUSE) { - char address[INET6_ADDRSTRLEN]; - parse_address(&host->error_addr, address, sizeof(address)); - printf("%s: %s @ %s. rta nan, lost %d%%", host->name, get_icmp_error_msg(host->icmp_type, host->icmp_code), address, 100); - } else { /* not marked as lost cause, so we have no flags for it */ - printf("%s: rta nan, lost 100%%", host->name); - } - } else { /* !icmp_recv */ - printf("%s", host->name); - /* rta text output */ - if (rta_mode) { - if (status == STATE_OK) { - printf(" rta %0.3fms", host->rta / 1000); - } else if (status == STATE_WARNING && host->rta_status == status) { - printf(" rta %0.3fms > %0.3fms", (float)host->rta / 1000, (float)warn.rta / 1000); - } else if (status == STATE_CRITICAL && host->rta_status == status) { - printf(" rta %0.3fms > %0.3fms", (float)host->rta / 1000, (float)crit.rta / 1000); - } - } - - /* pl text output */ - if (pl_mode) { - if (status == STATE_OK) { - printf(" lost %u%%", host->pl); - } else if (status == STATE_WARNING && host->pl_status == status) { - printf(" lost %u%% > %u%%", host->pl, warn.pl); - } else if (status == STATE_CRITICAL && host->pl_status == status) { - printf(" lost %u%% > %u%%", host->pl, crit.pl); - } - } - - /* jitter text output */ - if (jitter_mode) { - if (status == STATE_OK) { - printf(" jitter %0.3fms", (float)host->jitter); - } else if (status == STATE_WARNING && host->jitter_status == status) { - printf(" jitter %0.3fms > %0.3fms", (float)host->jitter, warn.jitter); - } else if (status == STATE_CRITICAL && host->jitter_status == status) { - printf(" jitter %0.3fms > %0.3fms", (float)host->jitter, crit.jitter); - } - } - - /* mos text output */ - if (mos_mode) { - if (status == STATE_OK) { - printf(" MOS %0.1f", (float)host->mos); - } else if (status == STATE_WARNING && host->mos_status == status) { - printf(" MOS %0.1f < %0.1f", (float)host->mos, (float)warn.mos); - } else if (status == STATE_CRITICAL && host->mos_status == status) { - printf(" MOS %0.1f < %0.1f", (float)host->mos, (float)crit.mos); - } - } - - /* score text output */ - if (score_mode) { - if (status == STATE_OK) { - printf(" Score %u", (int)host->score); - } else if (status == STATE_WARNING && host->score_status == status) { - printf(" Score %u < %u", (int)host->score, (int)warn.score); - } else if (status == STATE_CRITICAL && host->score_status == status) { - printf(" Score %u < %u", (int)host->score, (int)crit.score); - } - } - - /* order statis text output */ - if (order_mode) { - if (status == STATE_OK) { - printf(" Packets in order"); - } else if (status == STATE_CRITICAL && host->order_status == status) { - printf(" Packets out of order"); - } - } - } - host = host->next; - } - - /* iterate once more for pretty perfparse output */ - if (!(!rta_mode && !pl_mode && !jitter_mode && !score_mode && !mos_mode && order_mode)) { - printf("|"); - } - i = 0; - host = list; - while (host) { - if (debug) { - puts(""); - } - - if (rta_mode) { - if (host->pl < 100) { - printf("%srta=%0.3fms;%0.3f;%0.3f;0; %srtmax=%0.3fms;;;; %srtmin=%0.3fms;;;; ", (targets > 1) ? host->name : "", - host->rta / 1000, (float)warn.rta / 1000, (float)crit.rta / 1000, (targets > 1) ? host->name : "", - (float)host->rtmax / 1000, (targets > 1) ? host->name : "", - (host->rtmin < INFINITY) ? (float)host->rtmin / 1000 : (float)0); - } else { - printf("%srta=U;;;; %srtmax=U;;;; %srtmin=U;;;; ", (targets > 1) ? host->name : "", (targets > 1) ? host->name : "", - (targets > 1) ? host->name : ""); - } - } - - if (pl_mode) { - printf("%spl=%u%%;%u;%u;0;100 ", (targets > 1) ? host->name : "", host->pl, warn.pl, crit.pl); - } - - if (jitter_mode) { - if (host->pl < 100) { - printf("%sjitter_avg=%0.3fms;%0.3f;%0.3f;0; %sjitter_max=%0.3fms;;;; %sjitter_min=%0.3fms;;;; ", - (targets > 1) ? host->name : "", (float)host->jitter, (float)warn.jitter, (float)crit.jitter, - (targets > 1) ? host->name : "", (float)host->jitter_max / 1000, (targets > 1) ? host->name : "", - (float)host->jitter_min / 1000); - } else { - printf("%sjitter_avg=U;;;; %sjitter_max=U;;;; %sjitter_min=U;;;; ", (targets > 1) ? host->name : "", - (targets > 1) ? host->name : "", (targets > 1) ? host->name : ""); - } - } - - if (mos_mode) { - if (host->pl < 100) { - printf("%smos=%0.1f;%0.1f;%0.1f;0;5 ", (targets > 1) ? host->name : "", (float)host->mos, (float)warn.mos, (float)crit.mos); - } else { - printf("%smos=U;;;; ", (targets > 1) ? host->name : ""); - } - } - - if (score_mode) { - if (host->pl < 100) { - printf("%sscore=%u;%u;%u;0;100 ", (targets > 1) ? host->name : "", (int)host->score, (int)warn.score, (int)crit.score); - } else { - printf("%sscore=U;;;; ", (targets > 1) ? host->name : ""); - } - } - - host = host->next; - } + // if (targets_alive(number_of_targets, program_state->targets_down) == 0) { + // mp_subcheck sc_no_target_alive = mp_subcheck_init(); + // sc_no_target_alive = mp_set_subcheck_state(sc_no_target_alive, STATE_CRITICAL); + // sc_no_target_alive.output = strdup("No target is alive!"); + // mp_add_subcheck_to_check(overall, sc_no_target_alive); + // } if (min_hosts_alive > -1) { - if (hosts_ok >= min_hosts_alive) { - status = STATE_OK; - } else if ((hosts_ok + hosts_warn) >= min_hosts_alive) { - status = STATE_WARNING; + mp_subcheck sc_min_targets_alive = mp_subcheck_init(); + sc_min_targets_alive = mp_set_subcheck_default_state(sc_min_targets_alive, STATE_OK); + + if (targets_ok >= min_hosts_alive) { + sc_min_targets_alive = mp_set_subcheck_state(sc_min_targets_alive, STATE_OK); + xasprintf(&sc_min_targets_alive.output, "%u targets OK of a minimum of %u", targets_ok, + min_hosts_alive); + + // Overwrite main state here + overall->evaluation_function = &mp_eval_ok; + } else if ((targets_ok + targets_warn) >= min_hosts_alive) { + sc_min_targets_alive = mp_set_subcheck_state(sc_min_targets_alive, STATE_WARNING); + xasprintf(&sc_min_targets_alive.output, "%u targets OK or Warning of a minimum of %u", + targets_ok + targets_warn, min_hosts_alive); + overall->evaluation_function = &mp_eval_warning; + } else { + sc_min_targets_alive = mp_set_subcheck_state(sc_min_targets_alive, STATE_CRITICAL); + xasprintf(&sc_min_targets_alive.output, "%u targets OK or Warning of a minimum of %u", + targets_ok + targets_warn, min_hosts_alive); + overall->evaluation_function = &mp_eval_critical; } + + mp_add_subcheck_to_check(overall, sc_min_targets_alive); } /* finish with an empty line */ - puts(""); if (debug) { - printf("targets: %u, targets_alive: %u, hosts_ok: %u, hosts_warn: %u, min_hosts_alive: %i\n", targets, targets_alive, hosts_ok, - hosts_warn, min_hosts_alive); + printf( + "targets: %u, targets_alive: %u, hosts_ok: %u, hosts_warn: %u, min_hosts_alive: %i\n", + number_of_targets, targets_alive(number_of_targets, program_state->targets_down), + targets_ok, targets_warn, min_hosts_alive); } - - exit(status); } -static u_int get_timevaldiff(struct timeval *early, struct timeval *later) { - u_int ret; - struct timeval now; - - if (!later) { - gettimeofday(&now, &tz); - later = &now; - } - if (!early) { - early = &prog_start; - } - +static time_t get_timevaldiff(const struct timeval earlier, const struct timeval later) { /* if early > later we return 0 so as to indicate a timeout */ - if (early->tv_sec > later->tv_sec || (early->tv_sec == later->tv_sec && early->tv_usec > later->tv_usec)) { + if (earlier.tv_sec > later.tv_sec || + (earlier.tv_sec == later.tv_sec && earlier.tv_usec > later.tv_usec)) { return 0; } - ret = (later->tv_sec - early->tv_sec) * 1000000; - ret += later->tv_usec - early->tv_usec; + + time_t ret = (later.tv_sec - earlier.tv_sec) * 1000000; + ret += later.tv_usec - earlier.tv_usec; return ret; } -static int add_target_ip(char *arg, struct sockaddr_storage *in) { - struct rta_host *host; - struct sockaddr_in *sin, *host_sin; - struct sockaddr_in6 *sin6, *host_sin6; +static time_t get_timevaldiff_to_now(struct timeval earlier) { + struct timeval now; + gettimeofday(&now, NULL); - if (address_family == AF_INET) { - sin = (struct sockaddr_in *)in; - } else { - sin6 = (struct sockaddr_in6 *)in; + return get_timevaldiff(earlier, now); +} + +static add_target_ip_wrapper add_target_ip(struct sockaddr_storage address) { + assert((address.ss_family == AF_INET) || (address.ss_family == AF_INET6)); + + if (debug) { + char straddr[INET6_ADDRSTRLEN]; + parse_address((&address), straddr, sizeof(straddr)); + printf("add_target_ip called with: %s\n", straddr); } + struct sockaddr_in *sin; + struct sockaddr_in6 *sin6; + if (address.ss_family == AF_INET) { + sin = (struct sockaddr_in *)&address; + } else if (address.ss_family == AF_INET6) { + sin6 = (struct sockaddr_in6 *)&address; + } else { + assert(false); + } + + add_target_ip_wrapper result = { + .error_code = OK, + .target = NULL, + }; /* disregard obviously stupid addresses * (I didn't find an ipv6 equivalent to INADDR_NONE) */ - if (((address_family == AF_INET && (sin->sin_addr.s_addr == INADDR_NONE || sin->sin_addr.s_addr == INADDR_ANY))) || - (address_family == AF_INET6 && (sin6->sin6_addr.s6_addr == in6addr_any.s6_addr))) { - return -1; + if (((address.ss_family == AF_INET && + (sin->sin_addr.s_addr == INADDR_NONE || sin->sin_addr.s_addr == INADDR_ANY))) || + (address.ss_family == AF_INET6 && (sin6->sin6_addr.s6_addr == in6addr_any.s6_addr))) { + result.error_code = ERROR; + return result; } - /* no point in adding two identical IP's, so don't. ;) */ - host = list; - while (host) { - host_sin = (struct sockaddr_in *)&host->saddr_in; - host_sin6 = (struct sockaddr_in6 *)&host->saddr_in; - - if ((address_family == AF_INET && host_sin->sin_addr.s_addr == sin->sin_addr.s_addr) || - (address_family == AF_INET6 && host_sin6->sin6_addr.s6_addr == sin6->sin6_addr.s6_addr)) { - if (debug) { - printf("Identical IP already exists. Not adding %s\n", arg); - } - return -1; - } - host = host->next; - } + // get string representation of address + char straddr[INET6_ADDRSTRLEN]; + parse_address((&address), straddr, sizeof(straddr)); /* add the fresh ip */ - host = (struct rta_host *)malloc(sizeof(struct rta_host)); - if (!host) { - char straddr[INET6_ADDRSTRLEN]; - parse_address((struct sockaddr_storage *)&in, straddr, sizeof(straddr)); - crash("add_target_ip(%s, %s): malloc(%lu) failed", arg, straddr, sizeof(struct rta_host)); + ping_target *target = (ping_target *)calloc(1, sizeof(ping_target)); + if (!target) { + crash("add_target_ip(%s): malloc(%lu) failed", straddr, sizeof(ping_target)); } - memset(host, 0, sizeof(struct rta_host)); - /* set the values. use calling name for output */ - host->name = strdup(arg); + ping_target_create_wrapper target_wrapper = ping_target_create(address); - /* fill out the sockaddr_storage struct */ - if (address_family == AF_INET) { - host_sin = (struct sockaddr_in *)&host->saddr_in; - host_sin->sin_family = AF_INET; - host_sin->sin_addr.s_addr = sin->sin_addr.s_addr; + if (target_wrapper.errorcode == OK) { + *target = target_wrapper.host; + result.target = target; } else { - host_sin6 = (struct sockaddr_in6 *)&host->saddr_in; - host_sin6->sin6_family = AF_INET6; - memcpy(host_sin6->sin6_addr.s6_addr, sin6->sin6_addr.s6_addr, sizeof host_sin6->sin6_addr.s6_addr); + result.error_code = target_wrapper.errorcode; } - /* fill out the sockaddr_in struct */ - host->rtmin = INFINITY; - host->rtmax = 0; - host->jitter = 0; - host->jitter_max = 0; - host->jitter_min = INFINITY; - host->last_tdiff = 0; - host->order_status = STATE_OK; - host->last_icmp_seq = 0; - host->rta_status = 0; - host->pl_status = 0; - host->jitter_status = 0; - host->mos_status = 0; - host->score_status = 0; - host->pl_status = 0; - - if (!list) { - list = cursor = host; - } else { - cursor->next = host; - } - - cursor = host; - targets++; - - return 0; + return result; } /* wrapper for add_target_ip */ -static int add_target(char *arg) { - int error, result = -1; - struct sockaddr_storage ip; - struct addrinfo hints, *res, *p; - struct sockaddr_in *sin; - struct sockaddr_in6 *sin6; +static add_target_wrapper add_target(char *arg, const check_icmp_execution_mode mode, + sa_family_t enforced_proto) { + if (debug > 0) { + printf("add_target called with argument %s\n", arg); + } - switch (address_family) { - case -1: - /* -4 and -6 are not specified on cmdline */ - address_family = AF_INET; - sin = (struct sockaddr_in *)&ip; - result = inet_pton(address_family, arg, &sin->sin_addr); -#ifdef USE_IPV6 - if (result != 1) { - address_family = AF_INET6; - sin6 = (struct sockaddr_in6 *)&ip; - result = inet_pton(address_family, arg, &sin6->sin6_addr); - } -#endif - /* If we don't find any valid addresses, we still don't know the address_family */ - if (result != 1) { - address_family = -1; + struct sockaddr_storage address_storage = {}; + struct sockaddr_in *sin = NULL; + struct sockaddr_in6 *sin6 = NULL; + int error_code = -1; + + switch (enforced_proto) { + case AF_UNSPEC: + /* + * no enforced protocol family + * try to parse the address with each one + */ + sin = (struct sockaddr_in *)&address_storage; + error_code = inet_pton(AF_INET, arg, &sin->sin_addr); + address_storage.ss_family = AF_INET; + + if (error_code != 1) { + sin6 = (struct sockaddr_in6 *)&address_storage; + error_code = inet_pton(AF_INET6, arg, &sin6->sin6_addr); + address_storage.ss_family = AF_INET6; } break; case AF_INET: - sin = (struct sockaddr_in *)&ip; - result = inet_pton(address_family, arg, &sin->sin_addr); + sin = (struct sockaddr_in *)&address_storage; + error_code = inet_pton(AF_INET, arg, &sin->sin_addr); + address_storage.ss_family = AF_INET; break; case AF_INET6: - sin6 = (struct sockaddr_in6 *)&ip; - result = inet_pton(address_family, arg, &sin6->sin6_addr); + sin6 = (struct sockaddr_in6 *)&address_storage; + error_code = inet_pton(AF_INET, arg, &sin6->sin6_addr); + address_storage.ss_family = AF_INET6; break; default: crash("Address family not supported"); } - /* don't resolve if we don't have to */ - if (result == 1) { + add_target_wrapper result = { + .error_code = OK, + .targets = NULL, + .has_v4 = false, + .has_v6 = false, + }; + + // if error_code == 1 the address was a valid address parsed above + if (error_code == 1) { /* don't add all ip's if we were given a specific one */ - return add_target_ip(arg, &ip); - } else { - errno = 0; - memset(&hints, 0, sizeof(hints)); - if (address_family == -1) { - hints.ai_family = AF_UNSPEC; + add_target_ip_wrapper targeted = add_target_ip(address_storage); + + if (targeted.error_code != OK) { + result.error_code = ERROR; + return result; + } + + if (targeted.target->address.ss_family == AF_INET) { + result.has_v4 = true; + } else if (targeted.target->address.ss_family == AF_INET6) { + result.has_v6 = true; } else { - hints.ai_family = address_family == AF_INET ? PF_INET : PF_INET6; + assert(false); } - hints.ai_socktype = SOCK_RAW; - if ((error = getaddrinfo(arg, NULL, &hints, &res)) != 0) { - errno = 0; - crash("Failed to resolve %s: %s", arg, gai_strerror(error)); - return -1; - } - address_family = res->ai_family; + result.targets = targeted.target; + result.number_of_targets = 1; + return result; + } + + struct addrinfo hints = {}; + errno = 0; + hints.ai_family = enforced_proto; + hints.ai_socktype = SOCK_RAW; + + int error; + struct addrinfo *res; + if ((error = getaddrinfo(arg, NULL, &hints, &res)) != 0) { + errno = 0; + crash("Failed to resolve %s: %s", arg, gai_strerror(error)); + result.error_code = ERROR; + return result; } /* possibly add all the IP's as targets */ - for (p = res; p != NULL; p = p->ai_next) { - memcpy(&ip, p->ai_addr, p->ai_addrlen); - add_target_ip(arg, &ip); + for (struct addrinfo *address = res; address != NULL; address = address->ai_next) { + struct sockaddr_storage temporary_ip_address; + memcpy(&temporary_ip_address, address->ai_addr, address->ai_addrlen); + + add_target_ip_wrapper tmp = add_target_ip(temporary_ip_address); + + if (tmp.error_code != OK) { + // No proper error handling + // What to do? + } else { + if (result.targets == NULL) { + result.targets = tmp.target; + result.number_of_targets = 1; + } else { + result.number_of_targets += ping_target_list_append(result.targets, tmp.target); + } + if (address->ai_family == AF_INET) { + result.has_v4 = true; + } else if (address->ai_family == AF_INET6) { + result.has_v6 = true; + } + } /* this is silly, but it works */ if (mode == MODE_HOSTCHECK || mode == MODE_ALL) { @@ -1855,18 +1744,20 @@ static int add_target(char *arg) { } continue; } + + // Abort after first hit if not in of the modes above break; } freeaddrinfo(res); - return 0; + return result; } -static void set_source_ip(char *arg) { +static void set_source_ip(char *arg, const int icmp_sock, sa_family_t addr_family) { struct sockaddr_in src; memset(&src, 0, sizeof(src)); - src.sin_family = address_family; + src.sin_family = addr_family; if ((src.sin_addr.s_addr = inet_addr(arg)) == INADDR_NONE) { src.sin_addr.s_addr = get_ip_address(arg); } @@ -1878,8 +1769,8 @@ static void set_source_ip(char *arg) { /* TODO: Move this to netutils.c and also change check_dhcp to use that. */ static in_addr_t get_ip_address(const char *ifname) { // TODO: Rewrite this so the function return an error and we exit somewhere else - struct sockaddr_in ip; - ip.sin_addr.s_addr = 0; // Fake initialization to make compiler happy + struct sockaddr_in ip_address; + ip_address.sin_addr.s_addr = 0; // Fake initialization to make compiler happy #if defined(SIOCGIFADDR) struct ifreq ifr; @@ -1897,7 +1788,7 @@ static in_addr_t get_ip_address(const char *ifname) { errno = 0; crash("Cannot get interface IP address on this platform."); #endif - return ip.sin_addr.s_addr; + return ip_address.sin_addr.s_addr; } /* @@ -1906,103 +1797,127 @@ static in_addr_t get_ip_address(const char *ifname) { * s = seconds * return value is in microseconds */ -static u_int get_timevar(const char *str) { - char p, u, *ptr; - size_t len; - u_int i, d; /* integer and decimal, respectively */ - u_int factor = 1000; /* default to milliseconds */ +static get_timevar_wrapper get_timevar(const char *str) { + get_timevar_wrapper result = { + .error_code = OK, + .time_range = 0, + }; if (!str) { - return 0; + result.error_code = ERROR; + return result; } - len = strlen(str); + + size_t len = strlen(str); if (!len) { - return 0; + result.error_code = ERROR; + return result; } /* unit might be given as ms|m (millisec), * us|u (microsec) or just plain s, for seconds */ - p = '\0'; - u = str[len - 1]; + char tmp = '\0'; + char unit = str[len - 1]; if (len >= 2 && !isdigit((int)str[len - 2])) { - p = str[len - 2]; - } - if (p && u == 's') { - u = p; - } else if (!p) { - p = u; - } - if (debug > 2) { - printf("evaluating %s, u: %c, p: %c\n", str, u, p); + tmp = str[len - 2]; } - if (u == 'u') { + if (tmp && unit == 's') { + unit = tmp; + } else if (!tmp) { + tmp = unit; + } + + if (debug > 2) { + printf("evaluating %s, u: %c, p: %c\n", str, unit, tmp); + } + + unsigned int factor = 1000; /* default to milliseconds */ + if (unit == 'u') { factor = 1; /* microseconds */ - } else if (u == 'm') { + } else if (unit == 'm') { factor = 1000; /* milliseconds */ - } else if (u == 's') { + } else if (unit == 's') { factor = 1000000; /* seconds */ } + if (debug > 2) { printf("factor is %u\n", factor); } - i = strtoul(str, &ptr, 0); + char *ptr; + unsigned long pre_radix; + pre_radix = strtoul(str, &ptr, 0); if (!ptr || *ptr != '.' || strlen(ptr) < 2 || factor == 1) { - return i * factor; + result.time_range = (unsigned int)(pre_radix * factor); + return result; } /* time specified in usecs can't have decimal points, so ignore them */ if (factor == 1) { - return i; + result.time_range = (unsigned int)pre_radix; + return result; } - d = strtoul(ptr + 1, NULL, 0); + /* integer and decimal, respectively */ + unsigned int post_radix = (unsigned int)strtoul(ptr + 1, NULL, 0); /* d is decimal, so get rid of excess digits */ - while (d >= factor) { - d /= 10; + while (post_radix >= factor) { + post_radix /= 10; } /* the last parenthesis avoids floating point exceptions. */ - return ((i * factor) + (d * (factor / 10))); + result.time_range = (unsigned int)((pre_radix * factor) + (post_radix * (factor / 10))); + return result; } -/* not too good at checking errors, but it'll do (main() should barfe on -1) */ -static int get_threshold(char *str, threshold *th) { - char *p = NULL, i = 0; +static get_threshold_wrapper get_threshold(char *str, check_icmp_threshold threshold) { + get_threshold_wrapper result = { + .errorcode = OK, + .threshold = threshold, + }; - if (!str || !strlen(str) || !th) { - return -1; + if (!str || !strlen(str)) { + result.errorcode = ERROR; + return result; } /* pointer magic slims code by 10 lines. i is bof-stop on stupid libc's */ - p = &str[strlen(str) - 1]; - while (p != &str[1]) { - if (*p == '%') { - *p = '\0'; - } else if (*p == ',' && i) { - *p = '\0'; /* reset it so get_timevar(str) works nicely later */ - th->pl = (unsigned char)strtoul(p + 1, NULL, 0); + bool is_at_last_char = false; + char *tmp = &str[strlen(str) - 1]; + while (tmp != &str[1]) { + if (*tmp == '%') { + *tmp = '\0'; + } else if (*tmp == ',' && is_at_last_char) { + *tmp = '\0'; /* reset it so get_timevar(str) works nicely later */ + result.threshold.pl = (unsigned char)strtoul(tmp + 1, NULL, 0); break; } - i = 1; - p--; - } - th->rta = get_timevar(str); - - if (!th->rta) { - return -1; + is_at_last_char = true; + tmp--; } - if (th->rta > MAXTTL * 1000000) { - th->rta = MAXTTL * 1000000; - } - if (th->pl > 100) { - th->pl = 100; + get_timevar_wrapper parsed_time = get_timevar(str); + + if (parsed_time.error_code == OK) { + result.threshold.rta = parsed_time.time_range; + } else { + if (debug > 1) { + printf("%s: failed to parse rta threshold\n", __FUNCTION__); + } + result.errorcode = ERROR; + return result; } - return 0; + if (result.threshold.rta > MAXTTL * 1000000) { + result.threshold.rta = MAXTTL * 1000000; + } + if (result.threshold.pl > 100) { + result.threshold.pl = 100; + } + + return result; } /* @@ -2013,91 +1928,118 @@ static int get_threshold(char *str, threshold *th) { * @param[in] length strlen(str) * @param[out] warn Pointer to the warn threshold struct to which the values should be assigned * @param[out] crit Pointer to the crit threshold struct to which the values should be assigned - * @param[in] mode Determines whether this a threshold for rta, packet_loss, jitter, mos or score (exclusively) + * @param[in] mode Determines whether this a threshold for rta, packet_loss, jitter, mos or score + * (exclusively) */ -static bool get_threshold2(char *str, size_t length, threshold *warn, threshold *crit, threshold_mode mode) { - if (!str || !length || !warn || !crit) { - return false; +static get_threshold2_wrapper get_threshold2(char *str, size_t length, check_icmp_threshold warn, + check_icmp_threshold crit, threshold_mode mode) { + get_threshold2_wrapper result = { + .errorcode = OK, + .warn = warn, + .crit = crit, + }; + + if (!str || !length) { + result.errorcode = ERROR; + return result; } // p points to the last char in str - char *p = &str[length - 1]; + char *work_pointer = &str[length - 1]; // first_iteration is bof-stop on stupid libc's bool first_iteration = true; - while (p != &str[0]) { - if ((*p == 'm') || (*p == '%')) { - *p = '\0'; - } else if (*p == ',' && !first_iteration) { - *p = '\0'; /* reset it so get_timevar(str) works nicely later */ + while (work_pointer != &str[0]) { + if ((*work_pointer == 'm') || (*work_pointer == '%')) { + *work_pointer = '\0'; + } else if (*work_pointer == ',' && !first_iteration) { + *work_pointer = '\0'; /* reset it so get_timevar(str) works nicely later */ - char *start_of_value = p + 1; + char *start_of_value = work_pointer + 1; - if (!parse_threshold2_helper(start_of_value, strlen(start_of_value), crit, mode)) { - return false; + parse_threshold2_helper_wrapper tmp = + parse_threshold2_helper(start_of_value, strlen(start_of_value), result.crit, mode); + if (tmp.errorcode != OK) { + result.errorcode = ERROR; + return result; } + result.crit = tmp.result; } first_iteration = false; - p--; + work_pointer--; } - return parse_threshold2_helper(p, strlen(p), warn, mode); + parse_threshold2_helper_wrapper tmp = + parse_threshold2_helper(work_pointer, strlen(work_pointer), result.warn, mode); + if (tmp.errorcode != OK) { + result.errorcode = ERROR; + } else { + result.warn = tmp.result; + } + return result; } -static bool parse_threshold2_helper(char *s, size_t length, threshold *thr, threshold_mode mode) { +static parse_threshold2_helper_wrapper parse_threshold2_helper(char *threshold_string, + size_t length, + check_icmp_threshold thr, + threshold_mode mode) { char *resultChecker = {0}; + parse_threshold2_helper_wrapper result = { + .result = thr, + .errorcode = OK, + }; switch (mode) { case const_rta_mode: - thr->rta = strtod(s, &resultChecker) * 1000; + result.result.rta = (unsigned int)(strtod(threshold_string, &resultChecker) * 1000); break; case const_packet_loss_mode: - thr->pl = (unsigned char)strtoul(s, &resultChecker, 0); + result.result.pl = (unsigned char)strtoul(threshold_string, &resultChecker, 0); break; case const_jitter_mode: - thr->jitter = strtod(s, &resultChecker); - + result.result.jitter = strtod(threshold_string, &resultChecker); break; case const_mos_mode: - thr->mos = strtod(s, &resultChecker); + result.result.mos = strtod(threshold_string, &resultChecker); break; case const_score_mode: - thr->score = strtod(s, &resultChecker); + result.result.score = strtod(threshold_string, &resultChecker); break; } - if (resultChecker == s) { + if (resultChecker == threshold_string) { // Failed to parse - return false; + result.errorcode = ERROR; + return result; } - if (resultChecker != (s + length)) { + if (resultChecker != (threshold_string + length)) { // Trailing symbols - return false; + result.errorcode = ERROR; } - return true; + return result; } -unsigned short icmp_checksum(uint16_t *p, size_t n) { - unsigned short cksum; +unsigned short icmp_checksum(uint16_t *packet, size_t packet_size) { long sum = 0; /* sizeof(uint16_t) == 2 */ - while (n >= 2) { - sum += *(p++); - n -= 2; + while (packet_size >= 2) { + sum += *(packet++); + packet_size -= 2; } /* mop up the occasional odd byte */ - if (n == 1) { - sum += *((uint8_t *)p - 1); + if (packet_size == 1) { + sum += *((uint8_t *)packet - 1); } sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */ sum += (sum >> 16); /* add carry */ - cksum = ~sum; /* ones-complement, trunc to 16 bits */ + unsigned short cksum; + cksum = (unsigned short)~sum; /* ones-complement, trunc to 16 bits */ return cksum; } @@ -2121,13 +2063,14 @@ void print_help(void) { printf(" %s\n", _("Use IPv4 (default) or IPv6 to communicate with the targets")); printf(" %s\n", "-w"); printf(" %s", _("warning threshold (currently ")); - printf("%0.3fms,%u%%)\n", (float)warn.rta / 1000, warn.pl); + printf("%0.3fms,%u%%)\n", (float)DEFAULT_WARN_RTA / 1000, DEFAULT_WARN_PL); printf(" %s\n", "-c"); printf(" %s", _("critical threshold (currently ")); - printf("%0.3fms,%u%%)\n", (float)crit.rta / 1000, crit.pl); + printf("%0.3fms,%u%%)\n", (float)DEFAULT_CRIT_RTA / 1000, DEFAULT_CRIT_PL); printf(" %s\n", "-R"); - printf(" %s\n", _("RTA, round trip average, mode warning,critical, ex. 100ms,200ms unit in ms")); + printf(" %s\n", + _("RTA, round trip average, mode warning,critical, ex. 100ms,200ms unit in ms")); printf(" %s\n", "-P"); printf(" %s\n", _("packet loss mode, ex. 40%,50% , unit in %")); printf(" %s\n", "-J"); @@ -2144,28 +2087,29 @@ void print_help(void) { printf(" %s\n", _("specify a source IP address or device name")); printf(" %s\n", "-n"); printf(" %s", _("number of packets to send (currently ")); - printf("%u)\n", packets); + printf("%u)\n", DEFAULT_NUMBER_OF_PACKETS); printf(" %s\n", "-p"); printf(" %s", _("number of packets to send (currently ")); - printf("%u)\n", packets); + printf("%u)\n", DEFAULT_NUMBER_OF_PACKETS); printf(" %s\n", "-i"); printf(" %s", _("max packet interval (currently ")); - printf("%0.3fms)\n", (float)pkt_interval / 1000); + printf("%0.3fms)\n", (float)DEFAULT_PKT_INTERVAL / 1000); printf(" %s\n", "-I"); printf(" %s", _("max target interval (currently ")); - printf("%0.3fms)\n", (float)target_interval / 1000); + printf("%0.3fms)\n", (float)DEFAULT_TARGET_INTERVAL / 1000); printf(" %s\n", "-m"); printf(" %s", _("number of alive hosts required for success")); printf("\n"); printf(" %s\n", "-l"); printf(" %s", _("TTL on outgoing packets (currently ")); - printf("%u)\n", ttl); + printf("%u)\n", DEFAULT_TTL); printf(" %s\n", "-t"); printf(" %s", _("timeout value (seconds, currently ")); - printf("%u)\n", timeout); + printf("%u)\n", DEFAULT_TIMEOUT); printf(" %s\n", "-b"); printf(" %s\n", _("Number of icmp data bytes to send")); - printf(" %s %u + %d)\n", _("Packet size will be data bytes + icmp header (currently"), icmp_data_size, ICMP_MINLEN); + printf(" %s %lu + %d)\n", _("Packet size will be data bytes + icmp header (currently"), + DEFAULT_PING_DATA_SIZE, ICMP_MINLEN); printf(" %s\n", "-v"); printf(" %s\n", _("verbose")); printf("\n"); @@ -2175,12 +2119,15 @@ void print_help(void) { printf("\n"); printf(" %s\n", _("Threshold format for -w and -c is 200.25,60% for 200.25 msec RTA and 60%")); printf(" %s\n", _("packet loss. The default values should work well for most users.")); - printf(" %s\n", _("You can specify different RTA factors using the standardized abbreviations")); - printf(" %s\n", _("us (microseconds), ms (milliseconds, default) or just plain s for seconds.")); + printf(" %s\n", + _("You can specify different RTA factors using the standardized abbreviations")); + printf(" %s\n", + _("us (microseconds), ms (milliseconds, default) or just plain s for seconds.")); /* -d not yet implemented */ - /* printf ("%s\n", _("Threshold format for -d is warn,crit. 12,14 means WARNING if >= 12 hops")); - printf ("%s\n", _("are spent and CRITICAL if >= 14 hops are spent.")); - printf ("%s\n\n", _("NOTE: Some systems decrease TTL when forming ICMP_ECHOREPLY, others do not."));*/ + /* printf ("%s\n", _("Threshold format for -d is warn,crit. 12,14 means WARNING if >= 12 + hops")); printf ("%s\n", _("are spent and CRITICAL if >= 14 hops are spent.")); printf + ("%s\n\n", _("NOTE: Some systems decrease TTL when forming ICMP_ECHOREPLY, others do + not."));*/ printf("\n"); printf(" %s\n", _("The -v switch can be specified several times for increased verbosity.")); /* printf ("%s\n", _("Long options are currently unsupported.")); @@ -2194,3 +2141,334 @@ void print_usage(void) { printf("%s\n", _("Usage:")); printf(" %s [options] [-H] host1 host2 hostN\n", progname); } + +static add_host_wrapper add_host(char *arg, check_icmp_execution_mode mode, + sa_family_t enforced_proto) { + if (debug) { + printf("add_host called with argument %s\n", arg); + } + + add_host_wrapper result = { + .error_code = OK, + .host = check_icmp_target_container_init(), + .has_v4 = false, + .has_v6 = false, + }; + + add_target_wrapper targets = add_target(arg, mode, enforced_proto); + + if (targets.error_code != OK) { + result.error_code = targets.error_code; + return result; + } + + result.has_v4 = targets.has_v4; + result.has_v6 = targets.has_v6; + + result.host = check_icmp_target_container_init(); + + result.host.name = strdup(arg); + result.host.target_list = targets.targets; + result.host.number_of_targets = targets.number_of_targets; + + return result; +} + +mp_subcheck evaluate_target(ping_target target, check_icmp_mode_switches modes, + check_icmp_threshold warn, check_icmp_threshold crit) { + /* if no new mode selected, use old schema */ + if (!modes.rta_mode && !modes.pl_mode && !modes.jitter_mode && !modes.score_mode && + !modes.mos_mode && !modes.order_mode) { + modes.rta_mode = true; + modes.pl_mode = true; + } + + mp_subcheck result = mp_subcheck_init(); + result = mp_set_subcheck_default_state(result, STATE_OK); + + char address[INET6_ADDRSTRLEN]; + memset(address, 0, INET6_ADDRSTRLEN); + parse_address(&target.address, address, sizeof(address)); + + xasprintf(&result.output, "%s", address); + + double packet_loss; + time_t rta; + if (!target.icmp_recv) { + /* rta 0 is of course not entirely correct, but will still show up + * conspicuously as missing entries in perfparse and cacti */ + packet_loss = 100; + rta = 0; + result = mp_set_subcheck_state(result, STATE_CRITICAL); + /* up the down counter if not already counted */ + + if (target.flags & FLAG_LOST_CAUSE) { + xasprintf(&result.output, "%s: %s @ %s", result.output, + get_icmp_error_msg(target.icmp_type, target.icmp_code), address); + } else { /* not marked as lost cause, so we have no flags for it */ + xasprintf(&result.output, "%s", result.output); + } + } else { + packet_loss = + (unsigned char)((target.icmp_sent - target.icmp_recv) * 100) / target.icmp_sent; + rta = target.time_waited / target.icmp_recv; + } + + double EffectiveLatency; + double mos; /* Mean opinion score */ + double score; /* score */ + + if (target.icmp_recv > 1) { + /* + * This algorithm is probably pretty much blindly copied from + * locations like this one: + * https://www.slac.stanford.edu/comp/net/wan-mon/tutorial.html#mos It calculates a MOS + * value (range of 1 to 5, where 1 is bad and 5 really good). According to some quick + * research MOS originates from the Audio/Video transport network area. Whether it can + * and should be computed from ICMP data, I can not say. + * + * Anyway the basic idea is to map a value "R" with a range of 0-100 to the MOS value + * + * MOS stands likely for Mean Opinion Score ( + * https://en.wikipedia.org/wiki/Mean_Opinion_Score ) + * + * More links: + * - https://confluence.slac.stanford.edu/display/IEPM/MOS + */ + target.jitter = (target.jitter / (target.icmp_recv - 1) / 1000); + + /* + * Take the average round trip latency (in milliseconds), add + * round trip jitter, but double the impact to latency + * then add 10 for protocol latencies (in milliseconds). + */ + EffectiveLatency = ((double)rta / 1000) + target.jitter * 2 + 10; + + double R; + if (EffectiveLatency < 160) { + R = 93.2 - (EffectiveLatency / 40); + } else { + R = 93.2 - ((EffectiveLatency - 120) / 10); + } + + // Now, let us deduct 2.5 R values per percentage of packet loss (i.e. a + // loss of 5% will be entered as 5). + R = R - (packet_loss * 2.5); + + if (R < 0) { + R = 0; + } + + score = R; + mos = 1 + ((0.035) * R) + ((.000007) * R * (R - 60) * (100 - R)); + } else { + target.jitter = 0; + target.jitter_min = 0; + target.jitter_max = 0; + mos = 0; + } + + /* Check which mode is on and do the warn / Crit stuff */ + if (modes.rta_mode) { + mp_subcheck sc_rta = mp_subcheck_init(); + sc_rta = mp_set_subcheck_default_state(sc_rta, STATE_OK); + xasprintf(&sc_rta.output, "rta %0.3fms", (double)rta / 1000); + + if (rta >= crit.rta) { + sc_rta = mp_set_subcheck_state(sc_rta, STATE_CRITICAL); + xasprintf(&sc_rta.output, "%s > %0.3fms", sc_rta.output, (double)crit.rta / 1000); + } else if (rta >= warn.rta) { + sc_rta = mp_set_subcheck_state(sc_rta, STATE_WARNING); + xasprintf(&sc_rta.output, "%s > %0.3fms", sc_rta.output, (double)warn.rta / 1000); + } + + if (packet_loss < 100) { + mp_perfdata pd_rta = perfdata_init(); + xasprintf(&pd_rta.label, "%srta", address); + pd_rta.uom = strdup("ms"); + pd_rta.value = mp_create_pd_value(rta / 1000); + pd_rta.min = mp_create_pd_value(0); + + pd_rta.warn = mp_range_set_end(pd_rta.warn, mp_create_pd_value(warn.rta)); + pd_rta.crit = mp_range_set_end(pd_rta.crit, mp_create_pd_value(crit.rta)); + mp_add_perfdata_to_subcheck(&sc_rta, pd_rta); + + mp_perfdata pd_rt_min = perfdata_init(); + xasprintf(&pd_rt_min.label, "%srtmin", address); + pd_rt_min.value = mp_create_pd_value(target.rtmin / 1000); + pd_rt_min.uom = strdup("ms"); + mp_add_perfdata_to_subcheck(&sc_rta, pd_rt_min); + + mp_perfdata pd_rt_max = perfdata_init(); + xasprintf(&pd_rt_max.label, "%srtmax", address); + pd_rt_max.value = mp_create_pd_value(target.rtmax / 1000); + pd_rt_max.uom = strdup("ms"); + mp_add_perfdata_to_subcheck(&sc_rta, pd_rt_max); + } + + mp_add_subcheck_to_subcheck(&result, sc_rta); + } + + if (modes.pl_mode) { + mp_subcheck sc_pl = mp_subcheck_init(); + sc_pl = mp_set_subcheck_default_state(sc_pl, STATE_OK); + xasprintf(&sc_pl.output, "packet loss %.1f%%", packet_loss); + + if (packet_loss >= crit.pl) { + sc_pl = mp_set_subcheck_state(sc_pl, STATE_CRITICAL); + xasprintf(&sc_pl.output, "%s > %u%%", sc_pl.output, crit.pl); + } else if (packet_loss >= warn.pl) { + sc_pl = mp_set_subcheck_state(sc_pl, STATE_WARNING); + xasprintf(&sc_pl.output, "%s > %u%%", sc_pl.output, crit.pl); + } + + mp_perfdata pd_pl = perfdata_init(); + xasprintf(&pd_pl.label, "%spl", address); + pd_pl.uom = strdup("%"); + + pd_pl.warn = mp_range_set_end(pd_pl.warn, mp_create_pd_value(warn.pl)); + pd_pl.crit = mp_range_set_end(pd_pl.crit, mp_create_pd_value(crit.pl)); + pd_pl.value = mp_create_pd_value(packet_loss); + + mp_add_perfdata_to_subcheck(&sc_pl, pd_pl); + + mp_add_subcheck_to_subcheck(&result, sc_pl); + } + + if (modes.jitter_mode) { + mp_subcheck sc_jitter = mp_subcheck_init(); + sc_jitter = mp_set_subcheck_default_state(sc_jitter, STATE_OK); + xasprintf(&sc_jitter.output, "jitter %0.3fms", target.jitter); + + if (target.jitter >= crit.jitter) { + sc_jitter = mp_set_subcheck_state(sc_jitter, STATE_CRITICAL); + xasprintf(&sc_jitter.output, "%s > %0.3fms", sc_jitter.output, crit.jitter); + } else if (target.jitter >= warn.jitter) { + sc_jitter = mp_set_subcheck_state(sc_jitter, STATE_WARNING); + xasprintf(&sc_jitter.output, "%s > %0.3fms", sc_jitter.output, warn.jitter); + } + + if (packet_loss < 100) { + mp_perfdata pd_jitter = perfdata_init(); + pd_jitter.uom = strdup("ms"); + xasprintf(&pd_jitter.label, "%sjitter_avg", address); + pd_jitter.value = mp_create_pd_value(target.jitter); + pd_jitter.warn = mp_range_set_end(pd_jitter.warn, mp_create_pd_value(warn.jitter)); + pd_jitter.crit = mp_range_set_end(pd_jitter.crit, mp_create_pd_value(crit.jitter)); + mp_add_perfdata_to_subcheck(&sc_jitter, pd_jitter); + + mp_perfdata pd_jitter_min = perfdata_init(); + pd_jitter_min.uom = strdup("ms"); + xasprintf(&pd_jitter_min.label, "%sjitter_min", address); + pd_jitter_min.value = mp_create_pd_value(target.jitter_min); + mp_add_perfdata_to_subcheck(&sc_jitter, pd_jitter_min); + + mp_perfdata pd_jitter_max = perfdata_init(); + pd_jitter_max.uom = strdup("ms"); + xasprintf(&pd_jitter_max.label, "%sjitter_max", address); + pd_jitter_max.value = mp_create_pd_value(target.jitter_max); + mp_add_perfdata_to_subcheck(&sc_jitter, pd_jitter_max); + } + mp_add_subcheck_to_subcheck(&result, sc_jitter); + } + + if (modes.mos_mode) { + mp_subcheck sc_mos = mp_subcheck_init(); + sc_mos = mp_set_subcheck_default_state(sc_mos, STATE_OK); + xasprintf(&sc_mos.output, "MOS %0.1f", mos); + + if (mos <= crit.mos) { + sc_mos = mp_set_subcheck_state(sc_mos, STATE_CRITICAL); + xasprintf(&sc_mos.output, "%s < %0.1f", sc_mos.output, crit.mos); + } else if (mos <= warn.mos) { + sc_mos = mp_set_subcheck_state(sc_mos, STATE_WARNING); + xasprintf(&sc_mos.output, "%s < %0.1f", sc_mos.output, warn.mos); + } + + if (packet_loss < 100) { + mp_perfdata pd_mos = perfdata_init(); + xasprintf(&pd_mos.label, "%smos", address); + pd_mos.value = mp_create_pd_value(mos); + pd_mos.warn = mp_range_set_end(pd_mos.warn, mp_create_pd_value(warn.mos)); + pd_mos.crit = mp_range_set_end(pd_mos.crit, mp_create_pd_value(crit.mos)); + pd_mos.min = mp_create_pd_value(0); + pd_mos.max = mp_create_pd_value(5); + mp_add_perfdata_to_subcheck(&sc_mos, pd_mos); + } + mp_add_subcheck_to_subcheck(&result, sc_mos); + } + + if (modes.score_mode) { + mp_subcheck sc_score = mp_subcheck_init(); + sc_score = mp_set_subcheck_default_state(sc_score, STATE_OK); + xasprintf(&sc_score.output, "Score %f", score); + + if (score <= crit.score) { + sc_score = mp_set_subcheck_state(sc_score, STATE_CRITICAL); + xasprintf(&sc_score.output, "%s < %f", sc_score.output, crit.score); + } else if (score <= warn.score) { + sc_score = mp_set_subcheck_state(sc_score, STATE_WARNING); + xasprintf(&sc_score.output, "%s < %f", sc_score.output, warn.score); + } + + if (packet_loss < 100) { + mp_perfdata pd_score = perfdata_init(); + xasprintf(&pd_score.label, "%sscore", address); + pd_score.value = mp_create_pd_value(score); + pd_score.warn = mp_range_set_end(pd_score.warn, mp_create_pd_value(warn.score)); + pd_score.crit = mp_range_set_end(pd_score.crit, mp_create_pd_value(crit.score)); + pd_score.min = mp_create_pd_value(0); + pd_score.max = mp_create_pd_value(100); + mp_add_perfdata_to_subcheck(&sc_score, pd_score); + } + + mp_add_subcheck_to_subcheck(&result, sc_score); + } + + if (modes.order_mode) { + mp_subcheck sc_order = mp_subcheck_init(); + sc_order = mp_set_subcheck_default_state(sc_order, STATE_OK); + + if (target.found_out_of_order_packets) { + mp_set_subcheck_state(sc_order, STATE_CRITICAL); + xasprintf(&sc_order.output, "Packets out of order"); + } else { + xasprintf(&sc_order.output, "Packets in order"); + } + + mp_add_subcheck_to_subcheck(&result, sc_order); + } + + return result; +} + +evaluate_host_wrapper evaluate_host(check_icmp_target_container host, + check_icmp_mode_switches modes, check_icmp_threshold warn, + check_icmp_threshold crit) { + evaluate_host_wrapper result = { + .targets_warn = 0, + .targets_ok = 0, + .sc_host = mp_subcheck_init(), + }; + result.sc_host = mp_set_subcheck_default_state(result.sc_host, STATE_OK); + + result.sc_host.output = strdup(host.name); + + ping_target *target = host.target_list; + for (unsigned int i = 0; i < host.number_of_targets; i++) { + mp_subcheck sc_target = evaluate_target(*target, modes, warn, crit); + + mp_state_enum target_state = mp_compute_subcheck_state(sc_target); + + if (target_state == STATE_WARNING) { + result.targets_warn++; + } else if (target_state == STATE_OK) { + result.targets_ok++; + } + mp_add_subcheck_to_subcheck(&result.sc_host, sc_target); + + target = target->next; + } + + return result; +} diff --git a/plugins-root/check_icmp.d/check_icmp_helpers.c b/plugins-root/check_icmp.d/check_icmp_helpers.c new file mode 100644 index 00000000..ec786305 --- /dev/null +++ b/plugins-root/check_icmp.d/check_icmp_helpers.c @@ -0,0 +1,134 @@ +#include "./config.h" +#include +#include +#include +#include "./check_icmp_helpers.h" +#include "../../plugins/netutils.h" + +// timeout as a global variable to make it available to the timeout handler +unsigned int timeout = DEFAULT_TIMEOUT; + +check_icmp_config check_icmp_config_init() { + check_icmp_config tmp = { + .modes = + { + .order_mode = false, + .mos_mode = false, + .rta_mode = false, + .pl_mode = false, + .jitter_mode = false, + .score_mode = false, + }, + + .min_hosts_alive = -1, + .crit = {.pl = DEFAULT_CRIT_PL, + .rta = DEFAULT_CRIT_RTA, + .jitter = 50.0, + .mos = 3.0, + .score = 70.0}, + .warn = {.pl = DEFAULT_WARN_PL, + .rta = DEFAULT_WARN_RTA, + .jitter = 40.0, + .mos = 3.5, + .score = 80.0}, + + .ttl = DEFAULT_TTL, + .icmp_data_size = DEFAULT_PING_DATA_SIZE, + .icmp_pkt_size = DEFAULT_PING_DATA_SIZE + ICMP_MINLEN, + .pkt_interval = DEFAULT_PKT_INTERVAL, + .target_interval = 0, + .number_of_packets = DEFAULT_NUMBER_OF_PACKETS, + + .source_ip = NULL, + .need_v4 = false, + .need_v6 = false, + + .sender_id = 0, + + .mode = MODE_RTA, + + .number_of_targets = 0, + .targets = NULL, + + .number_of_hosts = 0, + .hosts = NULL, + }; + return tmp; +} + +ping_target ping_target_init() { + ping_target tmp = { + .rtmin = INFINITY, + + .jitter_min = INFINITY, + + .found_out_of_order_packets = false, + }; + + return tmp; +} + +check_icmp_state check_icmp_state_init() { + check_icmp_state tmp = {.icmp_sent = 0, .icmp_lost = 0, .icmp_recv = 0, .targets_down = 0}; + + return tmp; +} + +ping_target_create_wrapper ping_target_create(struct sockaddr_storage address) { + ping_target_create_wrapper result = { + .errorcode = OK, + }; + + struct sockaddr_storage *tmp_addr = &address; + + /* disregard obviously stupid addresses + * (I didn't find an ipv6 equivalent to INADDR_NONE) */ + if (((tmp_addr->ss_family == AF_INET && + (((struct sockaddr_in *)tmp_addr)->sin_addr.s_addr == INADDR_NONE || + ((struct sockaddr_in *)tmp_addr)->sin_addr.s_addr == INADDR_ANY))) || + (tmp_addr->ss_family == AF_INET6 && + (((struct sockaddr_in6 *)tmp_addr)->sin6_addr.s6_addr == in6addr_any.s6_addr))) { + result.errorcode = ERROR; + return result; + } + + /* add the fresh ip */ + ping_target target = ping_target_init(); + + /* fill out the sockaddr_storage struct */ + target.address = address; + + result.host = target; + + return result; +} + +check_icmp_target_container check_icmp_target_container_init() { + check_icmp_target_container tmp = { + .name = NULL, + .number_of_targets = 0, + .target_list = NULL, + }; + return tmp; +} + +unsigned int ping_target_list_append(ping_target *list, ping_target *elem) { + if (elem == NULL || list == NULL) { + return 0; + } + + while (list->next != NULL) { + list = list->next; + } + + list->next = elem; + + unsigned int result = 1; + + while (elem->next != NULL) { + result++; + elem = elem->next; + } + + return result; +} diff --git a/plugins-root/check_icmp.d/check_icmp_helpers.h b/plugins-root/check_icmp.d/check_icmp_helpers.h new file mode 100644 index 00000000..dc6ea40b --- /dev/null +++ b/plugins-root/check_icmp.d/check_icmp_helpers.h @@ -0,0 +1,68 @@ +#pragma once + +#include "../../lib/states.h" +#include +#include +#include +#include +#include +#include +#include + +typedef struct ping_target { + unsigned short id; /* id in **table, and icmp pkts */ + char *msg; /* icmp error message, if any */ + + struct sockaddr_storage address; /* the address of this host */ + struct sockaddr_storage error_addr; /* stores address of error replies */ + time_t time_waited; /* total time waited, in usecs */ + unsigned int icmp_sent, icmp_recv, icmp_lost; /* counters */ + unsigned char icmp_type, icmp_code; /* type and code from errors */ + unsigned short flags; /* control/status flags */ + + double rtmax; /* max rtt */ + double rtmin; /* min rtt */ + + double jitter; /* measured jitter */ + double jitter_max; /* jitter rtt maximum */ + double jitter_min; /* jitter rtt minimum */ + + time_t last_tdiff; + unsigned int last_icmp_seq; /* Last ICMP_SEQ to check out of order pkts */ + + bool found_out_of_order_packets; + + struct ping_target *next; +} ping_target; + +ping_target ping_target_init(); + +typedef struct { + char *name; + ping_target *target_list; + unsigned int number_of_targets; +} check_icmp_target_container; + +check_icmp_target_container check_icmp_target_container_init(); + +typedef struct { + unsigned int icmp_sent; + unsigned int icmp_recv; + unsigned int icmp_lost; + unsigned short targets_down; +} check_icmp_state; + +check_icmp_state check_icmp_state_init(); + +typedef struct { + int errorcode; + ping_target host; +} ping_target_create_wrapper; + +typedef struct { + int socket4; + int socket6; +} check_icmp_socket_set; + +ping_target_create_wrapper ping_target_create(struct sockaddr_storage address); +unsigned int ping_target_list_append(ping_target *list, ping_target *elem); diff --git a/plugins-root/check_icmp.d/config.h b/plugins-root/check_icmp.d/config.h new file mode 100644 index 00000000..fc9dd5a6 --- /dev/null +++ b/plugins-root/check_icmp.d/config.h @@ -0,0 +1,111 @@ +#pragma once + +#include "../../config.h" +#include "../../lib/states.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "./check_icmp_helpers.h" + +/* threshold structure. all values are maximum allowed, exclusive */ +typedef struct { + unsigned char pl; /* max allowed packet loss in percent */ + time_t rta; /* roundtrip time average, microseconds */ + double jitter; /* jitter time average, microseconds */ + double mos; /* MOS */ + double score; /* Score */ +} check_icmp_threshold; + +/* the different modes of this program are as follows: + * MODE_RTA: send all packets no matter what (mimic check_icmp and check_ping) + * MODE_HOSTCHECK: Return immediately upon any sign of life + * In addition, sends packets to ALL addresses assigned + * to this host (as returned by gethostbyname() or + * gethostbyaddr() and expects one host only to be checked at + * a time. Therefore, any packet response what so ever will + * count as a sign of life, even when received outside + * crit.rta limit. Do not misspell any additional IP's. + * MODE_ALL: Requires packets from ALL requested IP to return OK (default). + * MODE_ICMP: Default Mode + */ +typedef enum { + MODE_RTA, + MODE_HOSTCHECK, + MODE_ALL, + MODE_ICMP, +} check_icmp_execution_mode; + +typedef struct { + bool order_mode; + bool mos_mode; + bool rta_mode; + bool pl_mode; + bool jitter_mode; + bool score_mode; +} check_icmp_mode_switches; + +typedef struct { + check_icmp_mode_switches modes; + + int min_hosts_alive; + check_icmp_threshold crit; + check_icmp_threshold warn; + + unsigned long ttl; + unsigned short icmp_data_size; + unsigned short icmp_pkt_size; + time_t pkt_interval; + time_t target_interval; + unsigned short number_of_packets; + + char *source_ip; + bool need_v4; + bool need_v6; + + uint16_t sender_id; // PID of the main process, which is used as an ID in packets + + check_icmp_execution_mode mode; + + unsigned short number_of_targets; + ping_target *targets; + + unsigned short number_of_hosts; + check_icmp_target_container *hosts; +} check_icmp_config; + +check_icmp_config check_icmp_config_init(); + +/* the data structure */ +typedef struct icmp_ping_data { + struct timeval stime; /* timestamp (saved in protocol struct as well) */ + unsigned short ping_id; +} icmp_ping_data; + +#define MAX_IP_PKT_SIZE 65536 /* (theoretical) max IP packet size */ +#define IP_HDR_SIZE 20 +#define MAX_PING_DATA (MAX_IP_PKT_SIZE - IP_HDR_SIZE - ICMP_MINLEN) +#define MIN_PING_DATA_SIZE sizeof(struct icmp_ping_data) +#define DEFAULT_PING_DATA_SIZE (MIN_PING_DATA_SIZE + 44) + +/* 80 msec packet interval by default */ +#define DEFAULT_PKT_INTERVAL 80000 +#define DEFAULT_TARGET_INTERVAL 0 + +#define DEFAULT_WARN_RTA 200000 +#define DEFAULT_CRIT_RTA 500000 +#define DEFAULT_WARN_PL 40 +#define DEFAULT_CRIT_PL 80 + +#define DEFAULT_TIMEOUT 10 +#define DEFAULT_TTL 64 + +#define DEFAULT_NUMBER_OF_PACKETS 5 + +#define PACKET_BACKOFF_FACTOR 1.5 +#define TARGET_BACKOFF_FACTOR 1.5 diff --git a/plugins-root/t/check_icmp.t b/plugins-root/t/check_icmp.t index de1d88d2..d414c3c7 100644 --- a/plugins-root/t/check_icmp.t +++ b/plugins-root/t/check_icmp.t @@ -12,15 +12,12 @@ my $allow_sudo = getTestParameter( "NP_ALLOW_SUDO", "no" ); if ($allow_sudo eq "yes" or $> == 0) { - plan tests => 40; + plan tests => 17; } else { plan skip_all => "Need sudo to test check_icmp"; } my $sudo = $> == 0 ? '' : 'sudo'; -my $successOutput = '/OK - .*? rta (?:[\d\.]+ms)|(?:nan), lost \d+%/'; -my $failureOutput = '/(WARNING|CRITICAL) - .*? rta (?:[\d\.]+ms > [\d\.]+ms|nan)/'; - my $host_responsive = getTestParameter( "NP_HOST_RESPONSIVE", "The hostname of system responsive to network requests", "localhost" ); @@ -36,108 +33,85 @@ my $hostname_invalid = getTestParameter( "NP_HOSTNAME_INVALID", my $res; $res = NPTest->testCmd( - "$sudo ./check_icmp -H $host_responsive -w 10000ms,100% -c 10000ms,100%" + "$sudo ./check_icmp -H $host_responsive -w 100ms,100% -c 100ms,100%" ); is( $res->return_code, 0, "Syntax ok" ); -like( $res->output, $successOutput, "Output OK" ); $res = NPTest->testCmd( - "$sudo ./check_icmp -H $host_responsive -w 0ms,0% -c 10000ms,100%" + "$sudo ./check_icmp -H $host_responsive -w 0ms,0% -c 100ms,100%" ); is( $res->return_code, 1, "Syntax ok, with forced warning" ); -like( $res->output, $failureOutput, "Output OK" ); $res = NPTest->testCmd( "$sudo ./check_icmp -H $host_responsive -w 0,0% -c 0,0%" ); is( $res->return_code, 2, "Syntax ok, with forced critical" ); -like( $res->output, $failureOutput, "Output OK" ); $res = NPTest->testCmd( - "$sudo ./check_icmp -H $host_nonresponsive -w 10000ms,100% -c 10000ms,100% -t 2" + "$sudo ./check_icmp -H $host_nonresponsive -w 100ms,100% -c 100ms,100%" ); is( $res->return_code, 2, "Timeout - host nonresponsive" ); -like( $res->output, '/pl=100%/', "Error contains 'pl=100%' string (for 100% packet loss)" ); -like( $res->output, '/rta=U/', "Error contains 'rta=U' string" ); $res = NPTest->testCmd( - "$sudo ./check_icmp -w 10000ms,100% -c 10000ms,100%" + "$sudo ./check_icmp -w 100ms,100% -c 100ms,100%" ); is( $res->return_code, 3, "No hostname" ); -like( $res->output, '/No hosts to check/', "Output with appropriate error message"); $res = NPTest->testCmd( - "$sudo ./check_icmp -H $host_nonresponsive -w 10000ms,100% -c 10000ms,100% -n 1 -m 0 -t 2" + "$sudo ./check_icmp -H $host_nonresponsive -w 100ms,100% -c 100ms,100% -n 1 -m 0" ); is( $res->return_code, 0, "One host nonresponsive - zero required" ); -like( $res->output, $successOutput, "Output OK" ); $res = NPTest->testCmd( - "$sudo ./check_icmp -H $host_responsive -H $host_nonresponsive -w 10000ms,100% -c 10000ms,100% -n 1 -m 1 -t 2" + "$sudo ./check_icmp -H $host_responsive -H $host_nonresponsive -w 100ms,100% -c 100ms,100% -n 1 -m 1" ); is( $res->return_code, 0, "One of two host nonresponsive - one required" ); -like( $res->output, $successOutput, "Output OK" ); $res = NPTest->testCmd( - "$sudo ./check_icmp -H $host_responsive -H $host_nonresponsive -w 10000ms,100% -c 10000ms,100% -n 1 -m 2" + "$sudo ./check_icmp -H $host_responsive -H $host_nonresponsive -w 100ms,100% -c 100ms,100% -n 1 -m 2" ); is( $res->return_code, 2, "One of two host nonresponsive - two required" ); -like( $res->output, $failureOutput, "Output OK" ); $res = NPTest->testCmd( - "$sudo ./check_icmp -H $host_responsive -s 127.0.15.15 -w 10000ms,100% -c 10000ms,100% -n 1 -m 2" + "$sudo ./check_icmp -H $host_responsive -s 127.0.15.15 -w 100ms,100% -c 100ms,100% -n 1" ); is( $res->return_code, 0, "IPv4 source_ip accepted" ); -like( $res->output, $successOutput, "Output OK" ); $res = NPTest->testCmd( "$sudo ./check_icmp -H $host_responsive -b 65507" ); is( $res->return_code, 0, "Try max packet size" ); -like( $res->output, $successOutput, "Output OK - Didn't overflow" ); $res = NPTest->testCmd( - "$sudo ./check_icmp -H $host_responsive -R 100,100 -n 1 -t 2" + "$sudo ./check_icmp -H $host_responsive -R 100,100 -n 1" ); is( $res->return_code, 0, "rta works" ); -like( $res->output, $successOutput, "Output OK" ); $res = NPTest->testCmd( - "$sudo ./check_icmp -H $host_responsive -P 80,90 -n 1 -t 2" + "$sudo ./check_icmp -H $host_responsive -P 80,90 -n 1" ); is( $res->return_code, 0, "pl works" ); -like( $res->output, '/lost 0%/', "Output OK" ); $res = NPTest->testCmd( - "$sudo ./check_icmp -H $host_responsive -J 80,90 -t 2" + "$sudo ./check_icmp -H $host_responsive -J 80,90" ); is( $res->return_code, 0, "jitter works" ); -like( $res->output, '/jitter \d/', "Output OK" ); $res = NPTest->testCmd( - "$sudo ./check_icmp -H $host_responsive -M 4,3 -t 2" + "$sudo ./check_icmp -H $host_responsive -M 4,3" ); is( $res->return_code, 0, "mos works" ); -like( $res->output, '/MOS \d/', "Output OK" ); $res = NPTest->testCmd( - "$sudo ./check_icmp -H $host_responsive -S 80,70 -t 2" + "$sudo ./check_icmp -H $host_responsive -S 80,70" ); is( $res->return_code, 0, "score works" ); -like( $res->output, '/Score \d/', "Output OK" ); $res = NPTest->testCmd( - "$sudo ./check_icmp -H $host_responsive -O -t 2" + "$sudo ./check_icmp -H $host_responsive -O" ); is( $res->return_code, 0, "order works" ); -like( $res->output, '/Packets in order/', "Output OK" ); $res = NPTest->testCmd( - "$sudo ./check_icmp -H $host_responsive -O -S 80,70 -M 4,3 -J 80,90 -P 80,90 -R 100,100 -t 2" + "$sudo ./check_icmp -H $host_responsive -O -S 80,70 -M 4,3 -J 80,90 -P 80,90 -R 100,100" ); is( $res->return_code, 0, "order works" ); -like( $res->output, '/Packets in order/', "Output OK" ); -like( $res->output, '/Score \d/', "Output OK" ); -like( $res->output, '/MOS \d/', "Output OK" ); -like( $res->output, '/jitter \d/', "Output OK" ); -like( $res->output, '/lost 0%/', "Output OK" ); -like( $res->output, $successOutput, "Output OK" ); diff --git a/plugins/utils.h b/plugins/utils.h index 92a6c115..1d3c153c 100644 --- a/plugins/utils.h +++ b/plugins/utils.h @@ -76,7 +76,7 @@ char *strnl(char *); char *strpcpy(char *, const char *, const char *); char *strpcat(char *, const char *, const char *); int xvasprintf(char **strp, const char *fmt, va_list ap); -int xasprintf(char **strp, const char *fmt, ...); +int xasprintf(char **strp, const char *fmt, ...)__attribute__ ((format (printf, 2, 3))); void usage(const char *) __attribute__((noreturn)); void usage2(const char *, const char *) __attribute__((noreturn));